UnmanagedLibrary.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright 2015 gRPC authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #define GUICS
  15. using System;
  16. using System.IO;
  17. using System.Reflection;
  18. using System.Runtime.InteropServices;
  19. using System.Threading;
  20. namespace Mono.Terminal.Internal {
  21. /// <summary>
  22. /// Represents a dynamically loaded unmanaged library in a (partially) platform independent manner.
  23. /// First, the native library is loaded using dlopen (on Unix systems) or using LoadLibrary (on Windows).
  24. /// dlsym or GetProcAddress are then used to obtain symbol addresses. <c>Marshal.GetDelegateForFunctionPointer</c>
  25. /// transforms the addresses into delegates to native methods.
  26. /// See http://stackoverflow.com/questions/13461989/p-invoke-to-dynamically-loaded-library-on-mono.
  27. /// </summary>
  28. internal class UnmanagedLibrary {
  29. const string UnityEngineApplicationClassName = "UnityEngine.Application, UnityEngine";
  30. const string XamarinAndroidObjectClassName = "Java.Lang.Object, Mono.Android";
  31. const string XamarinIOSObjectClassName = "Foundation.NSObject, Xamarin.iOS";
  32. static bool IsWindows, IsLinux, IsMacOS;
  33. static bool Is64Bit;
  34. static bool IsMono, IsUnity, IsXamarinIOS, IsXamarinAndroid, IsXamarin;
  35. static bool IsNetCore;
  36. public static bool IsMacOSPlatform => IsMacOS;
  37. [DllImport ("libc")]
  38. static extern int uname (IntPtr buf);
  39. static string GetUname ()
  40. {
  41. var buffer = Marshal.AllocHGlobal (8192);
  42. try {
  43. if (uname (buffer) == 0) {
  44. return Marshal.PtrToStringAnsi (buffer);
  45. }
  46. return string.Empty;
  47. } catch {
  48. return string.Empty;
  49. } finally {
  50. if (buffer != IntPtr.Zero) {
  51. Marshal.FreeHGlobal (buffer);
  52. }
  53. }
  54. }
  55. static UnmanagedLibrary ()
  56. {
  57. var platform = Environment.OSVersion.Platform;
  58. IsMacOS = (platform == PlatformID.Unix && GetUname () == "Darwin");
  59. IsLinux = (platform == PlatformID.Unix && !IsMacOS);
  60. IsWindows = (platform == PlatformID.Win32NT || platform == PlatformID.Win32S || platform == PlatformID.Win32Windows);
  61. Is64Bit = Marshal.SizeOf (typeof (IntPtr)) == 8;
  62. IsMono = Type.GetType ("Mono.Runtime") != null;
  63. if (!IsMono) {
  64. IsNetCore = Type.GetType ("System.MathF") != null;
  65. }
  66. #if GUICS
  67. IsUnity = IsXamarinIOS = IsXamarinAndroid = IsXamarin = false;
  68. #else
  69. IsUnity = Type.GetType (UnityEngineApplicationClassName) != null;
  70. IsXamarinIOS = Type.GetType (XamarinIOSObjectClassName) != null;
  71. IsXamarinAndroid = Type.GetType (XamarinAndroidObjectClassName) != null;
  72. IsXamarin = IsXamarinIOS || IsXamarinAndroid;
  73. #endif
  74. }
  75. // flags for dlopen
  76. const int RTLD_LAZY = 1;
  77. const int RTLD_GLOBAL = 8;
  78. readonly string libraryPath;
  79. readonly IntPtr handle;
  80. //
  81. // if isFullPath is set to true, the provided array of libraries are full paths
  82. // and are tested for the file existing, otherwise the file is merely the name
  83. // of the shared library that we pass to dlopen
  84. //
  85. public UnmanagedLibrary (string [] libraryPathAlternatives, bool isFullPath)
  86. {
  87. if (isFullPath){
  88. this.libraryPath = FirstValidLibraryPath (libraryPathAlternatives);
  89. this.handle = PlatformSpecificLoadLibrary (this.libraryPath);
  90. } else {
  91. foreach (var lib in libraryPathAlternatives){
  92. this.handle = PlatformSpecificLoadLibrary (lib);
  93. if (this.handle != IntPtr.Zero)
  94. break;
  95. }
  96. }
  97. if (this.handle == IntPtr.Zero) {
  98. throw new IOException (string.Format ("Error loading native library \"{0}\"", this.libraryPath));
  99. }
  100. }
  101. /// <summary>
  102. /// Loads symbol in a platform specific way.
  103. /// </summary>
  104. /// <param name="symbolName"></param>
  105. /// <returns></returns>
  106. private IntPtr LoadSymbol (string symbolName)
  107. {s
  108. if (IsWindows) {
  109. // See http://stackoverflow.com/questions/10473310 for background on this.
  110. if (Is64Bit) {
  111. return Windows.GetProcAddress (this.handle, symbolName);
  112. } else {
  113. // Yes, we could potentially predict the size... but it's a lot simpler to just try
  114. // all the candidates. Most functions have a suffix of @0, @4 or @8 so we won't be trying
  115. // many options - and if it takes a little bit longer to fail if we've really got the wrong
  116. // library, that's not a big problem. This is only called once per function in the native library.
  117. symbolName = "_" + symbolName + "@";
  118. for (int stackSize = 0; stackSize < 128; stackSize += 4) {
  119. IntPtr candidate = Windows.GetProcAddress (this.handle, symbolName + stackSize);
  120. if (candidate != IntPtr.Zero) {
  121. return candidate;
  122. }
  123. }
  124. // Fail.
  125. return IntPtr.Zero;
  126. }
  127. }
  128. if (IsLinux) {
  129. if (IsMono) {
  130. return Mono.dlsym (this.handle, symbolName);
  131. }
  132. if (IsNetCore) {
  133. return CoreCLR.dlsym (this.handle, symbolName);
  134. }
  135. return Linux.dlsym (this.handle, symbolName);
  136. }
  137. if (IsMacOS) {
  138. return MacOSX.dlsym (this.handle, symbolName);
  139. }
  140. throw new InvalidOperationException ("Unsupported platform.");
  141. }
  142. public T GetNativeMethodDelegate<T> (string methodName)
  143. where T : class
  144. {
  145. var ptr = LoadSymbol (methodName);
  146. if (ptr == IntPtr.Zero) {
  147. throw new MissingMethodException (string.Format ("The native method \"{0}\" does not exist", methodName));
  148. }
  149. return Marshal.GetDelegateForFunctionPointer<T>(ptr); // non-generic version is obsolete
  150. }
  151. /// <summary>
  152. /// Loads library in a platform specific way.
  153. /// </summary>
  154. private static IntPtr PlatformSpecificLoadLibrary (string libraryPath)
  155. {
  156. if (IsWindows) {
  157. return Windows.LoadLibrary (libraryPath);
  158. }
  159. if (IsLinux) {
  160. if (IsMono) {
  161. return Mono.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  162. }
  163. if (IsNetCore) {
  164. return CoreCLR.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  165. }
  166. return Linux.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  167. }
  168. if (IsMacOS) {
  169. return MacOSX.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  170. }
  171. throw new InvalidOperationException ("Unsupported platform.");
  172. }
  173. private static string FirstValidLibraryPath (string [] libraryPathAlternatives)
  174. {
  175. foreach (var path in libraryPathAlternatives) {
  176. if (File.Exists (path)) {
  177. return path;
  178. }
  179. }
  180. throw new FileNotFoundException (
  181. String.Format ("Error loading native library. Not found in any of the possible locations: {0}",
  182. string.Join (",", libraryPathAlternatives)));
  183. }
  184. private static class Windows
  185. {
  186. [DllImport ("kernel32.dll")]
  187. internal static extern IntPtr LoadLibrary (string filename);
  188. [DllImport ("kernel32.dll")]
  189. internal static extern IntPtr GetProcAddress (IntPtr hModule, string procName);
  190. }
  191. private static class Linux
  192. {
  193. [DllImport ("libdl.so")]
  194. internal static extern IntPtr dlopen (string filename, int flags);
  195. [DllImport ("libdl.so")]
  196. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  197. }
  198. private static class MacOSX
  199. {
  200. [DllImport ("libSystem.dylib")]
  201. internal static extern IntPtr dlopen (string filename, int flags);
  202. [DllImport ("libSystem.dylib")]
  203. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  204. }
  205. /// <summary>
  206. /// On Linux systems, using using dlopen and dlsym results in
  207. /// DllNotFoundException("libdl.so not found") if libc6-dev
  208. /// is not installed. As a workaround, we load symbols for
  209. /// dlopen and dlsym from the current process as on Linux
  210. /// Mono sure is linked against these symbols.
  211. /// </summary>
  212. private static class Mono
  213. {
  214. [DllImport ("__Internal")]
  215. internal static extern IntPtr dlopen (string filename, int flags);
  216. [DllImport ("__Internal")]
  217. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  218. }
  219. /// <summary>
  220. /// Similarly as for Mono on Linux, we load symbols for
  221. /// dlopen and dlsym from the "libcoreclr.so",
  222. /// to avoid the dependency on libc-dev Linux.
  223. /// </summary>
  224. private static class CoreCLR
  225. {
  226. [DllImport ("libcoreclr.so")]
  227. internal static extern IntPtr dlopen (string filename, int flags);
  228. [DllImport ("libcoreclr.so")]
  229. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  230. }
  231. }
  232. }