UnmanagedLibrary.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. public IntPtr NativeLibraryHandle => handle;
  81. //
  82. // if isFullPath is set to true, the provided array of libraries are full paths
  83. // and are tested for the file existing, otherwise the file is merely the name
  84. // of the shared library that we pass to dlopen
  85. //
  86. public UnmanagedLibrary (string [] libraryPathAlternatives, bool isFullPath)
  87. {
  88. if (isFullPath){
  89. this.libraryPath = FirstValidLibraryPath (libraryPathAlternatives);
  90. this.handle = PlatformSpecificLoadLibrary (this.libraryPath);
  91. } else {
  92. foreach (var lib in libraryPathAlternatives){
  93. this.handle = PlatformSpecificLoadLibrary (lib);
  94. if (this.handle != IntPtr.Zero)
  95. break;
  96. }
  97. }
  98. if (this.handle == IntPtr.Zero) {
  99. throw new IOException (string.Format ("Error loading native library \"{0}\"", this.libraryPath));
  100. }
  101. }
  102. /// <summary>
  103. /// Loads symbol in a platform specific way.
  104. /// </summary>
  105. /// <param name="symbolName"></param>
  106. /// <returns></returns>
  107. public IntPtr LoadSymbol (string symbolName)
  108. {
  109. if (IsWindows) {
  110. // See http://stackoverflow.com/questions/10473310 for background on this.
  111. if (Is64Bit) {
  112. return Windows.GetProcAddress (this.handle, symbolName);
  113. } else {
  114. // Yes, we could potentially predict the size... but it's a lot simpler to just try
  115. // all the candidates. Most functions have a suffix of @0, @4 or @8 so we won't be trying
  116. // many options - and if it takes a little bit longer to fail if we've really got the wrong
  117. // library, that's not a big problem. This is only called once per function in the native library.
  118. symbolName = "_" + symbolName + "@";
  119. for (int stackSize = 0; stackSize < 128; stackSize += 4) {
  120. IntPtr candidate = Windows.GetProcAddress (this.handle, symbolName + stackSize);
  121. if (candidate != IntPtr.Zero) {
  122. return candidate;
  123. }
  124. }
  125. // Fail.
  126. return IntPtr.Zero;
  127. }
  128. }
  129. if (IsLinux) {
  130. if (IsMono) {
  131. return Mono.dlsym (this.handle, symbolName);
  132. }
  133. if (IsNetCore) {
  134. return CoreCLR.dlsym (this.handle, symbolName);
  135. }
  136. return Linux.dlsym (this.handle, symbolName);
  137. }
  138. if (IsMacOS) {
  139. return MacOSX.dlsym (this.handle, symbolName);
  140. }
  141. throw new InvalidOperationException ("Unsupported platform.");
  142. }
  143. public T GetNativeMethodDelegate<T> (string methodName)
  144. where T : class
  145. {
  146. var ptr = LoadSymbol (methodName);
  147. if (ptr == IntPtr.Zero) {
  148. throw new MissingMethodException (string.Format ("The native method \"{0}\" does not exist", methodName));
  149. }
  150. return Marshal.GetDelegateForFunctionPointer<T>(ptr); // non-generic version is obsolete
  151. }
  152. /// <summary>
  153. /// Loads library in a platform specific way.
  154. /// </summary>
  155. static IntPtr PlatformSpecificLoadLibrary (string libraryPath)
  156. {
  157. if (IsWindows) {
  158. return Windows.LoadLibrary (libraryPath);
  159. }
  160. if (IsLinux) {
  161. if (IsMono) {
  162. return Mono.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  163. }
  164. if (IsNetCore) {
  165. return CoreCLR.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  166. }
  167. return Linux.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  168. }
  169. if (IsMacOS) {
  170. return MacOSX.dlopen (libraryPath, RTLD_GLOBAL + RTLD_LAZY);
  171. }
  172. throw new InvalidOperationException ("Unsupported platform.");
  173. }
  174. static string FirstValidLibraryPath (string [] libraryPathAlternatives)
  175. {
  176. foreach (var path in libraryPathAlternatives) {
  177. if (File.Exists (path)) {
  178. return path;
  179. }
  180. }
  181. throw new FileNotFoundException (
  182. String.Format ("Error loading native library. Not found in any of the possible locations: {0}",
  183. string.Join (",", libraryPathAlternatives)));
  184. }
  185. static class Windows
  186. {
  187. [DllImport ("kernel32.dll")]
  188. internal static extern IntPtr LoadLibrary (string filename);
  189. [DllImport ("kernel32.dll")]
  190. internal static extern IntPtr GetProcAddress (IntPtr hModule, string procName);
  191. }
  192. static class Linux
  193. {
  194. [DllImport ("libdl.so")]
  195. internal static extern IntPtr dlopen (string filename, int flags);
  196. [DllImport ("libdl.so")]
  197. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  198. }
  199. static class MacOSX
  200. {
  201. [DllImport ("libSystem.dylib")]
  202. internal static extern IntPtr dlopen (string filename, int flags);
  203. [DllImport ("libSystem.dylib")]
  204. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  205. }
  206. /// <summary>
  207. /// On Linux systems, using using dlopen and dlsym results in
  208. /// DllNotFoundException("libdl.so not found") if libc6-dev
  209. /// is not installed. As a workaround, we load symbols for
  210. /// dlopen and dlsym from the current process as on Linux
  211. /// Mono sure is linked against these symbols.
  212. /// </summary>
  213. static class Mono
  214. {
  215. [DllImport ("__Internal")]
  216. internal static extern IntPtr dlopen (string filename, int flags);
  217. [DllImport ("__Internal")]
  218. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  219. }
  220. /// <summary>
  221. /// Similarly as for Mono on Linux, we load symbols for
  222. /// dlopen and dlsym from the "libcoreclr.so",
  223. /// to avoid the dependency on libc-dev Linux.
  224. /// </summary>
  225. static class CoreCLR
  226. {
  227. [DllImport ("libcoreclr.so")]
  228. internal static extern IntPtr dlopen (string filename, int flags);
  229. [DllImport ("libcoreclr.so")]
  230. internal static extern IntPtr dlsym (IntPtr handle, string symbol);
  231. }
  232. }
  233. }