NETHostWindows.cpp 14 KB

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