gd_mono.cpp 31 KB

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