NETHostWindows.cpp 16 KB

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