UnmanagedLibrary.cs 8.5 KB

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