gd_mono.cpp 47 KB

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