NETCore.cpp 13 KB

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