gd_mono.cpp 46 KB

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