NETCore.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. #ifdef disabled
  85. tpaList = String::EMPTY;
  86. FileSystem* fs = GetSubsystem<FileSystem>();
  87. Vector<String> results;
  88. fs->ScanDir(results, coreCLRFilesAbsPath_, "*.dll", SCAN_FILES, true);
  89. Vector<String> trustedAssemblies;
  90. for (unsigned i = 0; i < results.Size(); i++)
  91. {
  92. const String& assembly = results[i];
  93. // TODO: apply filtering if necessary
  94. trustedAssemblies.Push(coreCLRFilesAbsPath_ + assembly);
  95. }
  96. // trustedAssemblies.Push(coreCLRFilesAbsPath_ + "HelloWorld.exe");
  97. tpaList.Join(trustedAssemblies, ":");
  98. // LOGINFOF("NetCore:: TPALIST - %s", tpaList.CString());
  99. #endif
  100. }
  101. void NETCore::Shutdown()
  102. {
  103. RefCounted::SetRefCountedDeletedFunction(0);
  104. if (sShutdownCoreCLR && hostHandle_)
  105. {
  106. sShutdownCoreCLR(hostHandle_, domainId_);
  107. }
  108. if (coreCLRDLLHandle_)
  109. {
  110. SDL_UnloadObject(coreCLRDLLHandle_);
  111. }
  112. coreCLRDLLHandle_ = 0;
  113. hostHandle_ = 0;
  114. domainId_ = 0;
  115. sInitializeCoreCLR = 0;
  116. sExecuteAssembly = 0;
  117. sCreateDelegate = 0;
  118. sShutdownCoreCLR = 0;
  119. }
  120. bool NETCore::InitCoreCLRDLL(String& errorMsg)
  121. {
  122. #ifdef disabled
  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. #endif
  157. return true;
  158. }
  159. extern "C"
  160. {
  161. // http://ybeernet.blogspot.com/2011/03/techniques-of-calling-unmanaged-code.html
  162. // pinvoke is faster than [UnmanagedFunctionPointer] :/
  163. // [SuppressUnmanagedCodeSecurity] <--- add this attribute, in any event
  164. #ifdef ATOMIC_PLATFORM_WINDOWS
  165. #pragma warning(disable: 4244) // possible loss of data
  166. #define ATOMIC_EXPORT_API __declspec(dllexport)
  167. #else
  168. #define ATOMIC_EXPORT_API
  169. #endif
  170. ATOMIC_EXPORT_API ClassID csb_Atomic_RefCounted_GetClassID(RefCounted* refCounted)
  171. {
  172. if (!refCounted)
  173. return 0;
  174. return refCounted->GetClassID();
  175. }
  176. ATOMIC_EXPORT_API RefCounted* csb_AtomicEngine_GetSubsystem(const char* name)
  177. {
  178. return NETCore::GetContext()->GetSubsystem(name);
  179. }
  180. ATOMIC_EXPORT_API void csb_AtomicEngine_ReleaseRef(RefCounted* ref)
  181. {
  182. if (!ref)
  183. return;
  184. ref->ReleaseRef();
  185. }
  186. }
  187. void NETCore::WaitForDebuggerConnect()
  188. {
  189. netHost_->WaitForDebuggerConnect();
  190. }
  191. void NETCore::AddAssemblyLoadPath(const String& assemblyPath)
  192. {
  193. typedef void (*AddAssemblyLoadPathFunction)(const char* assemblyPath);
  194. AddAssemblyLoadPathFunction addAssemblyLoadPath;
  195. bool result = CreateDelegate(
  196. "AtomicNETBootstrap",
  197. "Atomic.Bootstrap.AtomicLoadContext",
  198. "AddAssemblyLoadPath",
  199. (void**) &addAssemblyLoadPath);
  200. if (result)
  201. {
  202. addAssemblyLoadPath(assemblyPath.CString());
  203. }
  204. }
  205. bool NETCore::CreateDelegate(const String& assemblyName, const String& qualifiedClassName, const String& methodName, void** funcOut)
  206. {
  207. return netHost_->CreateDelegate(assemblyName, qualifiedClassName, methodName, funcOut);
  208. /*
  209. if (!sCreateDelegate)
  210. return false;
  211. *funcOut = 0;
  212. // TODO: wrap in SharedPtr to control delegate lifetime?
  213. int st = sCreateDelegate(hostHandle_,
  214. domainId_,
  215. assemblyName.CString(),
  216. qualifiedClassName.CString(),
  217. methodName.CString(),
  218. funcOut);
  219. // ensure ptr isn't uninitialized
  220. if (st < 0)
  221. *funcOut = 0;
  222. return st >= 0;
  223. */
  224. }
  225. bool NETCore::Initialize(String& errorMsg)
  226. {
  227. #ifdef ATOMIC_PLATFORM_WINDOWS
  228. netHost_ = new NETHostWindows(context_);
  229. #else
  230. #endif
  231. netHost_->Initialize();
  232. SharedPtr<NETManaged> managed(new NETManaged(context_));
  233. context_->RegisterSubsystem(managed);
  234. SharedPtr<CSEventDispatcher> dispatcher(new CSEventDispatcher(context_));
  235. context_->RegisterSubsystem(dispatcher);
  236. context_->AddGlobalEventListener(dispatcher);
  237. if (!context_->GetEditorContext())
  238. {
  239. SubscribeToEvent(E_UPDATE, HANDLER(NETCore, HandleUpdate));
  240. }
  241. managed->Initialize();
  242. #ifdef disabled
  243. if (!InitCoreCLRDLL(errorMsg))
  244. {
  245. Shutdown();
  246. return false;
  247. }
  248. // Allowed property names:
  249. // APPBASE
  250. // - The base path of the application from which the exe and other assemblies will be loaded
  251. //
  252. // TRUSTED_PLATFORM_ASSEMBLIES
  253. // - The list of complete paths to each of the fully trusted assemblies
  254. //
  255. // APP_PATHS
  256. // - The list of paths which will be probed by the assembly loader
  257. //
  258. // APP_NI_PATHS
  259. // - The list of additional paths that the assembly loader will probe for ngen images
  260. //
  261. // NATIVE_DLL_SEARCH_DIRECTORIES
  262. // - The list of paths that will be probed for native DLLs called by PInvoke
  263. //
  264. const char *propertyKeys[] = {
  265. "TRUSTED_PLATFORM_ASSEMBLIES",
  266. "APP_PATHS",
  267. "APP_NI_PATHS",
  268. "NATIVE_DLL_SEARCH_DIRECTORIES",
  269. "AppDomainCompatSwitch"
  270. };
  271. String tpaList;
  272. GenerateTPAList(tpaList);
  273. String appPath = coreCLRFilesAbsPath_;// "/Users/josh/Desktop/";
  274. Vector<String> nativeSearch;
  275. nativeSearch.Push(coreCLRFilesAbsPath_);
  276. //nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngine-build/Source/AtomicNET/NETNative");
  277. //nativeSearch.Push("/Users/josh/Dev/atomic/AtomicGameEngine-build/Source/AtomicEditor/AtomicEditor.app/Contents/MacOS");
  278. String nativeDllSearchDirs;
  279. nativeDllSearchDirs.Join(nativeSearch, ":");
  280. const char *propertyValues[] = {
  281. // TRUSTED_PLATFORM_ASSEMBLIES
  282. tpaList.CString(),
  283. // APP_PATHS
  284. appPath.CString(),
  285. // APP_NI_PATHS
  286. appPath.CString(),
  287. // NATIVE_DLL_SEARCH_DIRECTORIES
  288. nativeDllSearchDirs.CString(),
  289. // AppDomainCompatSwitch
  290. "UseLatestBehaviorWhenTFMNotSpecified"
  291. };
  292. int st = sInitializeCoreCLR(
  293. "AtomicEditor.exe",
  294. "NETCore",
  295. sizeof(propertyKeys) / sizeof(propertyKeys[0]),
  296. propertyKeys,
  297. propertyValues,
  298. &hostHandle_,
  299. &domainId_);
  300. if (st < 0)
  301. {
  302. Shutdown();
  303. errorMsg = ToString("NETCore: coreclr_initialize failed - status: 0x%08x\n", st);
  304. return false;
  305. }
  306. typedef void (*StartupFunction)();
  307. StartupFunction startup;
  308. // The coreclr binding model will become locked upon loading the first assembly that is not on the TPA list, or
  309. // upon initializing the default context for the first time. For this test, test assemblies are located alongside
  310. // corerun, and hence will be on the TPA list. So, we should be able to set the default context once successfully,
  311. // and fail on the second try.
  312. // AssemblyLoadContext
  313. // https://github.com/dotnet/corefx/issues/3054
  314. // dnx loader
  315. // https://github.com/aspnet/dnx/tree/dev/src/Microsoft.Dnx.Loader
  316. st = sCreateDelegate(hostHandle_,
  317. domainId_,
  318. "AtomicNETBootstrap",
  319. "Atomic.Bootstrap.AtomicLoadContext",
  320. "Startup",
  321. (void**) &startup);
  322. if (st >= 0)
  323. {
  324. startup();
  325. }
  326. st = sCreateDelegate(hostHandle_,
  327. domainId_,
  328. "AtomicNETEngine",
  329. "AtomicEngine.Atomic",
  330. "Initialize",
  331. (void**) &startup);
  332. if (st >= 0)
  333. {
  334. startup();
  335. }
  336. /*
  337. RefCountedDeletedFunction rcdFunction;
  338. st = sCreateDelegate(hostHandle_,
  339. domainId_,
  340. "AtomicNETEngine",
  341. "AtomicEngine.NativeCore",
  342. "RefCountedDeleted",
  343. (void**) &rcdFunction);
  344. if (st >= 0)
  345. {
  346. RefCounted::SetRefCountedDeletedFunction(rcdFunction);
  347. }
  348. NETUpdateFunctionPtr updateFunction;
  349. st = sCreateDelegate(hostHandle_,
  350. domainId_,
  351. "AtomicNETEngine",
  352. "AtomicEngine.NativeCore",
  353. "NETUpdate",
  354. (void**) &updateFunction);
  355. if (st >= 0)
  356. {
  357. GetSubsystem<NETManaged>()->SetNETUpdate(updateFunction);
  358. }
  359. typedef void (*InpectAssemblyFuctionPtr)(const char* path);
  360. InpectAssemblyFuctionPtr inspectAssembly;
  361. st = sCreateDelegate(hostHandle_,
  362. domainId_,
  363. "AtomicEditor",
  364. "AtomicEditor.AtomicEditor",
  365. "InspectAssembly",
  366. (void**) &inspectAssembly);
  367. if (st >= 0)
  368. {
  369. //inspectAssembly("/Users/josh/Desktop/AtomicNETTest.dll");
  370. }
  371. */
  372. /*
  373. unsigned int exitCode;
  374. st = sExecuteAssembly(
  375. hostHandle_,
  376. domainId_,
  377. 0,
  378. 0,
  379. "/Users/josh/Desktop/OSX.x64.Debug/HelloWorld.exe",
  380. (unsigned int*)&exitCode);
  381. */
  382. #endif
  383. return true;
  384. }
  385. void NETCore::HandleUpdate(StringHash eventType, VariantMap& eventData)
  386. {
  387. using namespace Update;
  388. GetSubsystem<NETManaged>()->NETUpdate(eventData[P_TIMESTEP].GetFloat());
  389. }
  390. void RegisterNETCoreLibrary(Context* context)
  391. {
  392. NETAssemblyFile::RegisterObject(context);
  393. CSComponent::RegisterObject(context);
  394. }
  395. }