2
0

gd_mono.cpp 47 KB

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