NETCore.cpp 13 KB

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