gd_mono.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. /*************************************************************************/
  2. /* gd_mono.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  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 <mono/metadata/environment.h>
  32. #include <mono/metadata/exception.h>
  33. #include <mono/metadata/mono-config.h>
  34. #include <mono/metadata/mono-debug.h>
  35. #include <mono/metadata/mono-gc.h>
  36. #include <mono/metadata/profiler.h>
  37. #include "core/debugger/engine_debugger.h"
  38. #include "core/os/dir_access.h"
  39. #include "core/os/file_access.h"
  40. #include "core/os/os.h"
  41. #include "core/os/thread.h"
  42. #include "core/project_settings.h"
  43. #include "../csharp_script.h"
  44. #include "../godotsharp_dirs.h"
  45. #include "../utils/path_utils.h"
  46. #include "gd_mono_cache.h"
  47. #include "gd_mono_class.h"
  48. #include "gd_mono_marshal.h"
  49. #include "gd_mono_utils.h"
  50. #ifdef TOOLS_ENABLED
  51. #include "main/main.h"
  52. #endif
  53. #ifdef ANDROID_ENABLED
  54. #include "android_mono_config.h"
  55. #include "gd_mono_android.h"
  56. #endif
  57. // TODO:
  58. // This has turn into a gigantic mess. There's too much going on here. Too much #ifdef as well.
  59. // It's just painful to read... It needs to be re-structured. Please, clean this up, future me.
  60. GDMono *GDMono::singleton = NULL;
  61. namespace {
  62. #if defined(JAVASCRIPT_ENABLED)
  63. extern "C" {
  64. void mono_wasm_load_runtime(const char *managed_path, int enable_debugging);
  65. }
  66. #endif
  67. #if !defined(JAVASCRIPT_ENABLED)
  68. void gd_mono_setup_runtime_main_args() {
  69. CharString execpath = OS::get_singleton()->get_executable_path().utf8();
  70. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  71. List<CharString> cmdline_args_utf8;
  72. Vector<char *> main_args;
  73. main_args.resize(cmdline_args.size() + 1);
  74. main_args.write[0] = execpath.ptrw();
  75. int i = 1;
  76. for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) {
  77. CharString &stored = cmdline_args_utf8.push_back(E->get().utf8())->get();
  78. main_args.write[i] = stored.ptrw();
  79. i++;
  80. }
  81. mono_runtime_set_main_args(main_args.size(), main_args.ptrw());
  82. }
  83. void gd_mono_profiler_init() {
  84. String profiler_args = GLOBAL_DEF("mono/profiler/args", "log:calls,alloc,sample,output=output.mlpd");
  85. bool profiler_enabled = GLOBAL_DEF("mono/profiler/enabled", false);
  86. if (profiler_enabled) {
  87. mono_profiler_load(profiler_args.utf8());
  88. return;
  89. }
  90. const String env_var_name = "MONO_ENV_OPTIONS";
  91. if (OS::get_singleton()->has_environment(env_var_name)) {
  92. const auto mono_env_ops = OS::get_singleton()->get_environment(env_var_name);
  93. // Usually MONO_ENV_OPTIONS looks like: --profile=jb:prof=timeline,ctl=remote,host=127.0.0.1:55467
  94. const String prefix = "--profile=";
  95. if (mono_env_ops.begins_with(prefix)) {
  96. const auto ops = mono_env_ops.substr(prefix.length(), mono_env_ops.length());
  97. mono_profiler_load(ops.utf8());
  98. }
  99. }
  100. }
  101. #if defined(DEBUG_ENABLED)
  102. void gd_mono_debug_init() {
  103. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  104. CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8();
  105. #ifdef TOOLS_ENABLED
  106. int da_port = GLOBAL_DEF("mono/debugger_agent/port", 23685);
  107. bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
  108. int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
  109. if (Engine::get_singleton()->is_editor_hint() ||
  110. ProjectSettings::get_singleton()->get_resource_path().empty() ||
  111. Main::is_project_manager()) {
  112. if (da_args.size() == 0)
  113. return;
  114. }
  115. if (da_args.length() == 0) {
  116. da_args = String("--debugger-agent=transport=dt_socket,address=127.0.0.1:" + itos(da_port) +
  117. ",embedding=1,server=y,suspend=" + (da_suspend ? "y,timeout=" + itos(da_timeout) : "n"))
  118. .utf8();
  119. }
  120. #else
  121. if (da_args.length() == 0)
  122. return; // Exported games don't use the project settings to setup the debugger agent
  123. #endif
  124. // --debugger-agent=help
  125. const char *options[] = {
  126. "--soft-breakpoints",
  127. da_args.get_data()
  128. };
  129. mono_jit_parse_options(2, (char **)options);
  130. }
  131. #endif // defined(DEBUG_ENABLED)
  132. #endif // !defined(JAVASCRIPT_ENABLED)
  133. #if defined(JAVASCRIPT_ENABLED)
  134. MonoDomain *gd_initialize_mono_runtime() {
  135. const char *vfs_prefix = "managed";
  136. int enable_debugging = 0;
  137. #ifdef DEBUG_ENABLED
  138. enable_debugging = 1;
  139. #endif
  140. mono_wasm_load_runtime(vfs_prefix, enable_debugging);
  141. return mono_get_root_domain();
  142. }
  143. #else
  144. MonoDomain *gd_initialize_mono_runtime() {
  145. #ifdef DEBUG_ENABLED
  146. gd_mono_debug_init();
  147. #endif
  148. return mono_jit_init_version("GodotEngine.RootDomain", "v4.0.30319");
  149. }
  150. #endif
  151. } // namespace
  152. void GDMono::add_mono_shared_libs_dir_to_path() {
  153. // TODO: Replace this with a mono_dl_fallback
  154. // By default Mono seems to search shared libraries in the following directories:
  155. // Current working directory, @executable_path@ and PATH
  156. // The parent directory of the image file (assembly where the dllimport method is declared)
  157. // @executable_path@/../lib
  158. // @executable_path@/../Libraries (__MACH__ only)
  159. // This does not work when embedding Mono unless we use the same directory structure.
  160. // To fix this we append the directory containing our shared libraries to PATH.
  161. #if defined(WINDOWS_ENABLED) || defined(UNIX_ENABLED)
  162. String path_var("PATH");
  163. String path_value = OS::get_singleton()->get_environment(path_var);
  164. #ifdef WINDOWS_ENABLED
  165. path_value += ';';
  166. String bundled_bin_dir = GodotSharpDirs::get_data_mono_bin_dir();
  167. #ifdef TOOLS_ENABLED
  168. if (DirAccess::exists(bundled_bin_dir)) {
  169. path_value += bundled_bin_dir;
  170. } else {
  171. path_value += mono_reg_info.bin_dir;
  172. }
  173. #else
  174. if (DirAccess::exists(bundled_bin_dir))
  175. path_value += bundled_bin_dir;
  176. #endif // TOOLS_ENABLED
  177. #else
  178. path_value += ':';
  179. String bundled_lib_dir = GodotSharpDirs::get_data_mono_lib_dir();
  180. if (DirAccess::exists(bundled_lib_dir)) {
  181. path_value += bundled_lib_dir;
  182. } else {
  183. // TODO: Do we need to add the lib dir when using the system installed Mono on Unix platforms?
  184. }
  185. #endif // WINDOWS_ENABLED
  186. OS::get_singleton()->set_environment(path_var, path_value);
  187. #endif // WINDOWS_ENABLED || UNIX_ENABLED
  188. }
  189. void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir) {
  190. String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir();
  191. String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir();
  192. #ifdef TOOLS_ENABLED
  193. #if defined(WINDOWS_ENABLED)
  194. mono_reg_info = MonoRegUtils::find_mono();
  195. if (mono_reg_info.assembly_dir.length() && DirAccess::exists(mono_reg_info.assembly_dir)) {
  196. r_assembly_rootdir = mono_reg_info.assembly_dir;
  197. }
  198. if (mono_reg_info.config_dir.length() && DirAccess::exists(mono_reg_info.config_dir)) {
  199. r_config_dir = mono_reg_info.config_dir;
  200. }
  201. #elif defined(OSX_ENABLED)
  202. const char *c_assembly_rootdir = mono_assembly_getrootdir();
  203. const char *c_config_dir = mono_get_config_dir();
  204. if (!c_assembly_rootdir || !c_config_dir || !DirAccess::exists(c_assembly_rootdir) || !DirAccess::exists(c_config_dir)) {
  205. Vector<const char *> locations;
  206. locations.push_back("/Library/Frameworks/Mono.framework/Versions/Current/");
  207. locations.push_back("/usr/local/var/homebrew/linked/mono/");
  208. for (int i = 0; i < locations.size(); i++) {
  209. String hint_assembly_rootdir = path::join(locations[i], "lib");
  210. String hint_mscorlib_path = path::join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll");
  211. String hint_config_dir = path::join(locations[i], "etc");
  212. if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) {
  213. r_assembly_rootdir = hint_assembly_rootdir;
  214. r_config_dir = hint_config_dir;
  215. break;
  216. }
  217. }
  218. }
  219. #endif
  220. if (DirAccess::exists(bundled_assembly_rootdir)) {
  221. r_assembly_rootdir = bundled_assembly_rootdir;
  222. }
  223. if (DirAccess::exists(bundled_config_dir)) {
  224. r_config_dir = bundled_config_dir;
  225. }
  226. #ifdef WINDOWS_ENABLED
  227. if (r_assembly_rootdir.empty() || r_config_dir.empty()) {
  228. ERR_PRINT("Cannot find Mono in the registry.");
  229. // Assertion: if they are not set, then they weren't found in the registry
  230. CRASH_COND(mono_reg_info.assembly_dir.length() > 0 || mono_reg_info.config_dir.length() > 0);
  231. }
  232. #endif // WINDOWS_ENABLED
  233. #else
  234. // Export templates always use the bundled directories
  235. r_assembly_rootdir = bundled_assembly_rootdir;
  236. r_config_dir = bundled_config_dir;
  237. #endif
  238. }
  239. void GDMono::initialize() {
  240. ERR_FAIL_NULL(Engine::get_singleton());
  241. print_verbose("Mono: Initializing module...");
  242. char *runtime_build_info = mono_get_runtime_build_info();
  243. print_verbose("Mono JIT compiler version " + String(runtime_build_info));
  244. mono_free(runtime_build_info);
  245. _init_godot_api_hashes();
  246. _init_exception_policy();
  247. GDMonoLog::get_singleton()->initialize();
  248. #if !defined(JAVASCRIPT_ENABLED)
  249. String assembly_rootdir;
  250. String config_dir;
  251. determine_mono_dirs(assembly_rootdir, config_dir);
  252. // Leak if we call mono_set_dirs more than once
  253. mono_set_dirs(assembly_rootdir.length() ? assembly_rootdir.utf8().get_data() : NULL,
  254. config_dir.length() ? config_dir.utf8().get_data() : NULL);
  255. add_mono_shared_libs_dir_to_path();
  256. #endif
  257. #if defined(ANDROID_ENABLED)
  258. GDMonoAndroid::initialize();
  259. #endif
  260. GDMonoAssembly::initialize();
  261. #if !defined(JAVASCRIPT_ENABLED)
  262. gd_mono_profiler_init();
  263. #endif
  264. #ifdef ANDROID_ENABLED
  265. mono_config_parse_memory(get_godot_android_mono_config().utf8().get_data());
  266. #else
  267. mono_config_parse(NULL);
  268. #endif
  269. mono_install_unhandled_exception_hook(&unhandled_exception_hook, NULL);
  270. #ifndef TOOLS_ENABLED
  271. // Exported games that don't use C# must still work. They likely don't ship with mscorlib.
  272. // We only initialize the Mono runtime if we can find mscorlib. Otherwise it would crash.
  273. if (GDMonoAssembly::find_assembly("mscorlib.dll").empty()) {
  274. print_verbose("Mono: Skipping runtime initialization because 'mscorlib.dll' could not be found");
  275. return;
  276. }
  277. #endif
  278. #if !defined(NO_MONO_THREADS_SUSPEND_WORKAROUND)
  279. // FIXME: Temporary workaround. See: https://github.com/godotengine/godot/issues/29812
  280. if (!OS::get_singleton()->has_environment("MONO_THREADS_SUSPEND")) {
  281. OS::get_singleton()->set_environment("MONO_THREADS_SUSPEND", "preemptive");
  282. }
  283. #endif
  284. // NOTE: Internal calls must be registered after the Mono runtime initialization.
  285. // Otherwise registration fails with the error: 'assertion 'hash != NULL' failed'.
  286. root_domain = gd_initialize_mono_runtime();
  287. ERR_FAIL_NULL_MSG(root_domain, "Mono: Failed to initialize runtime.");
  288. GDMonoUtils::set_main_thread(GDMonoUtils::get_current_thread());
  289. #if !defined(JAVASCRIPT_ENABLED)
  290. gd_mono_setup_runtime_main_args(); // Required for System.Environment.GetCommandLineArgs
  291. #endif
  292. runtime_initialized = true;
  293. print_verbose("Mono: Runtime initialized");
  294. #if defined(ANDROID_ENABLED)
  295. GDMonoAndroid::register_internal_calls();
  296. #endif
  297. // mscorlib assembly MUST be present at initialization
  298. bool corlib_loaded = _load_corlib_assembly();
  299. ERR_FAIL_COND_MSG(!corlib_loaded, "Mono: Failed to load mscorlib assembly.");
  300. Error domain_load_err = _load_scripts_domain();
  301. ERR_FAIL_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain.");
  302. _register_internal_calls();
  303. print_verbose("Mono: INITIALIZED");
  304. }
  305. void GDMono::initialize_load_assemblies() {
  306. #ifndef MONO_GLUE_ENABLED
  307. CRASH_NOW_MSG("Mono: This binary was built with 'mono_glue=no'; cannot load assemblies.");
  308. #endif
  309. // Load assemblies. The API and tools assemblies are required,
  310. // the application is aborted if these assemblies cannot be loaded.
  311. _load_api_assemblies();
  312. #if defined(TOOLS_ENABLED)
  313. bool tool_assemblies_loaded = _load_tools_assemblies();
  314. CRASH_COND_MSG(!tool_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies.");
  315. #endif
  316. // Load the project's main assembly. This doesn't necessarily need to succeed.
  317. // The game may not be using .NET at all, or if the project does use .NET and
  318. // we're running in the editor, it may just happen to be it wasn't built yet.
  319. if (!_load_project_assembly()) {
  320. if (OS::get_singleton()->is_stdout_verbose())
  321. print_error("Mono: Failed to load project assembly");
  322. }
  323. }
  324. bool GDMono::_are_api_assemblies_out_of_sync() {
  325. bool out_of_sync = core_api_assembly.assembly && (core_api_assembly.out_of_sync || !GDMonoCache::cached_data.godot_api_cache_updated);
  326. #ifdef TOOLS_ENABLED
  327. if (!out_of_sync)
  328. out_of_sync = editor_api_assembly.assembly && editor_api_assembly.out_of_sync;
  329. #endif
  330. return out_of_sync;
  331. }
  332. namespace GodotSharpBindings {
  333. #ifdef MONO_GLUE_ENABLED
  334. uint64_t get_core_api_hash();
  335. #ifdef TOOLS_ENABLED
  336. uint64_t get_editor_api_hash();
  337. #endif
  338. uint32_t get_bindings_version();
  339. uint32_t get_cs_glue_version();
  340. void register_generated_icalls();
  341. #else
  342. uint64_t get_core_api_hash() {
  343. GD_UNREACHABLE();
  344. }
  345. #ifdef TOOLS_ENABLED
  346. uint64_t get_editor_api_hash() {
  347. GD_UNREACHABLE();
  348. }
  349. #endif
  350. uint32_t get_bindings_version() {
  351. GD_UNREACHABLE();
  352. }
  353. uint32_t get_cs_glue_version() {
  354. GD_UNREACHABLE();
  355. }
  356. void register_generated_icalls() {
  357. /* Fine, just do nothing */
  358. }
  359. #endif // MONO_GLUE_ENABLED
  360. } // namespace GodotSharpBindings
  361. void GDMono::_register_internal_calls() {
  362. GodotSharpBindings::register_generated_icalls();
  363. }
  364. void GDMono::_init_godot_api_hashes() {
  365. #if defined(MONO_GLUE_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  366. if (get_api_core_hash() != GodotSharpBindings::get_core_api_hash()) {
  367. ERR_PRINT("Mono: Core API hash mismatch.");
  368. }
  369. #ifdef TOOLS_ENABLED
  370. if (get_api_editor_hash() != GodotSharpBindings::get_editor_api_hash()) {
  371. ERR_PRINT("Mono: Editor API hash mismatch.");
  372. }
  373. #endif // TOOLS_ENABLED
  374. #endif // MONO_GLUE_ENABLED && DEBUG_METHODS_ENABLED
  375. }
  376. void GDMono::_init_exception_policy() {
  377. PropertyInfo exc_policy_prop = PropertyInfo(Variant::INT, "mono/unhandled_exception_policy", PROPERTY_HINT_ENUM,
  378. vformat("Terminate Application:%s,Log Error:%s", (int)POLICY_TERMINATE_APP, (int)POLICY_LOG_ERROR));
  379. unhandled_exception_policy = (UnhandledExceptionPolicy)(int)GLOBAL_DEF(exc_policy_prop.name, (int)POLICY_TERMINATE_APP);
  380. ProjectSettings::get_singleton()->set_custom_property_info(exc_policy_prop.name, exc_policy_prop);
  381. if (Engine::get_singleton()->is_editor_hint()) {
  382. // Unhandled exceptions should not terminate the editor
  383. unhandled_exception_policy = POLICY_LOG_ERROR;
  384. }
  385. }
  386. void GDMono::add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly) {
  387. assemblies[p_domain_id][p_assembly->get_name()] = p_assembly;
  388. }
  389. GDMonoAssembly **GDMono::get_loaded_assembly(const String &p_name) {
  390. MonoDomain *domain = mono_domain_get();
  391. uint32_t domain_id = domain ? mono_domain_get_id(domain) : 0;
  392. return assemblies[domain_id].getptr(p_name);
  393. }
  394. bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly) {
  395. CRASH_COND(!r_assembly);
  396. MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
  397. bool result = load_assembly(p_name, aname, r_assembly, p_refonly);
  398. mono_assembly_name_free(aname);
  399. mono_free(aname);
  400. return result;
  401. }
  402. bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) {
  403. CRASH_COND(!r_assembly);
  404. print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
  405. MonoImageOpenStatus status = MONO_IMAGE_OK;
  406. MonoAssembly *assembly = mono_assembly_load_full(p_aname, NULL, &status, p_refonly);
  407. if (!assembly)
  408. return false;
  409. ERR_FAIL_COND_V(status != MONO_IMAGE_OK, false);
  410. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  411. GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name);
  412. ERR_FAIL_COND_V(stored_assembly == NULL, false);
  413. ERR_FAIL_COND_V((*stored_assembly)->get_assembly() != assembly, false);
  414. *r_assembly = *stored_assembly;
  415. print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
  416. return true;
  417. }
  418. bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly) {
  419. CRASH_COND(!r_assembly);
  420. print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
  421. GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, p_refonly);
  422. if (!assembly)
  423. return false;
  424. #ifdef DEBUG_ENABLED
  425. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  426. GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name);
  427. ERR_FAIL_COND_V(stored_assembly == NULL, false);
  428. ERR_FAIL_COND_V(*stored_assembly != assembly, false);
  429. #endif
  430. *r_assembly = assembly;
  431. print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
  432. return true;
  433. }
  434. ApiAssemblyInfo::Version ApiAssemblyInfo::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, ApiAssemblyInfo::Type p_api_type) {
  435. ApiAssemblyInfo::Version api_assembly_version;
  436. const char *nativecalls_name = p_api_type == ApiAssemblyInfo::API_CORE ?
  437. BINDINGS_CLASS_NATIVECALLS :
  438. BINDINGS_CLASS_NATIVECALLS_EDITOR;
  439. GDMonoClass *nativecalls_klass = p_api_assembly->get_class(BINDINGS_NAMESPACE, nativecalls_name);
  440. if (nativecalls_klass) {
  441. GDMonoField *api_hash_field = nativecalls_klass->get_field("godot_api_hash");
  442. if (api_hash_field)
  443. api_assembly_version.godot_api_hash = GDMonoMarshal::unbox<uint64_t>(api_hash_field->get_value(NULL));
  444. GDMonoField *binds_ver_field = nativecalls_klass->get_field("bindings_version");
  445. if (binds_ver_field)
  446. api_assembly_version.bindings_version = GDMonoMarshal::unbox<uint32_t>(binds_ver_field->get_value(NULL));
  447. GDMonoField *cs_glue_ver_field = nativecalls_klass->get_field("cs_glue_version");
  448. if (cs_glue_ver_field)
  449. api_assembly_version.cs_glue_version = GDMonoMarshal::unbox<uint32_t>(cs_glue_ver_field->get_value(NULL));
  450. }
  451. return api_assembly_version;
  452. }
  453. String ApiAssemblyInfo::to_string(ApiAssemblyInfo::Type p_type) {
  454. return p_type == ApiAssemblyInfo::API_CORE ? "API_CORE" : "API_EDITOR";
  455. }
  456. bool GDMono::_load_corlib_assembly() {
  457. if (corlib_assembly)
  458. return true;
  459. bool success = load_assembly("mscorlib", &corlib_assembly);
  460. if (success)
  461. GDMonoCache::update_corlib_cache();
  462. return success;
  463. }
  464. #ifdef TOOLS_ENABLED
  465. bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config) {
  466. String src_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
  467. String dst_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config);
  468. String assembly_name = p_api_type == ApiAssemblyInfo::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME;
  469. // Create destination directory if needed
  470. if (!DirAccess::exists(dst_dir)) {
  471. DirAccess *da = DirAccess::create_for_path(dst_dir);
  472. Error err = da->make_dir_recursive(dst_dir);
  473. memdelete(da);
  474. if (err != OK) {
  475. ERR_PRINT("Failed to create destination directory for the API assemblies. Error: " + itos(err) + ".");
  476. return false;
  477. }
  478. }
  479. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  480. String xml_file = assembly_name + ".xml";
  481. if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK)
  482. WARN_PRINT("Failed to copy '" + xml_file + "'.");
  483. String pdb_file = assembly_name + ".pdb";
  484. if (da->copy(src_dir.plus_file(pdb_file), dst_dir.plus_file(pdb_file)) != OK)
  485. WARN_PRINT("Failed to copy '" + pdb_file + "'.");
  486. String assembly_file = assembly_name + ".dll";
  487. if (da->copy(src_dir.plus_file(assembly_file), dst_dir.plus_file(assembly_file)) != OK) {
  488. ERR_PRINT("Failed to copy '" + assembly_file + "'.");
  489. return false;
  490. }
  491. return true;
  492. }
  493. static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool &r_out_of_sync) {
  494. String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
  495. String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
  496. if (!FileAccess::exists(core_api_assembly_path) || !FileAccess::exists(editor_api_assembly_path))
  497. return false;
  498. String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg");
  499. if (!FileAccess::exists(cached_api_hash_path))
  500. return false;
  501. Ref<ConfigFile> cfg;
  502. cfg.instance();
  503. Error cfg_err = cfg->load(cached_api_hash_path);
  504. ERR_FAIL_COND_V(cfg_err != OK, false);
  505. // Checking the modified time is good enough
  506. if (FileAccess::get_modified_time(core_api_assembly_path) != (uint64_t)cfg->get_value("core", "modified_time") ||
  507. FileAccess::get_modified_time(editor_api_assembly_path) != (uint64_t)cfg->get_value("editor", "modified_time")) {
  508. return false;
  509. }
  510. r_out_of_sync = GodotSharpBindings::get_bindings_version() != (uint32_t)cfg->get_value("core", "bindings_version") ||
  511. GodotSharpBindings::get_cs_glue_version() != (uint32_t)cfg->get_value("core", "cs_glue_version") ||
  512. GodotSharpBindings::get_bindings_version() != (uint32_t)cfg->get_value("editor", "bindings_version") ||
  513. GodotSharpBindings::get_cs_glue_version() != (uint32_t)cfg->get_value("editor", "cs_glue_version") ||
  514. GodotSharpBindings::get_core_api_hash() != (uint64_t)cfg->get_value("core", "api_hash") ||
  515. GodotSharpBindings::get_editor_api_hash() != (uint64_t)cfg->get_value("editor", "api_hash");
  516. return true;
  517. }
  518. static void create_cached_api_hash_for(const String &p_api_assemblies_dir) {
  519. String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
  520. String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
  521. String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg");
  522. Ref<ConfigFile> cfg;
  523. cfg.instance();
  524. cfg->set_value("core", "modified_time", FileAccess::get_modified_time(core_api_assembly_path));
  525. cfg->set_value("editor", "modified_time", FileAccess::get_modified_time(editor_api_assembly_path));
  526. cfg->set_value("core", "bindings_version", GodotSharpBindings::get_bindings_version());
  527. cfg->set_value("core", "cs_glue_version", GodotSharpBindings::get_cs_glue_version());
  528. cfg->set_value("editor", "bindings_version", GodotSharpBindings::get_bindings_version());
  529. cfg->set_value("editor", "cs_glue_version", GodotSharpBindings::get_cs_glue_version());
  530. // This assumes the prebuilt api assemblies we copied to the project are not out of sync
  531. cfg->set_value("core", "api_hash", GodotSharpBindings::get_core_api_hash());
  532. cfg->set_value("editor", "api_hash", GodotSharpBindings::get_editor_api_hash());
  533. Error err = cfg->save(cached_api_hash_path);
  534. ERR_FAIL_COND(err != OK);
  535. }
  536. bool GDMono::_temp_domain_load_are_assemblies_out_of_sync(const String &p_config) {
  537. MonoDomain *temp_domain = GDMonoUtils::create_domain("GodotEngine.Domain.CheckApiAssemblies");
  538. ERR_FAIL_NULL_V(temp_domain, "Failed to create temporary domain to check API assemblies");
  539. _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(temp_domain);
  540. _GDMONO_SCOPE_DOMAIN_(temp_domain);
  541. GDMono::LoadedApiAssembly temp_core_api_assembly;
  542. GDMono::LoadedApiAssembly temp_editor_api_assembly;
  543. if (!_try_load_api_assemblies(temp_core_api_assembly, temp_editor_api_assembly,
  544. p_config, /* refonly: */ true, /* loaded_callback: */ NULL)) {
  545. return temp_core_api_assembly.out_of_sync || temp_editor_api_assembly.out_of_sync;
  546. }
  547. return true; // Failed to load, assume they're outdated assemblies
  548. }
  549. String GDMono::update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync, const bool *p_editor_api_out_of_sync) {
  550. #define FAIL_REASON(m_out_of_sync, m_prebuilt_exists) \
  551. ( \
  552. (m_out_of_sync ? \
  553. String("The assembly is invalidated ") : \
  554. String("The assembly was not found ")) + \
  555. (m_prebuilt_exists ? \
  556. String("and the prebuilt assemblies are missing.") : \
  557. String("and we failed to copy the prebuilt assemblies.")))
  558. String dst_assemblies_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config);
  559. String core_assembly_path = dst_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
  560. String editor_assembly_path = dst_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
  561. bool api_assemblies_out_of_sync = false;
  562. if (p_core_api_out_of_sync && p_editor_api_out_of_sync) {
  563. api_assemblies_out_of_sync = p_core_api_out_of_sync || p_editor_api_out_of_sync;
  564. } else if (FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) {
  565. // Determine if they're out of sync
  566. if (!try_get_cached_api_hash_for(dst_assemblies_dir, api_assemblies_out_of_sync)) {
  567. api_assemblies_out_of_sync = _temp_domain_load_are_assemblies_out_of_sync(p_config);
  568. }
  569. }
  570. // Note: Even if only one of the assemblies if missing or out of sync, we update both
  571. if (!api_assemblies_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path))
  572. return String(); // No update needed
  573. print_verbose("Updating '" + p_config + "' API assemblies");
  574. String prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
  575. String prebuilt_core_dll_path = prebuilt_api_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
  576. String prebuilt_editor_dll_path = prebuilt_api_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
  577. if (!FileAccess::exists(prebuilt_core_dll_path) || !FileAccess::exists(prebuilt_editor_dll_path)) {
  578. return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ false);
  579. }
  580. // Copy the prebuilt Api
  581. if (!copy_prebuilt_api_assembly(ApiAssemblyInfo::API_CORE, p_config) ||
  582. !copy_prebuilt_api_assembly(ApiAssemblyInfo::API_EDITOR, p_config)) {
  583. return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ true);
  584. }
  585. // Cache the api hash of the assemblies we just copied
  586. create_cached_api_hash_for(dst_assemblies_dir);
  587. return String(); // Updated successfully
  588. #undef FAIL_REASON
  589. }
  590. #endif
  591. bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) {
  592. if (r_loaded_api_assembly.assembly)
  593. return true;
  594. #ifdef TOOLS_ENABLED
  595. // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date
  596. // If running the project manager, load it from the prebuilt API directory
  597. String assembly_dir = !Main::is_project_manager() ?
  598. GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) :
  599. GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
  600. String assembly_path = assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
  601. bool success = FileAccess::exists(assembly_path) &&
  602. load_assembly_from(CORE_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly);
  603. #else
  604. bool success = load_assembly(CORE_API_ASSEMBLY_NAME, &r_loaded_api_assembly.assembly, p_refonly);
  605. #endif
  606. if (success) {
  607. ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_CORE);
  608. r_loaded_api_assembly.out_of_sync = GodotSharpBindings::get_core_api_hash() != api_assembly_ver.godot_api_hash ||
  609. GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
  610. GodotSharpBindings::get_cs_glue_version() != api_assembly_ver.cs_glue_version;
  611. } else {
  612. r_loaded_api_assembly.out_of_sync = false;
  613. }
  614. return success;
  615. }
  616. #ifdef TOOLS_ENABLED
  617. bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) {
  618. if (r_loaded_api_assembly.assembly)
  619. return true;
  620. // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date
  621. // If running the project manager, load it from the prebuilt API directory
  622. String assembly_dir = !Main::is_project_manager() ?
  623. GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) :
  624. GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
  625. String assembly_path = assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
  626. bool success = FileAccess::exists(assembly_path) &&
  627. load_assembly_from(EDITOR_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly);
  628. if (success) {
  629. ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_EDITOR);
  630. r_loaded_api_assembly.out_of_sync = GodotSharpBindings::get_editor_api_hash() != api_assembly_ver.godot_api_hash ||
  631. GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
  632. GodotSharpBindings::get_cs_glue_version() != api_assembly_ver.cs_glue_version;
  633. } else {
  634. r_loaded_api_assembly.out_of_sync = false;
  635. }
  636. return success;
  637. }
  638. #endif
  639. bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly,
  640. const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback) {
  641. if (!_load_core_api_assembly(r_core_api_assembly, p_config, p_refonly)) {
  642. if (OS::get_singleton()->is_stdout_verbose())
  643. print_error("Mono: Failed to load Core API assembly");
  644. return false;
  645. }
  646. #ifdef TOOLS_ENABLED
  647. if (!_load_editor_api_assembly(r_editor_api_assembly, p_config, p_refonly)) {
  648. if (OS::get_singleton()->is_stdout_verbose())
  649. print_error("Mono: Failed to load Editor API assembly");
  650. return false;
  651. }
  652. if (r_editor_api_assembly.out_of_sync)
  653. return false;
  654. #endif
  655. // Check if the core API assembly is out of sync only after trying to load the
  656. // editor API assembly. Otherwise, if both assemblies are out of sync, we would
  657. // only update the former as we won't know the latter also needs to be updated.
  658. if (r_core_api_assembly.out_of_sync)
  659. return false;
  660. if (p_callback)
  661. return p_callback();
  662. return true;
  663. }
  664. bool GDMono::_on_core_api_assembly_loaded() {
  665. GDMonoCache::update_godot_api_cache();
  666. if (!GDMonoCache::cached_data.godot_api_cache_updated)
  667. return false;
  668. get_singleton()->_install_trace_listener();
  669. return true;
  670. }
  671. bool GDMono::_try_load_api_assemblies_preset() {
  672. return _try_load_api_assemblies(core_api_assembly, editor_api_assembly,
  673. get_expected_api_build_config(), /* refonly: */ false, _on_core_api_assembly_loaded);
  674. }
  675. void GDMono::_load_api_assemblies() {
  676. bool api_assemblies_loaded = _try_load_api_assemblies_preset();
  677. if (!api_assemblies_loaded) {
  678. #ifdef TOOLS_ENABLED
  679. // The API assemblies are out of sync or some other error happened. Fine, try one more time, but
  680. // this time update them from the prebuilt assemblies directory before trying to load them again.
  681. // Shouldn't happen. The project manager loads the prebuilt API assemblies
  682. CRASH_COND_MSG(Main::is_project_manager(), "Failed to load one of the prebuilt API assemblies.");
  683. // 1. Unload the scripts domain
  684. Error domain_unload_err = _unload_scripts_domain();
  685. CRASH_COND_MSG(domain_unload_err != OK, "Mono: Failed to unload scripts domain.");
  686. // 2. Update the API assemblies
  687. String update_error = update_api_assemblies_from_prebuilt("Debug", &core_api_assembly.out_of_sync, &editor_api_assembly.out_of_sync);
  688. CRASH_COND_MSG(!update_error.empty(), update_error);
  689. // 3. Load the scripts domain again
  690. Error domain_load_err = _load_scripts_domain();
  691. CRASH_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain.");
  692. // 4. Try loading the updated assemblies
  693. api_assemblies_loaded = _try_load_api_assemblies_preset();
  694. #endif
  695. }
  696. if (!api_assemblies_loaded) {
  697. // welp... too bad
  698. if (_are_api_assemblies_out_of_sync()) {
  699. if (core_api_assembly.out_of_sync) {
  700. ERR_PRINT("The assembly '" CORE_API_ASSEMBLY_NAME "' is out of sync.");
  701. } else if (!GDMonoCache::cached_data.godot_api_cache_updated) {
  702. ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed.");
  703. }
  704. #ifdef TOOLS_ENABLED
  705. if (editor_api_assembly.out_of_sync) {
  706. ERR_PRINT("The assembly '" EDITOR_API_ASSEMBLY_NAME "' is out of sync.");
  707. }
  708. #endif
  709. CRASH_NOW();
  710. } else {
  711. CRASH_NOW_MSG("Failed to load one of the API assemblies.");
  712. }
  713. }
  714. }
  715. #ifdef TOOLS_ENABLED
  716. bool GDMono::_load_tools_assemblies() {
  717. if (tools_assembly && tools_project_editor_assembly)
  718. return true;
  719. bool success = load_assembly(TOOLS_ASM_NAME, &tools_assembly) &&
  720. load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_assembly);
  721. return success;
  722. }
  723. #endif
  724. bool GDMono::_load_project_assembly() {
  725. if (project_assembly)
  726. return true;
  727. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  728. String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
  729. if (appname_safe.empty()) {
  730. appname_safe = "UnnamedProject";
  731. }
  732. bool success = load_assembly(appname_safe, &project_assembly);
  733. if (success) {
  734. mono_assembly_set_main(project_assembly->get_assembly());
  735. }
  736. return success;
  737. }
  738. void GDMono::_install_trace_listener() {
  739. #ifdef DEBUG_ENABLED
  740. // Install the trace listener now before the project assembly is loaded
  741. GDMonoClass *debug_utils = get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, "DebuggingUtils");
  742. GDMonoMethod *install_func = debug_utils->get_method("InstallTraceListener");
  743. MonoException *exc = NULL;
  744. install_func->invoke_raw(NULL, NULL, &exc);
  745. if (exc) {
  746. GDMonoUtils::debug_print_unhandled_exception(exc);
  747. ERR_PRINT("Failed to install 'System.Diagnostics.Trace' listener.");
  748. }
  749. #endif
  750. }
  751. Error GDMono::_load_scripts_domain() {
  752. ERR_FAIL_COND_V(scripts_domain != NULL, ERR_BUG);
  753. print_verbose("Mono: Loading scripts domain...");
  754. scripts_domain = GDMonoUtils::create_domain("GodotEngine.Domain.Scripts");
  755. ERR_FAIL_NULL_V_MSG(scripts_domain, ERR_CANT_CREATE, "Mono: Could not create scripts app domain.");
  756. mono_domain_set(scripts_domain, true);
  757. return OK;
  758. }
  759. Error GDMono::_unload_scripts_domain() {
  760. ERR_FAIL_NULL_V(scripts_domain, ERR_BUG);
  761. print_verbose("Mono: Unloading scripts domain...");
  762. if (mono_domain_get() != root_domain)
  763. mono_domain_set(root_domain, true);
  764. finalizing_scripts_domain = true;
  765. if (!mono_domain_finalize(scripts_domain, 2000)) {
  766. ERR_PRINT("Mono: Domain finalization timeout.");
  767. }
  768. finalizing_scripts_domain = false;
  769. mono_gc_collect(mono_gc_max_generation());
  770. GDMonoCache::clear_godot_api_cache();
  771. _domain_assemblies_cleanup(mono_domain_get_id(scripts_domain));
  772. core_api_assembly.assembly = NULL;
  773. #ifdef TOOLS_ENABLED
  774. editor_api_assembly.assembly = NULL;
  775. #endif
  776. project_assembly = NULL;
  777. #ifdef TOOLS_ENABLED
  778. tools_assembly = NULL;
  779. tools_project_editor_assembly = NULL;
  780. #endif
  781. MonoDomain *domain = scripts_domain;
  782. scripts_domain = NULL;
  783. MonoException *exc = NULL;
  784. mono_domain_try_unload(domain, (MonoObject **)&exc);
  785. if (exc) {
  786. ERR_PRINT("Exception thrown when unloading scripts domain.");
  787. GDMonoUtils::debug_unhandled_exception(exc);
  788. return FAILED;
  789. }
  790. return OK;
  791. }
  792. #ifdef GD_MONO_HOT_RELOAD
  793. Error GDMono::reload_scripts_domain() {
  794. ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG);
  795. if (scripts_domain) {
  796. Error domain_unload_err = _unload_scripts_domain();
  797. ERR_FAIL_COND_V_MSG(domain_unload_err != OK, domain_unload_err, "Mono: Failed to unload scripts domain.");
  798. }
  799. CSharpLanguage::get_singleton()->_on_scripts_domain_unloaded();
  800. Error domain_load_err = _load_scripts_domain();
  801. ERR_FAIL_COND_V_MSG(domain_load_err != OK, domain_load_err, "Mono: Failed to load scripts domain.");
  802. // Load assemblies. The API and tools assemblies are required,
  803. // the application is aborted if these assemblies cannot be loaded.
  804. _load_api_assemblies();
  805. #if defined(TOOLS_ENABLED)
  806. bool tools_assemblies_loaded = _load_tools_assemblies();
  807. CRASH_COND_MSG(!tools_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies.");
  808. #endif
  809. // Load the project's main assembly. Here, during hot-reloading, we do
  810. // consider failing to load the project's main assembly to be an error.
  811. // However, unlike the API and tools assemblies, the application can continue working.
  812. if (!_load_project_assembly()) {
  813. print_error("Mono: Failed to load project assembly");
  814. return ERR_CANT_OPEN;
  815. }
  816. return OK;
  817. }
  818. #endif
  819. Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
  820. CRASH_COND(p_domain == NULL);
  821. CRASH_COND(p_domain == GDMono::get_singleton()->get_scripts_domain()); // Should use _unload_scripts_domain() instead
  822. String domain_name = mono_domain_get_friendly_name(p_domain);
  823. print_verbose("Mono: Unloading domain '" + domain_name + "'...");
  824. if (mono_domain_get() == p_domain)
  825. mono_domain_set(root_domain, true);
  826. if (!mono_domain_finalize(p_domain, 2000)) {
  827. ERR_PRINT("Mono: Domain finalization timeout.");
  828. }
  829. mono_gc_collect(mono_gc_max_generation());
  830. _domain_assemblies_cleanup(mono_domain_get_id(p_domain));
  831. MonoException *exc = NULL;
  832. mono_domain_try_unload(p_domain, (MonoObject **)&exc);
  833. if (exc) {
  834. ERR_PRINT("Exception thrown when unloading domain '" + domain_name + "'.");
  835. GDMonoUtils::debug_print_unhandled_exception(exc);
  836. return FAILED;
  837. }
  838. return OK;
  839. }
  840. GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
  841. MonoImage *image = mono_class_get_image(p_raw_class);
  842. if (image == corlib_assembly->get_image())
  843. return corlib_assembly->get_class(p_raw_class);
  844. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  845. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
  846. const String *k = NULL;
  847. while ((k = domain_assemblies.next(k))) {
  848. GDMonoAssembly *assembly = domain_assemblies.get(*k);
  849. if (assembly->get_image() == image) {
  850. GDMonoClass *klass = assembly->get_class(p_raw_class);
  851. if (klass)
  852. return klass;
  853. }
  854. }
  855. return NULL;
  856. }
  857. GDMonoClass *GDMono::get_class(const StringName &p_namespace, const StringName &p_name) {
  858. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  859. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
  860. const String *k = NULL;
  861. while ((k = domain_assemblies.next(k))) {
  862. GDMonoAssembly *assembly = domain_assemblies.get(*k);
  863. GDMonoClass *klass = assembly->get_class(p_namespace, p_name);
  864. if (klass)
  865. return klass;
  866. }
  867. return NULL;
  868. }
  869. void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) {
  870. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id];
  871. const String *k = NULL;
  872. while ((k = domain_assemblies.next(k))) {
  873. memdelete(domain_assemblies.get(*k));
  874. }
  875. assemblies.erase(p_domain_id);
  876. }
  877. void GDMono::unhandled_exception_hook(MonoObject *p_exc, void *) {
  878. // This method will be called by the runtime when a thrown exception is not handled.
  879. // It won't be called when we manually treat a thrown exception as unhandled.
  880. // We assume the exception was already printed before calling this hook.
  881. #ifdef DEBUG_ENABLED
  882. GDMonoUtils::debug_send_unhandled_exception_error((MonoException *)p_exc);
  883. if (EngineDebugger::is_active())
  884. EngineDebugger::get_singleton()->poll_events(false);
  885. #endif
  886. exit(mono_environment_exitcode_get());
  887. GD_UNREACHABLE();
  888. }
  889. GDMono::GDMono() {
  890. singleton = this;
  891. gdmono_log = memnew(GDMonoLog);
  892. runtime_initialized = false;
  893. finalizing_scripts_domain = false;
  894. root_domain = NULL;
  895. scripts_domain = NULL;
  896. corlib_assembly = NULL;
  897. project_assembly = NULL;
  898. #ifdef TOOLS_ENABLED
  899. tools_assembly = NULL;
  900. tools_project_editor_assembly = NULL;
  901. #endif
  902. api_core_hash = 0;
  903. #ifdef TOOLS_ENABLED
  904. api_editor_hash = 0;
  905. #endif
  906. unhandled_exception_policy = POLICY_TERMINATE_APP;
  907. }
  908. GDMono::~GDMono() {
  909. if (is_runtime_initialized()) {
  910. if (scripts_domain) {
  911. Error err = _unload_scripts_domain();
  912. if (err != OK) {
  913. ERR_PRINT("Mono: Failed to unload scripts domain.");
  914. }
  915. }
  916. const uint32_t *k = NULL;
  917. while ((k = assemblies.next(k))) {
  918. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies.get(*k);
  919. const String *kk = NULL;
  920. while ((kk = domain_assemblies.next(kk))) {
  921. memdelete(domain_assemblies.get(*kk));
  922. }
  923. }
  924. assemblies.clear();
  925. print_verbose("Mono: Runtime cleanup...");
  926. mono_jit_cleanup(root_domain);
  927. #if defined(ANDROID_ENABLED)
  928. GDMonoAndroid::cleanup();
  929. #endif
  930. print_verbose("Mono: Finalized");
  931. runtime_initialized = false;
  932. }
  933. if (gdmono_log)
  934. memdelete(gdmono_log);
  935. singleton = NULL;
  936. }
  937. _GodotSharp *_GodotSharp::singleton = NULL;
  938. void _GodotSharp::attach_thread() {
  939. GDMonoUtils::attach_current_thread();
  940. }
  941. void _GodotSharp::detach_thread() {
  942. GDMonoUtils::detach_current_thread();
  943. }
  944. int32_t _GodotSharp::get_domain_id() {
  945. MonoDomain *domain = mono_domain_get();
  946. CRASH_COND(!domain); // User must check if runtime is initialized before calling this method
  947. return mono_domain_get_id(domain);
  948. }
  949. int32_t _GodotSharp::get_scripts_domain_id() {
  950. MonoDomain *domain = GDMono::get_singleton()->get_scripts_domain();
  951. CRASH_COND(!domain); // User must check if scripts domain is loaded before calling this method
  952. return mono_domain_get_id(domain);
  953. }
  954. bool _GodotSharp::is_scripts_domain_loaded() {
  955. return GDMono::get_singleton()->is_runtime_initialized() && GDMono::get_singleton()->get_scripts_domain() != NULL;
  956. }
  957. bool _GodotSharp::_is_domain_finalizing_for_unload(int32_t p_domain_id) {
  958. return is_domain_finalizing_for_unload(p_domain_id);
  959. }
  960. bool _GodotSharp::is_domain_finalizing_for_unload() {
  961. return is_domain_finalizing_for_unload(mono_domain_get());
  962. }
  963. bool _GodotSharp::is_domain_finalizing_for_unload(int32_t p_domain_id) {
  964. return is_domain_finalizing_for_unload(mono_domain_get_by_id(p_domain_id));
  965. }
  966. bool _GodotSharp::is_domain_finalizing_for_unload(MonoDomain *p_domain) {
  967. if (!p_domain)
  968. return true;
  969. if (p_domain == GDMono::get_singleton()->get_scripts_domain() && GDMono::get_singleton()->is_finalizing_scripts_domain())
  970. return true;
  971. return mono_domain_is_unloading(p_domain);
  972. }
  973. bool _GodotSharp::is_runtime_shutting_down() {
  974. return mono_runtime_is_shutting_down();
  975. }
  976. bool _GodotSharp::is_runtime_initialized() {
  977. return GDMono::get_singleton()->is_runtime_initialized();
  978. }
  979. void _GodotSharp::_reload_assemblies(bool p_soft_reload) {
  980. #ifdef GD_MONO_HOT_RELOAD
  981. CSharpLanguage::get_singleton()->reload_assemblies(p_soft_reload);
  982. #endif
  983. }
  984. void _GodotSharp::_bind_methods() {
  985. ClassDB::bind_method(D_METHOD("attach_thread"), &_GodotSharp::attach_thread);
  986. ClassDB::bind_method(D_METHOD("detach_thread"), &_GodotSharp::detach_thread);
  987. ClassDB::bind_method(D_METHOD("get_domain_id"), &_GodotSharp::get_domain_id);
  988. ClassDB::bind_method(D_METHOD("get_scripts_domain_id"), &_GodotSharp::get_scripts_domain_id);
  989. ClassDB::bind_method(D_METHOD("is_scripts_domain_loaded"), &_GodotSharp::is_scripts_domain_loaded);
  990. ClassDB::bind_method(D_METHOD("is_domain_finalizing_for_unload", "domain_id"), &_GodotSharp::_is_domain_finalizing_for_unload);
  991. ClassDB::bind_method(D_METHOD("is_runtime_shutting_down"), &_GodotSharp::is_runtime_shutting_down);
  992. ClassDB::bind_method(D_METHOD("is_runtime_initialized"), &_GodotSharp::is_runtime_initialized);
  993. ClassDB::bind_method(D_METHOD("_reload_assemblies"), &_GodotSharp::_reload_assemblies);
  994. }
  995. _GodotSharp::_GodotSharp() {
  996. singleton = this;
  997. }
  998. _GodotSharp::~_GodotSharp() {
  999. singleton = NULL;
  1000. }