gd_mono.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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/exception.h>
  32. #include <mono/metadata/mono-config.h>
  33. #include <mono/metadata/mono-debug.h>
  34. #include <mono/metadata/mono-gc.h>
  35. #include "core/os/dir_access.h"
  36. #include "core/os/file_access.h"
  37. #include "core/os/os.h"
  38. #include "core/os/thread.h"
  39. #include "core/project_settings.h"
  40. #include "../csharp_script.h"
  41. #include "../glue/cs_glue_version.gen.h"
  42. #include "../godotsharp_dirs.h"
  43. #include "../utils/path_utils.h"
  44. #include "gd_mono_class.h"
  45. #include "gd_mono_marshal.h"
  46. #include "gd_mono_utils.h"
  47. #ifdef TOOLS_ENABLED
  48. #include "../editor/godotsharp_editor.h"
  49. #include "main/main.h"
  50. #endif
  51. #ifdef MONO_PRINT_HANDLER_ENABLED
  52. void gdmono_MonoPrintCallback(const char *string, mono_bool is_stdout) {
  53. if (is_stdout) {
  54. OS::get_singleton()->print(string);
  55. } else {
  56. OS::get_singleton()->printerr(string);
  57. }
  58. }
  59. #endif
  60. GDMono *GDMono::singleton = NULL;
  61. namespace {
  62. void setup_runtime_main_args() {
  63. CharString execpath = OS::get_singleton()->get_executable_path().utf8();
  64. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  65. List<CharString> cmdline_args_utf8;
  66. Vector<char *> main_args;
  67. main_args.resize(cmdline_args.size() + 1);
  68. main_args.write[0] = execpath.ptrw();
  69. int i = 1;
  70. for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) {
  71. CharString &stored = cmdline_args_utf8.push_back(E->get().utf8())->get();
  72. main_args.write[i] = stored.ptrw();
  73. i++;
  74. }
  75. mono_runtime_set_main_args(main_args.size(), main_args.ptrw());
  76. }
  77. #ifdef DEBUG_ENABLED
  78. static bool _wait_for_debugger_msecs(uint32_t p_msecs) {
  79. do {
  80. if (mono_is_debugger_attached())
  81. return true;
  82. int last_tick = OS::get_singleton()->get_ticks_msec();
  83. OS::get_singleton()->delay_usec((p_msecs < 25 ? p_msecs : 25) * 1000);
  84. int tdiff = OS::get_singleton()->get_ticks_msec() - last_tick;
  85. if (tdiff > p_msecs) {
  86. p_msecs = 0;
  87. } else {
  88. p_msecs -= tdiff;
  89. }
  90. } while (p_msecs > 0);
  91. return mono_is_debugger_attached();
  92. }
  93. void gdmono_debug_init() {
  94. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  95. int da_port = GLOBAL_DEF("mono/debugger_agent/port", 23685);
  96. bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
  97. int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
  98. #ifdef TOOLS_ENABLED
  99. if (Engine::get_singleton()->is_editor_hint() ||
  100. ProjectSettings::get_singleton()->get_resource_path().empty() ||
  101. Main::is_project_manager()) {
  102. return;
  103. }
  104. #endif
  105. CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8();
  106. if (da_args == "") {
  107. da_args = String("--debugger-agent=transport=dt_socket,address=127.0.0.1:" + itos(da_port) +
  108. ",embedding=1,server=y,suspend=" + (da_suspend ? "y,timeout=" + itos(da_timeout) : "n"))
  109. .utf8();
  110. }
  111. // --debugger-agent=help
  112. const char *options[] = {
  113. "--soft-breakpoints",
  114. da_args.get_data()
  115. };
  116. mono_jit_parse_options(2, (char **)options);
  117. }
  118. #endif
  119. } // namespace
  120. void GDMono::initialize() {
  121. ERR_FAIL_NULL(Engine::get_singleton());
  122. print_verbose("Mono: Initializing module...");
  123. #ifdef DEBUG_METHODS_ENABLED
  124. _initialize_and_check_api_hashes();
  125. #endif
  126. GDMonoLog::get_singleton()->initialize();
  127. #ifdef MONO_PRINT_HANDLER_ENABLED
  128. mono_trace_set_print_handler(gdmono_MonoPrintCallback);
  129. mono_trace_set_printerr_handler(gdmono_MonoPrintCallback);
  130. #endif
  131. String assembly_rootdir;
  132. String config_dir;
  133. #ifdef TOOLS_ENABLED
  134. #ifdef WINDOWS_ENABLED
  135. mono_reg_info = MonoRegUtils::find_mono();
  136. if (mono_reg_info.assembly_dir.length() && DirAccess::exists(mono_reg_info.assembly_dir)) {
  137. assembly_rootdir = mono_reg_info.assembly_dir;
  138. }
  139. if (mono_reg_info.config_dir.length() && DirAccess::exists(mono_reg_info.config_dir)) {
  140. config_dir = mono_reg_info.config_dir;
  141. }
  142. #elif OSX_ENABLED
  143. const char *c_assembly_rootdir = mono_assembly_getrootdir();
  144. const char *c_config_dir = mono_get_config_dir();
  145. if (!c_assembly_rootdir || !c_config_dir || !DirAccess::exists(c_assembly_rootdir) || !DirAccess::exists(c_config_dir)) {
  146. Vector<const char *> locations;
  147. locations.push_back("/Library/Frameworks/Mono.framework/Versions/Current/");
  148. locations.push_back("/usr/local/var/homebrew/linked/mono/");
  149. for (int i = 0; i < locations.size(); i++) {
  150. String hint_assembly_rootdir = path_join(locations[i], "lib");
  151. String hint_mscorlib_path = path_join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll");
  152. String hint_config_dir = path_join(locations[i], "etc");
  153. if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) {
  154. assembly_rootdir = hint_assembly_rootdir;
  155. config_dir = hint_config_dir;
  156. break;
  157. }
  158. }
  159. }
  160. #endif
  161. #endif // TOOLS_ENABLED
  162. String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir();
  163. String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir();
  164. #ifdef TOOLS_ENABLED
  165. if (DirAccess::exists(bundled_assembly_rootdir) && DirAccess::exists(bundled_config_dir)) {
  166. assembly_rootdir = bundled_assembly_rootdir;
  167. config_dir = bundled_config_dir;
  168. }
  169. #else
  170. // These are always the directories in export templates
  171. assembly_rootdir = bundled_assembly_rootdir;
  172. config_dir = bundled_config_dir;
  173. #endif
  174. // Leak if we call mono_set_dirs more than once
  175. mono_set_dirs(assembly_rootdir.length() ? assembly_rootdir.utf8().get_data() : NULL,
  176. config_dir.length() ? config_dir.utf8().get_data() : NULL);
  177. GDMonoAssembly::initialize();
  178. #ifdef DEBUG_ENABLED
  179. gdmono_debug_init();
  180. #endif
  181. mono_config_parse(NULL);
  182. mono_install_unhandled_exception_hook(&unhandled_exception_hook, NULL);
  183. root_domain = mono_jit_init_version("GodotEngine.RootDomain", "v4.0.30319");
  184. ERR_EXPLAIN("Mono: Failed to initialize runtime");
  185. ERR_FAIL_NULL(root_domain);
  186. GDMonoUtils::set_main_thread(GDMonoUtils::get_current_thread());
  187. setup_runtime_main_args(); // Required for System.Environment.GetCommandLineArgs
  188. runtime_initialized = true;
  189. print_verbose("Mono: Runtime initialized");
  190. // mscorlib assembly MUST be present at initialization
  191. ERR_EXPLAIN("Mono: Failed to load mscorlib assembly");
  192. ERR_FAIL_COND(!_load_corlib_assembly());
  193. #ifdef TOOLS_ENABLED
  194. // The tools domain must be loaded here, before the scripts domain.
  195. // Otherwise domain unload on the scripts domain will hang indefinitely.
  196. ERR_EXPLAIN("Mono: Failed to load tools domain");
  197. ERR_FAIL_COND(_load_tools_domain() != OK);
  198. // TODO move to editor init callback, and do it lazily when required before editor init (e.g.: bindings generation)
  199. ERR_EXPLAIN("Mono: Failed to load Editor Tools assembly");
  200. ERR_FAIL_COND(!_load_editor_tools_assembly());
  201. #endif
  202. ERR_EXPLAIN("Mono: Failed to load scripts domain");
  203. ERR_FAIL_COND(_load_scripts_domain() != OK);
  204. #ifdef DEBUG_ENABLED
  205. bool debugger_attached = _wait_for_debugger_msecs(500);
  206. if (!debugger_attached && OS::get_singleton()->is_stdout_verbose())
  207. print_error("Mono: Debugger wait timeout");
  208. #endif
  209. _register_internal_calls();
  210. // The following assemblies are not required at initialization
  211. #ifdef MONO_GLUE_ENABLED
  212. if (_load_api_assemblies()) {
  213. // Everything is fine with the api assemblies, load the project assembly
  214. _load_project_assembly();
  215. } else {
  216. if ((core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated))
  217. #ifdef TOOLS_ENABLED
  218. || (editor_api_assembly && editor_api_assembly_out_of_sync)
  219. #endif
  220. ) {
  221. #ifdef TOOLS_ENABLED
  222. // The assembly was successfully loaded, but the full api could not be cached.
  223. // This is most likely an outdated assembly loaded because of an invalid version in the
  224. // metadata, so we invalidate the version in the metadata and unload the script domain.
  225. if (core_api_assembly_out_of_sync) {
  226. ERR_PRINT("The loaded Core API assembly is out of sync");
  227. metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
  228. } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) {
  229. ERR_PRINT("The loaded Core API assembly is in sync, but the cache update failed");
  230. metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
  231. }
  232. if (editor_api_assembly_out_of_sync) {
  233. ERR_PRINT("The loaded Editor API assembly is out of sync");
  234. metadata_set_api_assembly_invalidated(APIAssembly::API_EDITOR, true);
  235. }
  236. print_line("Mono: Proceeding to unload scripts domain because of invalid API assemblies.");
  237. Error err = _unload_scripts_domain();
  238. if (err != OK) {
  239. WARN_PRINT("Mono: Failed to unload scripts domain");
  240. }
  241. #else
  242. ERR_PRINT("The loaded API assembly is invalid");
  243. CRASH_NOW();
  244. #endif // TOOLS_ENABLED
  245. }
  246. }
  247. #else
  248. print_verbose("Mono: Glue disabled, ignoring script assemblies.");
  249. #endif // MONO_GLUE_ENABLED
  250. print_verbose("Mono: INITIALIZED");
  251. }
  252. #ifdef MONO_GLUE_ENABLED
  253. namespace GodotSharpBindings {
  254. uint64_t get_core_api_hash();
  255. #ifdef TOOLS_ENABLED
  256. uint64_t get_editor_api_hash();
  257. #endif // TOOLS_ENABLED
  258. uint32_t get_bindings_version();
  259. void register_generated_icalls();
  260. } // namespace GodotSharpBindings
  261. #endif
  262. void GDMono::_register_internal_calls() {
  263. #ifdef MONO_GLUE_ENABLED
  264. GodotSharpBindings::register_generated_icalls();
  265. #endif
  266. #ifdef TOOLS_ENABLED
  267. GodotSharpEditor::register_internal_calls();
  268. #endif
  269. }
  270. #ifdef DEBUG_METHODS_ENABLED
  271. void GDMono::_initialize_and_check_api_hashes() {
  272. api_core_hash = ClassDB::get_api_hash(ClassDB::API_CORE);
  273. #ifdef MONO_GLUE_ENABLED
  274. if (api_core_hash != GodotSharpBindings::get_core_api_hash()) {
  275. ERR_PRINT("Mono: Core API hash mismatch!");
  276. }
  277. #endif
  278. #ifdef TOOLS_ENABLED
  279. api_editor_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR);
  280. #ifdef MONO_GLUE_ENABLED
  281. if (api_editor_hash != GodotSharpBindings::get_editor_api_hash()) {
  282. ERR_PRINT("Mono: Editor API hash mismatch!");
  283. }
  284. #endif
  285. #endif // TOOLS_ENABLED
  286. }
  287. #endif // DEBUG_METHODS_ENABLED
  288. void GDMono::add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly) {
  289. assemblies[p_domain_id][p_assembly->get_name()] = p_assembly;
  290. }
  291. GDMonoAssembly **GDMono::get_loaded_assembly(const String &p_name) {
  292. MonoDomain *domain = mono_domain_get();
  293. uint32_t domain_id = domain ? mono_domain_get_id(domain) : 0;
  294. return assemblies[domain_id].getptr(p_name);
  295. }
  296. bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly) {
  297. CRASH_COND(!r_assembly);
  298. MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
  299. bool result = load_assembly(p_name, aname, r_assembly, p_refonly);
  300. mono_assembly_name_free(aname);
  301. mono_free(aname);
  302. return result;
  303. }
  304. bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) {
  305. CRASH_COND(!r_assembly);
  306. print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
  307. MonoImageOpenStatus status = MONO_IMAGE_OK;
  308. MonoAssembly *assembly = mono_assembly_load_full(p_aname, NULL, &status, p_refonly);
  309. if (!assembly)
  310. return false;
  311. ERR_FAIL_COND_V(status != MONO_IMAGE_OK, false);
  312. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  313. GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name);
  314. ERR_FAIL_COND_V(stored_assembly == NULL, false);
  315. ERR_FAIL_COND_V((*stored_assembly)->get_assembly() != assembly, false);
  316. *r_assembly = *stored_assembly;
  317. print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
  318. return true;
  319. }
  320. bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly) {
  321. CRASH_COND(!r_assembly);
  322. print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
  323. GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, p_refonly);
  324. if (!assembly)
  325. return false;
  326. #ifdef DEBUG_ENABLED
  327. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  328. GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name);
  329. ERR_FAIL_COND_V(stored_assembly == NULL, false);
  330. ERR_FAIL_COND_V(*stored_assembly != assembly, false);
  331. #endif
  332. *r_assembly = assembly;
  333. print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
  334. return true;
  335. }
  336. APIAssembly::Version APIAssembly::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, APIAssembly::Type p_api_type) {
  337. APIAssembly::Version api_assembly_version;
  338. const char *nativecalls_name = p_api_type == APIAssembly::API_CORE ?
  339. BINDINGS_CLASS_NATIVECALLS :
  340. BINDINGS_CLASS_NATIVECALLS_EDITOR;
  341. GDMonoClass *nativecalls_klass = p_api_assembly->get_class(BINDINGS_NAMESPACE, nativecalls_name);
  342. if (nativecalls_klass) {
  343. GDMonoField *api_hash_field = nativecalls_klass->get_field("godot_api_hash");
  344. if (api_hash_field)
  345. api_assembly_version.godot_api_hash = GDMonoMarshal::unbox<uint64_t>(api_hash_field->get_value(NULL));
  346. GDMonoField *binds_ver_field = nativecalls_klass->get_field("bindings_version");
  347. if (binds_ver_field)
  348. api_assembly_version.bindings_version = GDMonoMarshal::unbox<uint32_t>(binds_ver_field->get_value(NULL));
  349. GDMonoField *cs_glue_ver_field = nativecalls_klass->get_field("cs_glue_version");
  350. if (cs_glue_ver_field)
  351. api_assembly_version.cs_glue_version = GDMonoMarshal::unbox<uint32_t>(cs_glue_ver_field->get_value(NULL));
  352. }
  353. return api_assembly_version;
  354. }
  355. String APIAssembly::to_string(APIAssembly::Type p_type) {
  356. return p_type == APIAssembly::API_CORE ? "API_CORE" : "API_EDITOR";
  357. }
  358. bool GDMono::_load_corlib_assembly() {
  359. if (corlib_assembly)
  360. return true;
  361. bool success = load_assembly("mscorlib", &corlib_assembly);
  362. if (success)
  363. GDMonoUtils::update_corlib_cache();
  364. return success;
  365. }
  366. bool GDMono::_load_core_api_assembly() {
  367. if (core_api_assembly)
  368. return true;
  369. #ifdef TOOLS_ENABLED
  370. if (metadata_is_api_assembly_invalidated(APIAssembly::API_CORE)) {
  371. print_verbose("Mono: Skipping loading of Core API assembly because it was invalidated");
  372. return false;
  373. }
  374. #endif
  375. String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(CORE_API_ASSEMBLY_NAME ".dll");
  376. if (!FileAccess::exists(assembly_path))
  377. return false;
  378. bool success = load_assembly_from(CORE_API_ASSEMBLY_NAME,
  379. assembly_path,
  380. &core_api_assembly);
  381. if (success) {
  382. #ifdef MONO_GLUE_ENABLED
  383. APIAssembly::Version api_assembly_ver = APIAssembly::Version::get_from_loaded_assembly(core_api_assembly, APIAssembly::API_CORE);
  384. core_api_assembly_out_of_sync = GodotSharpBindings::get_core_api_hash() != api_assembly_ver.godot_api_hash ||
  385. GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
  386. CS_GLUE_VERSION != api_assembly_ver.cs_glue_version;
  387. if (!core_api_assembly_out_of_sync) {
  388. GDMonoUtils::update_godot_api_cache();
  389. }
  390. #else
  391. GDMonoUtils::update_godot_api_cache();
  392. #endif
  393. }
  394. return success;
  395. }
  396. #ifdef TOOLS_ENABLED
  397. bool GDMono::_load_editor_api_assembly() {
  398. if (editor_api_assembly)
  399. return true;
  400. if (metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR)) {
  401. print_verbose("Mono: Skipping loading of Editor API assembly because it was invalidated");
  402. return false;
  403. }
  404. String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
  405. if (!FileAccess::exists(assembly_path))
  406. return false;
  407. bool success = load_assembly_from(EDITOR_API_ASSEMBLY_NAME,
  408. assembly_path,
  409. &editor_api_assembly);
  410. if (success) {
  411. #ifdef MONO_GLUE_ENABLED
  412. APIAssembly::Version api_assembly_ver = APIAssembly::Version::get_from_loaded_assembly(editor_api_assembly, APIAssembly::API_EDITOR);
  413. editor_api_assembly_out_of_sync = GodotSharpBindings::get_editor_api_hash() != api_assembly_ver.godot_api_hash ||
  414. GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
  415. CS_GLUE_VERSION != api_assembly_ver.cs_glue_version;
  416. #endif
  417. }
  418. return success;
  419. }
  420. #endif
  421. #ifdef TOOLS_ENABLED
  422. bool GDMono::_load_editor_tools_assembly() {
  423. if (editor_tools_assembly)
  424. return true;
  425. _GDMONO_SCOPE_DOMAIN_(tools_domain)
  426. return load_assembly(EDITOR_TOOLS_ASSEMBLY_NAME, &editor_tools_assembly);
  427. }
  428. #endif
  429. bool GDMono::_load_project_assembly() {
  430. if (project_assembly)
  431. return true;
  432. String name = ProjectSettings::get_singleton()->get("application/config/name");
  433. if (name.empty()) {
  434. name = "UnnamedProject";
  435. }
  436. bool success = load_assembly(name, &project_assembly);
  437. if (success) {
  438. mono_assembly_set_main(project_assembly->get_assembly());
  439. CSharpLanguage::get_singleton()->project_assembly_loaded();
  440. } else {
  441. if (OS::get_singleton()->is_stdout_verbose())
  442. print_error("Mono: Failed to load project assembly");
  443. }
  444. return success;
  445. }
  446. bool GDMono::_load_api_assemblies() {
  447. if (!_load_core_api_assembly()) {
  448. if (OS::get_singleton()->is_stdout_verbose())
  449. print_error("Mono: Failed to load Core API assembly");
  450. return false;
  451. }
  452. if (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated)
  453. return false;
  454. #ifdef TOOLS_ENABLED
  455. if (!_load_editor_api_assembly()) {
  456. if (OS::get_singleton()->is_stdout_verbose())
  457. print_error("Mono: Failed to load Editor API assembly");
  458. return false;
  459. }
  460. if (editor_api_assembly_out_of_sync)
  461. return false;
  462. #endif
  463. return true;
  464. }
  465. #ifdef TOOLS_ENABLED
  466. String GDMono::_get_api_assembly_metadata_path() {
  467. return GodotSharpDirs::get_res_metadata_dir().plus_file("api_assemblies.cfg");
  468. }
  469. void GDMono::metadata_set_api_assembly_invalidated(APIAssembly::Type p_api_type, bool p_invalidated) {
  470. String section = APIAssembly::to_string(p_api_type);
  471. String path = _get_api_assembly_metadata_path();
  472. Ref<ConfigFile> metadata;
  473. metadata.instance();
  474. metadata->load(path);
  475. metadata->set_value(section, "invalidated", p_invalidated);
  476. String assembly_path = GodotSharpDirs::get_res_assemblies_dir()
  477. .plus_file(p_api_type == APIAssembly::API_CORE ?
  478. CORE_API_ASSEMBLY_NAME ".dll" :
  479. EDITOR_API_ASSEMBLY_NAME ".dll");
  480. ERR_FAIL_COND(!FileAccess::exists(assembly_path));
  481. uint64_t modified_time = FileAccess::get_modified_time(assembly_path);
  482. metadata->set_value(section, "invalidated_asm_modified_time", String::num_uint64(modified_time));
  483. String dir = path.get_base_dir();
  484. if (!DirAccess::exists(dir)) {
  485. DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  486. ERR_FAIL_COND(!da);
  487. Error err = da->make_dir_recursive(ProjectSettings::get_singleton()->globalize_path(dir));
  488. ERR_FAIL_COND(err != OK);
  489. }
  490. Error save_err = metadata->save(path);
  491. ERR_FAIL_COND(save_err != OK);
  492. }
  493. bool GDMono::metadata_is_api_assembly_invalidated(APIAssembly::Type p_api_type) {
  494. String section = APIAssembly::to_string(p_api_type);
  495. Ref<ConfigFile> metadata;
  496. metadata.instance();
  497. metadata->load(_get_api_assembly_metadata_path());
  498. String assembly_path = GodotSharpDirs::get_res_assemblies_dir()
  499. .plus_file(p_api_type == APIAssembly::API_CORE ?
  500. CORE_API_ASSEMBLY_NAME ".dll" :
  501. EDITOR_API_ASSEMBLY_NAME ".dll");
  502. if (!FileAccess::exists(assembly_path))
  503. return false;
  504. uint64_t modified_time = FileAccess::get_modified_time(assembly_path);
  505. uint64_t stored_modified_time = metadata->get_value(section, "invalidated_asm_modified_time", 0);
  506. return metadata->get_value(section, "invalidated", false) && modified_time <= stored_modified_time;
  507. }
  508. #endif
  509. Error GDMono::_load_scripts_domain() {
  510. ERR_FAIL_COND_V(scripts_domain != NULL, ERR_BUG);
  511. print_verbose("Mono: Loading scripts domain...");
  512. scripts_domain = GDMonoUtils::create_domain("GodotEngine.ScriptsDomain");
  513. ERR_EXPLAIN("Mono: Could not create scripts app domain");
  514. ERR_FAIL_NULL_V(scripts_domain, ERR_CANT_CREATE);
  515. mono_domain_set(scripts_domain, true);
  516. return OK;
  517. }
  518. Error GDMono::_unload_scripts_domain() {
  519. ERR_FAIL_NULL_V(scripts_domain, ERR_BUG);
  520. print_verbose("Mono: Unloading scripts domain...");
  521. if (mono_domain_get() != root_domain)
  522. mono_domain_set(root_domain, true);
  523. mono_gc_collect(mono_gc_max_generation());
  524. finalizing_scripts_domain = true;
  525. if (!mono_domain_finalize(scripts_domain, 2000)) {
  526. ERR_PRINT("Mono: Domain finalization timeout");
  527. }
  528. finalizing_scripts_domain = false;
  529. mono_gc_collect(mono_gc_max_generation());
  530. _domain_assemblies_cleanup(mono_domain_get_id(scripts_domain));
  531. core_api_assembly = NULL;
  532. project_assembly = NULL;
  533. #ifdef TOOLS_ENABLED
  534. editor_api_assembly = NULL;
  535. #endif
  536. core_api_assembly_out_of_sync = false;
  537. editor_api_assembly_out_of_sync = false;
  538. MonoDomain *domain = scripts_domain;
  539. scripts_domain = NULL;
  540. MonoException *exc = NULL;
  541. mono_domain_try_unload(domain, (MonoObject **)&exc);
  542. if (exc) {
  543. ERR_PRINT("Exception thrown when unloading scripts domain");
  544. GDMonoUtils::debug_unhandled_exception(exc);
  545. return FAILED;
  546. }
  547. return OK;
  548. }
  549. #ifdef TOOLS_ENABLED
  550. Error GDMono::_load_tools_domain() {
  551. ERR_FAIL_COND_V(tools_domain != NULL, ERR_BUG);
  552. print_verbose("Mono: Loading tools domain...");
  553. tools_domain = GDMonoUtils::create_domain("GodotEngine.ToolsDomain");
  554. ERR_EXPLAIN("Mono: Could not create tools app domain");
  555. ERR_FAIL_NULL_V(tools_domain, ERR_CANT_CREATE);
  556. return OK;
  557. }
  558. #endif
  559. #ifdef TOOLS_ENABLED
  560. Error GDMono::reload_scripts_domain() {
  561. ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG);
  562. if (scripts_domain) {
  563. Error err = _unload_scripts_domain();
  564. if (err != OK) {
  565. ERR_PRINT("Mono: Failed to unload scripts domain");
  566. return err;
  567. }
  568. }
  569. Error err = _load_scripts_domain();
  570. if (err != OK) {
  571. ERR_PRINT("Mono: Failed to load scripts domain");
  572. return err;
  573. }
  574. #ifdef MONO_GLUE_ENABLED
  575. if (!_load_api_assemblies()) {
  576. if ((core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated)) ||
  577. (editor_api_assembly && editor_api_assembly_out_of_sync)) {
  578. // The assembly was successfully loaded, but the full api could not be cached.
  579. // This is most likely an outdated assembly loaded because of an invalid version in the
  580. // metadata, so we invalidate the version in the metadata and unload the script domain.
  581. if (core_api_assembly_out_of_sync) {
  582. ERR_PRINT("The loaded Core API assembly is out of sync");
  583. metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
  584. } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) {
  585. ERR_PRINT("The loaded Core API assembly is in sync, but the cache update failed");
  586. metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
  587. }
  588. if (editor_api_assembly_out_of_sync) {
  589. ERR_PRINT("The loaded Editor API assembly is out of sync");
  590. metadata_set_api_assembly_invalidated(APIAssembly::API_EDITOR, true);
  591. }
  592. Error err = _unload_scripts_domain();
  593. if (err != OK) {
  594. WARN_PRINT("Mono: Failed to unload scripts domain");
  595. }
  596. return ERR_CANT_RESOLVE;
  597. } else {
  598. return ERR_CANT_OPEN;
  599. }
  600. }
  601. if (!_load_project_assembly()) {
  602. return ERR_CANT_OPEN;
  603. }
  604. #else
  605. print_verbose("Mono: Glue disabled, ignoring script assemblies.");
  606. #endif // MONO_GLUE_ENABLED
  607. return OK;
  608. }
  609. #endif
  610. Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
  611. CRASH_COND(p_domain == NULL);
  612. String domain_name = mono_domain_get_friendly_name(p_domain);
  613. print_verbose("Mono: Unloading domain `" + domain_name + "`...");
  614. if (mono_domain_get() == p_domain)
  615. mono_domain_set(root_domain, true);
  616. mono_gc_collect(mono_gc_max_generation());
  617. if (!mono_domain_finalize(p_domain, 2000)) {
  618. ERR_PRINT("Mono: Domain finalization timeout");
  619. }
  620. mono_gc_collect(mono_gc_max_generation());
  621. _domain_assemblies_cleanup(mono_domain_get_id(p_domain));
  622. MonoException *exc = NULL;
  623. mono_domain_try_unload(p_domain, (MonoObject **)&exc);
  624. if (exc) {
  625. ERR_PRINTS("Exception thrown when unloading domain `" + domain_name + "`");
  626. GDMonoUtils::debug_unhandled_exception(exc);
  627. return FAILED;
  628. }
  629. return OK;
  630. }
  631. GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
  632. MonoImage *image = mono_class_get_image(p_raw_class);
  633. if (image == corlib_assembly->get_image())
  634. return corlib_assembly->get_class(p_raw_class);
  635. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  636. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
  637. const String *k = NULL;
  638. while ((k = domain_assemblies.next(k))) {
  639. GDMonoAssembly *assembly = domain_assemblies.get(*k);
  640. if (assembly->get_image() == image) {
  641. GDMonoClass *klass = assembly->get_class(p_raw_class);
  642. if (klass)
  643. return klass;
  644. }
  645. }
  646. return NULL;
  647. }
  648. void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) {
  649. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id];
  650. const String *k = NULL;
  651. while ((k = domain_assemblies.next(k))) {
  652. memdelete(domain_assemblies.get(*k));
  653. }
  654. assemblies.erase(p_domain_id);
  655. }
  656. void GDMono::unhandled_exception_hook(MonoObject *p_exc, void *) {
  657. // This method will be called by the runtime when a thrown exception is not handled.
  658. // It won't be called when we manually treat a thrown exception as unhandled.
  659. // We assume the exception was already printed before calling this hook.
  660. #ifdef DEBUG_ENABLED
  661. GDMonoUtils::debug_send_unhandled_exception_error((MonoException *)p_exc);
  662. if (ScriptDebugger::get_singleton())
  663. ScriptDebugger::get_singleton()->idle_poll();
  664. #endif
  665. abort();
  666. _UNREACHABLE_();
  667. }
  668. GDMono::GDMono() {
  669. singleton = this;
  670. gdmono_log = memnew(GDMonoLog);
  671. runtime_initialized = false;
  672. finalizing_scripts_domain = false;
  673. root_domain = NULL;
  674. scripts_domain = NULL;
  675. #ifdef TOOLS_ENABLED
  676. tools_domain = NULL;
  677. #endif
  678. core_api_assembly_out_of_sync = false;
  679. editor_api_assembly_out_of_sync = false;
  680. corlib_assembly = NULL;
  681. core_api_assembly = NULL;
  682. project_assembly = NULL;
  683. #ifdef TOOLS_ENABLED
  684. editor_api_assembly = NULL;
  685. editor_tools_assembly = NULL;
  686. #endif
  687. #ifdef DEBUG_METHODS_ENABLED
  688. api_core_hash = 0;
  689. #ifdef TOOLS_ENABLED
  690. api_editor_hash = 0;
  691. #endif
  692. #endif
  693. }
  694. GDMono::~GDMono() {
  695. if (is_runtime_initialized()) {
  696. if (scripts_domain) {
  697. Error err = _unload_scripts_domain();
  698. if (err != OK) {
  699. WARN_PRINT("Mono: Failed to unload scripts domain");
  700. }
  701. }
  702. const uint32_t *k = NULL;
  703. while ((k = assemblies.next(k))) {
  704. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies.get(*k);
  705. const String *kk = NULL;
  706. while ((kk = domain_assemblies.next(kk))) {
  707. memdelete(domain_assemblies.get(*kk));
  708. }
  709. }
  710. assemblies.clear();
  711. GDMonoUtils::clear_cache();
  712. print_verbose("Mono: Runtime cleanup...");
  713. mono_jit_cleanup(root_domain);
  714. runtime_initialized = false;
  715. }
  716. if (gdmono_log)
  717. memdelete(gdmono_log);
  718. singleton = NULL;
  719. }
  720. _GodotSharp *_GodotSharp::singleton = NULL;
  721. void _GodotSharp::attach_thread() {
  722. GDMonoUtils::attach_current_thread();
  723. }
  724. void _GodotSharp::detach_thread() {
  725. GDMonoUtils::detach_current_thread();
  726. }
  727. int32_t _GodotSharp::get_domain_id() {
  728. MonoDomain *domain = mono_domain_get();
  729. CRASH_COND(!domain); // User must check if runtime is initialized before calling this method
  730. return mono_domain_get_id(domain);
  731. }
  732. int32_t _GodotSharp::get_scripts_domain_id() {
  733. MonoDomain *domain = SCRIPTS_DOMAIN;
  734. CRASH_COND(!domain); // User must check if scripts domain is loaded before calling this method
  735. return mono_domain_get_id(domain);
  736. }
  737. bool _GodotSharp::is_scripts_domain_loaded() {
  738. return GDMono::get_singleton()->is_runtime_initialized() && SCRIPTS_DOMAIN != NULL;
  739. }
  740. bool _GodotSharp::_is_domain_finalizing_for_unload(int32_t p_domain_id) {
  741. return is_domain_finalizing_for_unload(p_domain_id);
  742. }
  743. bool _GodotSharp::is_domain_finalizing_for_unload() {
  744. return is_domain_finalizing_for_unload(mono_domain_get());
  745. }
  746. bool _GodotSharp::is_domain_finalizing_for_unload(int32_t p_domain_id) {
  747. return is_domain_finalizing_for_unload(mono_domain_get_by_id(p_domain_id));
  748. }
  749. bool _GodotSharp::is_domain_finalizing_for_unload(MonoDomain *p_domain) {
  750. if (!p_domain)
  751. return true;
  752. if (p_domain == SCRIPTS_DOMAIN && GDMono::get_singleton()->is_finalizing_scripts_domain())
  753. return true;
  754. return mono_domain_is_unloading(p_domain);
  755. }
  756. bool _GodotSharp::is_runtime_shutting_down() {
  757. return mono_runtime_is_shutting_down();
  758. }
  759. bool _GodotSharp::is_runtime_initialized() {
  760. return GDMono::get_singleton()->is_runtime_initialized();
  761. }
  762. void _GodotSharp::_bind_methods() {
  763. ClassDB::bind_method(D_METHOD("attach_thread"), &_GodotSharp::attach_thread);
  764. ClassDB::bind_method(D_METHOD("detach_thread"), &_GodotSharp::detach_thread);
  765. ClassDB::bind_method(D_METHOD("get_domain_id"), &_GodotSharp::get_domain_id);
  766. ClassDB::bind_method(D_METHOD("get_scripts_domain_id"), &_GodotSharp::get_scripts_domain_id);
  767. ClassDB::bind_method(D_METHOD("is_scripts_domain_loaded"), &_GodotSharp::is_scripts_domain_loaded);
  768. ClassDB::bind_method(D_METHOD("is_domain_finalizing_for_unload", "domain_id"), &_GodotSharp::_is_domain_finalizing_for_unload);
  769. ClassDB::bind_method(D_METHOD("is_runtime_shutting_down"), &_GodotSharp::is_runtime_shutting_down);
  770. ClassDB::bind_method(D_METHOD("is_runtime_initialized"), &_GodotSharp::is_runtime_initialized);
  771. }
  772. _GodotSharp::_GodotSharp() {
  773. singleton = this;
  774. queue_empty = true;
  775. #ifndef NO_THREADS
  776. queue_mutex = Mutex::create();
  777. #endif
  778. }
  779. _GodotSharp::~_GodotSharp() {
  780. singleton = NULL;
  781. if (queue_mutex) {
  782. memdelete(queue_mutex);
  783. }
  784. }