NETCore.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. namespace Atomic
  11. {
  12. /*
  13. 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
  14. export PAL_DBG_CHANNELS="+all.all"
  15. */
  16. #ifdef ATOMIC_PLATFORM_OSX
  17. static const char * const sCoreClrDll = "libcoreclr.dylib";
  18. #else
  19. static const char * const sCoreClrDll = "libcoreclr.so";
  20. #endif
  21. // Prototype of the coreclr_initialize function from the libcoreclr.so
  22. typedef int (*InitializeCoreCLRFunction)(
  23. const char* exePath,
  24. const char* appDomainFriendlyName,
  25. int propertyCount,
  26. const char** propertyKeys,
  27. const char** propertyValues,
  28. void** hostHandle,
  29. unsigned int* domainId);
  30. // Prototype of the coreclr_shutdown function from the libcoreclr.so
  31. typedef int (*ShutdownCoreCLRFunction)(
  32. void* hostHandle,
  33. unsigned int domainId);
  34. // Prototype of the coreclr_execute_assembly function from the libcoreclr.so
  35. typedef int (*ExecuteAssemblyFunction)(
  36. void* hostHandle,
  37. unsigned int domainId,
  38. int argc,
  39. const char** argv,
  40. const char* managedAssemblyPath,
  41. unsigned int* exitCode);
  42. typedef int (*CreateDelegateFunction)(
  43. void* hostHandle,
  44. unsigned int domainId,
  45. const char* entryPointAssemblyName,
  46. const char* entryPointTypeName,
  47. const char* entryPointMethodName,
  48. void** delegate);
  49. static InitializeCoreCLRFunction sInitializeCoreCLR = 0;
  50. static ExecuteAssemblyFunction sExecuteAssembly = 0;
  51. static CreateDelegateFunction sCreateDelegate = 0;
  52. static ShutdownCoreCLRFunction sShutdownCoreCLR = 0;
  53. /// Register NETCore library objects.
  54. void ATOMIC_API RegisterNETCoreLibrary(Context* context);
  55. WeakPtr<Context> NETCore::csContext_;
  56. WeakPtr<NETCore> NETCore::instance_;
  57. NETCore::NETCore(Context* context) :
  58. Object(context),
  59. coreCLRDLLHandle_(0),
  60. hostHandle_(0),
  61. domainId_(0)
  62. {
  63. RegisterNETCoreLibrary(context_);
  64. assert(!instance_);
  65. instance_ = this;
  66. csContext_ = context;
  67. SharedPtr<NETManaged> managed(new NETManaged(context_));
  68. context_->RegisterSubsystem(managed);
  69. SharedPtr<CSEventDispatcher> dispatcher(new CSEventDispatcher(context_));
  70. context_->RegisterSubsystem(dispatcher);
  71. context_->AddGlobalEventListener(dispatcher);
  72. SubscribeToEvent(E_UPDATE, HANDLER(NETCore, HandleUpdate));
  73. }
  74. NETCore::~NETCore()
  75. {
  76. context_->RemoveGlobalEventListener(context_->GetSubsystem<CSEventDispatcher>());
  77. context_->RemoveSubsystem(CSEventDispatcher::GetTypeStatic());
  78. context_->RemoveSubsystem(NETManaged::GetTypeStatic());
  79. instance_ = NULL;
  80. }
  81. void NETCore::GenerateTPAList(String& tpaList)
  82. {
  83. tpaList = String::EMPTY;
  84. FileSystem* fs = GetSubsystem<FileSystem>();
  85. Vector<String> results;
  86. fs->ScanDir(results, coreCLRFilesAbsPath_, "*.dll", SCAN_FILES, true);
  87. Vector<String> trustedAssemblies;
  88. for (unsigned i = 0; i < results.Size(); i++)
  89. {
  90. const String& assembly = results[i];
  91. // TODO: apply filtering if necessary
  92. trustedAssemblies.Push(coreCLRFilesAbsPath_ + assembly);
  93. }
  94. trustedAssemblies.Push(coreCLRFilesAbsPath_ + "HelloWorld.exe");
  95. tpaList.Join(trustedAssemblies, ":");
  96. // LOGINFOF("NetCore:: TPALIST - %s", tpaList.CString());
  97. }
  98. void NETCore::Shutdown()
  99. {
  100. RefCounted::SetRefCountedDeletedFunction(0);
  101. if (sShutdownCoreCLR && hostHandle_)
  102. {
  103. sShutdownCoreCLR(hostHandle_, domainId_);
  104. }
  105. if (coreCLRDLLHandle_)
  106. {
  107. SDL_UnloadObject(coreCLRDLLHandle_);
  108. }
  109. coreCLRDLLHandle_ = 0;
  110. hostHandle_ = 0;
  111. domainId_ = 0;
  112. sInitializeCoreCLR = 0;
  113. sExecuteAssembly = 0;
  114. sCreateDelegate = 0;
  115. sShutdownCoreCLR = 0;
  116. }
  117. bool NETCore::InitCoreCLRDLL(String& errorMsg)
  118. {
  119. String coreClrDllPath = AddTrailingSlash(coreCLRFilesAbsPath_) + sCoreClrDll;
  120. coreCLRDLLHandle_ = SDL_LoadObject(coreClrDllPath.CString());
  121. if (coreCLRDLLHandle_ == NULL)
  122. {
  123. errorMsg = ToString("NETCore: Unable to load %s with error %s",
  124. coreClrDllPath.CString(),
  125. SDL_GetError());
  126. return false;
  127. }
  128. sInitializeCoreCLR = (InitializeCoreCLRFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_initialize");
  129. if (!sInitializeCoreCLR)
  130. {
  131. errorMsg = ToString("NETCore: Unable to get coreclr_initialize entry point in %s", coreClrDllPath.CString());
  132. return false;
  133. }
  134. sShutdownCoreCLR = (ShutdownCoreCLRFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_shutdown");
  135. if (!sShutdownCoreCLR)
  136. {
  137. errorMsg = ToString("NETCore: Unable to get coreclr_shutdown entry point in %s", coreClrDllPath.CString());
  138. return false;
  139. }
  140. sCreateDelegate = (CreateDelegateFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_create_delegate");
  141. if (!sCreateDelegate)
  142. {
  143. errorMsg = ToString("NETCore: Unable to get coreclr_create_delegate entry point in %s", coreClrDllPath.CString());
  144. return false;
  145. }
  146. sExecuteAssembly = (ExecuteAssemblyFunction) SDL_LoadFunction(coreCLRDLLHandle_, "coreclr_execute_assembly");
  147. if (!sExecuteAssembly)
  148. {
  149. errorMsg = ToString("NETCore: Unable to get coreclr_execute_assembly entry point in %s", coreClrDllPath.CString());
  150. return false;
  151. }
  152. return true;
  153. }
  154. extern "C"
  155. {
  156. // http://ybeernet.blogspot.com/2011/03/techniques-of-calling-unmanaged-code.html
  157. // pinvoke is faster than [UnmanagedFunctionPointer] :/
  158. // [SuppressUnmanagedCodeSecurity] <--- add this attribute, in any event
  159. int csb_Atomic_Test(unsigned id)
  160. {
  161. printf("Flibberty Gibbets %u", id);
  162. return id;
  163. }
  164. ClassID csb_Atomic_RefCounted_GetClassID(RefCounted* refCounted)
  165. {
  166. if (!refCounted)
  167. return 0;
  168. return refCounted->GetClassID();
  169. }
  170. RefCounted* csb_AtomicEngine_GetSubsystem(const char* name)
  171. {
  172. return NETCore::GetContext()->GetSubsystem(name);
  173. }
  174. void csb_AtomicEngine_ReleaseRef(RefCounted* ref)
  175. {
  176. if (!ref)
  177. return;
  178. ref->ReleaseRef();
  179. }
  180. }
  181. bool NETCore::Initialize(const String &coreCLRFilesAbsPath, String& errorMsg)
  182. {
  183. coreCLRFilesAbsPath_ = AddTrailingSlash(coreCLRFilesAbsPath);
  184. if (!InitCoreCLRDLL(errorMsg))
  185. {
  186. Shutdown();
  187. return false;
  188. }
  189. // Allowed property names:
  190. // APPBASE
  191. // - The base path of the application from which the exe and other assemblies will be loaded
  192. //
  193. // TRUSTED_PLATFORM_ASSEMBLIES
  194. // - The list of complete paths to each of the fully trusted assemblies
  195. //
  196. // APP_PATHS
  197. // - The list of paths which will be probed by the assembly loader
  198. //
  199. // APP_NI_PATHS
  200. // - The list of additional paths that the assembly loader will probe for ngen images
  201. //
  202. // NATIVE_DLL_SEARCH_DIRECTORIES
  203. // - The list of paths that will be probed for native DLLs called by PInvoke
  204. //
  205. const char *propertyKeys[] = {
  206. "TRUSTED_PLATFORM_ASSEMBLIES",
  207. "APP_PATHS",
  208. "APP_NI_PATHS",
  209. "NATIVE_DLL_SEARCH_DIRECTORIES",
  210. "AppDomainCompatSwitch"
  211. };
  212. String tpaList;
  213. GenerateTPAList(tpaList);
  214. String appPath = "/Users/josh/Desktop/";
  215. Vector<String> nativeSearch;
  216. nativeSearch.Push(coreCLRFilesAbsPath_);
  217. nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngineSharp-build/Source/AtomicNET/NETNative");
  218. nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngineSharp-build/Source/AtomicEditor/AtomicEditor.app/Contents/MacOS");
  219. String nativeDllSearchDirs;
  220. nativeDllSearchDirs.Join(nativeSearch, ":");
  221. const char *propertyValues[] = {
  222. // TRUSTED_PLATFORM_ASSEMBLIES
  223. tpaList.CString(),
  224. // APP_PATHS
  225. appPath.CString(),
  226. // APP_NI_PATHS
  227. appPath.CString(),
  228. // NATIVE_DLL_SEARCH_DIRECTORIES
  229. nativeDllSearchDirs.CString(),
  230. // AppDomainCompatSwitch
  231. "UseLatestBehaviorWhenTFMNotSpecified"
  232. };
  233. int st = sInitializeCoreCLR(
  234. "AtomicEditor",
  235. "NETCore",
  236. sizeof(propertyKeys) / sizeof(propertyKeys[0]),
  237. propertyKeys,
  238. propertyValues,
  239. &hostHandle_,
  240. &domainId_);
  241. if (st < 0)
  242. {
  243. Shutdown();
  244. errorMsg = ToString("NETCore: coreclr_initialize failed - status: 0x%08x\n", st);
  245. return false;
  246. }
  247. typedef void (*StartupFunction)();
  248. StartupFunction startup;
  249. // The coreclr binding model will become locked upon loading the first assembly that is not on the TPA list, or
  250. // upon initializing the default context for the first time. For this test, test assemblies are located alongside
  251. // corerun, and hence will be on the TPA list. So, we should be able to set the default context once successfully,
  252. // and fail on the second try.
  253. // AssemblyLoadContext
  254. // https://github.com/dotnet/corefx/issues/3054
  255. // dnx loader
  256. // https://github.com/aspnet/dnx/tree/dev/src/Microsoft.Dnx.Loader
  257. st = sCreateDelegate(hostHandle_,
  258. domainId_,
  259. "AtomicNETBootstrap",
  260. "Atomic.Bootstrap.AtomicLoadContext",
  261. "Startup",
  262. (void**) &startup);
  263. if (st >= 0)
  264. {
  265. startup();
  266. }
  267. st = sCreateDelegate(hostHandle_,
  268. domainId_,
  269. "AtomicNETRuntime",
  270. "AtomicEngine.AtomicNETRuntime",
  271. "Startup",
  272. (void**) &startup);
  273. if (st >= 0)
  274. {
  275. startup();
  276. }
  277. RefCountedDeletedFunction rcdFunction;
  278. st = sCreateDelegate(hostHandle_,
  279. domainId_,
  280. "AtomicNETRuntime",
  281. "AtomicEngine.NativeCore",
  282. "RefCountedDeleted",
  283. (void**) &rcdFunction);
  284. if (st >= 0)
  285. {
  286. RefCounted::SetRefCountedDeletedFunction(rcdFunction);
  287. }
  288. NETUpdateFunctionPtr updateFunction;
  289. st = sCreateDelegate(hostHandle_,
  290. domainId_,
  291. "AtomicNETRuntime",
  292. "AtomicEngine.NativeCore",
  293. "NETUpdate",
  294. (void**) &updateFunction);
  295. if (st >= 0)
  296. {
  297. GetSubsystem<NETManaged>()->SetNETUpdate(updateFunction);
  298. }
  299. typedef void (*InpectAssemblyFuctionPtr)(const char* path);
  300. InpectAssemblyFuctionPtr inspectAssembly;
  301. //https://github.com/Microsoft/dotnetsamples/tree/master/System.Reflection.Metadata
  302. //https://github.com/dotnet/corefx/tree/master/src/System.Reflection.Metadata/tests
  303. //http://www.cnetion.com/getting-field-values-using-mono-cecil-qq-AUvBjRFgivICeoL1jxJy.php
  304. // https://github.com/Reactive-Extensions/IL2JS/blob/master/CCI2/PeReader/ILReader.cs
  305. // https://github.com/Reactive-Extensions/IL2JS
  306. // custom attr loading: https://github.com/Reactive-Extensions/IL2JS/blob/a4570f9c69b6c40d001e7539b952266d67609ca9/CST/PELoader.cs#L2352
  307. // custom attr: https://www.simple-talk.com/blogs/2011/06/03/anatomy-of-a-net-assembly-custom-attribute-encoding/
  308. // custom attr: https://github.com/jbevain/cecil/blob/67a2569688a13a6cb487f9af5c3418f7a8f43e3c/Mono.Cecil/AssemblyReader.cs
  309. st = sCreateDelegate(hostHandle_,
  310. domainId_,
  311. "AtomicEditor",
  312. "AtomicEditor.AssemblyInspector",
  313. "InspectAssembly",
  314. (void**) &inspectAssembly);
  315. if (st >= 0)
  316. {
  317. inspectAssembly("/Users/josh/Desktop/AtomicNETTest.dll");
  318. }
  319. /*
  320. unsigned int exitCode;
  321. st = sExecuteAssembly(
  322. hostHandle_,
  323. domainId_,
  324. 0,
  325. 0,
  326. "/Users/josh/Desktop/OSX.x64.Debug/HelloWorld.exe",
  327. (unsigned int*)&exitCode);
  328. */
  329. return true;
  330. }
  331. void NETCore::HandleUpdate(StringHash eventType, VariantMap& eventData)
  332. {
  333. using namespace Update;
  334. GetSubsystem<NETManaged>()->NETUpdate(eventData[P_TIMESTEP].GetFloat());
  335. }
  336. void RegisterNETCoreLibrary(Context* context)
  337. {
  338. CSComponent::RegisterObject(context);
  339. }
  340. }