NETCore.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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::AddAssemblyLoadPath(const String& assemblyPath)
  184. {
  185. typedef void (*AddAssemblyLoadPathFunction)(const char* assemblyPath);
  186. AddAssemblyLoadPathFunction addAssemblyLoadPath;
  187. bool result = CreateDelegate(
  188. "AtomicNETBootstrap",
  189. "Atomic.Bootstrap.AtomicLoadContext",
  190. "AddAssemblyLoadPath",
  191. (void**) &addAssemblyLoadPath);
  192. if (result)
  193. {
  194. addAssemblyLoadPath(assemblyPath.CString());
  195. }
  196. }
  197. bool NETCore::CreateDelegate(const String& assemblyName, const String& qualifiedClassName, const String& methodName, void** funcOut)
  198. {
  199. return netHost_->CreateDelegate(assemblyName, qualifiedClassName, methodName, funcOut);
  200. /*
  201. if (!sCreateDelegate)
  202. return false;
  203. *funcOut = 0;
  204. // TODO: wrap in SharedPtr to control delegate lifetime?
  205. int st = sCreateDelegate(hostHandle_,
  206. domainId_,
  207. assemblyName.CString(),
  208. qualifiedClassName.CString(),
  209. methodName.CString(),
  210. funcOut);
  211. // ensure ptr isn't uninitialized
  212. if (st < 0)
  213. *funcOut = 0;
  214. return st >= 0;
  215. */
  216. }
  217. bool NETCore::Initialize(const String &coreCLRFilesAbsPath, const String &assemblyLoadPaths, String& errorMsg)
  218. {
  219. coreCLRFilesAbsPath_ = AddTrailingSlash(coreCLRFilesAbsPath);
  220. #ifdef ATOMIC_PLATFORM_WINDOWS
  221. netHost_ = new NETHostWindows(context_);
  222. #else
  223. #endif
  224. netHost_->Initialize(coreCLRFilesAbsPath_, assemblyLoadPaths);
  225. SharedPtr<NETManaged> managed(new NETManaged(context_));
  226. context_->RegisterSubsystem(managed);
  227. SharedPtr<CSEventDispatcher> dispatcher(new CSEventDispatcher(context_));
  228. context_->RegisterSubsystem(dispatcher);
  229. context_->AddGlobalEventListener(dispatcher);
  230. if (!context_->GetEditorContext())
  231. {
  232. SubscribeToEvent(E_UPDATE, HANDLER(NETCore, HandleUpdate));
  233. }
  234. managed->Initialize();
  235. #ifdef disabled
  236. if (!InitCoreCLRDLL(errorMsg))
  237. {
  238. Shutdown();
  239. return false;
  240. }
  241. // Allowed property names:
  242. // APPBASE
  243. // - The base path of the application from which the exe and other assemblies will be loaded
  244. //
  245. // TRUSTED_PLATFORM_ASSEMBLIES
  246. // - The list of complete paths to each of the fully trusted assemblies
  247. //
  248. // APP_PATHS
  249. // - The list of paths which will be probed by the assembly loader
  250. //
  251. // APP_NI_PATHS
  252. // - The list of additional paths that the assembly loader will probe for ngen images
  253. //
  254. // NATIVE_DLL_SEARCH_DIRECTORIES
  255. // - The list of paths that will be probed for native DLLs called by PInvoke
  256. //
  257. const char *propertyKeys[] = {
  258. "TRUSTED_PLATFORM_ASSEMBLIES",
  259. "APP_PATHS",
  260. "APP_NI_PATHS",
  261. "NATIVE_DLL_SEARCH_DIRECTORIES",
  262. "AppDomainCompatSwitch"
  263. };
  264. String tpaList;
  265. GenerateTPAList(tpaList);
  266. String appPath = coreCLRFilesAbsPath_;// "/Users/josh/Desktop/";
  267. Vector<String> nativeSearch;
  268. nativeSearch.Push(coreCLRFilesAbsPath_);
  269. //nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngine-build/Source/AtomicNET/NETNative");
  270. //nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngine-build/Source/AtomicEditor/AtomicEditor.app/Contents/MacOS");
  271. String nativeDllSearchDirs;
  272. nativeDllSearchDirs.Join(nativeSearch, ":");
  273. const char *propertyValues[] = {
  274. // TRUSTED_PLATFORM_ASSEMBLIES
  275. tpaList.CString(),
  276. // APP_PATHS
  277. appPath.CString(),
  278. // APP_NI_PATHS
  279. appPath.CString(),
  280. // NATIVE_DLL_SEARCH_DIRECTORIES
  281. nativeDllSearchDirs.CString(),
  282. // AppDomainCompatSwitch
  283. "UseLatestBehaviorWhenTFMNotSpecified"
  284. };
  285. int st = sInitializeCoreCLR(
  286. "AtomicEditor.exe",
  287. "NETCore",
  288. sizeof(propertyKeys) / sizeof(propertyKeys[0]),
  289. propertyKeys,
  290. propertyValues,
  291. &hostHandle_,
  292. &domainId_);
  293. if (st < 0)
  294. {
  295. Shutdown();
  296. errorMsg = ToString("NETCore: coreclr_initialize failed - status: 0x%08x\n", st);
  297. return false;
  298. }
  299. typedef void (*StartupFunction)();
  300. StartupFunction startup;
  301. // The coreclr binding model will become locked upon loading the first assembly that is not on the TPA list, or
  302. // upon initializing the default context for the first time. For this test, test assemblies are located alongside
  303. // corerun, and hence will be on the TPA list. So, we should be able to set the default context once successfully,
  304. // and fail on the second try.
  305. // AssemblyLoadContext
  306. // https://github.com/dotnet/corefx/issues/3054
  307. // dnx loader
  308. // https://github.com/aspnet/dnx/tree/dev/src/Microsoft.Dnx.Loader
  309. st = sCreateDelegate(hostHandle_,
  310. domainId_,
  311. "AtomicNETBootstrap",
  312. "Atomic.Bootstrap.AtomicLoadContext",
  313. "Startup",
  314. (void**) &startup);
  315. if (st >= 0)
  316. {
  317. startup();
  318. }
  319. st = sCreateDelegate(hostHandle_,
  320. domainId_,
  321. "AtomicNETEngine",
  322. "AtomicEngine.Atomic",
  323. "Initialize",
  324. (void**) &startup);
  325. if (st >= 0)
  326. {
  327. startup();
  328. }
  329. /*
  330. RefCountedDeletedFunction rcdFunction;
  331. st = sCreateDelegate(hostHandle_,
  332. domainId_,
  333. "AtomicNETEngine",
  334. "AtomicEngine.NativeCore",
  335. "RefCountedDeleted",
  336. (void**) &rcdFunction);
  337. if (st >= 0)
  338. {
  339. RefCounted::SetRefCountedDeletedFunction(rcdFunction);
  340. }
  341. NETUpdateFunctionPtr updateFunction;
  342. st = sCreateDelegate(hostHandle_,
  343. domainId_,
  344. "AtomicNETEngine",
  345. "AtomicEngine.NativeCore",
  346. "NETUpdate",
  347. (void**) &updateFunction);
  348. if (st >= 0)
  349. {
  350. GetSubsystem<NETManaged>()->SetNETUpdate(updateFunction);
  351. }
  352. typedef void (*InpectAssemblyFuctionPtr)(const char* path);
  353. InpectAssemblyFuctionPtr inspectAssembly;
  354. st = sCreateDelegate(hostHandle_,
  355. domainId_,
  356. "AtomicEditor",
  357. "AtomicEditor.AtomicEditor",
  358. "InspectAssembly",
  359. (void**) &inspectAssembly);
  360. if (st >= 0)
  361. {
  362. //inspectAssembly("/Users/josh/Desktop/AtomicNETTest.dll");
  363. }
  364. */
  365. /*
  366. unsigned int exitCode;
  367. st = sExecuteAssembly(
  368. hostHandle_,
  369. domainId_,
  370. 0,
  371. 0,
  372. "/Users/josh/Desktop/OSX.x64.Debug/HelloWorld.exe",
  373. (unsigned int*)&exitCode);
  374. */
  375. #endif
  376. return true;
  377. }
  378. void NETCore::HandleUpdate(StringHash eventType, VariantMap& eventData)
  379. {
  380. using namespace Update;
  381. GetSubsystem<NETManaged>()->NETUpdate(eventData[P_TIMESTEP].GetFloat());
  382. }
  383. void RegisterNETCoreLibrary(Context* context)
  384. {
  385. NETAssemblyFile::RegisterObject(context);
  386. CSComponent::RegisterObject(context);
  387. }
  388. }