gd_mono.cpp 44 KB

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