gd_mono.cpp 46 KB

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