coreruncommon.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. //
  5. // Code that is used by both the Unix corerun and coreconsole.
  6. //
  7. #include "config.h"
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <assert.h>
  11. #include <dirent.h>
  12. #include <dlfcn.h>
  13. #include <limits.h>
  14. #include <set>
  15. #include <string>
  16. #include <string.h>
  17. #include <sys/stat.h>
  18. #if defined(__FreeBSD__)
  19. #include <sys/types.h>
  20. #include <sys/param.h>
  21. #endif
  22. #if HAVE_GETAUXVAL
  23. #include <sys/auxv.h>
  24. #endif
  25. #if defined(HAVE_SYS_SYSCTL_H) || defined(__FreeBSD__)
  26. #include <sys/sysctl.h>
  27. #endif
  28. #include "coreruncommon.h"
  29. #include "coreclrhost.h"
  30. #include <unistd.h>
  31. #ifndef SUCCEEDED
  32. #define SUCCEEDED(Status) ((Status) >= 0)
  33. #endif // !SUCCEEDED
  34. // Name of the environment variable controlling server GC.
  35. // If set to 1, server GC is enabled on startup. If 0, server GC is
  36. // disabled. Server GC is off by default.
  37. static const char* serverGcVar = "COMPlus_gcServer";
  38. // Name of environment variable to control "System.Globalization.Invariant"
  39. // Set to 1 for Globalization Invariant mode to be true. Default is false.
  40. static const char* globalizationInvariantVar = "CORECLR_GLOBAL_INVARIANT";
  41. #if defined(__linux__)
  42. #define symlinkEntrypointExecutable "/proc/self/exe"
  43. #elif !defined(__APPLE__)
  44. #define symlinkEntrypointExecutable "/proc/curproc/exe"
  45. #endif
  46. bool GetEntrypointExecutableAbsolutePath(std::string& entrypointExecutable)
  47. {
  48. bool result = false;
  49. entrypointExecutable.clear();
  50. // Get path to the executable for the current process using
  51. // platform specific means.
  52. #if defined(__APPLE__)
  53. // On Mac, we ask the OS for the absolute path to the entrypoint executable
  54. uint32_t lenActualPath = 0;
  55. if (_NSGetExecutablePath(nullptr, &lenActualPath) == -1)
  56. {
  57. // OSX has placed the actual path length in lenActualPath,
  58. // so re-attempt the operation
  59. std::string resizedPath(lenActualPath, '\0');
  60. char *pResizedPath = const_cast<char *>(resizedPath.c_str());
  61. if (_NSGetExecutablePath(pResizedPath, &lenActualPath) == 0)
  62. {
  63. entrypointExecutable.assign(pResizedPath);
  64. result = true;
  65. }
  66. }
  67. #elif defined (__FreeBSD__)
  68. static const int name[] = {
  69. CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1
  70. };
  71. char path[PATH_MAX];
  72. size_t len;
  73. len = sizeof(path);
  74. if (sysctl(name, 4, path, &len, nullptr, 0) == 0)
  75. {
  76. entrypointExecutable.assign(path);
  77. result = true;
  78. }
  79. else
  80. {
  81. // ENOMEM
  82. result = false;
  83. }
  84. #elif defined(__NetBSD__) && defined(KERN_PROC_PATHNAME)
  85. static const int name[] = {
  86. CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME,
  87. };
  88. char path[MAXPATHLEN];
  89. size_t len;
  90. len = sizeof(path);
  91. if (sysctl(name, __arraycount(name), path, &len, NULL, 0) != -1)
  92. {
  93. entrypointExecutable.assign(path);
  94. result = true;
  95. }
  96. else
  97. {
  98. result = false;
  99. }
  100. #else
  101. #if HAVE_GETAUXVAL && defined(AT_EXECFN)
  102. const char *execfn = (const char *)getauxval(AT_EXECFN);
  103. if (execfn)
  104. {
  105. entrypointExecutable.assign(execfn);
  106. result = true;
  107. }
  108. else
  109. #endif
  110. // On other OSs, return the symlink that will be resolved by GetAbsolutePath
  111. // to fetch the entrypoint EXE absolute path, inclusive of filename.
  112. result = GetAbsolutePath(symlinkEntrypointExecutable, entrypointExecutable);
  113. #endif
  114. return result;
  115. }
  116. bool GetAbsolutePath(const char* path, std::string& absolutePath)
  117. {
  118. bool result = false;
  119. char realPath[PATH_MAX];
  120. if (realpath(path, realPath) != nullptr && realPath[0] != '\0')
  121. {
  122. absolutePath.assign(realPath);
  123. // realpath should return canonicalized path without the trailing slash
  124. assert(absolutePath.back() != '/');
  125. result = true;
  126. }
  127. return result;
  128. }
  129. bool GetDirectory(const char* absolutePath, std::string& directory)
  130. {
  131. directory.assign(absolutePath);
  132. size_t lastSlash = directory.rfind('/');
  133. if (lastSlash != std::string::npos)
  134. {
  135. directory.erase(lastSlash);
  136. return true;
  137. }
  138. return false;
  139. }
  140. bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)
  141. {
  142. std::string clrFilesRelativePath;
  143. const char* clrFilesPathLocal = clrFilesPath;
  144. if (clrFilesPathLocal == nullptr)
  145. {
  146. // There was no CLR files path specified, use the folder of the corerun/coreconsole
  147. if (!GetDirectory(currentExePath, clrFilesRelativePath))
  148. {
  149. perror("Failed to get directory from argv[0]");
  150. return false;
  151. }
  152. clrFilesPathLocal = clrFilesRelativePath.c_str();
  153. // TODO: consider using an env variable (if defined) as a fall-back.
  154. // The windows version of the corerun uses core_root env variable
  155. }
  156. if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))
  157. {
  158. perror("Failed to convert CLR files path to absolute path");
  159. return false;
  160. }
  161. return true;
  162. }
  163. void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)
  164. {
  165. const char * const tpaExtensions[] = {
  166. ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir
  167. ".dll",
  168. ".ni.exe",
  169. ".exe",
  170. };
  171. DIR* dir = opendir(directory);
  172. if (dir == nullptr)
  173. {
  174. return;
  175. }
  176. std::set<std::string> addedAssemblies;
  177. // Walk the directory for each extension separately so that we first get files with .ni.dll extension,
  178. // then files with .dll extension, etc.
  179. for (size_t extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++)
  180. {
  181. const char* ext = tpaExtensions[extIndex];
  182. int extLength = strlen(ext);
  183. struct dirent* entry;
  184. // For all entries in the directory
  185. while ((entry = readdir(dir)) != nullptr)
  186. {
  187. // We are interested in files only
  188. switch (entry->d_type)
  189. {
  190. case DT_REG:
  191. break;
  192. // Handle symlinks and file systems that do not support d_type
  193. case DT_LNK:
  194. case DT_UNKNOWN:
  195. {
  196. std::string fullFilename;
  197. fullFilename.append(directory);
  198. fullFilename.append("/");
  199. fullFilename.append(entry->d_name);
  200. struct stat sb;
  201. if (stat(fullFilename.c_str(), &sb) == -1)
  202. {
  203. continue;
  204. }
  205. if (!S_ISREG(sb.st_mode))
  206. {
  207. continue;
  208. }
  209. }
  210. break;
  211. default:
  212. continue;
  213. }
  214. std::string filename(entry->d_name);
  215. // Check if the extension matches the one we are looking for
  216. int extPos = filename.length() - extLength;
  217. if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))
  218. {
  219. continue;
  220. }
  221. std::string filenameWithoutExt(filename.substr(0, extPos));
  222. // Make sure if we have an assembly with multiple extensions present,
  223. // we insert only one version of it.
  224. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())
  225. {
  226. addedAssemblies.insert(filenameWithoutExt);
  227. tpaList.append(directory);
  228. tpaList.append("/");
  229. tpaList.append(filename);
  230. tpaList.append(":");
  231. }
  232. }
  233. // Rewind the directory stream to be able to iterate over it for the next extension
  234. rewinddir(dir);
  235. }
  236. closedir(dir);
  237. }
  238. const char* GetEnvValueBoolean(const char* envVariable)
  239. {
  240. const char* envValue = std::getenv(envVariable);
  241. if (envValue == nullptr)
  242. {
  243. envValue = "0";
  244. }
  245. // CoreCLR expects strings "true" and "false" instead of "1" and "0".
  246. return (std::strcmp(envValue, "1") == 0 || strcasecmp(envValue, "true") == 0) ? "true" : "false";
  247. }
  248. static void *TryLoadHostPolicy(const char *hostPolicyPath)
  249. {
  250. #if defined(__APPLE__)
  251. static const char LibrarySuffix[] = ".dylib";
  252. #else // Various Linux-related OS-es
  253. static const char LibrarySuffix[] = ".so";
  254. #endif
  255. std::string hostPolicyCompletePath(hostPolicyPath);
  256. hostPolicyCompletePath.append(LibrarySuffix);
  257. void *libraryPtr = dlopen(hostPolicyCompletePath.c_str(), RTLD_LAZY);
  258. if (libraryPtr == nullptr)
  259. {
  260. fprintf(stderr, "Failed to load mock hostpolicy at path '%s'. Error: %s", hostPolicyCompletePath.c_str(), dlerror());
  261. }
  262. return libraryPtr;
  263. }
  264. int ExecuteManagedAssembly(
  265. const char* currentExeAbsolutePath,
  266. const char* clrFilesAbsolutePath,
  267. const char* managedAssemblyAbsolutePath,
  268. int managedAssemblyArgc,
  269. const char** managedAssemblyArgv)
  270. {
  271. // Indicates failure
  272. int exitCode = -1;
  273. #ifdef _ARM_
  274. // libunwind library is used to unwind stack frame, but libunwind for ARM
  275. // does not support ARM vfpv3/NEON registers in DWARF format correctly.
  276. // Therefore let's disable stack unwinding using DWARF information
  277. // See https://github.com/dotnet/coreclr/issues/6698
  278. //
  279. // libunwind use following methods to unwind stack frame.
  280. // UNW_ARM_METHOD_ALL 0xFF
  281. // UNW_ARM_METHOD_DWARF 0x01
  282. // UNW_ARM_METHOD_FRAME 0x02
  283. // UNW_ARM_METHOD_EXIDX 0x04
  284. putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
  285. #endif // _ARM_
  286. std::string coreClrDllPath(clrFilesAbsolutePath);
  287. coreClrDllPath.append("/");
  288. coreClrDllPath.append(coreClrDll);
  289. if (coreClrDllPath.length() >= PATH_MAX)
  290. {
  291. fprintf(stderr, "Absolute path to libcoreclr.so too long\n");
  292. return -1;
  293. }
  294. // Get just the path component of the managed assembly path
  295. std::string appPath;
  296. GetDirectory(managedAssemblyAbsolutePath, appPath);
  297. std::string tpaList;
  298. if (strlen(managedAssemblyAbsolutePath) > 0)
  299. {
  300. // Target assembly should be added to the tpa list. Otherwise corerun.exe
  301. // may find wrong assembly to execute.
  302. // Details can be found at https://github.com/dotnet/coreclr/issues/5631
  303. tpaList = managedAssemblyAbsolutePath;
  304. tpaList.append(":");
  305. }
  306. // Construct native search directory paths
  307. std::string nativeDllSearchDirs(appPath);
  308. char *coreLibraries = getenv("CORE_LIBRARIES");
  309. if (coreLibraries)
  310. {
  311. nativeDllSearchDirs.append(":");
  312. nativeDllSearchDirs.append(coreLibraries);
  313. if (std::strcmp(coreLibraries, clrFilesAbsolutePath) != 0)
  314. {
  315. AddFilesFromDirectoryToTpaList(coreLibraries, tpaList);
  316. }
  317. }
  318. nativeDllSearchDirs.append(":");
  319. nativeDllSearchDirs.append(clrFilesAbsolutePath);
  320. void* hostpolicyLib = nullptr;
  321. char* mockHostpolicyPath = getenv("MOCK_HOSTPOLICY");
  322. if (mockHostpolicyPath)
  323. {
  324. hostpolicyLib = TryLoadHostPolicy(mockHostpolicyPath);
  325. if (hostpolicyLib == nullptr)
  326. {
  327. return -1;
  328. }
  329. }
  330. AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);
  331. void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);
  332. if (coreclrLib != nullptr)
  333. {
  334. coreclr_initialize_ptr initializeCoreCLR = (coreclr_initialize_ptr)dlsym(coreclrLib, "coreclr_initialize");
  335. coreclr_execute_assembly_ptr executeAssembly = (coreclr_execute_assembly_ptr)dlsym(coreclrLib, "coreclr_execute_assembly");
  336. coreclr_shutdown_2_ptr shutdownCoreCLR = (coreclr_shutdown_2_ptr)dlsym(coreclrLib, "coreclr_shutdown_2");
  337. if (initializeCoreCLR == nullptr)
  338. {
  339. fprintf(stderr, "Function coreclr_initialize not found in the libcoreclr.so\n");
  340. }
  341. else if (executeAssembly == nullptr)
  342. {
  343. fprintf(stderr, "Function coreclr_execute_assembly not found in the libcoreclr.so\n");
  344. }
  345. else if (shutdownCoreCLR == nullptr)
  346. {
  347. fprintf(stderr, "Function coreclr_shutdown_2 not found in the libcoreclr.so\n");
  348. }
  349. else
  350. {
  351. // Check whether we are enabling server GC (off by default)
  352. const char* useServerGc = GetEnvValueBoolean(serverGcVar);
  353. // Check Globalization Invariant mode (false by default)
  354. const char* globalizationInvariant = GetEnvValueBoolean(globalizationInvariantVar);
  355. // Allowed property names:
  356. // APPBASE
  357. // - The base path of the application from which the exe and other assemblies will be loaded
  358. //
  359. // TRUSTED_PLATFORM_ASSEMBLIES
  360. // - The list of complete paths to each of the fully trusted assemblies
  361. //
  362. // APP_PATHS
  363. // - The list of paths which will be probed by the assembly loader
  364. //
  365. // APP_NI_PATHS
  366. // - The list of additional paths that the assembly loader will probe for ngen images
  367. //
  368. // NATIVE_DLL_SEARCH_DIRECTORIES
  369. // - The list of paths that will be probed for native DLLs called by PInvoke
  370. //
  371. const char *propertyKeys[] = {
  372. "TRUSTED_PLATFORM_ASSEMBLIES",
  373. "APP_PATHS",
  374. "APP_NI_PATHS",
  375. "NATIVE_DLL_SEARCH_DIRECTORIES",
  376. "System.GC.Server",
  377. "System.Globalization.Invariant",
  378. };
  379. const char *propertyValues[] = {
  380. // TRUSTED_PLATFORM_ASSEMBLIES
  381. tpaList.c_str(),
  382. // APP_PATHS
  383. appPath.c_str(),
  384. // APP_NI_PATHS
  385. appPath.c_str(),
  386. // NATIVE_DLL_SEARCH_DIRECTORIES
  387. nativeDllSearchDirs.c_str(),
  388. // System.GC.Server
  389. useServerGc,
  390. // System.Globalization.Invariant
  391. globalizationInvariant,
  392. };
  393. void* hostHandle;
  394. unsigned int domainId;
  395. int st = initializeCoreCLR(
  396. currentExeAbsolutePath,
  397. "unixcorerun",
  398. sizeof(propertyKeys) / sizeof(propertyKeys[0]),
  399. propertyKeys,
  400. propertyValues,
  401. &hostHandle,
  402. &domainId);
  403. if (!SUCCEEDED(st))
  404. {
  405. fprintf(stderr, "coreclr_initialize failed - status: 0x%08x\n", st);
  406. exitCode = -1;
  407. }
  408. else
  409. {
  410. st = executeAssembly(
  411. hostHandle,
  412. domainId,
  413. managedAssemblyArgc,
  414. managedAssemblyArgv,
  415. managedAssemblyAbsolutePath,
  416. (unsigned int*)&exitCode);
  417. if (!SUCCEEDED(st))
  418. {
  419. fprintf(stderr, "coreclr_execute_assembly failed - status: 0x%08x\n", st);
  420. exitCode = -1;
  421. }
  422. int latchedExitCode = 0;
  423. st = shutdownCoreCLR(hostHandle, domainId, &latchedExitCode);
  424. if (!SUCCEEDED(st))
  425. {
  426. fprintf(stderr, "coreclr_shutdown failed - status: 0x%08x\n", st);
  427. exitCode = -1;
  428. }
  429. if (exitCode != -1)
  430. {
  431. exitCode = latchedExitCode;
  432. }
  433. }
  434. }
  435. }
  436. else
  437. {
  438. const char* error = dlerror();
  439. fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error);
  440. }
  441. if (hostpolicyLib)
  442. {
  443. if(dlclose(hostpolicyLib) != 0)
  444. {
  445. fprintf(stderr, "Warning - dlclose of mock hostpolicy failed.\n");
  446. }
  447. }
  448. return exitCode;
  449. }