NETHostWindows.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #include <Atomic/IO/Log.h>
  2. #include <Atomic/IO/FileSystem.h>
  3. #include "NETHostWindows.h"
  4. // https://github.com/dotnet/coreclr/blob/master/Documentation/project-docs/clr-configuration-knobs.md
  5. // set COMPLUS_LogEnable=1
  6. // set COMPLUS_LogToConsole=1
  7. // set COMPLUS_LogLevel=9
  8. // set COMPLUS_ManagedLogFacility=0x00001000
  9. namespace Atomic
  10. {
  11. NETHostWindows::NETHostWindows(Context* context) :
  12. NETHost(context),
  13. clrRuntimeHost_(0),
  14. clrModule_(0),
  15. appDomainID_(0)
  16. {
  17. }
  18. NETHostWindows::~NETHostWindows()
  19. {
  20. }
  21. bool NETHostWindows::CreateDelegate(const String& assemblyName, const String& qualifiedClassName, const String& methodName, void** funcOut)
  22. {
  23. if (!clrRuntimeHost_)
  24. return false;
  25. HRESULT hr = clrRuntimeHost_->CreateDelegate(appDomainID_, WString(assemblyName).CString(), WString(qualifiedClassName).CString(), WString(methodName).CString(), (INT_PTR *)funcOut);
  26. if (FAILED(hr))
  27. {
  28. return false;
  29. }
  30. return true;
  31. }
  32. bool NETHostWindows::Initialize(const String& coreCLRFilesAbsPath)
  33. {
  34. // It is very important that this is the native path "\\" vs "/" as find files will return "/" or "\" depending
  35. // on what you give it, which will result in the domain failing to initialize as coreclr can't handle "/" on init
  36. coreCLRFilesAbsPath_ = GetNativePath(AddTrailingSlash(coreCLRFilesAbsPath));
  37. if (!LoadCLRDLL())
  38. return false;
  39. if (!InitCLRRuntimeHost())
  40. return false;
  41. if (!CreateAppDomain())
  42. return false;
  43. // MOVE THIS!
  44. typedef void (*StartupFunction)();
  45. StartupFunction startup;
  46. // The coreclr binding model will become locked upon loading the first assembly that is not on the TPA list, or
  47. // upon initializing the default context for the first time. For this test, test assemblies are located alongside
  48. // corerun, and hence will be on the TPA list. So, we should be able to set the default context once successfully,
  49. // and fail on the second try.
  50. // AssemblyLoadContext
  51. // https://github.com/dotnet/corefx/issues/3054
  52. // dnx loader
  53. // https://github.com/aspnet/dnx/tree/dev/src/Microsoft.Dnx.Loader
  54. bool result = CreateDelegate(
  55. "AtomicNETBootstrap",
  56. "Atomic.Bootstrap.AtomicLoadContext",
  57. "Startup",
  58. (void**) &startup);
  59. if (result)
  60. {
  61. startup();
  62. }
  63. result = CreateDelegate(
  64. "AtomicNETEngine",
  65. "AtomicEngine.Atomic",
  66. "Initialize",
  67. (void**) &startup);
  68. if (result)
  69. {
  70. startup();
  71. }
  72. return true;
  73. }
  74. bool NETHostWindows::LoadCLRDLL()
  75. {
  76. WString wcoreCLRDLLPath(coreCLRFilesAbsPath_ + "coreclr.dll");
  77. HMODULE result = ::LoadLibraryExW(wcoreCLRDLLPath.CString(), NULL, 0);
  78. if (!result)
  79. {
  80. LOGERRORF("Unable to load CoreCLR from %s", (coreCLRFilesAbsPath_ + "coreclr.dll").CString() );
  81. return false;
  82. }
  83. // Pin the module - CoreCLR.dll does not support being unloaded.
  84. HMODULE dummy_coreCLRModule;
  85. if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, wcoreCLRDLLPath.CString(), &dummy_coreCLRModule))
  86. {
  87. LOGERRORF("Unable to pin CoreCLR module: %s", (coreCLRFilesAbsPath_ + "coreclr.dll").CString() );
  88. return false;
  89. }
  90. clrModule_ = result;
  91. return true;
  92. }
  93. bool NETHostWindows::CreateAppDomain()
  94. {
  95. wchar_t appPath[MAX_LONGPATH] = W("C:\\Dev\\coreclr\\x64\\");
  96. wchar_t appNiPath[MAX_LONGPATH * 2] = W("");
  97. wcscpy_s(appNiPath, appPath);
  98. wcscat_s(appNiPath, MAX_LONGPATH * 2, W(";"));
  99. wcscat_s(appNiPath, MAX_LONGPATH * 2, appPath);
  100. // Construct native search directory paths
  101. wchar_t nativeDllSearchDirs[MAX_LONGPATH * 3];
  102. wcscpy_s(nativeDllSearchDirs, appPath);
  103. wcscat_s(nativeDllSearchDirs, MAX_LONGPATH * 3, W(";"));
  104. wcscat_s(nativeDllSearchDirs, MAX_LONGPATH * 3, WString(coreCLRFilesAbsPath_).CString());
  105. //-------------------------------------------------------------
  106. // Create an AppDomain
  107. // Allowed property names:
  108. // APPBASE
  109. // - The base path of the application from which the exe and other assemblies will be loaded
  110. //
  111. // TRUSTED_PLATFORM_ASSEMBLIES
  112. // - The list of complete paths to each of the fully trusted assemblies
  113. //
  114. // APP_PATHS
  115. // - The list of paths which will be probed by the assembly loader
  116. //
  117. // APP_NI_PATHS
  118. // - The list of additional paths that the assembly loader will probe for ngen images
  119. //
  120. // NATIVE_DLL_SEARCH_DIRECTORIES
  121. // - The list of paths that will be probed for native DLLs called by PInvoke
  122. //
  123. // IMPORTANT: ALL PATHS MUST USE "\" and not "/"
  124. const wchar_t *property_keys[] = {
  125. W("TRUSTED_PLATFORM_ASSEMBLIES"),
  126. W("APP_PATHS"),
  127. W("APP_NI_PATHS"),
  128. W("NATIVE_DLL_SEARCH_DIRECTORIES"),
  129. W("AppDomainCompatSwitch")
  130. };
  131. const wchar_t *property_values[] = {
  132. // TRUSTED_PLATFORM_ASSEMBLIES
  133. tpaList_.CStr(),
  134. // APP_PATHS
  135. appPath,
  136. // APP_NI_PATHS
  137. appNiPath,
  138. // NATIVE_DLL_SEARCH_DIRECTORIES
  139. nativeDllSearchDirs,
  140. // AppDomainCompatSwitch
  141. W("UseLatestBehaviorWhenTFMNotSpecified")
  142. };
  143. HRESULT hr = clrRuntimeHost_->CreateAppDomainWithManager(
  144. W("AtomicNETDomain"), // The friendly name of the AppDomain
  145. // Flags:
  146. // APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS
  147. // - By default CoreCLR only allows platform neutral assembly to be run. To allow
  148. // assemblies marked as platform specific, include this flag
  149. //
  150. // APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP
  151. // - Allows sandboxed applications to make P/Invoke calls and use COM interop
  152. //
  153. // APPDOMAIN_SECURITY_SANDBOXED
  154. // - Enables sandboxing. If not set, the app is considered full trust
  155. //
  156. // APPDOMAIN_IGNORE_UNHANDLED_EXCEPTION
  157. // - Prevents the application from being torn down if a managed exception is unhandled
  158. //
  159. APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS |
  160. APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP |
  161. APPDOMAIN_DISABLE_TRANSPARENCY_ENFORCEMENT,
  162. NULL, // Name of the assembly that contains the AppDomainManager implementation
  163. NULL, // The AppDomainManager implementation type name
  164. sizeof(property_keys)/sizeof(wchar_t*), // The number of properties
  165. property_keys,
  166. property_values,
  167. &appDomainID_);
  168. if (FAILED(hr)) {
  169. LOGERRORF("Failed call to CreateAppDomainWithManager. ERRORCODE:%u ", hr);
  170. return false;
  171. }
  172. return true;
  173. }
  174. bool NETHostWindows::InitCLRRuntimeHost()
  175. {
  176. if (!clrModule_)
  177. return false;
  178. FnGetCLRRuntimeHost pfnGetCLRRuntimeHost =
  179. (FnGetCLRRuntimeHost)::GetProcAddress(clrModule_, "GetCLRRuntimeHost");
  180. if (!pfnGetCLRRuntimeHost)
  181. {
  182. LOGERRORF("Unable to get GetCLRRuntimeHost function from module: %s", (coreCLRFilesAbsPath_ + "coreclr.dll").CString() );
  183. return false;
  184. }
  185. HRESULT hr = pfnGetCLRRuntimeHost(IID_ICLRRuntimeHost2, (IUnknown**)&clrRuntimeHost_);
  186. if (FAILED(hr))
  187. {
  188. LOGERRORF("Failed to get ICLRRuntimeHost2 interface. ERRORCODE: %u", hr);
  189. return false;
  190. }
  191. // Set up the startup flags for the clr runtime
  192. STARTUP_FLAGS dwStartupFlags = (STARTUP_FLAGS)(
  193. STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN |
  194. STARTUP_FLAGS::STARTUP_SINGLE_APPDOMAIN /* |
  195. STARTUP_FLAGS::STARTUP_SERVER_GC*/
  196. );
  197. // Default startup flags
  198. hr = clrRuntimeHost_->SetStartupFlags(dwStartupFlags);
  199. if (FAILED(hr))
  200. {
  201. LOGERRORF("Failed to set startup flags. ERRORCODE: %u", hr);
  202. return false;
  203. }
  204. /*
  205. // Authenticate with either CORECLR_HOST_AUTHENTICATION_KEY or CORECLR_HOST_AUTHENTICATION_KEY_NONGEN
  206. hr = clrRuntimeHost_->Authenticate(CORECLR_HOST_AUTHENTICATION_KEY);
  207. if (FAILED(hr))
  208. {
  209. LOGERRORF("CoreCLR failed to authenticate. ERRORCODE: %u", hr);
  210. return false;
  211. }
  212. */
  213. hr = clrRuntimeHost_->Start();
  214. if (FAILED(hr))
  215. {
  216. LOGERRORF("Failed to start CoreCLR. ERRORCODE: %u", hr);
  217. return false;
  218. }
  219. if (!GenerateTPAList())
  220. {
  221. LOGERRORF("Failed to generate TPA List");
  222. return false;
  223. }
  224. return true;
  225. }
  226. bool NETHostWindows::TPAListContainsFile(wchar_t* fileNameWithoutExtension, wchar_t** rgTPAExtensions, int countExtensions)
  227. {
  228. if (!tpaList_.CStr()) return false;
  229. for (int iExtension = 0; iExtension < countExtensions; iExtension++)
  230. {
  231. wchar_t fileName[MAX_LONGPATH];
  232. wcscpy_s(fileName, MAX_LONGPATH, W("\\")); // So that we don't match other files that end with the current file name
  233. wcscat_s(fileName, MAX_LONGPATH, fileNameWithoutExtension);
  234. wcscat_s(fileName, MAX_LONGPATH, rgTPAExtensions[iExtension] + 1);
  235. wcscat_s(fileName, MAX_LONGPATH, W(";")); // So that we don't match other files that begin with the current file name
  236. if (wcsstr(tpaList_.CStr(), fileName))
  237. {
  238. return true;
  239. }
  240. }
  241. return false;
  242. }
  243. void NETHostWindows::RemoveExtensionAndNi(wchar_t* fileName)
  244. {
  245. // Remove extension, if it exists
  246. wchar_t* extension = wcsrchr(fileName, W('.'));
  247. if (extension != NULL)
  248. {
  249. extension[0] = W('\0');
  250. // Check for .ni
  251. size_t len = wcslen(fileName);
  252. if (len > 3 &&
  253. fileName[len - 1] == W('i') &&
  254. fileName[len - 2] == W('n') &&
  255. fileName[len - 3] == W('.') )
  256. {
  257. fileName[len - 3] = W('\0');
  258. }
  259. }
  260. }
  261. void NETHostWindows::AddFilesFromDirectoryToTPAList(const wchar_t* targetPath, wchar_t** rgTPAExtensions, int countExtensions)
  262. {
  263. wchar_t assemblyPath[MAX_LONGPATH];
  264. for (int iExtension = 0; iExtension < countExtensions; iExtension++)
  265. {
  266. wcscpy_s(assemblyPath, MAX_LONGPATH, targetPath);
  267. const size_t dirLength = wcslen(targetPath);
  268. wchar_t* const fileNameBuffer = assemblyPath + dirLength;
  269. const size_t fileNameBufferSize = MAX_LONGPATH - dirLength;
  270. wcscat_s(assemblyPath, rgTPAExtensions[iExtension]);
  271. WIN32_FIND_DATA data;
  272. HANDLE findHandle = FindFirstFile(assemblyPath, &data);
  273. if (findHandle != INVALID_HANDLE_VALUE)
  274. {
  275. do
  276. {
  277. if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
  278. {
  279. // It seems that CoreCLR doesn't always use the first instance of an assembly on the TPA list (ni's may be preferred
  280. // over il, even if they appear later). So, only include the first instance of a simple assembly name to allow
  281. // users the opportunity to override Framework assemblies by placing dlls in %CORE_LIBRARIES%
  282. // ToLower for case-insensitive comparisons
  283. wchar_t* fileNameChar = data.cFileName;
  284. while (*fileNameChar)
  285. {
  286. *fileNameChar = towlower(*fileNameChar);
  287. fileNameChar++;
  288. }
  289. // Remove extension
  290. wchar_t fileNameWithoutExtension[MAX_LONGPATH];
  291. wcscpy_s(fileNameWithoutExtension, MAX_LONGPATH, data.cFileName);
  292. RemoveExtensionAndNi(fileNameWithoutExtension);
  293. // Add to the list if not already on it
  294. if (!TPAListContainsFile(fileNameWithoutExtension, rgTPAExtensions, countExtensions))
  295. {
  296. const size_t fileLength = wcslen(data.cFileName);
  297. const size_t assemblyPathLength = dirLength + fileLength;
  298. wcsncpy_s(fileNameBuffer, fileNameBufferSize, data.cFileName, fileLength);
  299. tpaList_.Append(assemblyPath, assemblyPathLength);
  300. tpaList_.Append(W(";"), 1);
  301. }
  302. else
  303. {
  304. LOGINFOF("NETHostWindows skipping assembly");
  305. }
  306. }
  307. } while (0 != FindNextFile(findHandle, &data));
  308. FindClose(findHandle);
  309. }
  310. }
  311. }
  312. bool NETHostWindows::GenerateTPAList()
  313. {
  314. wchar_t *rgTPAExtensions[] = {
  315. W("*.ni.dll"), // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir
  316. W("*.dll"),
  317. W("*.ni.exe"),
  318. W("*.exe"),
  319. };
  320. AddFilesFromDirectoryToTPAList(WString(coreCLRFilesAbsPath_).CString(), rgTPAExtensions, _countof(rgTPAExtensions));
  321. return true;
  322. }
  323. }
  324. /*
  325. RETAIL_CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogEnable, W("LogEnable"), "Turns on the traditional CLR log.")
  326. RETAIL_CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogFacility, W("LogFacility"), "Specifies a facility mask for CLR log. (See 'loglf.h'; VM interprets string value as hex number.) Also used by stresslog.")
  327. RETAIL_CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogFacility2, W("LogFacility2"), "Specifies a facility mask for CLR log. (See 'loglf.h'; VM interprets string value as hex number.) Also used by stresslog.")
  328. RETAIL_CONFIG_DWORD_INFO(EXTERNAL_logFatalError, W("logFatalError"), 1, "Specifies whether EventReporter logs fatal errors in the Windows event log.")
  329. CONFIG_STRING_INFO_EX(INTERNAL_LogFile, W("LogFile"), "Specifies a file name for the CLR log.", CLRConfig::REGUTIL_default)
  330. CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogFileAppend, W("LogFileAppend"), "Specifies whether to append to or replace the CLR log file.")
  331. CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogFlushFile, W("LogFlushFile"), "Specifies whether to flush the CLR log file file on each write.")
  332. RETAIL_CONFIG_DWORD_INFO_DIRECT_ACCESS(EXTERNAL_LogLevel, W("LogLevel"), "4=10 msgs, 9=1000000, 10=everything")
  333. RETAIL_CONFIG_STRING_INFO_DIRECT_ACCESS(INTERNAL_LogPath, W("LogPath"), "?Fusion debug log path.")
  334. RETAIL_CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogToConsole, W("LogToConsole"), "Writes the CLR log to console.")
  335. CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogToDebugger, W("LogToDebugger"), "Writes the CLR log to debugger (OutputDebugStringA).")
  336. CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogToFile, W("LogToFile"), "Writes the CLR log to a file.")
  337. CONFIG_DWORD_INFO_DIRECT_ACCESS(INTERNAL_LogWithPid, W("LogWithPid"), "Appends pid to filename for the CLR log.")
  338. RETAIL_CONFIG_DWORD_INFO_EX(EXTERNAL_FusionLogFileNamesIncludePid, W("FusionLogFileNamesIncludePid"), 0, "Fusion logging will append process id to log filenames.", CLRConfig::REGUTIL_default)
  339. */