UnmanagedLibrary.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 Unix.Terminal {
  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. #if GUICS
  35. static bool IsMono;
  36. #else
  37. static bool IsMono, IsUnity, IsXamarinIOS, IsXamarinAndroid, IsXamarin;
  38. #endif
  39. static bool IsNetCore;
  40. public static bool IsMacOSPlatform => IsMacOS;
  41. [DllImport ("libc")]
  42. static extern int uname (IntPtr buf);
  43. static string GetUname ()
  44. {
  45. var buffer = Marshal.AllocHGlobal (8192);
  46. try {
  47. if (uname (buffer) == 0) {
  48. return Marshal.PtrToStringAnsi (buffer);
  49. }
  50. return string.Empty;
  51. } catch {
  52. return string.Empty;
  53. } finally {
  54. if (buffer != IntPtr.Zero) {
  55. Marshal.FreeHGlobal (buffer);
  56. }
  57. }
  58. }
  59. static UnmanagedLibrary ()
  60. {
  61. var platform = Environment.OSVersion.Platform;
  62. IsMacOS = (platform == PlatformID.Unix && GetUname () == "Darwin");
  63. IsLinux = (platform == PlatformID.Unix && !IsMacOS);
  64. IsWindows = (platform == PlatformID.Win32NT || platform == PlatformID.Win32S || platform == PlatformID.Win32Windows);
  65. Is64Bit = Marshal.SizeOf (typeof (IntPtr)) == 8;
  66. IsMono = Type.GetType ("Mono.Runtime") != null;
  67. if (!IsMono) {
  68. IsNetCore = Type.GetType ("System.MathF") != null;
  69. }
  70. #if GUICS
  71. //IsUnity = IsXamarinIOS = IsXamarinAndroid = IsXamarin = false;
  72. #else
  73. IsUnity = Type.GetType (UnityEngineApplicationClassName) != null;
  74. IsXamarinIOS = Type.GetType (XamarinIOSObjectClassName) != null;
  75. IsXamarinAndroid = Type.GetType (XamarinAndroidObjectClassName) != null;
  76. IsXamarin = IsXamarinIOS || IsXamarinAndroid;
  77. #endif
  78. }
  79. // flags for dlopen
  80. const int RTLD_LAZY = 1;
  81. const int RTLD_GLOBAL = 8;
  82. readonly string libraryPath;
  83. readonly IntPtr handle;
  84. public IntPtr NativeLibraryHandle => handle;
  85. //
  86. // if isFullPath is set to true, the provided array of libraries are full paths
  87. // and are tested for the file existing, otherwise the file is merely the name
  88. // of the shared library that we pass to dlopen
  89. //
  90. public UnmanagedLibrary (string [] libraryPathAlternatives, bool isFullPath)
  91. {
  92. if (isFullPath) {
  93. this.libraryPath = FirstValidLibraryPath (libraryPathAlternatives);
  94. this.handle = PlatformSpecificLoadLibrary (this.libraryPath);
  95. } else {
  96. foreach (var lib in libraryPathAlternatives) {
  97. this.handle = PlatformSpecificLoadLibrary (lib);
  98. if (this.handle != IntPtr.Zero)
  99. break;
  100. }
  101. }
  102. if (this.handle == IntPtr.Zero) {
  103. throw new IOException ($"Error loading native library \"{string.Join (", ", libraryPathAlternatives)}\"");
  104. }
  105. }
  106. /// <summary>
  107. /// Loads symbol in a platform specific way.
  108. /// </summary>
  109. /// <param name="symbolName"></param>
  110. /// <returns></returns>
  111. public IntPtr LoadSymbol (string symbolName)
  112. {
  113. if (IsWindows) {
  114. // See http://stackoverflow.com/questions/10473310 for background on this.
  115. if (Is64Bit) {
  116. return Windows.GetProcAddress (this.handle, symbolName);
  117. } else {
  118. // Yes, we could potentially predict the size... but it's a lot simpler to just try
  119. // all the candidates. Most functions have a suffix of @0, @4 or @8 so we won't be trying
  120. // many options - and if it takes a little bit longer to fail if we've really got the wrong
  121. // library, that's not a big problem. This is only called once per function in the native library.
  122. symbolName = "_" + symbolName + "@";
  123. for (int stackSize = 0; stackSize < 128; stackSize += 4) {
  124. IntPtr candidate = Windows.GetProcAddress (this.handle, symbolName + stackSize);
  125. if (candidate != IntPtr.Zero) {
  126. return candidate;
  127. }
  128. }
  129. // Fail.
  130. return IntPtr.Zero;
  131. }
  132. }
  133. if (IsLinux) {
  134. if (IsMono) {
  135. return Mono.dlsym (this.handle, symbolName);
  136. }
  137. if (IsNetCore) {
  138. return CoreCLR.dlsym (this.handle, symbolName);
  139. }
  140. return Linux.dlsym (this.handle, symbolName);
  141. }
  142. if (IsMacOS) {
  143. return MacOSX.dlsym (this.handle, symbolName);
  144. }
  145. throw new InvalidOperationException ("Unsupported platform.");
  146. }
  147. public T GetNativeMethodDelegate<T> (string methodName)
  148. where T : class
  149. {
  150. var ptr = LoadSymbol (methodName);
  151. if (ptr == IntPtr.Zero) {
  152. throw new MissingMethodException (string.Format ("The native method \"{0}\" does not exist", methodName));
  153. }
  154. return Marshal.GetDelegateForFunctionPointer<T> (ptr); // non-generic version is obsolete
  155. }
  156. /// <summary>
  157. /// Loads library in a platform specific way.
  158. /// </summary>
  159. static IntPtr PlatformSpecificLoadLibrary (string libraryPath)
  160. {
  161. if (IsWindows) {
  162. return Windows.LoadLibrary (libraryPath);
  163. }
  164. if (IsLinux) {
  165. if (IsMono) {
  166. return Mono.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  167. }
  168. if (IsNetCore) {
  169. try {
  170. return CoreCLR.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  171. } catch (Exception) {
  172. IsNetCore = false;
  173. }
  174. }
  175. return Linux.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  176. }
  177. if (IsMacOS) {
  178. return MacOSX.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  179. }
  180. throw new InvalidOperationException ("Unsupported platform.");
  181. }
  182. static string FirstValidLibraryPath (string [] libraryPathAlternatives)
  183. {
  184. foreach (var path in libraryPathAlternatives) {
  185. if (File.Exists (path)) {
  186. return path;
  187. }
  188. }
  189. throw new FileNotFoundException (
  190. String.Format ("Error loading native library. Not found in any of the possible locations: {0}",
  191. string.Join (",", libraryPathAlternatives)));
  192. }
  193. static class Windows {
  194. [DllImport ("kernel32.dll")]
  195. internal static extern IntPtr LoadLibrary (string filename);
  196. [DllImport ("kernel32.dll")]
  197. internal static extern IntPtr GetProcAddress (IntPtr hModule, string procName);
  198. }
  199. static class Linux {
  200. [DllImport ("libdl.so")]
  201. internal static extern IntPtr dlopen (string filename, int flags);
  202. [DllImport ("libdl.so")]
  203. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  204. }
  205. static class MacOSX {
  206. [DllImport ("libSystem.dylib")]
  207. internal static extern IntPtr dlopen (string filename, int flags);
  208. [DllImport ("libSystem.dylib")]
  209. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  210. }
  211. /// <summary>
  212. /// On Linux systems, using using dlopen and dlsym results in
  213. /// DllNotFoundException("libdl.so not found") if libc6-dev
  214. /// is not installed. As a workaround, we load symbols for
  215. /// dlopen and dlsym from the current process as on Linux
  216. /// Mono sure is linked against these symbols.
  217. /// </summary>
  218. static class Mono {
  219. [DllImport ("__Internal")]
  220. internal static extern IntPtr dlopen (string filename, int flags);
  221. [DllImport ("__Internal")]
  222. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  223. }
  224. /// <summary>
  225. /// Similarly as for Mono on Linux, we load symbols for
  226. /// dlopen and dlsym from the "libcoreclr.so",
  227. /// to avoid the dependency on libc-dev Linux.
  228. /// </summary>
  229. static class CoreCLR {
  230. #if NET6_0
  231. // Custom resolver to support true single-file apps
  232. // (those which run directly from bundle; in-memory).
  233. // -1 on Unix means self-referencing binary (libcoreclr.so)
  234. // 0 means fallback to CoreCLR's internal resolution
  235. // Note: meaning of -1 stay the same even for non-single-file form factors.
  236. static CoreCLR() => NativeLibrary.SetDllImportResolver(typeof(CoreCLR).Assembly,
  237. (string libraryName, Assembly assembly, DllImportSearchPath? searchPath) =>
  238. libraryName == "libcoreclr.so" ? (IntPtr)(-1) : IntPtr.Zero);
  239. #endif
  240. [DllImport ("libcoreclr.so")]
  241. internal static extern IntPtr dlopen (string filename, int flags);
  242. [DllImport ("libcoreclr.so")]
  243. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  244. }
  245. }
  246. }