NETCore.cpp 12 KB

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