gd_mono.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. /*************************************************************************/
  2. /* gd_mono.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 "os/dir_access.h"
  36. #include "os/file_access.h"
  37. #include "os/os.h"
  38. #include "os/thread.h"
  39. #include "project_settings.h"
  40. #include "../csharp_script.h"
  41. #include "../utils/path_utils.h"
  42. #include "gd_mono_utils.h"
  43. #ifdef TOOLS_ENABLED
  44. #include "../editor/godotsharp_editor.h"
  45. #endif
  46. void gdmono_unhandled_exception_hook(MonoObject *exc, void *user_data) {
  47. (void)user_data; // UNUSED
  48. ERR_PRINT(GDMonoUtils::get_exception_name_and_message(exc).utf8());
  49. mono_print_unhandled_exception(exc);
  50. abort();
  51. }
  52. #ifdef MONO_PRINT_HANDLER_ENABLED
  53. void gdmono_MonoPrintCallback(const char *string, mono_bool is_stdout) {
  54. if (is_stdout) {
  55. OS::get_singleton()->print(string);
  56. } else {
  57. OS::get_singleton()->printerr(string);
  58. }
  59. }
  60. #endif
  61. GDMono *GDMono::singleton = NULL;
  62. #ifdef DEBUG_ENABLED
  63. static bool _wait_for_debugger_msecs(uint32_t p_msecs) {
  64. do {
  65. if (mono_is_debugger_attached())
  66. return true;
  67. int last_tick = OS::get_singleton()->get_ticks_msec();
  68. OS::get_singleton()->delay_usec((p_msecs < 25 ? p_msecs : 25) * 1000);
  69. int tdiff = OS::get_singleton()->get_ticks_msec() - last_tick;
  70. if (tdiff > p_msecs) {
  71. p_msecs = 0;
  72. } else {
  73. p_msecs -= tdiff;
  74. }
  75. } while (p_msecs > 0);
  76. return mono_is_debugger_attached();
  77. }
  78. #endif
  79. #ifdef TOOLS_ENABLED
  80. // temporary workaround. should be provided from Main::setup/setup2 instead
  81. bool _is_project_manager_requested() {
  82. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  83. for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) {
  84. const String &arg = E->get();
  85. if (arg == "-p" || arg == "--project-manager")
  86. return true;
  87. }
  88. return false;
  89. }
  90. #endif
  91. #ifdef DEBUG_ENABLED
  92. void gdmono_debug_init() {
  93. mono_debug_init(MONO_DEBUG_FORMAT_MONO);
  94. int da_port = GLOBAL_DEF("mono/debugger_agent/port", 23685);
  95. bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
  96. int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
  97. #ifdef TOOLS_ENABLED
  98. if (Engine::get_singleton()->is_editor_hint() ||
  99. ProjectSettings::get_singleton()->get_resource_path().empty() ||
  100. _is_project_manager_requested()) {
  101. return;
  102. }
  103. #endif
  104. CharString da_args = String("--debugger-agent=transport=dt_socket,address=127.0.0.1:" + itos(da_port) +
  105. ",embedding=1,server=y,suspend=" + (da_suspend ? "y,timeout=" + itos(da_timeout) : "n"))
  106. .utf8();
  107. // --debugger-agent=help
  108. const char *options[] = {
  109. "--soft-breakpoints",
  110. da_args.get_data()
  111. };
  112. mono_jit_parse_options(2, (char **)options);
  113. }
  114. #endif
  115. void GDMono::initialize() {
  116. ERR_FAIL_NULL(Engine::get_singleton());
  117. OS::get_singleton()->print("Mono: Initializing module...\n");
  118. #ifdef DEBUG_METHODS_ENABLED
  119. _initialize_and_check_api_hashes();
  120. #endif
  121. GDMonoLog::get_singleton()->initialize();
  122. #ifdef MONO_PRINT_HANDLER_ENABLED
  123. mono_trace_set_print_handler(gdmono_MonoPrintCallback);
  124. mono_trace_set_printerr_handler(gdmono_MonoPrintCallback);
  125. #endif
  126. #ifdef WINDOWS_ENABLED
  127. mono_reg_info = MonoRegUtils::find_mono();
  128. CharString assembly_dir;
  129. CharString config_dir;
  130. if (mono_reg_info.assembly_dir.length() && DirAccess::exists(mono_reg_info.assembly_dir)) {
  131. assembly_dir = mono_reg_info.assembly_dir.utf8();
  132. }
  133. if (mono_reg_info.config_dir.length() && DirAccess::exists(mono_reg_info.config_dir)) {
  134. config_dir = mono_reg_info.config_dir.utf8();
  135. }
  136. mono_set_dirs(assembly_dir.length() ? assembly_dir.get_data() : NULL,
  137. config_dir.length() ? config_dir.get_data() : NULL);
  138. #else
  139. mono_set_dirs(NULL, NULL);
  140. #endif
  141. GDMonoAssembly::initialize();
  142. #ifdef DEBUG_ENABLED
  143. gdmono_debug_init();
  144. #endif
  145. mono_config_parse(NULL);
  146. root_domain = mono_jit_init_version("GodotEngine.RootDomain", "v4.0.30319");
  147. ERR_EXPLAIN("Mono: Failed to initialize runtime");
  148. ERR_FAIL_NULL(root_domain);
  149. GDMonoUtils::set_main_thread(GDMonoUtils::get_current_thread());
  150. runtime_initialized = true;
  151. OS::get_singleton()->print("Mono: Runtime initialized\n");
  152. // mscorlib assembly MUST be present at initialization
  153. ERR_EXPLAIN("Mono: Failed to load mscorlib assembly");
  154. ERR_FAIL_COND(!_load_corlib_assembly());
  155. #ifdef TOOLS_ENABLED
  156. // The tools domain must be loaded here, before the scripts domain.
  157. // Otherwise domain unload on the scripts domain will hang indefinitely.
  158. ERR_EXPLAIN("Mono: Failed to load tools domain");
  159. ERR_FAIL_COND(_load_tools_domain() != OK);
  160. // TODO move to editor init callback, and do it lazily when required before editor init (e.g.: bindings generation)
  161. ERR_EXPLAIN("Mono: Failed to load Editor Tools assembly");
  162. ERR_FAIL_COND(!_load_editor_tools_assembly());
  163. #endif
  164. ERR_EXPLAIN("Mono: Failed to load scripts domain");
  165. ERR_FAIL_COND(_load_scripts_domain() != OK);
  166. #ifdef DEBUG_ENABLED
  167. bool debugger_attached = _wait_for_debugger_msecs(500);
  168. if (!debugger_attached && OS::get_singleton()->is_stdout_verbose())
  169. OS::get_singleton()->printerr("Mono: Debugger wait timeout\n");
  170. #endif
  171. _register_internal_calls();
  172. // The following assemblies are not required at initialization
  173. _load_all_script_assemblies();
  174. mono_install_unhandled_exception_hook(gdmono_unhandled_exception_hook, NULL);
  175. OS::get_singleton()->print("Mono: ALL IS GOOD\n");
  176. }
  177. #ifndef MONO_GLUE_DISABLED
  178. namespace GodotSharpBindings {
  179. uint64_t get_core_api_hash();
  180. uint64_t get_editor_api_hash();
  181. void register_generated_icalls();
  182. } // namespace GodotSharpBindings
  183. #endif
  184. void GDMono::_register_internal_calls() {
  185. #ifndef MONO_GLUE_DISABLED
  186. GodotSharpBindings::register_generated_icalls();
  187. #endif
  188. #ifdef TOOLS_ENABLED
  189. GodotSharpBuilds::_register_internal_calls();
  190. #endif
  191. }
  192. #ifdef DEBUG_METHODS_ENABLED
  193. void GDMono::_initialize_and_check_api_hashes() {
  194. api_core_hash = ClassDB::get_api_hash(ClassDB::API_CORE);
  195. #ifndef MONO_GLUE_DISABLED
  196. if (api_core_hash != GodotSharpBindings::get_core_api_hash()) {
  197. ERR_PRINT("Mono: Core API hash mismatch!");
  198. }
  199. #endif
  200. #ifdef TOOLS_ENABLED
  201. api_editor_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR);
  202. #ifndef MONO_GLUE_DISABLED
  203. if (api_editor_hash != GodotSharpBindings::get_editor_api_hash()) {
  204. ERR_PRINT("Mono: Editor API hash mismatch!");
  205. }
  206. #endif
  207. #endif // TOOLS_ENABLED
  208. }
  209. #endif // DEBUG_METHODS_ENABLED
  210. void GDMono::add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly) {
  211. assemblies[p_domain_id][p_assembly->get_name()] = p_assembly;
  212. }
  213. GDMonoAssembly **GDMono::get_loaded_assembly(const String &p_name) {
  214. MonoDomain *domain = mono_domain_get();
  215. uint32_t domain_id = domain ? mono_domain_get_id(domain) : 0;
  216. return assemblies[domain_id].getptr(p_name);
  217. }
  218. bool GDMono::_load_assembly(const String &p_name, GDMonoAssembly **r_assembly) {
  219. CRASH_COND(!r_assembly);
  220. if (OS::get_singleton()->is_stdout_verbose())
  221. OS::get_singleton()->print((String() + "Mono: Loading assembly " + p_name + "...\n").utf8());
  222. MonoImageOpenStatus status = MONO_IMAGE_OK;
  223. MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
  224. MonoAssembly *assembly = mono_assembly_load_full(aname, NULL, &status, false);
  225. mono_assembly_name_free(aname);
  226. if (!assembly)
  227. return false;
  228. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  229. GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name);
  230. ERR_FAIL_COND_V(status != MONO_IMAGE_OK, false);
  231. ERR_FAIL_COND_V(stored_assembly == NULL, false);
  232. ERR_FAIL_COND_V((*stored_assembly)->get_assembly() != assembly, false);
  233. *r_assembly = *stored_assembly;
  234. if (OS::get_singleton()->is_stdout_verbose())
  235. OS::get_singleton()->print(String("Mono: Assembly " + p_name + " loaded from path: " + (*r_assembly)->get_path() + "\n").utf8());
  236. return true;
  237. }
  238. bool GDMono::_load_corlib_assembly() {
  239. if (corlib_assembly)
  240. return true;
  241. bool success = _load_assembly("mscorlib", &corlib_assembly);
  242. if (success)
  243. GDMonoUtils::update_corlib_cache();
  244. return success;
  245. }
  246. bool GDMono::_load_core_api_assembly() {
  247. if (api_assembly)
  248. return true;
  249. bool success = _load_assembly(API_ASSEMBLY_NAME, &api_assembly);
  250. if (success)
  251. GDMonoUtils::update_godot_api_cache();
  252. return success;
  253. }
  254. #ifdef TOOLS_ENABLED
  255. bool GDMono::_load_editor_api_assembly() {
  256. if (editor_api_assembly)
  257. return true;
  258. return _load_assembly(EDITOR_API_ASSEMBLY_NAME, &editor_api_assembly);
  259. }
  260. #endif
  261. #ifdef TOOLS_ENABLED
  262. bool GDMono::_load_editor_tools_assembly() {
  263. if (editor_tools_assembly)
  264. return true;
  265. _GDMONO_SCOPE_DOMAIN_(tools_domain)
  266. return _load_assembly(EDITOR_TOOLS_ASSEMBLY_NAME, &editor_tools_assembly);
  267. }
  268. #endif
  269. bool GDMono::_load_project_assembly() {
  270. if (project_assembly)
  271. return true;
  272. String name = ProjectSettings::get_singleton()->get("application/config/name");
  273. if (name.empty()) {
  274. name = "UnnamedProject";
  275. }
  276. bool success = _load_assembly(name, &project_assembly);
  277. if (success)
  278. mono_assembly_set_main(project_assembly->get_assembly());
  279. return success;
  280. }
  281. bool GDMono::_load_all_script_assemblies() {
  282. #ifndef MONO_GLUE_DISABLED
  283. if (!_load_core_api_assembly()) {
  284. if (OS::get_singleton()->is_stdout_verbose())
  285. OS::get_singleton()->printerr("Mono: Failed to load Core API assembly\n");
  286. return false;
  287. } else {
  288. #ifdef TOOLS_ENABLED
  289. if (!_load_editor_api_assembly()) {
  290. if (OS::get_singleton()->is_stdout_verbose())
  291. OS::get_singleton()->printerr("Mono: Failed to load Editor API assembly\n");
  292. return false;
  293. }
  294. #endif
  295. }
  296. if (!_load_project_assembly()) {
  297. if (OS::get_singleton()->is_stdout_verbose())
  298. OS::get_singleton()->printerr("Mono: Failed to load project assembly\n");
  299. return false;
  300. }
  301. return true;
  302. #else
  303. if (OS::get_singleton()->is_stdout_verbose())
  304. OS::get_singleton()->print("Mono: Glue disbled, ignoring script assemblies\n");
  305. return true;
  306. #endif
  307. }
  308. Error GDMono::_load_scripts_domain() {
  309. ERR_FAIL_COND_V(scripts_domain != NULL, ERR_BUG);
  310. if (OS::get_singleton()->is_stdout_verbose()) {
  311. OS::get_singleton()->print("Mono: Loading scripts domain...\n");
  312. }
  313. scripts_domain = GDMonoUtils::create_domain("GodotEngine.ScriptsDomain");
  314. ERR_EXPLAIN("Mono: Could not create scripts app domain");
  315. ERR_FAIL_NULL_V(scripts_domain, ERR_CANT_CREATE);
  316. mono_domain_set(scripts_domain, true);
  317. return OK;
  318. }
  319. Error GDMono::_unload_scripts_domain() {
  320. ERR_FAIL_NULL_V(scripts_domain, ERR_BUG);
  321. if (OS::get_singleton()->is_stdout_verbose()) {
  322. OS::get_singleton()->print("Mono: Unloading scripts domain...\n");
  323. }
  324. _GodotSharp::get_singleton()->_dispose_callback();
  325. if (mono_domain_get() != root_domain)
  326. mono_domain_set(root_domain, true);
  327. mono_gc_collect(mono_gc_max_generation());
  328. finalizing_scripts_domain = true;
  329. mono_domain_finalize(scripts_domain, 2000);
  330. finalizing_scripts_domain = false;
  331. mono_gc_collect(mono_gc_max_generation());
  332. _domain_assemblies_cleanup(mono_domain_get_id(scripts_domain));
  333. api_assembly = NULL;
  334. project_assembly = NULL;
  335. #ifdef TOOLS_ENABLED
  336. editor_api_assembly = NULL;
  337. #endif
  338. MonoDomain *domain = scripts_domain;
  339. scripts_domain = NULL;
  340. _GodotSharp::get_singleton()->_dispose_callback();
  341. MonoObject *ex = NULL;
  342. mono_domain_try_unload(domain, &ex);
  343. if (ex) {
  344. ERR_PRINT("Exception thrown when unloading scripts domain:");
  345. mono_print_unhandled_exception(ex);
  346. return FAILED;
  347. }
  348. return OK;
  349. }
  350. #ifdef TOOLS_ENABLED
  351. Error GDMono::_load_tools_domain() {
  352. ERR_FAIL_COND_V(tools_domain != NULL, ERR_BUG);
  353. if (OS::get_singleton()->is_stdout_verbose()) {
  354. OS::get_singleton()->print("Mono: Loading tools domain...\n");
  355. }
  356. tools_domain = GDMonoUtils::create_domain("GodotEngine.ToolsDomain");
  357. ERR_EXPLAIN("Mono: Could not create tools app domain");
  358. ERR_FAIL_NULL_V(tools_domain, ERR_CANT_CREATE);
  359. return OK;
  360. }
  361. #endif
  362. #ifdef TOOLS_ENABLED
  363. Error GDMono::reload_scripts_domain() {
  364. ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG);
  365. if (scripts_domain) {
  366. Error err = _unload_scripts_domain();
  367. if (err != OK) {
  368. ERR_PRINT("Mono: Failed to unload scripts domain");
  369. return err;
  370. }
  371. }
  372. Error err = _load_scripts_domain();
  373. if (err != OK) {
  374. ERR_PRINT("Mono: Failed to load scripts domain");
  375. return err;
  376. }
  377. if (!_load_all_script_assemblies()) {
  378. if (OS::get_singleton()->is_stdout_verbose())
  379. OS::get_singleton()->printerr("Mono: Failed to load script assemblies\n");
  380. return ERR_CANT_OPEN;
  381. }
  382. return OK;
  383. }
  384. #endif
  385. GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
  386. MonoImage *image = mono_class_get_image(p_raw_class);
  387. if (image == corlib_assembly->get_image())
  388. return corlib_assembly->get_class(p_raw_class);
  389. uint32_t domain_id = mono_domain_get_id(mono_domain_get());
  390. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
  391. const String *k = NULL;
  392. while ((k = domain_assemblies.next(k))) {
  393. GDMonoAssembly *assembly = domain_assemblies.get(*k);
  394. if (assembly->get_image() == image) {
  395. GDMonoClass *klass = assembly->get_class(p_raw_class);
  396. if (klass)
  397. return klass;
  398. }
  399. }
  400. return NULL;
  401. }
  402. void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) {
  403. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id];
  404. const String *k = NULL;
  405. while ((k = domain_assemblies.next(k))) {
  406. memdelete(domain_assemblies.get(*k));
  407. }
  408. assemblies.erase(p_domain_id);
  409. }
  410. GDMono::GDMono() {
  411. singleton = this;
  412. gdmono_log = memnew(GDMonoLog);
  413. runtime_initialized = false;
  414. finalizing_scripts_domain = false;
  415. root_domain = NULL;
  416. scripts_domain = NULL;
  417. #ifdef TOOLS_ENABLED
  418. tools_domain = NULL;
  419. #endif
  420. corlib_assembly = NULL;
  421. api_assembly = NULL;
  422. project_assembly = NULL;
  423. #ifdef TOOLS_ENABLED
  424. editor_api_assembly = NULL;
  425. editor_tools_assembly = NULL;
  426. #endif
  427. #ifdef DEBUG_METHODS_ENABLED
  428. api_core_hash = 0;
  429. #ifdef TOOLS_ENABLED
  430. api_editor_hash = 0;
  431. #endif
  432. #endif
  433. }
  434. GDMono::~GDMono() {
  435. if (runtime_initialized) {
  436. if (scripts_domain) {
  437. Error err = _unload_scripts_domain();
  438. if (err != OK) {
  439. WARN_PRINT("Mono: Failed to unload scripts domain");
  440. }
  441. }
  442. const uint32_t *k = NULL;
  443. while ((k = assemblies.next(k))) {
  444. HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies.get(*k);
  445. const String *kk = NULL;
  446. while ((kk = domain_assemblies.next(kk))) {
  447. memdelete(domain_assemblies.get(*kk));
  448. }
  449. }
  450. assemblies.clear();
  451. GDMonoUtils::clear_cache();
  452. OS::get_singleton()->print("Mono: Runtime cleanup...\n");
  453. runtime_initialized = false;
  454. mono_jit_cleanup(root_domain);
  455. }
  456. if (gdmono_log)
  457. memdelete(gdmono_log);
  458. singleton = NULL;
  459. }
  460. _GodotSharp *_GodotSharp::singleton = NULL;
  461. void _GodotSharp::_dispose_object(Object *p_object) {
  462. if (p_object->get_script_instance()) {
  463. CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  464. if (cs_instance) {
  465. cs_instance->mono_object_disposed();
  466. return;
  467. }
  468. }
  469. // Unsafe refcount decrement. The managed instance also counts as a reference.
  470. // See: CSharpLanguage::alloc_instance_binding_data(Object *p_object)
  471. if (Object::cast_to<Reference>(p_object)->unreference()) {
  472. memdelete(p_object);
  473. }
  474. }
  475. void _GodotSharp::_dispose_callback() {
  476. #ifndef NO_THREADS
  477. queue_mutex->lock();
  478. #endif
  479. for (List<Object *>::Element *E = obj_delete_queue.front(); E; E = E->next()) {
  480. _dispose_object(E->get());
  481. }
  482. for (List<NodePath *>::Element *E = np_delete_queue.front(); E; E = E->next()) {
  483. memdelete(E->get());
  484. }
  485. for (List<RID *>::Element *E = rid_delete_queue.front(); E; E = E->next()) {
  486. memdelete(E->get());
  487. }
  488. obj_delete_queue.clear();
  489. np_delete_queue.clear();
  490. rid_delete_queue.clear();
  491. queue_empty = true;
  492. #ifndef NO_THREADS
  493. queue_mutex->unlock();
  494. #endif
  495. }
  496. void _GodotSharp::attach_thread() {
  497. GDMonoUtils::attach_current_thread();
  498. }
  499. void _GodotSharp::detach_thread() {
  500. GDMonoUtils::detach_current_thread();
  501. }
  502. bool _GodotSharp::is_finalizing_domain() {
  503. return GDMono::get_singleton()->is_finalizing_scripts_domain();
  504. }
  505. bool _GodotSharp::is_domain_loaded() {
  506. return GDMono::get_singleton()->get_scripts_domain() != NULL;
  507. }
  508. #define ENQUEUE_FOR_DISPOSAL(m_queue, m_inst) \
  509. m_queue.push_back(m_inst); \
  510. if (queue_empty) { \
  511. queue_empty = false; \
  512. call_deferred("_dispose_callback"); \
  513. }
  514. void _GodotSharp::queue_dispose(Object *p_object) {
  515. if (GDMonoUtils::is_main_thread() && !GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  516. _dispose_object(p_object);
  517. } else {
  518. #ifndef NO_THREADS
  519. queue_mutex->lock();
  520. #endif
  521. ENQUEUE_FOR_DISPOSAL(obj_delete_queue, p_object);
  522. #ifndef NO_THREADS
  523. queue_mutex->unlock();
  524. #endif
  525. }
  526. }
  527. void _GodotSharp::queue_dispose(NodePath *p_node_path) {
  528. if (GDMonoUtils::is_main_thread() && !GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  529. memdelete(p_node_path);
  530. } else {
  531. #ifndef NO_THREADS
  532. queue_mutex->lock();
  533. #endif
  534. ENQUEUE_FOR_DISPOSAL(np_delete_queue, p_node_path);
  535. #ifndef NO_THREADS
  536. queue_mutex->unlock();
  537. #endif
  538. }
  539. }
  540. void _GodotSharp::queue_dispose(RID *p_rid) {
  541. if (GDMonoUtils::is_main_thread() && !GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  542. memdelete(p_rid);
  543. } else {
  544. #ifndef NO_THREADS
  545. queue_mutex->lock();
  546. #endif
  547. ENQUEUE_FOR_DISPOSAL(rid_delete_queue, p_rid);
  548. #ifndef NO_THREADS
  549. queue_mutex->unlock();
  550. #endif
  551. }
  552. }
  553. void _GodotSharp::_bind_methods() {
  554. ClassDB::bind_method(D_METHOD("attach_thread"), &_GodotSharp::attach_thread);
  555. ClassDB::bind_method(D_METHOD("detach_thread"), &_GodotSharp::detach_thread);
  556. ClassDB::bind_method(D_METHOD("is_finalizing_domain"), &_GodotSharp::is_finalizing_domain);
  557. ClassDB::bind_method(D_METHOD("is_domain_loaded"), &_GodotSharp::is_domain_loaded);
  558. ClassDB::bind_method(D_METHOD("_dispose_callback"), &_GodotSharp::_dispose_callback);
  559. }
  560. _GodotSharp::_GodotSharp() {
  561. singleton = this;
  562. queue_empty = true;
  563. #ifndef NO_THREADS
  564. queue_mutex = Mutex::create();
  565. #endif
  566. }
  567. _GodotSharp::~_GodotSharp() {
  568. singleton = NULL;
  569. if (queue_mutex) {
  570. memdelete(queue_mutex);
  571. }
  572. }