gd_mono.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. /**************************************************************************/
  2. /* gd_mono.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gd_mono.h"
  31. #include "../csharp_script.h"
  32. #include "../glue/runtime_interop.h"
  33. #include "../godotsharp_dirs.h"
  34. #include "../thirdparty/coreclr_delegates.h"
  35. #include "../thirdparty/hostfxr.h"
  36. #include "../utils/path_utils.h"
  37. #include "gd_mono_cache.h"
  38. #ifdef TOOLS_ENABLED
  39. #include "../editor/hostfxr_resolver.h"
  40. #endif
  41. #include "core/config/project_settings.h"
  42. #include "core/debugger/engine_debugger.h"
  43. #include "core/io/dir_access.h"
  44. #include "core/io/file_access.h"
  45. #include "core/os/os.h"
  46. #include "core/os/thread.h"
  47. #ifdef UNIX_ENABLED
  48. #include <dlfcn.h>
  49. #endif
  50. GDMono *GDMono::singleton = nullptr;
  51. namespace {
  52. hostfxr_initialize_for_dotnet_command_line_fn hostfxr_initialize_for_dotnet_command_line = nullptr;
  53. hostfxr_initialize_for_runtime_config_fn hostfxr_initialize_for_runtime_config = nullptr;
  54. hostfxr_get_runtime_delegate_fn hostfxr_get_runtime_delegate = nullptr;
  55. hostfxr_close_fn hostfxr_close = nullptr;
  56. #ifndef TOOLS_ENABLED
  57. typedef int(CORECLR_DELEGATE_CALLTYPE *coreclr_create_delegate_fn)(void *hostHandle, unsigned int domainId, const char *entryPointAssemblyName, const char *entryPointTypeName, const char *entryPointMethodName, void **delegate);
  58. typedef int(CORECLR_DELEGATE_CALLTYPE *coreclr_initialize_fn)(const char *exePath, const char *appDomainFriendlyName, int propertyCount, const char **propertyKeys, const char **propertyValues, void **hostHandle, unsigned int *domainId);
  59. coreclr_create_delegate_fn coreclr_create_delegate = nullptr;
  60. coreclr_initialize_fn coreclr_initialize = nullptr;
  61. #endif
  62. #ifdef _WIN32
  63. static_assert(sizeof(char_t) == sizeof(char16_t));
  64. using HostFxrCharString = Char16String;
  65. #define HOSTFXR_STR(m_str) L##m_str
  66. #else
  67. static_assert(sizeof(char_t) == sizeof(char));
  68. using HostFxrCharString = CharString;
  69. #define HOSTFXR_STR(m_str) m_str
  70. #endif
  71. HostFxrCharString str_to_hostfxr(const String &p_str) {
  72. #ifdef _WIN32
  73. return p_str.utf16();
  74. #else
  75. return p_str.utf8();
  76. #endif
  77. }
  78. const char_t *get_data(const HostFxrCharString &p_char_str) {
  79. return (const char_t *)p_char_str.get_data();
  80. }
  81. String find_hostfxr() {
  82. #ifdef TOOLS_ENABLED
  83. String dotnet_root;
  84. String fxr_path;
  85. if (godotsharp::hostfxr_resolver::try_get_path(dotnet_root, fxr_path)) {
  86. return fxr_path;
  87. }
  88. // hostfxr_resolver doesn't look for dotnet in `PATH`. If it fails, we try to find the dotnet
  89. // executable in `PATH` here and pass its location as `dotnet_root` to `get_hostfxr_path`.
  90. String dotnet_exe = path::find_executable("dotnet");
  91. if (!dotnet_exe.is_empty()) {
  92. // The file found in PATH may be a symlink
  93. dotnet_exe = path::abspath(path::realpath(dotnet_exe));
  94. // TODO:
  95. // Sometimes, the symlink may not point to the dotnet executable in the dotnet root.
  96. // That's the case with snaps. The snap install should have been found with the
  97. // previous `get_hostfxr_path`, but it would still be better to do this properly
  98. // and use something like `dotnet --list-sdks/runtimes` to find the actual location.
  99. // This way we could also check if the proper sdk or runtime is installed. This would
  100. // allow us to fail gracefully and show some helpful information in the editor.
  101. dotnet_root = dotnet_exe.get_base_dir();
  102. if (godotsharp::hostfxr_resolver::try_get_path_from_dotnet_root(dotnet_root, fxr_path)) {
  103. return fxr_path;
  104. }
  105. }
  106. ERR_PRINT(String() + ".NET: One of the dependent libraries is missing. " +
  107. "Typically when the `hostfxr`, `hostpolicy` or `coreclr` dynamic " +
  108. "libraries are not present in the expected locations.");
  109. return String();
  110. #else
  111. #if defined(WINDOWS_ENABLED)
  112. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  113. .path_join("hostfxr.dll");
  114. #elif defined(MACOS_ENABLED)
  115. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  116. .path_join("libhostfxr.dylib");
  117. #elif defined(UNIX_ENABLED)
  118. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  119. .path_join("libhostfxr.so");
  120. #else
  121. #error "Platform not supported (yet?)"
  122. #endif
  123. if (FileAccess::exists(probe_path)) {
  124. return probe_path;
  125. }
  126. return String();
  127. #endif
  128. }
  129. #ifndef TOOLS_ENABLED
  130. String find_monosgen() {
  131. #if defined(ANDROID_ENABLED)
  132. // Android includes all native libraries in the libs directory of the APK
  133. // so we assume it exists and use only the name to dlopen it.
  134. return "libmonosgen-2.0.so";
  135. #else
  136. #if defined(WINDOWS_ENABLED)
  137. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  138. .path_join("monosgen-2.0.dll");
  139. #elif defined(MACOS_ENABLED)
  140. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  141. .path_join("libmonosgen-2.0.dylib");
  142. #elif defined(UNIX_ENABLED)
  143. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  144. .path_join("libmonosgen-2.0.so");
  145. #else
  146. #error "Platform not supported (yet?)"
  147. #endif
  148. if (FileAccess::exists(probe_path)) {
  149. return probe_path;
  150. }
  151. return String();
  152. #endif
  153. }
  154. String find_coreclr() {
  155. #if defined(WINDOWS_ENABLED)
  156. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  157. .path_join("coreclr.dll");
  158. #elif defined(MACOS_ENABLED)
  159. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  160. .path_join("libcoreclr.dylib");
  161. #elif defined(UNIX_ENABLED)
  162. String probe_path = GodotSharpDirs::get_api_assemblies_dir()
  163. .path_join("libcoreclr.so");
  164. #else
  165. #error "Platform not supported (yet?)"
  166. #endif
  167. if (FileAccess::exists(probe_path)) {
  168. return probe_path;
  169. }
  170. return String();
  171. }
  172. #endif
  173. bool load_hostfxr(void *&r_hostfxr_dll_handle) {
  174. String hostfxr_path = find_hostfxr();
  175. if (hostfxr_path.is_empty()) {
  176. return false;
  177. }
  178. print_verbose("Found hostfxr: " + hostfxr_path);
  179. Error err = OS::get_singleton()->open_dynamic_library(hostfxr_path, r_hostfxr_dll_handle);
  180. if (err != OK) {
  181. return false;
  182. }
  183. void *lib = r_hostfxr_dll_handle;
  184. void *symbol = nullptr;
  185. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_initialize_for_dotnet_command_line", symbol);
  186. ERR_FAIL_COND_V(err != OK, false);
  187. hostfxr_initialize_for_dotnet_command_line = (hostfxr_initialize_for_dotnet_command_line_fn)symbol;
  188. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_initialize_for_runtime_config", symbol);
  189. ERR_FAIL_COND_V(err != OK, false);
  190. hostfxr_initialize_for_runtime_config = (hostfxr_initialize_for_runtime_config_fn)symbol;
  191. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_get_runtime_delegate", symbol);
  192. ERR_FAIL_COND_V(err != OK, false);
  193. hostfxr_get_runtime_delegate = (hostfxr_get_runtime_delegate_fn)symbol;
  194. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "hostfxr_close", symbol);
  195. ERR_FAIL_COND_V(err != OK, false);
  196. hostfxr_close = (hostfxr_close_fn)symbol;
  197. return (hostfxr_initialize_for_runtime_config &&
  198. hostfxr_get_runtime_delegate &&
  199. hostfxr_close);
  200. }
  201. #ifndef TOOLS_ENABLED
  202. bool load_coreclr(void *&r_coreclr_dll_handle) {
  203. String coreclr_path = find_coreclr();
  204. bool is_monovm = false;
  205. if (coreclr_path.is_empty()) {
  206. // Fallback to MonoVM (should have the same API as CoreCLR).
  207. coreclr_path = find_monosgen();
  208. is_monovm = true;
  209. }
  210. if (coreclr_path.is_empty()) {
  211. return false;
  212. }
  213. const String coreclr_name = is_monovm ? "monosgen" : "coreclr";
  214. print_verbose("Found " + coreclr_name + ": " + coreclr_path);
  215. Error err = OS::get_singleton()->open_dynamic_library(coreclr_path, r_coreclr_dll_handle);
  216. if (err != OK) {
  217. return false;
  218. }
  219. void *lib = r_coreclr_dll_handle;
  220. void *symbol = nullptr;
  221. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "coreclr_initialize", symbol);
  222. ERR_FAIL_COND_V(err != OK, false);
  223. coreclr_initialize = (coreclr_initialize_fn)symbol;
  224. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "coreclr_create_delegate", symbol);
  225. ERR_FAIL_COND_V(err != OK, false);
  226. coreclr_create_delegate = (coreclr_create_delegate_fn)symbol;
  227. return (coreclr_initialize &&
  228. coreclr_create_delegate);
  229. }
  230. #endif
  231. #ifdef TOOLS_ENABLED
  232. load_assembly_and_get_function_pointer_fn initialize_hostfxr_for_config(const char_t *p_config_path) {
  233. hostfxr_handle cxt = nullptr;
  234. int rc = hostfxr_initialize_for_runtime_config(p_config_path, nullptr, &cxt);
  235. if (rc != 0 || cxt == nullptr) {
  236. hostfxr_close(cxt);
  237. ERR_FAIL_V_MSG(nullptr, "hostfxr_initialize_for_runtime_config failed with code: " + itos(rc));
  238. }
  239. void *load_assembly_and_get_function_pointer = nullptr;
  240. rc = hostfxr_get_runtime_delegate(cxt,
  241. hdt_load_assembly_and_get_function_pointer, &load_assembly_and_get_function_pointer);
  242. if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) {
  243. ERR_FAIL_V_MSG(nullptr, "hostfxr_get_runtime_delegate failed with code: " + itos(rc));
  244. }
  245. hostfxr_close(cxt);
  246. return (load_assembly_and_get_function_pointer_fn)load_assembly_and_get_function_pointer;
  247. }
  248. #else
  249. load_assembly_and_get_function_pointer_fn initialize_hostfxr_self_contained(
  250. const char_t *p_main_assembly_path) {
  251. hostfxr_handle cxt = nullptr;
  252. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  253. List<HostFxrCharString> argv_store;
  254. Vector<const char_t *> argv;
  255. argv.resize(cmdline_args.size() + 1);
  256. argv.write[0] = p_main_assembly_path;
  257. int i = 1;
  258. for (const String &E : cmdline_args) {
  259. HostFxrCharString &stored = argv_store.push_back(str_to_hostfxr(E))->get();
  260. argv.write[i] = get_data(stored);
  261. i++;
  262. }
  263. int rc = hostfxr_initialize_for_dotnet_command_line(argv.size(), argv.ptrw(), nullptr, &cxt);
  264. if (rc != 0 || cxt == nullptr) {
  265. hostfxr_close(cxt);
  266. ERR_FAIL_V_MSG(nullptr, "hostfxr_initialize_for_dotnet_command_line failed with code: " + itos(rc));
  267. }
  268. void *load_assembly_and_get_function_pointer = nullptr;
  269. rc = hostfxr_get_runtime_delegate(cxt,
  270. hdt_load_assembly_and_get_function_pointer, &load_assembly_and_get_function_pointer);
  271. if (rc != 0 || load_assembly_and_get_function_pointer == nullptr) {
  272. ERR_FAIL_V_MSG(nullptr, "hostfxr_get_runtime_delegate failed with code: " + itos(rc));
  273. }
  274. hostfxr_close(cxt);
  275. return (load_assembly_and_get_function_pointer_fn)load_assembly_and_get_function_pointer;
  276. }
  277. #endif
  278. #ifdef TOOLS_ENABLED
  279. using godot_plugins_initialize_fn = bool (*)(void *, bool, gdmono::PluginCallbacks *, GDMonoCache::ManagedCallbacks *, const void **, int32_t);
  280. #else
  281. using godot_plugins_initialize_fn = bool (*)(void *, GDMonoCache::ManagedCallbacks *, const void **, int32_t);
  282. #endif
  283. #ifdef TOOLS_ENABLED
  284. godot_plugins_initialize_fn initialize_hostfxr_and_godot_plugins(bool &r_runtime_initialized) {
  285. godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
  286. HostFxrCharString godot_plugins_path = str_to_hostfxr(
  287. GodotSharpDirs::get_api_assemblies_dir().path_join("GodotPlugins.dll"));
  288. HostFxrCharString config_path = str_to_hostfxr(
  289. GodotSharpDirs::get_api_assemblies_dir().path_join("GodotPlugins.runtimeconfig.json"));
  290. load_assembly_and_get_function_pointer_fn load_assembly_and_get_function_pointer =
  291. initialize_hostfxr_for_config(get_data(config_path));
  292. if (load_assembly_and_get_function_pointer == nullptr) {
  293. // Show a message box to the user to make the problem explicit (and explain a potential crash).
  294. OS::get_singleton()->alert(TTR("Unable to load .NET runtime, no compatible version was found.\nAttempting to create/edit a project will lead to a crash.\n\nPlease install the .NET SDK 6.0 or later from https://dotnet.microsoft.com/en-us/download and restart Godot."), TTR("Failed to load .NET runtime"));
  295. ERR_FAIL_V_MSG(nullptr, ".NET: Failed to load compatible .NET runtime");
  296. }
  297. r_runtime_initialized = true;
  298. print_verbose(".NET: hostfxr initialized");
  299. int rc = load_assembly_and_get_function_pointer(get_data(godot_plugins_path),
  300. HOSTFXR_STR("GodotPlugins.Main, GodotPlugins"),
  301. HOSTFXR_STR("InitializeFromEngine"),
  302. UNMANAGEDCALLERSONLY_METHOD,
  303. nullptr,
  304. (void **)&godot_plugins_initialize);
  305. ERR_FAIL_COND_V_MSG(rc != 0, nullptr, ".NET: Failed to get GodotPlugins initialization function pointer");
  306. return godot_plugins_initialize;
  307. }
  308. #else
  309. godot_plugins_initialize_fn initialize_hostfxr_and_godot_plugins(bool &r_runtime_initialized) {
  310. godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
  311. String assembly_name = path::get_csharp_project_name();
  312. HostFxrCharString assembly_path = str_to_hostfxr(GodotSharpDirs::get_api_assemblies_dir()
  313. .path_join(assembly_name + ".dll"));
  314. load_assembly_and_get_function_pointer_fn load_assembly_and_get_function_pointer =
  315. initialize_hostfxr_self_contained(get_data(assembly_path));
  316. ERR_FAIL_NULL_V(load_assembly_and_get_function_pointer, nullptr);
  317. r_runtime_initialized = true;
  318. print_verbose(".NET: hostfxr initialized");
  319. int rc = load_assembly_and_get_function_pointer(get_data(assembly_path),
  320. get_data(str_to_hostfxr("GodotPlugins.Game.Main, " + assembly_name)),
  321. HOSTFXR_STR("InitializeFromGameProject"),
  322. UNMANAGEDCALLERSONLY_METHOD,
  323. nullptr,
  324. (void **)&godot_plugins_initialize);
  325. ERR_FAIL_COND_V_MSG(rc != 0, nullptr, ".NET: Failed to get GodotPlugins initialization function pointer");
  326. return godot_plugins_initialize;
  327. }
  328. godot_plugins_initialize_fn try_load_native_aot_library(void *&r_aot_dll_handle) {
  329. String assembly_name = path::get_csharp_project_name();
  330. #if defined(WINDOWS_ENABLED)
  331. String native_aot_so_path = GodotSharpDirs::get_api_assemblies_dir().path_join(assembly_name + ".dll");
  332. #elif defined(MACOS_ENABLED) || defined(IOS_ENABLED)
  333. String native_aot_so_path = GodotSharpDirs::get_api_assemblies_dir().path_join(assembly_name + ".dylib");
  334. #elif defined(UNIX_ENABLED)
  335. String native_aot_so_path = GodotSharpDirs::get_api_assemblies_dir().path_join(assembly_name + ".so");
  336. #else
  337. #error "Platform not supported (yet?)"
  338. #endif
  339. Error err = OS::get_singleton()->open_dynamic_library(native_aot_so_path, r_aot_dll_handle);
  340. if (err != OK) {
  341. return nullptr;
  342. }
  343. void *lib = r_aot_dll_handle;
  344. void *symbol = nullptr;
  345. err = OS::get_singleton()->get_dynamic_library_symbol_handle(lib, "godotsharp_game_main_init", symbol);
  346. ERR_FAIL_COND_V(err != OK, nullptr);
  347. return (godot_plugins_initialize_fn)symbol;
  348. }
  349. #endif
  350. #ifndef TOOLS_ENABLED
  351. String make_tpa_list() {
  352. String tpa_list;
  353. #if defined(WINDOWS_ENABLED)
  354. String separator = ";";
  355. #else
  356. String separator = ":";
  357. #endif
  358. String assemblies_dir = GodotSharpDirs::get_api_assemblies_dir();
  359. PackedStringArray files = DirAccess::get_files_at(assemblies_dir);
  360. for (const String &file : files) {
  361. tpa_list += assemblies_dir.path_join(file);
  362. tpa_list += separator;
  363. }
  364. return tpa_list;
  365. }
  366. godot_plugins_initialize_fn initialize_coreclr_and_godot_plugins(bool &r_runtime_initialized) {
  367. godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
  368. String assembly_name = path::get_csharp_project_name();
  369. String tpa_list = make_tpa_list();
  370. const char *prop_keys[] = { "TRUSTED_PLATFORM_ASSEMBLIES" };
  371. const char *prop_values[] = { tpa_list.utf8().get_data() };
  372. int nprops = sizeof(prop_keys) / sizeof(prop_keys[0]);
  373. void *coreclr_handle = nullptr;
  374. unsigned int domain_id = 0;
  375. int rc = coreclr_initialize(nullptr, nullptr, nprops, (const char **)&prop_keys, (const char **)&prop_values, &coreclr_handle, &domain_id);
  376. ERR_FAIL_COND_V_MSG(rc != 0, nullptr, ".NET: Failed to initialize CoreCLR.");
  377. r_runtime_initialized = true;
  378. print_verbose(".NET: CoreCLR initialized");
  379. coreclr_create_delegate(coreclr_handle, domain_id,
  380. assembly_name.utf8().get_data(),
  381. "GodotPlugins.Game.Main",
  382. "InitializeFromGameProject",
  383. (void **)&godot_plugins_initialize);
  384. ERR_FAIL_NULL_V_MSG(godot_plugins_initialize, nullptr, ".NET: Failed to get GodotPlugins initialization function pointer");
  385. return godot_plugins_initialize;
  386. }
  387. #endif
  388. } // namespace
  389. bool GDMono::should_initialize() {
  390. #ifdef TOOLS_ENABLED
  391. // The editor always needs to initialize the .NET module for now.
  392. return true;
  393. #else
  394. return OS::get_singleton()->has_feature("dotnet");
  395. #endif
  396. }
  397. static bool _on_core_api_assembly_loaded() {
  398. if (!GDMonoCache::godot_api_cache_updated) {
  399. return false;
  400. }
  401. bool debug;
  402. #ifdef DEBUG_ENABLED
  403. debug = true;
  404. #else
  405. debug = false;
  406. #endif
  407. GDMonoCache::managed_callbacks.GD_OnCoreApiAssemblyLoaded(debug);
  408. return true;
  409. }
  410. void GDMono::initialize() {
  411. print_verbose(".NET: Initializing module...");
  412. _init_godot_api_hashes();
  413. godot_plugins_initialize_fn godot_plugins_initialize = nullptr;
  414. #if !defined(IOS_ENABLED)
  415. // Check that the .NET assemblies directory exists before trying to use it.
  416. if (!DirAccess::exists(GodotSharpDirs::get_api_assemblies_dir())) {
  417. OS::get_singleton()->alert(vformat(RTR("Unable to find the .NET assemblies directory.\nMake sure the '%s' directory exists and contains the .NET assemblies."), GodotSharpDirs::get_api_assemblies_dir()), RTR(".NET assemblies not found"));
  418. ERR_FAIL_MSG(".NET: Assemblies not found");
  419. }
  420. #endif
  421. if (load_hostfxr(hostfxr_dll_handle)) {
  422. godot_plugins_initialize = initialize_hostfxr_and_godot_plugins(runtime_initialized);
  423. ERR_FAIL_NULL(godot_plugins_initialize);
  424. } else {
  425. #if !defined(TOOLS_ENABLED)
  426. if (load_coreclr(coreclr_dll_handle)) {
  427. godot_plugins_initialize = initialize_coreclr_and_godot_plugins(runtime_initialized);
  428. } else {
  429. godot_plugins_initialize = try_load_native_aot_library(hostfxr_dll_handle);
  430. if (godot_plugins_initialize != nullptr) {
  431. runtime_initialized = true;
  432. }
  433. }
  434. if (godot_plugins_initialize == nullptr) {
  435. ERR_FAIL_MSG(".NET: Failed to load hostfxr");
  436. }
  437. #else
  438. // Show a message box to the user to make the problem explicit (and explain a potential crash).
  439. OS::get_singleton()->alert(TTR("Unable to load .NET runtime, specifically hostfxr.\nAttempting to create/edit a project will lead to a crash.\n\nPlease install the .NET SDK 6.0 or later from https://dotnet.microsoft.com/en-us/download and restart Godot."), TTR("Failed to load .NET runtime"));
  440. ERR_FAIL_MSG(".NET: Failed to load hostfxr");
  441. #endif
  442. }
  443. int32_t interop_funcs_size = 0;
  444. const void **interop_funcs = godotsharp::get_runtime_interop_funcs(interop_funcs_size);
  445. GDMonoCache::ManagedCallbacks managed_callbacks{};
  446. void *godot_dll_handle = nullptr;
  447. #if defined(UNIX_ENABLED) && !defined(MACOS_ENABLED) && !defined(IOS_ENABLED)
  448. // Managed code can access it on its own on other platforms
  449. godot_dll_handle = dlopen(nullptr, RTLD_NOW);
  450. #endif
  451. #ifdef TOOLS_ENABLED
  452. gdmono::PluginCallbacks plugin_callbacks_res;
  453. bool init_ok = godot_plugins_initialize(godot_dll_handle,
  454. Engine::get_singleton()->is_editor_hint(),
  455. &plugin_callbacks_res, &managed_callbacks,
  456. interop_funcs, interop_funcs_size);
  457. ERR_FAIL_COND_MSG(!init_ok, ".NET: GodotPlugins initialization failed");
  458. plugin_callbacks = plugin_callbacks_res;
  459. #else
  460. bool init_ok = godot_plugins_initialize(godot_dll_handle, &managed_callbacks,
  461. interop_funcs, interop_funcs_size);
  462. ERR_FAIL_COND_MSG(!init_ok, ".NET: GodotPlugins initialization failed");
  463. #endif
  464. GDMonoCache::update_godot_api_cache(managed_callbacks);
  465. print_verbose(".NET: GodotPlugins initialized");
  466. _on_core_api_assembly_loaded();
  467. #ifdef TOOLS_ENABLED
  468. _try_load_project_assembly();
  469. #endif
  470. initialized = true;
  471. }
  472. #ifdef TOOLS_ENABLED
  473. void GDMono::_try_load_project_assembly() {
  474. if (Engine::get_singleton()->is_project_manager_hint()) {
  475. return;
  476. }
  477. // Load the project's main assembly. This doesn't necessarily need to succeed.
  478. // The game may not be using .NET at all, or if the project does use .NET and
  479. // we're running in the editor, it may just happen to be it wasn't built yet.
  480. if (!_load_project_assembly()) {
  481. if (OS::get_singleton()->is_stdout_verbose()) {
  482. print_error(".NET: Failed to load project assembly");
  483. }
  484. }
  485. }
  486. #endif
  487. void GDMono::_init_godot_api_hashes() {
  488. #ifdef DEBUG_METHODS_ENABLED
  489. get_api_core_hash();
  490. #ifdef TOOLS_ENABLED
  491. get_api_editor_hash();
  492. #endif // TOOLS_ENABLED
  493. #endif // DEBUG_METHODS_ENABLED
  494. }
  495. #ifdef TOOLS_ENABLED
  496. bool GDMono::_load_project_assembly() {
  497. String assembly_name = path::get_csharp_project_name();
  498. String assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
  499. .path_join(assembly_name + ".dll");
  500. assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
  501. if (!FileAccess::exists(assembly_path)) {
  502. return false;
  503. }
  504. String loaded_assembly_path;
  505. bool success = plugin_callbacks.LoadProjectAssemblyCallback(assembly_path.utf16(), &loaded_assembly_path);
  506. if (success) {
  507. project_assembly_path = loaded_assembly_path.simplify_path();
  508. project_assembly_modified_time = FileAccess::get_modified_time(loaded_assembly_path);
  509. }
  510. return success;
  511. }
  512. #endif
  513. #ifdef GD_MONO_HOT_RELOAD
  514. void GDMono::reload_failure() {
  515. if (++project_load_failure_count >= (int)GLOBAL_GET("dotnet/project/assembly_reload_attempts")) {
  516. // After reloading a project has failed n times in a row, update the path and modification time
  517. // to stop any further attempts at loading this assembly, which probably is never going to work anyways.
  518. project_load_failure_count = 0;
  519. ERR_PRINT_ED(".NET: Giving up on assembly reloading. Please restart the editor if unloading was failing.");
  520. String assembly_name = path::get_csharp_project_name();
  521. String assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir().path_join(assembly_name + ".dll");
  522. assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
  523. project_assembly_path = assembly_path.simplify_path();
  524. project_assembly_modified_time = FileAccess::get_modified_time(assembly_path);
  525. }
  526. }
  527. Error GDMono::reload_project_assemblies() {
  528. ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG);
  529. finalizing_scripts_domain = true;
  530. if (!get_plugin_callbacks().UnloadProjectPluginCallback()) {
  531. ERR_PRINT_ED(".NET: Failed to unload assemblies. Please check https://github.com/godotengine/godot/issues/78513 for more information.");
  532. reload_failure();
  533. return FAILED;
  534. }
  535. finalizing_scripts_domain = false;
  536. // Load the project's main assembly. Here, during hot-reloading, we do
  537. // consider failing to load the project's main assembly to be an error.
  538. if (!_load_project_assembly()) {
  539. ERR_PRINT_ED(".NET: Failed to load project assembly.");
  540. reload_failure();
  541. return ERR_CANT_OPEN;
  542. }
  543. if (project_load_failure_count > 0) {
  544. project_load_failure_count = 0;
  545. ERR_PRINT_ED(".NET: Assembly reloading succeeded after failures.");
  546. }
  547. return OK;
  548. }
  549. #endif
  550. GDMono::GDMono() {
  551. singleton = this;
  552. }
  553. GDMono::~GDMono() {
  554. finalizing_scripts_domain = true;
  555. if (hostfxr_dll_handle) {
  556. OS::get_singleton()->close_dynamic_library(hostfxr_dll_handle);
  557. }
  558. if (coreclr_dll_handle) {
  559. OS::get_singleton()->close_dynamic_library(coreclr_dll_handle);
  560. }
  561. finalizing_scripts_domain = false;
  562. runtime_initialized = false;
  563. singleton = nullptr;
  564. }
  565. namespace mono_bind {
  566. GodotSharp *GodotSharp::singleton = nullptr;
  567. void GodotSharp::reload_assemblies(bool p_soft_reload) {
  568. #ifdef GD_MONO_HOT_RELOAD
  569. CRASH_COND(CSharpLanguage::get_singleton() == nullptr);
  570. // This method may be called more than once with `call_deferred`, so we need to check
  571. // again if reloading is needed to avoid reloading multiple times unnecessarily.
  572. if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) {
  573. CSharpLanguage::get_singleton()->reload_assemblies(p_soft_reload);
  574. }
  575. #endif
  576. }
  577. GodotSharp::GodotSharp() {
  578. singleton = this;
  579. }
  580. GodotSharp::~GodotSharp() {
  581. singleton = nullptr;
  582. }
  583. } // namespace mono_bind