NETCore.cpp 12 KB

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