NETCore.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. #include <ThirdParty/SDL/include/SDL.h>
  2. #include <Atomic/Core/CoreEvents.h>
  3. #include <Atomic/IO/FileSystem.h>
  4. #include <Atomic/IO/Log.h>
  5. #include <Atomic/Core/StringUtils.h>
  6. #include "CSEventHelper.h"
  7. #include "CSComponent.h"
  8. #include "NETCore.h"
  9. #include "NETManaged.h"
  10. #include "NETAssemblyFile.h"
  11. #ifdef ATOMIC_PLATFORM_WINDOWS
  12. #include "Platforms/Windows/NETHostWindows.h"
  13. #else
  14. #endif
  15. namespace Atomic
  16. {
  17. /*
  18. mcs /nostdlib /noconfig /r:System.Console.dll /r:System.Runtime.dll /r:System.IO.dll /r:System.IO.FileSystem.dll /r:mscorlib.dll HelloWorld.cs
  19. export PAL_DBG_CHANNELS="+all.all"
  20. */
  21. #ifdef ATOMIC_PLATFORM_OSX
  22. static const char * const sCoreClrDll = "libcoreclr.dylib";
  23. #elif ATOMIC_PLATFORM_WINDOWS
  24. static const char * const sCoreClrDll = "coreclr.dll";
  25. #else
  26. static const char * const sCoreClrDll = "libcoreclr.so";
  27. #endif
  28. // Prototype of the coreclr_initialize function from the libcoreclr.so
  29. typedef int (*InitializeCoreCLRFunction)(
  30. const char* exePath,
  31. const char* appDomainFriendlyName,
  32. int propertyCount,
  33. const char** propertyKeys,
  34. const char** propertyValues,
  35. void** hostHandle,
  36. unsigned int* domainId);
  37. // Prototype of the coreclr_shutdown function from the libcoreclr.so
  38. typedef int (*ShutdownCoreCLRFunction)(
  39. void* hostHandle,
  40. unsigned int domainId);
  41. // Prototype of the coreclr_execute_assembly function from the libcoreclr.so
  42. typedef int (*ExecuteAssemblyFunction)(
  43. void* hostHandle,
  44. unsigned int domainId,
  45. int argc,
  46. const char** argv,
  47. const char* managedAssemblyPath,
  48. unsigned int* exitCode);
  49. typedef int (*CreateDelegateFunction)(
  50. void* hostHandle,
  51. unsigned int domainId,
  52. const char* entryPointAssemblyName,
  53. const char* entryPointTypeName,
  54. const char* entryPointMethodName,
  55. void** delegate);
  56. static InitializeCoreCLRFunction sInitializeCoreCLR = 0;
  57. static ExecuteAssemblyFunction sExecuteAssembly = 0;
  58. static CreateDelegateFunction sCreateDelegate = 0;
  59. static ShutdownCoreCLRFunction sShutdownCoreCLR = 0;
  60. /// Register NETCore library objects.
  61. void ATOMIC_API RegisterNETCoreLibrary(Context* context);
  62. WeakPtr<Context> NETCore::csContext_;
  63. WeakPtr<NETCore> NETCore::instance_;
  64. NETCore::NETCore(Context* context) :
  65. Object(context),
  66. coreCLRDLLHandle_(0),
  67. hostHandle_(0),
  68. domainId_(0)
  69. {
  70. RegisterNETCoreLibrary(context_);
  71. assert(!instance_);
  72. instance_ = this;
  73. csContext_ = context;
  74. }
  75. NETCore::~NETCore()
  76. {
  77. context_->RemoveGlobalEventListener(context_->GetSubsystem<CSEventDispatcher>());
  78. context_->RemoveSubsystem(CSEventDispatcher::GetTypeStatic());
  79. context_->RemoveSubsystem(NETManaged::GetTypeStatic());
  80. instance_ = NULL;
  81. }
  82. void NETCore::GenerateTPAList(String& tpaList)
  83. {
  84. tpaList = String::EMPTY;
  85. FileSystem* fs = GetSubsystem<FileSystem>();
  86. Vector<String> results;
  87. fs->ScanDir(results, coreCLRFilesAbsPath_, "*.dll", SCAN_FILES, true);
  88. Vector<String> trustedAssemblies;
  89. for (unsigned i = 0; i < results.Size(); i++)
  90. {
  91. const String& assembly = results[i];
  92. // TODO: apply filtering if necessary
  93. trustedAssemblies.Push(coreCLRFilesAbsPath_ + assembly);
  94. }
  95. // trustedAssemblies.Push(coreCLRFilesAbsPath_ + "HelloWorld.exe");
  96. tpaList.Join(trustedAssemblies, ":");
  97. // LOGINFOF("NetCore:: TPALIST - %s", tpaList.CString());
  98. }
  99. void NETCore::Shutdown()
  100. {
  101. RefCounted::SetRefCountedDeletedFunction(0);
  102. if (sShutdownCoreCLR && hostHandle_)
  103. {
  104. sShutdownCoreCLR(hostHandle_, domainId_);
  105. }
  106. if (coreCLRDLLHandle_)
  107. {
  108. SDL_UnloadObject(coreCLRDLLHandle_);
  109. }
  110. coreCLRDLLHandle_ = 0;
  111. hostHandle_ = 0;
  112. domainId_ = 0;
  113. sInitializeCoreCLR = 0;
  114. sExecuteAssembly = 0;
  115. sCreateDelegate = 0;
  116. sShutdownCoreCLR = 0;
  117. }
  118. bool NETCore::InitCoreCLRDLL(String& errorMsg)
  119. {
  120. String coreClrDllPath = AddTrailingSlash(coreCLRFilesAbsPath_) + sCoreClrDll;
  121. coreCLRDLLHandle_ = SDL_LoadObject(coreClrDllPath.CString());
  122. if (coreCLRDLLHandle_ == NULL)
  123. {
  124. errorMsg = ToString("NETCore: Unable to load %s with error %s",
  125. coreClrDllPath.CString(),
  126. SDL_GetError());
  127. return false;
  128. }
  129. sInitializeCoreCLR = (InitializeCoreCLRFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_initialize");
  130. if (!sInitializeCoreCLR)
  131. {
  132. errorMsg = ToString("NETCore: Unable to get coreclr_initialize entry point in %s", coreClrDllPath.CString());
  133. return false;
  134. }
  135. sShutdownCoreCLR = (ShutdownCoreCLRFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_shutdown");
  136. if (!sShutdownCoreCLR)
  137. {
  138. errorMsg = ToString("NETCore: Unable to get coreclr_shutdown entry point in %s", coreClrDllPath.CString());
  139. return false;
  140. }
  141. sCreateDelegate = (CreateDelegateFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_create_delegate");
  142. if (!sCreateDelegate)
  143. {
  144. errorMsg = ToString("NETCore: Unable to get coreclr_create_delegate entry point in %s", coreClrDllPath.CString());
  145. return false;
  146. }
  147. sExecuteAssembly = (ExecuteAssemblyFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_execute_assembly");
  148. if (!sExecuteAssembly)
  149. {
  150. errorMsg = ToString("NETCore: Unable to get coreclr_execute_assembly entry point in %s", coreClrDllPath.CString());
  151. return false;
  152. }
  153. return true;
  154. }
  155. extern "C"
  156. {
  157. // http://ybeernet.blogspot.com/2011/03/techniques-of-calling-unmanaged-code.html
  158. // pinvoke is faster than [UnmanagedFunctionPointer] :/
  159. // [SuppressUnmanagedCodeSecurity] <--- add this attribute, in any event
  160. #ifdef ATOMIC_PLATFORM_WINDOWS
  161. #pragma warning(disable: 4244) // possible loss of data
  162. #define ATOMIC_EXPORT_API __declspec(dllexport)
  163. #else
  164. #define ATOMIC_EXPORT_API
  165. #endif
  166. ATOMIC_EXPORT_API ClassID csb_Atomic_RefCounted_GetClassID(RefCounted* refCounted)
  167. {
  168. if (!refCounted)
  169. return 0;
  170. return refCounted->GetClassID();
  171. }
  172. ATOMIC_EXPORT_API RefCounted* csb_AtomicEngine_GetSubsystem(const char* name)
  173. {
  174. return NETCore::GetContext()->GetSubsystem(name);
  175. }
  176. ATOMIC_EXPORT_API void csb_AtomicEngine_ReleaseRef(RefCounted* ref)
  177. {
  178. if (!ref)
  179. return;
  180. ref->ReleaseRef();
  181. }
  182. }
  183. void NETCore::WaitForDebuggerConnect()
  184. {
  185. netHost_->WaitForDebuggerConnect();
  186. }
  187. void NETCore::AddAssemblyLoadPath(const String& assemblyPath)
  188. {
  189. typedef void (*AddAssemblyLoadPathFunction)(const char* assemblyPath);
  190. AddAssemblyLoadPathFunction addAssemblyLoadPath;
  191. bool result = CreateDelegate(
  192. "AtomicNETBootstrap",
  193. "Atomic.Bootstrap.AtomicLoadContext",
  194. "AddAssemblyLoadPath",
  195. (void**) &addAssemblyLoadPath);
  196. if (result)
  197. {
  198. addAssemblyLoadPath(assemblyPath.CString());
  199. }
  200. }
  201. bool NETCore::CreateDelegate(const String& assemblyName, const String& qualifiedClassName, const String& methodName, void** funcOut)
  202. {
  203. return netHost_->CreateDelegate(assemblyName, qualifiedClassName, methodName, funcOut);
  204. /*
  205. if (!sCreateDelegate)
  206. return false;
  207. *funcOut = 0;
  208. // TODO: wrap in SharedPtr to control delegate lifetime?
  209. int st = sCreateDelegate(hostHandle_,
  210. domainId_,
  211. assemblyName.CString(),
  212. qualifiedClassName.CString(),
  213. methodName.CString(),
  214. funcOut);
  215. // ensure ptr isn't uninitialized
  216. if (st < 0)
  217. *funcOut = 0;
  218. return st >= 0;
  219. */
  220. }
  221. bool NETCore::Initialize(const String &coreCLRFilesAbsPath, const String &assemblyLoadPaths, String& errorMsg)
  222. {
  223. coreCLRFilesAbsPath_ = AddTrailingSlash(coreCLRFilesAbsPath);
  224. #ifdef ATOMIC_PLATFORM_WINDOWS
  225. netHost_ = new NETHostWindows(context_);
  226. #else
  227. #endif
  228. netHost_->Initialize(coreCLRFilesAbsPath_, assemblyLoadPaths);
  229. SharedPtr<NETManaged> managed(new NETManaged(context_));
  230. context_->RegisterSubsystem(managed);
  231. SharedPtr<CSEventDispatcher> dispatcher(new CSEventDispatcher(context_));
  232. context_->RegisterSubsystem(dispatcher);
  233. context_->AddGlobalEventListener(dispatcher);
  234. if (!context_->GetEditorContext())
  235. {
  236. SubscribeToEvent(E_UPDATE, HANDLER(NETCore, HandleUpdate));
  237. }
  238. managed->Initialize();
  239. #ifdef disabled
  240. if (!InitCoreCLRDLL(errorMsg))
  241. {
  242. Shutdown();
  243. return false;
  244. }
  245. // Allowed property names:
  246. // APPBASE
  247. // - The base path of the application from which the exe and other assemblies will be loaded
  248. //
  249. // TRUSTED_PLATFORM_ASSEMBLIES
  250. // - The list of complete paths to each of the fully trusted assemblies
  251. //
  252. // APP_PATHS
  253. // - The list of paths which will be probed by the assembly loader
  254. //
  255. // APP_NI_PATHS
  256. // - The list of additional paths that the assembly loader will probe for ngen images
  257. //
  258. // NATIVE_DLL_SEARCH_DIRECTORIES
  259. // - The list of paths that will be probed for native DLLs called by PInvoke
  260. //
  261. const char *propertyKeys[] = {
  262. "TRUSTED_PLATFORM_ASSEMBLIES",
  263. "APP_PATHS",
  264. "APP_NI_PATHS",
  265. "NATIVE_DLL_SEARCH_DIRECTORIES",
  266. "AppDomainCompatSwitch"
  267. };
  268. String tpaList;
  269. GenerateTPAList(tpaList);
  270. String appPath = coreCLRFilesAbsPath_;// "/Users/josh/Desktop/";
  271. Vector<String> nativeSearch;
  272. nativeSearch.Push(coreCLRFilesAbsPath_);
  273. //nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngine-build/Source/AtomicNET/NETNative");
  274. //nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngine-build/Source/AtomicEditor/AtomicEditor.app/Contents/MacOS");
  275. String nativeDllSearchDirs;
  276. nativeDllSearchDirs.Join(nativeSearch, ":");
  277. const char *propertyValues[] = {
  278. // TRUSTED_PLATFORM_ASSEMBLIES
  279. tpaList.CString(),
  280. // APP_PATHS
  281. appPath.CString(),
  282. // APP_NI_PATHS
  283. appPath.CString(),
  284. // NATIVE_DLL_SEARCH_DIRECTORIES
  285. nativeDllSearchDirs.CString(),
  286. // AppDomainCompatSwitch
  287. "UseLatestBehaviorWhenTFMNotSpecified"
  288. };
  289. int st = sInitializeCoreCLR(
  290. "AtomicEditor.exe",
  291. "NETCore",
  292. sizeof(propertyKeys) / sizeof(propertyKeys[0]),
  293. propertyKeys,
  294. propertyValues,
  295. &hostHandle_,
  296. &domainId_);
  297. if (st < 0)
  298. {
  299. Shutdown();
  300. errorMsg = ToString("NETCore: coreclr_initialize failed - status: 0x%08x\n", st);
  301. return false;
  302. }
  303. typedef void (*StartupFunction)();
  304. StartupFunction startup;
  305. // The coreclr binding model will become locked upon loading the first assembly that is not on the TPA list, or
  306. // upon initializing the default context for the first time. For this test, test assemblies are located alongside
  307. // corerun, and hence will be on the TPA list. So, we should be able to set the default context once successfully,
  308. // and fail on the second try.
  309. // AssemblyLoadContext
  310. // https://github.com/dotnet/corefx/issues/3054
  311. // dnx loader
  312. // https://github.com/aspnet/dnx/tree/dev/src/Microsoft.Dnx.Loader
  313. st = sCreateDelegate(hostHandle_,
  314. domainId_,
  315. "AtomicNETBootstrap",
  316. "Atomic.Bootstrap.AtomicLoadContext",
  317. "Startup",
  318. (void**) &startup);
  319. if (st >= 0)
  320. {
  321. startup();
  322. }
  323. st = sCreateDelegate(hostHandle_,
  324. domainId_,
  325. "AtomicNETEngine",
  326. "AtomicEngine.Atomic",
  327. "Initialize",
  328. (void**) &startup);
  329. if (st >= 0)
  330. {
  331. startup();
  332. }
  333. /*
  334. RefCountedDeletedFunction rcdFunction;
  335. st = sCreateDelegate(hostHandle_,
  336. domainId_,
  337. "AtomicNETEngine",
  338. "AtomicEngine.NativeCore",
  339. "RefCountedDeleted",
  340. (void**) &rcdFunction);
  341. if (st >= 0)
  342. {
  343. RefCounted::SetRefCountedDeletedFunction(rcdFunction);
  344. }
  345. NETUpdateFunctionPtr updateFunction;
  346. st = sCreateDelegate(hostHandle_,
  347. domainId_,
  348. "AtomicNETEngine",
  349. "AtomicEngine.NativeCore",
  350. "NETUpdate",
  351. (void**) &updateFunction);
  352. if (st >= 0)
  353. {
  354. GetSubsystem<NETManaged>()->SetNETUpdate(updateFunction);
  355. }
  356. typedef void (*InpectAssemblyFuctionPtr)(const char* path);
  357. InpectAssemblyFuctionPtr inspectAssembly;
  358. st = sCreateDelegate(hostHandle_,
  359. domainId_,
  360. "AtomicEditor",
  361. "AtomicEditor.AtomicEditor",
  362. "InspectAssembly",
  363. (void**) &inspectAssembly);
  364. if (st >= 0)
  365. {
  366. //inspectAssembly("/Users/josh/Desktop/AtomicNETTest.dll");
  367. }
  368. */
  369. /*
  370. unsigned int exitCode;
  371. st = sExecuteAssembly(
  372. hostHandle_,
  373. domainId_,
  374. 0,
  375. 0,
  376. "/Users/josh/Desktop/OSX.x64.Debug/HelloWorld.exe",
  377. (unsigned int*)&exitCode);
  378. */
  379. #endif
  380. return true;
  381. }
  382. void NETCore::HandleUpdate(StringHash eventType, VariantMap& eventData)
  383. {
  384. using namespace Update;
  385. GetSubsystem<NETManaged>()->NETUpdate(eventData[P_TIMESTEP].GetFloat());
  386. }
  387. void RegisterNETCoreLibrary(Context* context)
  388. {
  389. NETAssemblyFile::RegisterObject(context);
  390. CSComponent::RegisterObject(context);
  391. }
  392. }