diff options
author | Ignacio Roldán Etcheverry <ignalfonsore@gmail.com> | 2021-09-12 20:21:15 +0200 |
---|---|---|
committer | Ignacio Roldán Etcheverry <ignalfonsore@gmail.com> | 2022-08-22 03:35:59 +0200 |
commit | 513ee857a938c466e0f7146f66db771b9c6e2024 (patch) | |
tree | 9b05c59a6d63f8cc18460e69c1a782ef6fe2713f /modules/mono/mono_gd | |
parent | 5e37d073bb86492e8c415964ffd554a2fa08920d (diff) |
C#: Restructure code prior move to .NET Core
The main focus here was to remove the majority of code that relied on
Mono's embedding APIs, specially the reflection APIs. The embedding
APIs we still use are the bare minimum we need for things to work.
A lot of code was moved to C#. We no longer deal with any managed
objects (`MonoObject*`, and such) in native code, and all marshaling
is done in C#.
The reason for restructuring the code and move away from embedding APIs
is that once we move to .NET Core, we will be limited by the much more
minimal .NET hosting.
PERFORMANCE REGRESSIONS
-----------------------
Some parts of the code were written with little to no concern about
performance. This includes code that calls into script methods and
accesses script fields, properties and events.
The reason for this is that all of that will be moved to source
generators, so any work prior to that would be a waste of time.
DISABLED FEATURES
-----------------
Some code was removed as it no longer makes sense (or won't make sense
in the future).
Other parts were commented out with `#if 0`s and TODO warnings because
it doesn't make much sense to work on them yet as those parts will
change heavily when we switch to .NET Core but also when we start
introducing source generators.
As such, the following features were disabled temporarily:
- Assembly-reloading (will be done with ALCs in .NET Core).
- Properties/fields exports and script method listing (will be
handled by source generators in the future).
- Exception logging in the editor and stack info for errors.
- Exporting games.
- Building of C# projects. We no longer copy the Godot API assemblies
to the project directory, so MSBuild won't be able to find them. The
idea is to turn them into NuGet packages in the future, which could
also be obtained from local NuGet sources during development.
Diffstat (limited to 'modules/mono/mono_gd')
26 files changed, 194 insertions, 3582 deletions
diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index bf387be4c8..ce4fc0c5a0 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -48,8 +48,6 @@ #include "../godotsharp_dirs.h" #include "../utils/path_utils.h" #include "gd_mono_cache.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" #include "gd_mono_utils.h" #ifdef ANDROID_ENABLED @@ -411,7 +409,9 @@ void GDMono::initialize_load_assemblies() { // Load assemblies. The API and tools assemblies are required, // the application is aborted if these assemblies cannot be loaded. - _load_api_assemblies(); + if (!_try_load_api_assemblies()) { + CRASH_NOW_MSG("Failed to load one of the API assemblies."); + } #if defined(TOOLS_ENABLED) bool tool_assemblies_loaded = _load_tools_assemblies(); @@ -432,24 +432,12 @@ void GDMono::initialize_load_assemblies() { } } -bool GDMono::_are_api_assemblies_out_of_sync() { - bool out_of_sync = core_api_assembly.assembly && (core_api_assembly.out_of_sync || !GDMonoCache::cached_data.godot_api_cache_updated); -#ifdef TOOLS_ENABLED - if (!out_of_sync) { - out_of_sync = editor_api_assembly.assembly && editor_api_assembly.out_of_sync; - } -#endif - return out_of_sync; -} - void godot_register_object_icalls(); -void godot_register_scene_tree_icalls(); void godot_register_placeholder_icalls(); void GDMono::_register_internal_calls() { // Registers internal calls that were not generated. godot_register_object_icalls(); - godot_register_scene_tree_icalls(); godot_register_placeholder_icalls(); } @@ -490,35 +478,35 @@ GDMonoAssembly *GDMono::get_loaded_assembly(const String &p_name) { return result ? *result : nullptr; } -bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly) { +bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly) { #ifdef DEBUG_ENABLED CRASH_COND(!r_assembly); #endif MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8()); - bool result = load_assembly(p_name, aname, r_assembly, p_refonly); + bool result = load_assembly(p_name, aname, r_assembly); mono_assembly_name_free(aname); mono_free(aname); return result; } -bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) { +bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly) { #ifdef DEBUG_ENABLED CRASH_COND(!r_assembly); #endif - return load_assembly(p_name, p_aname, r_assembly, p_refonly, GDMonoAssembly::get_default_search_dirs()); + return load_assembly(p_name, p_aname, r_assembly, GDMonoAssembly::get_default_search_dirs()); } -bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly, const Vector<String> &p_search_dirs) { +bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, const Vector<String> &p_search_dirs) { #ifdef DEBUG_ENABLED CRASH_COND(!r_assembly); #endif - print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "..."); + print_verbose("Mono: Loading assembly " + p_name + "..."); - GDMonoAssembly *assembly = GDMonoAssembly::load(p_name, p_aname, p_refonly, p_search_dirs); + GDMonoAssembly *assembly = GDMonoAssembly::load(p_name, p_aname, /* refonly: */ false, p_search_dirs); if (!assembly) { return false; @@ -526,17 +514,17 @@ bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMo *r_assembly = assembly; - print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path()); + print_verbose("Mono: Assembly " + p_name + " loaded from path: " + (*r_assembly)->get_path()); return true; } -bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly) { +bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly) { CRASH_COND(!r_assembly); - print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "..."); + print_verbose("Mono: Loading assembly " + p_name + "..."); - GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, p_refonly); + GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, /* refonly: */ false); if (!assembly) { return false; @@ -544,279 +532,41 @@ bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMo *r_assembly = assembly; - print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path()); + print_verbose("Mono: Assembly " + p_name + " loaded from path: " + (*r_assembly)->get_path()); return true; } -ApiAssemblyInfo::Version ApiAssemblyInfo::Version::get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, ApiAssemblyInfo::Type p_api_type) { - ApiAssemblyInfo::Version api_assembly_version; - - const char *nativecalls_name = p_api_type == ApiAssemblyInfo::API_CORE - ? BINDINGS_CLASS_NATIVECALLS - : BINDINGS_CLASS_NATIVECALLS_EDITOR; - - GDMonoClass *nativecalls_klass = p_api_assembly->get_class(BINDINGS_NAMESPACE, nativecalls_name); - - if (nativecalls_klass) { - GDMonoField *api_hash_field = nativecalls_klass->get_field("godot_api_hash"); - if (api_hash_field) { - api_assembly_version.godot_api_hash = GDMonoMarshal::unbox<uint64_t>(api_hash_field->get_value(nullptr)); - } - } - - return api_assembly_version; -} - -String ApiAssemblyInfo::to_string(ApiAssemblyInfo::Type p_type) { - return p_type == ApiAssemblyInfo::API_CORE ? "API_CORE" : "API_EDITOR"; -} - bool GDMono::_load_corlib_assembly() { if (corlib_assembly) { return true; } - bool success = load_assembly("mscorlib", &corlib_assembly); - - if (success) { - GDMonoCache::update_corlib_cache(); - } - - return success; -} - -#ifdef TOOLS_ENABLED -bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config) { - String src_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); - String dst_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config); - - String assembly_name = p_api_type == ApiAssemblyInfo::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME; - - // Create destination directory if needed - if (!DirAccess::exists(dst_dir)) { - Ref<DirAccess> da = DirAccess::create_for_path(dst_dir); - Error err = da->make_dir_recursive(dst_dir); - - if (err != OK) { - ERR_PRINT("Failed to create destination directory for the API assemblies. Error: " + itos(err) + "."); - return false; - } - } - - Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - - String xml_file = assembly_name + ".xml"; - if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK) { - WARN_PRINT("Failed to copy '" + xml_file + "'."); - } - - String pdb_file = assembly_name + ".pdb"; - if (da->copy(src_dir.plus_file(pdb_file), dst_dir.plus_file(pdb_file)) != OK) { - WARN_PRINT("Failed to copy '" + pdb_file + "'."); - } - - String assembly_file = assembly_name + ".dll"; - if (da->copy(src_dir.plus_file(assembly_file), dst_dir.plus_file(assembly_file)) != OK) { - ERR_PRINT("Failed to copy '" + assembly_file + "'."); - return false; - } - - return true; -} - -static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool &r_out_of_sync) { - String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); - String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - - if (!FileAccess::exists(core_api_assembly_path) || !FileAccess::exists(editor_api_assembly_path)) { - return false; - } - - String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg"); - - if (!FileAccess::exists(cached_api_hash_path)) { - return false; - } - - Ref<ConfigFile> cfg; - cfg.instantiate(); - Error cfg_err = cfg->load(cached_api_hash_path); - ERR_FAIL_COND_V(cfg_err != OK, false); - - // Checking the modified time is good enough - if (FileAccess::get_modified_time(core_api_assembly_path) != (uint64_t)cfg->get_value("core", "modified_time") || - FileAccess::get_modified_time(editor_api_assembly_path) != (uint64_t)cfg->get_value("editor", "modified_time")) { - return false; - } - - r_out_of_sync = GDMono::get_singleton()->get_api_core_hash() != (uint64_t)cfg->get_value("core", "api_hash") || - GDMono::get_singleton()->get_api_editor_hash() != (uint64_t)cfg->get_value("editor", "api_hash"); - - return true; -} - -static void create_cached_api_hash_for(const String &p_api_assemblies_dir) { - String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); - String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg"); - - Ref<ConfigFile> cfg; - cfg.instantiate(); - - cfg->set_value("core", "modified_time", FileAccess::get_modified_time(core_api_assembly_path)); - cfg->set_value("editor", "modified_time", FileAccess::get_modified_time(editor_api_assembly_path)); - - // This assumes the prebuilt api assemblies we copied to the project are not out of sync - cfg->set_value("core", "api_hash", GDMono::get_singleton()->get_api_core_hash()); - cfg->set_value("editor", "api_hash", GDMono::get_singleton()->get_api_editor_hash()); - - Error err = cfg->save(cached_api_hash_path); - ERR_FAIL_COND(err != OK); -} - -bool GDMono::_temp_domain_load_are_assemblies_out_of_sync(const String &p_config) { - MonoDomain *temp_domain = GDMonoUtils::create_domain("GodotEngine.Domain.CheckApiAssemblies"); - ERR_FAIL_NULL_V(temp_domain, "Failed to create temporary domain to check API assemblies"); - _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(temp_domain); - - _GDMONO_SCOPE_DOMAIN_(temp_domain); - - GDMono::LoadedApiAssembly temp_core_api_assembly; - GDMono::LoadedApiAssembly temp_editor_api_assembly; - - if (!_try_load_api_assemblies(temp_core_api_assembly, temp_editor_api_assembly, - p_config, /* refonly: */ true, /* loaded_callback: */ nullptr)) { - return temp_core_api_assembly.out_of_sync || temp_editor_api_assembly.out_of_sync; - } - - return true; // Failed to load, assume they're outdated assemblies -} - -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) { -#define FAIL_REASON(m_out_of_sync, m_prebuilt_exists) \ - ( \ - (m_out_of_sync ? String("The assembly is invalidated ") : String("The assembly was not found ")) + \ - (m_prebuilt_exists ? String("and the prebuilt assemblies are missing.") : String("and we failed to copy the prebuilt assemblies."))) - - String dst_assemblies_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config); - - String core_assembly_path = dst_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); - String editor_assembly_path = dst_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - - bool api_assemblies_out_of_sync = false; - - if (p_core_api_out_of_sync && p_editor_api_out_of_sync) { - api_assemblies_out_of_sync = *p_core_api_out_of_sync || *p_editor_api_out_of_sync; - } else if (FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) { - // Determine if they're out of sync - if (!try_get_cached_api_hash_for(dst_assemblies_dir, api_assemblies_out_of_sync)) { - api_assemblies_out_of_sync = _temp_domain_load_are_assemblies_out_of_sync(p_config); - } - } - - // Note: Even if only one of the assemblies if missing or out of sync, we update both - - if (!api_assemblies_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) { - return String(); // No update needed - } - - print_verbose("Updating '" + p_config + "' API assemblies"); - - String prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); - String prebuilt_core_dll_path = prebuilt_api_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); - String prebuilt_editor_dll_path = prebuilt_api_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - - if (!FileAccess::exists(prebuilt_core_dll_path) || !FileAccess::exists(prebuilt_editor_dll_path)) { - return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ false); - } - - // Copy the prebuilt Api - if (!copy_prebuilt_api_assembly(ApiAssemblyInfo::API_CORE, p_config) || - !copy_prebuilt_api_assembly(ApiAssemblyInfo::API_EDITOR, p_config)) { - return FAIL_REASON(api_assemblies_out_of_sync, /* prebuilt_exists: */ true); - } - - // Cache the api hash of the assemblies we just copied - create_cached_api_hash_for(dst_assemblies_dir); - - return String(); // Updated successfully - -#undef FAIL_REASON + return load_assembly("mscorlib", &corlib_assembly); } -#endif -bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) { - if (r_loaded_api_assembly.assembly) { +bool GDMono::_load_core_api_assembly(GDMonoAssembly **r_loaded_api_assembly, const String &p_config) { + if (*r_loaded_api_assembly) { return true; } -#ifdef TOOLS_ENABLED - // 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 - - // If running the project manager, load it from the prebuilt API directory - String assembly_dir = !Engine::get_singleton()->is_project_manager_hint() - ? GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) - : GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); - - String assembly_path = assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll"); - - bool success = FileAccess::exists(assembly_path) && - load_assembly_from(CORE_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly); -#else - bool success = load_assembly(CORE_API_ASSEMBLY_NAME, &r_loaded_api_assembly.assembly, p_refonly); -#endif - -#ifdef DEBUG_METHODS_ENABLED - if (success) { - ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_CORE); - r_loaded_api_assembly.out_of_sync = get_api_core_hash() != api_assembly_ver.godot_api_hash; - } else { - r_loaded_api_assembly.out_of_sync = false; - } -#else - r_loaded_api_assembly.out_of_sync = false; -#endif - - return success; + return load_assembly(CORE_API_ASSEMBLY_NAME, r_loaded_api_assembly); } #ifdef TOOLS_ENABLED -bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) { - if (r_loaded_api_assembly.assembly) { +bool GDMono::_load_editor_api_assembly(GDMonoAssembly **r_loaded_api_assembly, const String &p_config) { + if (*r_loaded_api_assembly) { return true; } - // 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 - - // If running the project manager, load it from the prebuilt API directory - String assembly_dir = !Engine::get_singleton()->is_project_manager_hint() - ? GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) - : GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config); - - String assembly_path = assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll"); - - bool success = FileAccess::exists(assembly_path) && - load_assembly_from(EDITOR_API_ASSEMBLY_NAME, assembly_path, &r_loaded_api_assembly.assembly, p_refonly); - -#ifdef DEBUG_METHODS_ENABLED - if (success) { - ApiAssemblyInfo::Version api_assembly_ver = ApiAssemblyInfo::Version::get_from_loaded_assembly(r_loaded_api_assembly.assembly, ApiAssemblyInfo::API_EDITOR); - r_loaded_api_assembly.out_of_sync = get_api_editor_hash() != api_assembly_ver.godot_api_hash; - } else { - r_loaded_api_assembly.out_of_sync = false; - } -#else - r_loaded_api_assembly.out_of_sync = false; -#endif - - return success; + return load_assembly(EDITOR_API_ASSEMBLY_NAME, r_loaded_api_assembly); } #endif -bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly, - const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback) { - if (!_load_core_api_assembly(r_core_api_assembly, p_config, p_refonly)) { +bool GDMono::_try_load_api_assemblies() { + String config = get_expected_api_build_config(); + + if (!_load_core_api_assembly(&core_api_assembly, config)) { if (OS::get_singleton()->is_stdout_verbose()) { print_error("Mono: Failed to load Core API assembly"); } @@ -824,30 +574,15 @@ bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, Lo } #ifdef TOOLS_ENABLED - if (!_load_editor_api_assembly(r_editor_api_assembly, p_config, p_refonly)) { + if (!_load_editor_api_assembly(&editor_api_assembly, config)) { if (OS::get_singleton()->is_stdout_verbose()) { print_error("Mono: Failed to load Editor API assembly"); } return false; } - - if (r_editor_api_assembly.out_of_sync) { - return false; - } #endif - // Check if the core API assembly is out of sync only after trying to load the - // editor API assembly. Otherwise, if both assemblies are out of sync, we would - // only update the former as we won't know the latter also needs to be updated. - if (r_core_api_assembly.out_of_sync) { - return false; - } - - if (p_callback) { - return p_callback(); - } - - return true; + return _on_core_api_assembly_loaded(); } bool GDMono::_on_core_api_assembly_loaded() { @@ -862,72 +597,14 @@ bool GDMono::_on_core_api_assembly_loaded() { return true; } -bool GDMono::_try_load_api_assemblies_preset() { - return _try_load_api_assemblies(core_api_assembly, editor_api_assembly, - get_expected_api_build_config(), /* refonly: */ false, _on_core_api_assembly_loaded); -} - -void GDMono::_load_api_assemblies() { - bool api_assemblies_loaded = _try_load_api_assemblies_preset(); - -#if defined(TOOLS_ENABLED) && !defined(GD_MONO_SINGLE_APPDOMAIN) - if (!api_assemblies_loaded) { - // The API assemblies are out of sync or some other error happened. Fine, try one more time, but - // this time update them from the prebuilt assemblies directory before trying to load them again. - - // Shouldn't happen. The project manager loads the prebuilt API assemblies - CRASH_COND_MSG(Engine::get_singleton()->is_project_manager_hint(), "Failed to load one of the prebuilt API assemblies."); - - // 1. Unload the scripts domain - Error domain_unload_err = _unload_scripts_domain(); - CRASH_COND_MSG(domain_unload_err != OK, "Mono: Failed to unload scripts domain."); - - // 2. Update the API assemblies - String update_error = update_api_assemblies_from_prebuilt("Debug", &core_api_assembly.out_of_sync, &editor_api_assembly.out_of_sync); - CRASH_COND_MSG(!update_error.is_empty(), update_error); - - // 3. Load the scripts domain again - Error domain_load_err = _load_scripts_domain(); - CRASH_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain."); - - // 4. Try loading the updated assemblies - api_assemblies_loaded = _try_load_api_assemblies_preset(); - } -#endif - - if (!api_assemblies_loaded) { - // welp... too bad - - if (_are_api_assemblies_out_of_sync()) { - if (core_api_assembly.out_of_sync) { - ERR_PRINT("The assembly '" CORE_API_ASSEMBLY_NAME "' is out of sync."); - } else if (!GDMonoCache::cached_data.godot_api_cache_updated) { - ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed."); - } - -#ifdef TOOLS_ENABLED - if (editor_api_assembly.out_of_sync) { - ERR_PRINT("The assembly '" EDITOR_API_ASSEMBLY_NAME "' is out of sync."); - } -#endif - - CRASH_NOW(); - } else { - CRASH_NOW_MSG("Failed to load one of the API assemblies."); - } - } -} - #ifdef TOOLS_ENABLED bool GDMono::_load_tools_assemblies() { if (tools_assembly && tools_project_editor_assembly) { return true; } - bool success = load_assembly(TOOLS_ASM_NAME, &tools_assembly) && - load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_assembly); - - return success; + return load_assembly(TOOLS_ASM_NAME, &tools_assembly) && + load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_assembly); } #endif @@ -946,7 +623,12 @@ bool GDMono::_load_project_assembly() { if (success) { mono_assembly_set_main(project_assembly->get_assembly()); - CSharpLanguage::get_singleton()->lookup_scripts_in_assembly(project_assembly); + MonoException *exc = nullptr; + GDMonoCache::cached_data.methodthunk_ScriptManagerBridge_LookupScriptsInAssembly.invoke( + mono_assembly_get_object(mono_domain_get(), project_assembly->get_assembly()), &exc); + if (exc) { + GDMonoUtils::debug_print_unhandled_exception(exc); + } } return success; @@ -955,11 +637,8 @@ bool GDMono::_load_project_assembly() { void GDMono::_install_trace_listener() { #ifdef DEBUG_ENABLED // Install the trace listener now before the project assembly is loaded - GDMonoClass *debug_utils = get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, "DebuggingUtils"); - GDMonoMethod *install_func = debug_utils->get_method("InstallTraceListener"); - MonoException *exc = nullptr; - install_func->invoke_raw(nullptr, nullptr, &exc); + GDMonoCache::cached_data.methodthunk_DebuggingUtils_InstallTraceListener.invoke(&exc); if (exc) { GDMonoUtils::debug_print_unhandled_exception(exc); ERR_PRINT("Failed to install 'System.Diagnostics.Trace' listener."); @@ -1007,9 +686,9 @@ Error GDMono::_unload_scripts_domain() { _domain_assemblies_cleanup(mono_domain_get_id(scripts_domain)); - core_api_assembly.assembly = nullptr; + core_api_assembly = nullptr; #ifdef TOOLS_ENABLED - editor_api_assembly.assembly = nullptr; + editor_api_assembly = nullptr; #endif project_assembly = nullptr; @@ -1051,7 +730,9 @@ Error GDMono::reload_scripts_domain() { // Load assemblies. The API and tools assemblies are required, // the application is aborted if these assemblies cannot be loaded. - _load_api_assemblies(); + if (!_try_load_api_assemblies()) { + CRASH_NOW_MSG("Failed to load one of the API assemblies."); + } #if defined(TOOLS_ENABLED) bool tools_assemblies_loaded = _load_tools_assemblies(); @@ -1104,49 +785,6 @@ Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) { } #endif -GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) { - MonoImage *image = mono_class_get_image(p_raw_class); - - if (image == corlib_assembly->get_image()) { - return corlib_assembly->get_class(p_raw_class); - } - - int32_t domain_id = mono_domain_get_id(mono_domain_get()); - HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id]; - - for (const KeyValue<String, GDMonoAssembly *> &E : domain_assemblies) { - GDMonoAssembly *assembly = E.value; - if (assembly->get_image() == image) { - GDMonoClass *klass = assembly->get_class(p_raw_class); - if (klass) { - return klass; - } - } - } - - return nullptr; -} - -GDMonoClass *GDMono::get_class(const StringName &p_namespace, const StringName &p_name) { - GDMonoClass *klass = corlib_assembly->get_class(p_namespace, p_name); - if (klass) { - return klass; - } - - int32_t domain_id = mono_domain_get_id(mono_domain_get()); - HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id]; - - for (const KeyValue<String, GDMonoAssembly *> &E : domain_assemblies) { - GDMonoAssembly *assembly = E.value; - klass = assembly->get_class(p_namespace, p_name); - if (klass) { - return klass; - } - } - - return nullptr; -} - void GDMono::_domain_assemblies_cleanup(int32_t p_domain_id) { HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id]; diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index bc871fe750..ac99aecabd 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -41,31 +41,6 @@ #include "../utils/mono_reg_utils.h" #endif -namespace ApiAssemblyInfo { -enum Type { - API_CORE, - API_EDITOR -}; - -struct Version { - uint64_t godot_api_hash = 0; - - bool operator==(const Version &p_other) const { - return godot_api_hash == p_other.godot_api_hash; - } - - Version() {} - - Version(uint64_t p_godot_api_hash) : - godot_api_hash(p_godot_api_hash) { - } - - static Version get_from_loaded_assembly(GDMonoAssembly *p_api_assembly, Type p_api_type); -}; - -String to_string(Type p_type); -} // namespace ApiAssemblyInfo - class GDMono { public: enum UnhandledExceptionPolicy { @@ -73,13 +48,6 @@ public: POLICY_LOG_ERROR }; - struct LoadedApiAssembly { - GDMonoAssembly *assembly = nullptr; - bool out_of_sync = false; - - LoadedApiAssembly() {} - }; - private: bool runtime_initialized; bool finalizing_scripts_domain; @@ -98,17 +66,12 @@ private: GDMonoAssembly *tools_project_editor_assembly = nullptr; #endif - LoadedApiAssembly core_api_assembly; - LoadedApiAssembly editor_api_assembly; - - typedef bool (*CoreApiAssemblyLoadedCallback)(); + GDMonoAssembly *core_api_assembly; + GDMonoAssembly *editor_api_assembly; - bool _are_api_assemblies_out_of_sync(); - bool _temp_domain_load_are_assemblies_out_of_sync(const String &p_config); - - bool _load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly); + bool _load_core_api_assembly(GDMonoAssembly **r_loaded_api_assembly, const String &p_config); #ifdef TOOLS_ENABLED - bool _load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly); + bool _load_editor_api_assembly(GDMonoAssembly **r_loaded_api_assembly, const String &p_config); #endif static bool _on_core_api_assembly_loaded(); @@ -119,10 +82,7 @@ private: #endif bool _load_project_assembly(); - bool _try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly, - const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback); - bool _try_load_api_assemblies_preset(); - void _load_api_assemblies(); + bool _try_load_api_assemblies(); void _install_trace_listener(); @@ -184,11 +144,6 @@ public: #endif } -#ifdef TOOLS_ENABLED - bool copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config); - String update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync = nullptr, const bool *p_editor_api_out_of_sync = nullptr); -#endif - static GDMono *get_singleton() { return singleton; } [[noreturn]] static void unhandled_exception_hook(MonoObject *p_exc, void *p_user_data); @@ -206,29 +161,24 @@ public: _FORCE_INLINE_ MonoDomain *get_scripts_domain() { return scripts_domain; } _FORCE_INLINE_ GDMonoAssembly *get_corlib_assembly() const { return corlib_assembly; } - _FORCE_INLINE_ GDMonoAssembly *get_core_api_assembly() const { return core_api_assembly.assembly; } + _FORCE_INLINE_ GDMonoAssembly *get_core_api_assembly() const { return core_api_assembly; } _FORCE_INLINE_ GDMonoAssembly *get_project_assembly() const { return project_assembly; } #ifdef TOOLS_ENABLED - _FORCE_INLINE_ GDMonoAssembly *get_editor_api_assembly() const { return editor_api_assembly.assembly; } _FORCE_INLINE_ GDMonoAssembly *get_tools_assembly() const { return tools_assembly; } - _FORCE_INLINE_ GDMonoAssembly *get_tools_project_editor_assembly() const { return tools_project_editor_assembly; } #endif #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED) const MonoRegInfo &get_mono_reg_info() { return mono_reg_info; } #endif - GDMonoClass *get_class(MonoClass *p_raw_class); - GDMonoClass *get_class(const StringName &p_namespace, const StringName &p_name); - #ifdef GD_MONO_HOT_RELOAD Error reload_scripts_domain(); #endif - bool load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly = false); - bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly = false); - bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly, const Vector<String> &p_search_dirs); - bool load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly = false); + bool load_assembly(const String &p_name, GDMonoAssembly **r_assembly); + bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly); + bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, const Vector<String> &p_search_dirs); + bool load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly); Error finalize_and_unload_domain(MonoDomain *p_domain); diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index 42c6b6305f..605216d331 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -40,8 +40,8 @@ #include "core/templates/list.h" #include "../godotsharp_dirs.h" +#include "gd_mono.h" #include "gd_mono_cache.h" -#include "gd_mono_class.h" Vector<String> GDMonoAssembly::search_dirs; @@ -73,21 +73,18 @@ void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const Strin } if (p_custom_config.is_empty()) { - r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir()); + r_search_dirs.push_back(GodotSharpDirs::get_api_assemblies_dir()); } else { String api_config = p_custom_config == "ExportRelease" ? "Release" : "Debug"; - r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir().plus_file(api_config)); + r_search_dirs.push_back(GodotSharpDirs::get_api_assemblies_base_dir().plus_file(api_config)); } - r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir()); + r_search_dirs.push_back(GodotSharpDirs::get_api_assemblies_base_dir()); r_search_dirs.push_back(OS::get_singleton()->get_resource_dir()); r_search_dirs.push_back(OS::get_singleton()->get_executable_path().get_base_dir()); #ifdef TOOLS_ENABLED r_search_dirs.push_back(GodotSharpDirs::get_data_editor_tools_dir()); - - // For GodotTools to find the api assemblies - r_search_dirs.push_back(GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug")); #endif } @@ -330,13 +327,6 @@ no_pdb: void GDMonoAssembly::unload() { ERR_FAIL_NULL(image); // Should not be called if already unloaded - for (const KeyValue<MonoClass *, GDMonoClass *> &E : cached_raw) { - memdelete(E.value); - } - - cached_classes.clear(); - cached_raw.clear(); - assembly = nullptr; image = nullptr; } @@ -345,90 +335,6 @@ String GDMonoAssembly::get_path() const { return String::utf8(mono_image_get_filename(image)); } -bool GDMonoAssembly::has_attribute(GDMonoClass *p_attr_class) { -#ifdef DEBUG_ENABLED - ERR_FAIL_NULL_V(p_attr_class, false); -#endif - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return false; - } - - return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); -} - -MonoObject *GDMonoAssembly::get_attribute(GDMonoClass *p_attr_class) { -#ifdef DEBUG_ENABLED - ERR_FAIL_NULL_V(p_attr_class, nullptr); -#endif - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return nullptr; - } - - return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); -} - -void GDMonoAssembly::fetch_attributes() { - ERR_FAIL_COND(attributes != nullptr); - - attributes = mono_custom_attrs_from_assembly(assembly); - attrs_fetched = true; -} - -GDMonoClass *GDMonoAssembly::get_class(const StringName &p_namespace, const StringName &p_name) { - ERR_FAIL_NULL_V(image, nullptr); - - ClassKey key(p_namespace, p_name); - - GDMonoClass **match = cached_classes.getptr(key); - - if (match) { - return *match; - } - - MonoClass *mono_class = mono_class_from_name(image, String(p_namespace).utf8(), String(p_name).utf8()); - - if (!mono_class) { - return nullptr; - } - - GDMonoClass *wrapped_class = memnew(GDMonoClass(p_namespace, p_name, mono_class, this)); - - cached_classes[key] = wrapped_class; - cached_raw[mono_class] = wrapped_class; - - return wrapped_class; -} - -GDMonoClass *GDMonoAssembly::get_class(MonoClass *p_mono_class) { - ERR_FAIL_NULL_V(image, nullptr); - - HashMap<MonoClass *, GDMonoClass *>::Iterator match = cached_raw.find(p_mono_class); - - if (match) { - return match->value; - } - - StringName namespace_name = String::utf8(mono_class_get_namespace(p_mono_class)); - StringName class_name = String::utf8(mono_class_get_name(p_mono_class)); - - GDMonoClass *wrapped_class = memnew(GDMonoClass(namespace_name, class_name, p_mono_class, this)); - - cached_classes[ClassKey(namespace_name, class_name)] = wrapped_class; - cached_raw[p_mono_class] = wrapped_class; - - return wrapped_class; -} - GDMonoAssembly *GDMonoAssembly::load(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs) { if (GDMono::get_singleton()->get_corlib_assembly() && (p_name == "mscorlib" || p_name == "mscorlib.dll")) { return GDMono::get_singleton()->get_corlib_assembly(); diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h index 0a3ae6c4fe..f67a3e0f25 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.h +++ b/modules/mono/mono_gd/gd_mono_assembly.h @@ -40,47 +40,14 @@ #include "gd_mono_utils.h" class GDMonoAssembly { - struct ClassKey { - struct Hasher { - static _FORCE_INLINE_ uint32_t hash(const ClassKey &p_key) { - uint32_t hash = 0; - - GDMonoUtils::hash_combine(hash, p_key.namespace_name.hash()); - GDMonoUtils::hash_combine(hash, p_key.class_name.hash()); - - return hash; - } - }; - - _FORCE_INLINE_ bool operator==(const ClassKey &p_a) const { - return p_a.class_name == class_name && p_a.namespace_name == namespace_name; - } - - ClassKey() {} - - ClassKey(const StringName &p_namespace_name, const StringName &p_class_name) { - namespace_name = p_namespace_name; - class_name = p_class_name; - } - - StringName namespace_name; - StringName class_name; - }; - String name; MonoImage *image = nullptr; MonoAssembly *assembly = nullptr; - bool attrs_fetched = false; - MonoCustomAttrInfo *attributes = nullptr; - #ifdef GD_MONO_HOT_RELOAD uint64_t modified_time = 0; #endif - HashMap<ClassKey, GDMonoClass *, ClassKey::Hasher> cached_classes; - HashMap<MonoClass *, GDMonoClass *> cached_raw; - static Vector<String> search_dirs; static void assembly_load_hook(MonoAssembly *assembly, void *user_data); @@ -111,14 +78,6 @@ public: String get_path() const; - bool has_attribute(GDMonoClass *p_attr_class); - MonoObject *get_attribute(GDMonoClass *p_attr_class); - - void fetch_attributes(); - - GDMonoClass *get_class(const StringName &p_namespace, const StringName &p_name); - GDMonoClass *get_class(MonoClass *p_mono_class); - static String find_assembly(const String &p_name); static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String(), const String &p_custom_bcl_dir = String()); diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp index 54e49cf5f5..37c8e7d021 100644 --- a/modules/mono/mono_gd/gd_mono_cache.cpp +++ b/modules/mono/mono_gd/gd_mono_cache.cpp @@ -31,210 +31,76 @@ #include "gd_mono_cache.h" #include "gd_mono.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" -#include "gd_mono_method.h" #include "gd_mono_utils.h" namespace GDMonoCache { CachedData cached_data; -#define CACHE_AND_CHECK(m_var, m_val) \ - { \ - CRASH_COND(m_var != nullptr); \ - m_var = m_val; \ - ERR_FAIL_COND_MSG(m_var == nullptr, "Mono Cache: Member " #m_var " is null."); \ - } +static MonoMethod *get_mono_method(MonoClass *p_mono_class, const char *p_method_name, int p_param_count) { + ERR_FAIL_NULL_V(p_mono_class, nullptr); + return mono_class_get_method_from_name(p_mono_class, p_method_name, p_param_count); +} + +static MonoClass *get_mono_class(GDMonoAssembly *p_assembly, const char *p_namespace, const char *p_name) { + ERR_FAIL_NULL_V(p_assembly->get_image(), nullptr); + return mono_class_from_name(p_assembly->get_image(), p_namespace, p_name); +} -#define CACHE_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(cached_data.class_##m_class, m_val) -#define CACHE_FIELD_AND_CHECK(m_class, m_field, m_val) CACHE_AND_CHECK(cached_data.field_##m_class##_##m_field, m_val) -#define CACHE_METHOD_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(cached_data.method_##m_class##_##m_method, m_val) -#define CACHE_PROPERTY_AND_CHECK(m_class, m_property, m_val) CACHE_AND_CHECK(cached_data.property_##m_class##_##m_property, m_val) - -#define CACHE_METHOD_THUNK_AND_CHECK_IMPL(m_var, m_val) \ - { \ - CRASH_COND(!m_var.is_null()); \ - ERR_FAIL_COND_MSG(m_val == nullptr, "Mono Cache: Method for member " #m_var " is null."); \ - m_var.set_from_method(m_val); \ - ERR_FAIL_COND_MSG(m_var.is_null(), "Mono Cache: Member " #m_var " is null."); \ +void update_godot_api_cache() { +#define CACHE_METHOD_THUNK_AND_CHECK_IMPL(m_var, m_val) \ + { \ + CRASH_COND(!m_var.is_null()); \ + val = m_val; \ + ERR_FAIL_COND_MSG(val == nullptr, "Mono Cache: Method for member " #m_var " is null."); \ + m_var.set_from_method(val); \ + ERR_FAIL_COND_MSG(m_var.is_null(), "Mono Cache: Member " #m_var " is null."); \ } #define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_METHOD_THUNK_AND_CHECK_IMPL(cached_data.methodthunk_##m_class##_##m_method, m_val) -void CachedData::clear_corlib_cache() { - corlib_cache_updated = false; +#define GODOT_API_CLASS(m_class) (get_mono_class(GDMono::get_singleton()->get_core_api_assembly(), BINDINGS_NAMESPACE, #m_class)) +#define GODOT_API_BRIDGE_CLASS(m_class) (get_mono_class(GDMono::get_singleton()->get_core_api_assembly(), BINDINGS_NAMESPACE_BRIDGE, #m_class)) - class_MonoObject = nullptr; - class_String = nullptr; + MonoMethod *val = nullptr; -#ifdef DEBUG_ENABLED - class_System_Diagnostics_StackTrace = nullptr; - methodthunk_System_Diagnostics_StackTrace_GetFrames.nullify(); - method_System_Diagnostics_StackTrace_ctor_bool = nullptr; - method_System_Diagnostics_StackTrace_ctor_Exception_bool = nullptr; -#endif + CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, get_mono_method(GODOT_API_CLASS(SignalAwaiter), "SignalCallback", 4)); - class_KeyNotFoundException = nullptr; -} + CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, InvokeWithVariantArgs, get_mono_method(GODOT_API_CLASS(DelegateUtils), "InvokeWithVariantArgs", 4)); + CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, DelegateEquals, get_mono_method(GODOT_API_CLASS(DelegateUtils), "DelegateEquals", 2)); -void CachedData::clear_godot_api_cache() { - godot_api_cache_updated = false; - - class_GodotObject = nullptr; - class_GodotResource = nullptr; - class_Node = nullptr; - class_Control = nullptr; - class_Callable = nullptr; - class_SignalInfo = nullptr; - class_ISerializationListener = nullptr; - -#ifdef DEBUG_ENABLED - class_DebuggingUtils = nullptr; - methodthunk_DebuggingUtils_GetStackFrameInfo.nullify(); -#endif - - class_ExportAttribute = nullptr; - field_ExportAttribute_hint = nullptr; - field_ExportAttribute_hintString = nullptr; - class_SignalAttribute = nullptr; - class_ToolAttribute = nullptr; - class_RPCAttribute = nullptr; - property_RPCAttribute_Mode = nullptr; - property_RPCAttribute_CallLocal = nullptr; - property_RPCAttribute_TransferMode = nullptr; - property_RPCAttribute_TransferChannel = nullptr; - class_GodotMethodAttribute = nullptr; - field_GodotMethodAttribute_methodName = nullptr; - class_ScriptPathAttribute = nullptr; - field_ScriptPathAttribute_path = nullptr; - class_AssemblyHasScriptsAttribute = nullptr; - field_AssemblyHasScriptsAttribute_requiresLookup = nullptr; - field_AssemblyHasScriptsAttribute_scriptTypes = nullptr; - - field_GodotObject_ptr = nullptr; - - methodthunk_GodotObject_Dispose.nullify(); - methodthunk_SignalAwaiter_SignalCallback.nullify(); - - methodthunk_Delegate_Equals.nullify(); - - methodthunk_DelegateUtils_TrySerializeDelegateWithGCHandle.nullify(); - methodthunk_DelegateUtils_TryDeserializeDelegateWithGCHandle.nullify(); - methodthunk_DelegateUtils_TrySerializeDelegate.nullify(); - methodthunk_DelegateUtils_TryDeserializeDelegate.nullify(); - methodthunk_DelegateUtils_InvokeWithVariantArgs.nullify(); - methodthunk_DelegateUtils_DelegateEquals.nullify(); - methodthunk_DelegateUtils_FreeGCHandle.nullify(); - - methodthunk_Marshaling_managed_to_variant_type.nullify(); - methodthunk_Marshaling_try_get_array_element_type.nullify(); - methodthunk_Marshaling_variant_to_mono_object_of_type.nullify(); - methodthunk_Marshaling_variant_to_mono_object.nullify(); - methodthunk_Marshaling_mono_object_to_variant_out.nullify(); - - methodthunk_Marshaling_SetFieldValue.nullify(); - - methodthunk_MarshalUtils_TypeHasFlagsAttribute.nullify(); -} + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, FrameCallback, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "FrameCallback", 0)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, CreateManagedForGodotObjectBinding, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "CreateManagedForGodotObjectBinding", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, CreateManagedForGodotObjectScriptInstance, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "CreateManagedForGodotObjectScriptInstance", 4)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, GetScriptNativeName, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "GetScriptNativeName", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, LookupScriptsInAssembly, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "LookupScriptsInAssembly", 1)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, SetGodotObjectPtr, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "SetGodotObjectPtr", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, RaiseEventSignal, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "RaiseEventSignal", 5)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, GetScriptSignalList, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "GetScriptSignalList", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, HasScriptSignal, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "HasScriptSignal", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, HasMethodUnknownParams, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "HasMethodUnknownParams", 3)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, ScriptIsOrInherits, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "ScriptIsOrInherits", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, AddScriptBridge, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "AddScriptBridge", 2)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, RemoveScriptBridge, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "RemoveScriptBridge", 1)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, UpdateScriptClassInfo, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "UpdateScriptClassInfo", 3)); + CACHE_METHOD_THUNK_AND_CHECK(ScriptManagerBridge, SwapGCHandleForType, get_mono_method(GODOT_API_BRIDGE_CLASS(ScriptManagerBridge), "SwapGCHandleForType", 3)); -#define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class)) + CACHE_METHOD_THUNK_AND_CHECK(CSharpInstanceBridge, Call, get_mono_method(GODOT_API_BRIDGE_CLASS(CSharpInstanceBridge), "Call", 6)); + CACHE_METHOD_THUNK_AND_CHECK(CSharpInstanceBridge, Set, get_mono_method(GODOT_API_BRIDGE_CLASS(CSharpInstanceBridge), "Set", 3)); + CACHE_METHOD_THUNK_AND_CHECK(CSharpInstanceBridge, Get, get_mono_method(GODOT_API_BRIDGE_CLASS(CSharpInstanceBridge), "Get", 3)); + CACHE_METHOD_THUNK_AND_CHECK(CSharpInstanceBridge, CallDispose, get_mono_method(GODOT_API_BRIDGE_CLASS(CSharpInstanceBridge), "CallDispose", 2)); + CACHE_METHOD_THUNK_AND_CHECK(CSharpInstanceBridge, CallToString, get_mono_method(GODOT_API_BRIDGE_CLASS(CSharpInstanceBridge), "CallToString", 3)); -void update_corlib_cache() { - CACHE_CLASS_AND_CHECK(MonoObject, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_object_class())); - CACHE_CLASS_AND_CHECK(String, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_string_class())); + CACHE_METHOD_THUNK_AND_CHECK(GCHandleBridge, FreeGCHandle, get_mono_method(GODOT_API_BRIDGE_CLASS(GCHandleBridge), "FreeGCHandle", 1)); -#ifdef DEBUG_ENABLED - CACHE_CLASS_AND_CHECK(System_Diagnostics_StackTrace, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Diagnostics", "StackTrace")); - CACHE_METHOD_THUNK_AND_CHECK(System_Diagnostics_StackTrace, GetFrames, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method("GetFrames")); - CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(bool)", true)); - CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_Exception_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(System.Exception,bool)", true)); -#endif - - CACHE_METHOD_THUNK_AND_CHECK(Delegate, Equals, GDMono::get_singleton()->get_corlib_assembly()->get_class("System", "Delegate")->get_method_with_desc("System.Delegate:Equals(object)", true)); - - CACHE_CLASS_AND_CHECK(KeyNotFoundException, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections.Generic", "KeyNotFoundException")); - - cached_data.corlib_cache_updated = true; -} - -void update_godot_api_cache() { - CACHE_CLASS_AND_CHECK(GodotObject, GODOT_API_CLASS(Object)); - CACHE_CLASS_AND_CHECK(GodotResource, GODOT_API_CLASS(Resource)); - CACHE_CLASS_AND_CHECK(Node, GODOT_API_CLASS(Node)); - CACHE_CLASS_AND_CHECK(Control, GODOT_API_CLASS(Control)); - CACHE_CLASS_AND_CHECK(Callable, GODOT_API_CLASS(Callable)); - CACHE_CLASS_AND_CHECK(SignalInfo, GODOT_API_CLASS(SignalInfo)); - CACHE_CLASS_AND_CHECK(ISerializationListener, GODOT_API_CLASS(ISerializationListener)); - -#ifdef DEBUG_ENABLED - CACHE_CLASS_AND_CHECK(DebuggingUtils, GODOT_API_CLASS(DebuggingUtils)); -#endif - - // Attributes - CACHE_CLASS_AND_CHECK(ExportAttribute, GODOT_API_CLASS(ExportAttribute)); - CACHE_FIELD_AND_CHECK(ExportAttribute, hint, CACHED_CLASS(ExportAttribute)->get_field("hint")); - CACHE_FIELD_AND_CHECK(ExportAttribute, hintString, CACHED_CLASS(ExportAttribute)->get_field("hintString")); - CACHE_CLASS_AND_CHECK(SignalAttribute, GODOT_API_CLASS(SignalAttribute)); - CACHE_CLASS_AND_CHECK(ToolAttribute, GODOT_API_CLASS(ToolAttribute)); - CACHE_CLASS_AND_CHECK(RPCAttribute, GODOT_API_CLASS(RPCAttribute)); - CACHE_PROPERTY_AND_CHECK(RPCAttribute, Mode, CACHED_CLASS(RPCAttribute)->get_property("Mode")); - CACHE_PROPERTY_AND_CHECK(RPCAttribute, CallLocal, CACHED_CLASS(RPCAttribute)->get_property("CallLocal")); - CACHE_PROPERTY_AND_CHECK(RPCAttribute, TransferMode, CACHED_CLASS(RPCAttribute)->get_property("TransferMode")); - CACHE_PROPERTY_AND_CHECK(RPCAttribute, TransferChannel, CACHED_CLASS(RPCAttribute)->get_property("TransferChannel")); - CACHE_CLASS_AND_CHECK(GodotMethodAttribute, GODOT_API_CLASS(GodotMethodAttribute)); - CACHE_FIELD_AND_CHECK(GodotMethodAttribute, methodName, CACHED_CLASS(GodotMethodAttribute)->get_field("methodName")); - CACHE_CLASS_AND_CHECK(ScriptPathAttribute, GODOT_API_CLASS(ScriptPathAttribute)); - CACHE_FIELD_AND_CHECK(ScriptPathAttribute, path, CACHED_CLASS(ScriptPathAttribute)->get_field("path")); - CACHE_CLASS_AND_CHECK(AssemblyHasScriptsAttribute, GODOT_API_CLASS(AssemblyHasScriptsAttribute)); - CACHE_FIELD_AND_CHECK(AssemblyHasScriptsAttribute, requiresLookup, CACHED_CLASS(AssemblyHasScriptsAttribute)->get_field("requiresLookup")); - CACHE_FIELD_AND_CHECK(AssemblyHasScriptsAttribute, scriptTypes, CACHED_CLASS(AssemblyHasScriptsAttribute)->get_field("scriptTypes")); - - CACHE_FIELD_AND_CHECK(GodotObject, ptr, CACHED_CLASS(GodotObject)->get_field(BINDINGS_PTR_FIELD)); - - CACHE_METHOD_THUNK_AND_CHECK(GodotObject, Dispose, CACHED_CLASS(GodotObject)->get_method("Dispose", 0)); - CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, GODOT_API_CLASS(SignalAwaiter)->get_method("SignalCallback", 1)); - - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, TrySerializeDelegateWithGCHandle, GODOT_API_CLASS(DelegateUtils)->get_method("TrySerializeDelegateWithGCHandle", 2)); - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, TryDeserializeDelegateWithGCHandle, GODOT_API_CLASS(DelegateUtils)->get_method("TryDeserializeDelegateWithGCHandle", 2)); - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, TrySerializeDelegate, GODOT_API_CLASS(DelegateUtils)->get_method("TrySerializeDelegate", 2)); - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, TryDeserializeDelegate, GODOT_API_CLASS(DelegateUtils)->get_method("TryDeserializeDelegate", 2)); - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, InvokeWithVariantArgs, GODOT_API_CLASS(DelegateUtils)->get_method("InvokeWithVariantArgs", 4)); - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, DelegateEquals, GODOT_API_CLASS(DelegateUtils)->get_method("DelegateEquals", 2)); - CACHE_METHOD_THUNK_AND_CHECK(DelegateUtils, FreeGCHandle, GODOT_API_CLASS(DelegateUtils)->get_method("FreeGCHandle", 1)); - - GDMonoClass *gd_mono_marshal_class = GDMono::get_singleton()->get_core_api_assembly()->get_class( - "Godot.NativeInterop", "Marshaling"); - - ERR_FAIL_COND_MSG(gd_mono_marshal_class == nullptr, - "Mono Cache: Class `Godot.NativeInterop.Marshaling` not found."); - - CACHE_METHOD_THUNK_AND_CHECK(Marshaling, managed_to_variant_type, - gd_mono_marshal_class->get_method("managed_to_variant_type", 2)); - CACHE_METHOD_THUNK_AND_CHECK(Marshaling, try_get_array_element_type, - gd_mono_marshal_class->get_method("try_get_array_element_type", 2)); - CACHE_METHOD_THUNK_AND_CHECK(Marshaling, variant_to_mono_object_of_type, - gd_mono_marshal_class->get_method("variant_to_mono_object_of_type", 2)); - CACHE_METHOD_THUNK_AND_CHECK(Marshaling, variant_to_mono_object, - gd_mono_marshal_class->get_method("variant_to_mono_object", 1)); - CACHE_METHOD_THUNK_AND_CHECK(Marshaling, mono_object_to_variant_out, - gd_mono_marshal_class->get_method("mono_object_to_variant_out", 3)); - - CACHE_METHOD_THUNK_AND_CHECK(Marshaling, SetFieldValue, - gd_mono_marshal_class->get_method("SetFieldValue", 3)); - - CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeHasFlagsAttribute, GODOT_API_CLASS(MarshalUtils)->get_method("TypeHasFlagsAttribute", 1)); - -#ifdef DEBUG_ENABLED - CACHE_METHOD_THUNK_AND_CHECK(DebuggingUtils, GetStackFrameInfo, GODOT_API_CLASS(DebuggingUtils)->get_method("GetStackFrameInfo", 4)); -#endif + CACHE_METHOD_THUNK_AND_CHECK(DebuggingUtils, InstallTraceListener, get_mono_method(GODOT_API_CLASS(DebuggingUtils), "InstallTraceListener", 0)); MonoException *exc = nullptr; - GDMono::get_singleton() - ->get_core_api_assembly() - ->get_class("Godot", "Dispatcher") - ->get_method("InitializeDefaultGodotTaskScheduler") - ->invoke(nullptr, &exc); + MonoMethod *init_default_godot_task_scheduler = + get_mono_method(GODOT_API_CLASS(Dispatcher), "InitializeDefaultGodotTaskScheduler", 0); + ERR_FAIL_COND_MSG(init_default_godot_task_scheduler == nullptr, + "Mono Cache: InitializeDefaultGodotTaskScheduler is null."); + mono_runtime_invoke(init_default_godot_task_scheduler, nullptr, nullptr, (MonoObject **)&exc); if (exc) { GDMonoUtils::debug_unhandled_exception(exc); diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index 5876583260..5785347938 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -31,115 +31,57 @@ #ifndef GD_MONO_CACHE_H #define GD_MONO_CACHE_H -#include "gd_mono_header.h" #include "gd_mono_method_thunk.h" +class CSharpScript; + namespace GDMonoCache { struct CachedData { - // ----------------------------------------------- - // corlib classes - - // Let's use the no-namespace format for these too - GDMonoClass *class_MonoObject = nullptr; // object - GDMonoClass *class_String = nullptr; // string - -#ifdef DEBUG_ENABLED - GDMonoClass *class_System_Diagnostics_StackTrace = nullptr; - GDMonoMethodThunkR<MonoArray *, MonoObject *> methodthunk_System_Diagnostics_StackTrace_GetFrames; - GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_bool = nullptr; - GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_Exception_bool = nullptr; -#endif - - GDMonoClass *class_KeyNotFoundException = nullptr; - // ----------------------------------------------- - - GDMonoClass *class_GodotObject = nullptr; - GDMonoClass *class_GodotResource = nullptr; - GDMonoClass *class_Node = nullptr; - GDMonoClass *class_Control = nullptr; - GDMonoClass *class_Callable = nullptr; - GDMonoClass *class_SignalInfo = nullptr; - GDMonoClass *class_ISerializationListener = nullptr; - -#ifdef DEBUG_ENABLED - GDMonoClass *class_DebuggingUtils = nullptr; - GDMonoMethodThunk<MonoObject *, MonoString **, int *, MonoString **> methodthunk_DebuggingUtils_GetStackFrameInfo; -#endif - - GDMonoClass *class_ExportAttribute = nullptr; - GDMonoField *field_ExportAttribute_hint = nullptr; - GDMonoField *field_ExportAttribute_hintString = nullptr; - GDMonoClass *class_SignalAttribute = nullptr; - GDMonoClass *class_ToolAttribute = nullptr; - GDMonoClass *class_RPCAttribute = nullptr; - GDMonoProperty *property_RPCAttribute_Mode = nullptr; - GDMonoProperty *property_RPCAttribute_CallLocal = nullptr; - GDMonoProperty *property_RPCAttribute_TransferMode = nullptr; - GDMonoProperty *property_RPCAttribute_TransferChannel = nullptr; - GDMonoClass *class_GodotMethodAttribute = nullptr; - GDMonoField *field_GodotMethodAttribute_methodName = nullptr; - GDMonoClass *class_ScriptPathAttribute = nullptr; - GDMonoField *field_ScriptPathAttribute_path = nullptr; - GDMonoClass *class_AssemblyHasScriptsAttribute = nullptr; - GDMonoField *field_AssemblyHasScriptsAttribute_requiresLookup = nullptr; - GDMonoField *field_AssemblyHasScriptsAttribute_scriptTypes = nullptr; - - - GDMonoField *field_GodotObject_ptr = nullptr; - - GDMonoMethodThunk<MonoObject *> methodthunk_GodotObject_Dispose; - GDMonoMethodThunk<MonoObject *, MonoArray *> methodthunk_SignalAwaiter_SignalCallback; - - GDMonoMethodThunkR<MonoBoolean, MonoObject *, MonoObject *> methodthunk_Delegate_Equals; - - GDMonoMethodThunkR<MonoBoolean, void *, MonoObject *> methodthunk_DelegateUtils_TrySerializeDelegateWithGCHandle; - GDMonoMethodThunkR<MonoBoolean, MonoObject *, void **> methodthunk_DelegateUtils_TryDeserializeDelegateWithGCHandle; - - GDMonoMethodThunkR<MonoBoolean, MonoDelegate *, MonoObject *> methodthunk_DelegateUtils_TrySerializeDelegate; - GDMonoMethodThunkR<MonoBoolean, MonoObject *, MonoDelegate **> methodthunk_DelegateUtils_TryDeserializeDelegate; - - GDMonoMethodThunk<void *, const Variant **, uint32_t, const Variant *> methodthunk_DelegateUtils_InvokeWithVariantArgs; - GDMonoMethodThunkR<MonoBoolean, void *, void *> methodthunk_DelegateUtils_DelegateEquals; - GDMonoMethodThunk<void *> methodthunk_DelegateUtils_FreeGCHandle; - - GDMonoMethodThunkR<int32_t, MonoReflectionType *, MonoBoolean *> methodthunk_Marshaling_managed_to_variant_type; - GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *, MonoReflectionType **> methodthunk_Marshaling_try_get_array_element_type; - GDMonoMethodThunkR<MonoObject *, const Variant *, MonoReflectionType *> methodthunk_Marshaling_variant_to_mono_object_of_type; - GDMonoMethodThunkR<MonoObject *, const Variant *> methodthunk_Marshaling_variant_to_mono_object; - GDMonoMethodThunk<MonoObject *, MonoBoolean, Variant *> methodthunk_Marshaling_mono_object_to_variant_out; - - GDMonoMethodThunk<MonoReflectionField *, MonoObject *, const Variant *> methodthunk_Marshaling_SetFieldValue; - - GDMonoMethodThunkR<MonoBoolean, MonoReflectionType *> methodthunk_MarshalUtils_TypeHasFlagsAttribute; - - bool corlib_cache_updated; - bool godot_api_cache_updated; - - void clear_corlib_cache(); - void clear_godot_api_cache(); - - CachedData() { - clear_corlib_cache(); - clear_godot_api_cache(); - } + // Mono method thunks require structs to be boxed, even if passed by ref (out, ref, in). + // As such we need to use pointers instead for now, instead of by ref parameters. + + GDMonoMethodThunk<GCHandleIntPtr, const Variant **, int, bool *> methodthunk_SignalAwaiter_SignalCallback; + + GDMonoMethodThunk<GCHandleIntPtr, const Variant **, uint32_t, const Variant *> methodthunk_DelegateUtils_InvokeWithVariantArgs; + GDMonoMethodThunkR<bool, GCHandleIntPtr, GCHandleIntPtr> methodthunk_DelegateUtils_DelegateEquals; + + GDMonoMethodThunk<> methodthunk_ScriptManagerBridge_FrameCallback; + GDMonoMethodThunkR<GCHandleIntPtr, const StringName *, Object *> methodthunk_ScriptManagerBridge_CreateManagedForGodotObjectBinding; + GDMonoMethodThunk<const CSharpScript *, Object *, const Variant **, int> methodthunk_ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance; + GDMonoMethodThunk<const CSharpScript *, StringName *> methodthunk_ScriptManagerBridge_GetScriptNativeName; + GDMonoMethodThunk<MonoReflectionAssembly *> methodthunk_ScriptManagerBridge_LookupScriptsInAssembly; + GDMonoMethodThunk<GCHandleIntPtr, Object *> methodthunk_ScriptManagerBridge_SetGodotObjectPtr; + GDMonoMethodThunk<GCHandleIntPtr, const StringName *, const Variant **, int, bool *> methodthunk_ScriptManagerBridge_RaiseEventSignal; + GDMonoMethodThunk<const CSharpScript *, Dictionary *> methodthunk_ScriptManagerBridge_GetScriptSignalList; + GDMonoMethodThunkR<bool, const CSharpScript *, const String *> methodthunk_ScriptManagerBridge_HasScriptSignal; + GDMonoMethodThunkR<bool, const CSharpScript *, const String *, bool> methodthunk_ScriptManagerBridge_HasMethodUnknownParams; + GDMonoMethodThunkR<bool, const CSharpScript *, const CSharpScript *> methodthunk_ScriptManagerBridge_ScriptIsOrInherits; + GDMonoMethodThunkR<bool, const CSharpScript *, const String *> methodthunk_ScriptManagerBridge_AddScriptBridge; + GDMonoMethodThunk<const CSharpScript *> methodthunk_ScriptManagerBridge_RemoveScriptBridge; + GDMonoMethodThunk<const CSharpScript *, bool *, Dictionary *> methodthunk_ScriptManagerBridge_UpdateScriptClassInfo; + GDMonoMethodThunkR<bool, GCHandleIntPtr, GCHandleIntPtr *, bool> methodthunk_ScriptManagerBridge_SwapGCHandleForType; + + GDMonoMethodThunk<GCHandleIntPtr, const StringName *, const Variant **, int, Callable::CallError *, Variant *> methodthunk_CSharpInstanceBridge_Call; + GDMonoMethodThunkR<bool, GCHandleIntPtr, const StringName *, const Variant *> methodthunk_CSharpInstanceBridge_Set; + GDMonoMethodThunkR<bool, GCHandleIntPtr, const StringName *, Variant *> methodthunk_CSharpInstanceBridge_Get; + GDMonoMethodThunk<GCHandleIntPtr, bool> methodthunk_CSharpInstanceBridge_CallDispose; + GDMonoMethodThunk<GCHandleIntPtr, String *, bool *> methodthunk_CSharpInstanceBridge_CallToString; + + GDMonoMethodThunk<GCHandleIntPtr> methodthunk_GCHandleBridge_FreeGCHandle; + + GDMonoMethodThunk<> methodthunk_DebuggingUtils_InstallTraceListener; + + bool godot_api_cache_updated = false; }; extern CachedData cached_data; -void update_corlib_cache(); void update_godot_api_cache(); inline void clear_godot_api_cache() { - cached_data.clear_godot_api_cache(); + cached_data = CachedData(); } } // namespace GDMonoCache -#define CACHED_CLASS(m_class) (GDMonoCache::cached_data.class_##m_class) -#define CACHED_CLASS_RAW(m_class) (GDMonoCache::cached_data.class_##m_class->get_mono_ptr()) -#define CACHED_FIELD(m_class, m_field) (GDMonoCache::cached_data.field_##m_class##_##m_field) -#define CACHED_METHOD(m_class, m_method) (GDMonoCache::cached_data.method_##m_class##_##m_method) -#define CACHED_METHOD_THUNK(m_class, m_method) (GDMonoCache::cached_data.methodthunk_##m_class##_##m_method) -#define CACHED_PROPERTY(m_class, m_property) (GDMonoCache::cached_data.property_##m_class##_##m_property) - #endif // GD_MONO_CACHE_H diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp deleted file mode 100644 index 24b46d2ce8..0000000000 --- a/modules/mono/mono_gd/gd_mono_class.cpp +++ /dev/null @@ -1,569 +0,0 @@ -/*************************************************************************/ -/* gd_mono_class.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "gd_mono_class.h" - -#include <mono/metadata/attrdefs.h> -#include <mono/metadata/debug-helpers.h> - -#include "gd_mono_assembly.h" -#include "gd_mono_cache.h" -#include "gd_mono_marshal.h" - -String GDMonoClass::get_full_name(MonoClass *p_mono_class) { - // mono_type_get_full_name is not exposed to embedders, but this seems to do the job - MonoReflectionType *type_obj = mono_type_get_object(mono_domain_get(), get_mono_type(p_mono_class)); - - MonoException *exc = nullptr; - MonoString *str = GDMonoUtils::object_to_string((MonoObject *)type_obj, &exc); - UNHANDLED_EXCEPTION(exc); - - return GDMonoMarshal::mono_string_to_godot(str); -} - -MonoType *GDMonoClass::get_mono_type(MonoClass *p_mono_class) { - return mono_class_get_type(p_mono_class); -} - -String GDMonoClass::get_full_name() const { - return get_full_name(mono_class); -} - -String GDMonoClass::get_type_desc() const { - return GDMonoUtils::get_type_desc(get_mono_type()); -} - -MonoType *GDMonoClass::get_mono_type() const { - // Careful, you cannot compare two MonoType*. - // There is mono_metadata_type_equal, how is this different from comparing two MonoClass*? - return get_mono_type(mono_class); -} - -uint32_t GDMonoClass::get_flags() const { - return mono_class_get_flags(mono_class); -} - -bool GDMonoClass::is_static() const { - uint32_t static_class_flags = MONO_TYPE_ATTR_ABSTRACT | MONO_TYPE_ATTR_SEALED; - return (get_flags() & static_class_flags) == static_class_flags; -} - -bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const { - return mono_class_is_assignable_from(mono_class, p_from->mono_class); -} - -StringName GDMonoClass::get_namespace() const { - GDMonoClass *nesting_class = get_nesting_class(); - if (!nesting_class) { - return namespace_name; - } - return nesting_class->get_namespace(); -} - -String GDMonoClass::get_name_for_lookup() const { - GDMonoClass *nesting_class = get_nesting_class(); - if (!nesting_class) { - return class_name; - } - return nesting_class->get_name_for_lookup() + "/" + class_name; -} - -GDMonoClass *GDMonoClass::get_parent_class() const { - MonoClass *parent_mono_class = mono_class_get_parent(mono_class); - return parent_mono_class ? GDMono::get_singleton()->get_class(parent_mono_class) : nullptr; -} - -GDMonoClass *GDMonoClass::get_nesting_class() const { - MonoClass *nesting_type = mono_class_get_nesting_type(mono_class); - return nesting_type ? GDMono::get_singleton()->get_class(nesting_type) : nullptr; -} - -#ifdef TOOLS_ENABLED -Vector<MonoClassField *> GDMonoClass::get_enum_fields() { - bool class_is_enum = mono_class_is_enum(mono_class); - ERR_FAIL_COND_V(!class_is_enum, Vector<MonoClassField *>()); - - Vector<MonoClassField *> enum_fields; - - void *iter = nullptr; - MonoClassField *raw_field = nullptr; - while ((raw_field = mono_class_get_fields(get_mono_ptr(), &iter)) != nullptr) { - uint32_t field_flags = mono_field_get_flags(raw_field); - - // Enums have an instance field named value__ which holds the value of the enum. - // Enum constants are static, so we will use this to ignore the value__ field. - if (field_flags & MONO_FIELD_ATTR_PUBLIC && field_flags & MONO_FIELD_ATTR_STATIC) { - enum_fields.push_back(raw_field); - } - } - - return enum_fields; -} -#endif - -bool GDMonoClass::has_attribute(GDMonoClass *p_attr_class) { -#ifdef DEBUG_ENABLED - ERR_FAIL_NULL_V(p_attr_class, false); -#endif - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return false; - } - - return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); -} - -MonoObject *GDMonoClass::get_attribute(GDMonoClass *p_attr_class) { -#ifdef DEBUG_ENABLED - ERR_FAIL_NULL_V(p_attr_class, nullptr); -#endif - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return nullptr; - } - - return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); -} - -void GDMonoClass::fetch_attributes() { - ERR_FAIL_COND(attributes != nullptr); - - attributes = mono_custom_attrs_from_class(get_mono_ptr()); - attrs_fetched = true; -} - -void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base) { - CRASH_COND(!CACHED_CLASS(GodotObject)->is_assignable_from(this)); - - if (methods_fetched) { - return; - } - - void *iter = nullptr; - MonoMethod *raw_method = nullptr; - while ((raw_method = mono_class_get_methods(get_mono_ptr(), &iter)) != nullptr) { - StringName name = String::utf8(mono_method_get_name(raw_method)); - - // get_method implicitly fetches methods and adds them to this->methods - GDMonoMethod *method = get_method(raw_method, name); - ERR_CONTINUE(!method); - - if (method->get_name() != name) { -#ifdef DEBUG_ENABLED - String fullname = method->get_ret_type_full_name() + " " + name + "(" + method->get_signature_desc(true) + ")"; - WARN_PRINT("Method '" + fullname + "' is hidden by Godot API method. Should be '" + - method->get_full_name_no_class() + "'. In class '" + namespace_name + "." + class_name + "'."); -#endif - continue; - } - -#ifdef DEBUG_ENABLED - // For debug builds, we also fetched from native base classes as well before if this is not a native base class. - // This allows us to warn the user here if they are using snake_case by mistake. - - if (p_native_base != this) { - GDMonoClass *native_top = p_native_base; - while (native_top) { - GDMonoMethod *m = native_top->get_method(name, method->get_parameters_count()); - - if (m && m->get_name() != name) { - // found - String fullname = m->get_ret_type_full_name() + " " + name + "(" + m->get_signature_desc(true) + ")"; - WARN_PRINT("Method '" + fullname + "' should be '" + m->get_full_name_no_class() + - "'. In class '" + namespace_name + "." + class_name + "'."); - break; - } - - if (native_top == CACHED_CLASS(GodotObject)) { - break; - } - - native_top = native_top->get_parent_class(); - } - } -#endif - - uint32_t flags = mono_method_get_flags(method->mono_method, nullptr); - - if (!(flags & MONO_METHOD_ATTR_VIRTUAL)) { - continue; - } - - // Virtual method of Godot Object derived type, let's try to find GodotMethod attribute - - GDMonoClass *top = p_native_base; - - while (top) { - GDMonoMethod *base_method = top->get_method(name, method->get_parameters_count()); - - if (base_method && base_method->has_attribute(CACHED_CLASS(GodotMethodAttribute))) { - // Found base method with GodotMethod attribute. - // We get the original API method name from this attribute. - // This name must point to the virtual method. - - MonoObject *attr = base_method->get_attribute(CACHED_CLASS(GodotMethodAttribute)); - - StringName godot_method_name = CACHED_FIELD(GodotMethodAttribute, methodName)->get_string_value(attr); -#ifdef DEBUG_ENABLED - CRASH_COND(godot_method_name == StringName()); -#endif - MethodKey key = MethodKey(godot_method_name, method->get_parameters_count()); - GDMonoMethod **existing_method = methods.getptr(key); - if (existing_method) { - memdelete(*existing_method); // Must delete old one - } - methods.insert(key, method); - - break; - } - - if (top == CACHED_CLASS(GodotObject)) { - break; - } - - top = top->get_parent_class(); - } - } - - methods_fetched = true; -} - -GDMonoMethod *GDMonoClass::get_fetched_method_unknown_params(const StringName &p_name) { - ERR_FAIL_COND_V(!methods_fetched, nullptr); - - for (const KeyValue<MethodKey, GDMonoMethod *> &E : methods) { - if (E.key.name == p_name) { - return E.value; - } - } - - return nullptr; -} - -bool GDMonoClass::has_fetched_method_unknown_params(const StringName &p_name) { - return get_fetched_method_unknown_params(p_name) != nullptr; -} - -bool GDMonoClass::implements_interface(GDMonoClass *p_interface) { - return mono_class_implements_interface(mono_class, p_interface->get_mono_ptr()); -} - -bool GDMonoClass::has_public_parameterless_ctor() { - GDMonoMethod *ctor = get_method(".ctor", 0); - return ctor && ctor->get_visibility() == IMonoClassMember::PUBLIC; -} - -GDMonoMethod *GDMonoClass::get_method(const StringName &p_name, uint16_t p_params_count) { - MethodKey key = MethodKey(p_name, p_params_count); - - GDMonoMethod **match = methods.getptr(key); - - if (match) { - return *match; - } - - if (methods_fetched) { - return nullptr; - } - - MonoMethod *raw_method = mono_class_get_method_from_name(mono_class, String(p_name).utf8().get_data(), p_params_count); - - if (raw_method) { - GDMonoMethod *method = memnew(GDMonoMethod(p_name, raw_method)); - methods.insert(key, method); - - return method; - } - - return nullptr; -} - -GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method) { - MonoMethodSignature *sig = mono_method_signature(p_raw_method); - - int params_count = mono_signature_get_param_count(sig); - StringName method_name = String::utf8(mono_method_get_name(p_raw_method)); - - return get_method(p_raw_method, method_name, params_count); -} - -GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name) { - MonoMethodSignature *sig = mono_method_signature(p_raw_method); - int params_count = mono_signature_get_param_count(sig); - return get_method(p_raw_method, p_name, params_count); -} - -GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name, uint16_t p_params_count) { - ERR_FAIL_NULL_V(p_raw_method, nullptr); - - MethodKey key = MethodKey(p_name, p_params_count); - - GDMonoMethod **match = methods.getptr(key); - - if (match) { - return *match; - } - - GDMonoMethod *method = memnew(GDMonoMethod(p_name, p_raw_method)); - methods.insert(key, method); - - return method; -} - -GDMonoMethod *GDMonoClass::get_method_with_desc(const String &p_description, bool p_include_namespace) { - MonoMethodDesc *desc = mono_method_desc_new(p_description.utf8().get_data(), p_include_namespace); - MonoMethod *method = mono_method_desc_search_in_class(desc, mono_class); - mono_method_desc_free(desc); - - if (!method) { - return nullptr; - } - - ERR_FAIL_COND_V(mono_method_get_class(method) != mono_class, nullptr); - - return get_method(method); -} - -GDMonoField *GDMonoClass::get_field(const StringName &p_name) { - HashMap<StringName, GDMonoField *>::Iterator result = fields.find(p_name); - - if (result) { - return result->value; - } - - if (fields_fetched) { - return nullptr; - } - - MonoClassField *raw_field = mono_class_get_field_from_name(mono_class, String(p_name).utf8().get_data()); - - if (raw_field) { - GDMonoField *field = memnew(GDMonoField(raw_field, this)); - fields.insert(p_name, field); - - return field; - } - - return nullptr; -} - -const Vector<GDMonoField *> &GDMonoClass::get_all_fields() { - if (fields_fetched) { - return fields_list; - } - - void *iter = nullptr; - MonoClassField *raw_field = nullptr; - while ((raw_field = mono_class_get_fields(mono_class, &iter)) != nullptr) { - StringName name = String::utf8(mono_field_get_name(raw_field)); - - HashMap<StringName, GDMonoField *>::Iterator match = fields.find(name); - - if (match) { - fields_list.push_back(match->value); - } else { - GDMonoField *field = memnew(GDMonoField(raw_field, this)); - fields.insert(name, field); - fields_list.push_back(field); - } - } - - fields_fetched = true; - - return fields_list; -} - -GDMonoProperty *GDMonoClass::get_property(const StringName &p_name) { - HashMap<StringName, GDMonoProperty *>::Iterator result = properties.find(p_name); - - if (result) { - return result->value; - } - - if (properties_fetched) { - return nullptr; - } - - MonoProperty *raw_property = mono_class_get_property_from_name(mono_class, String(p_name).utf8().get_data()); - - if (raw_property) { - GDMonoProperty *property = memnew(GDMonoProperty(raw_property, this)); - properties.insert(p_name, property); - - return property; - } - - return nullptr; -} - -const Vector<GDMonoProperty *> &GDMonoClass::get_all_properties() { - if (properties_fetched) { - return properties_list; - } - - void *iter = nullptr; - MonoProperty *raw_property = nullptr; - while ((raw_property = mono_class_get_properties(mono_class, &iter)) != nullptr) { - StringName name = String::utf8(mono_property_get_name(raw_property)); - - HashMap<StringName, GDMonoProperty *>::Iterator match = properties.find(name); - - if (match) { - properties_list.push_back(match->value); - } else { - GDMonoProperty *property = memnew(GDMonoProperty(raw_property, this)); - properties.insert(name, property); - properties_list.push_back(property); - } - } - - properties_fetched = true; - - return properties_list; -} - -const Vector<GDMonoClass *> &GDMonoClass::get_all_delegates() { - if (delegates_fetched) { - return delegates_list; - } - - // NOTE: Temporarily reverted d28be4d5808947606b8189ae1b2900b8fd2925cf, while we move code to C# - - void *iter = nullptr; - MonoClass *raw_class = nullptr; - while ((raw_class = mono_class_get_nested_types(mono_class, &iter)) != nullptr) { - if (mono_class_is_delegate(raw_class)) { - StringName name = String::utf8(mono_class_get_name(raw_class)); - - HashMap<StringName, GDMonoClass *>::Iterator match = delegates.find(name); - - if (match) { - delegates_list.push_back(match->value); - } else { - GDMonoClass *delegate = memnew(GDMonoClass(String::utf8(mono_class_get_namespace(raw_class)), String::utf8(mono_class_get_name(raw_class)), raw_class, assembly)); - delegates.insert(name, delegate); - delegates_list.push_back(delegate); - } - } - } - - delegates_fetched = true; - - return delegates_list; -} - -const Vector<GDMonoMethod *> &GDMonoClass::get_all_methods() { - if (!method_list_fetched) { - void *iter = nullptr; - MonoMethod *raw_method = nullptr; - while ((raw_method = mono_class_get_methods(get_mono_ptr(), &iter)) != nullptr) { - method_list.push_back(memnew(GDMonoMethod(String::utf8(mono_method_get_name(raw_method)), raw_method))); - } - - method_list_fetched = true; - } - - return method_list; -} - -GDMonoClass::GDMonoClass(const StringName &p_namespace, const StringName &p_name, MonoClass *p_class, GDMonoAssembly *p_assembly) { - namespace_name = p_namespace; - class_name = p_name; - mono_class = p_class; - assembly = p_assembly; - - attrs_fetched = false; - attributes = nullptr; - - methods_fetched = false; - method_list_fetched = false; - fields_fetched = false; - properties_fetched = false; - delegates_fetched = false; -} - -GDMonoClass::~GDMonoClass() { - if (attributes) { - mono_custom_attrs_free(attributes); - } - - for (const KeyValue<StringName, GDMonoField *> &E : fields) { - memdelete(E.value); - } - - for (const KeyValue<StringName, GDMonoProperty *> &E : properties) { - memdelete(E.value); - } - - { - // Ugly workaround... - // We may have duplicated values, because we redirect snake_case methods to PascalCasel (only Godot API methods). - // This way, we end with both the snake_case name and the PascalCasel name paired with the same method. - // Therefore, we must avoid deleting the same pointer twice. - - int offset = 0; - Vector<GDMonoMethod *> deleted_methods; - deleted_methods.resize(methods.size()); - - for (const KeyValue<MethodKey, GDMonoMethod *> &E : methods) { - GDMonoMethod *method = E.value; - - if (method) { - for (int i = 0; i < offset; i++) { - if (deleted_methods[i] == method) { - // Already deleted - goto already_deleted; - } - } - - deleted_methods.write[offset] = method; - ++offset; - - memdelete(method); - } - - already_deleted:; - } - - methods.clear(); - } - - for (int i = 0; i < method_list.size(); ++i) { - memdelete(method_list[i]); - } -} diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h deleted file mode 100644 index 6b35da30f9..0000000000 --- a/modules/mono/mono_gd/gd_mono_class.h +++ /dev/null @@ -1,160 +0,0 @@ -/*************************************************************************/ -/* gd_mono_class.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef GD_MONO_CLASS_H -#define GD_MONO_CLASS_H - -#include "core/string/ustring.h" -#include "core/templates/rb_map.h" - -#include "gd_mono_field.h" -#include "gd_mono_header.h" -#include "gd_mono_method.h" -#include "gd_mono_property.h" -#include "gd_mono_utils.h" - -class GDMonoClass { - struct MethodKey { - struct Hasher { - static _FORCE_INLINE_ uint32_t hash(const MethodKey &p_key) { - uint32_t hash = 0; - - GDMonoUtils::hash_combine(hash, p_key.name.hash()); - GDMonoUtils::hash_combine(hash, HashMapHasherDefault::hash(p_key.params_count)); - - return hash; - } - }; - - _FORCE_INLINE_ bool operator==(const MethodKey &p_a) const { - return p_a.params_count == params_count && p_a.name == name; - } - - MethodKey() {} - - MethodKey(const StringName &p_name, uint16_t p_params_count) : - name(p_name), params_count(p_params_count) { - } - - StringName name; - uint16_t params_count = 0; - }; - - StringName namespace_name; - StringName class_name; - - MonoClass *mono_class = nullptr; - GDMonoAssembly *assembly = nullptr; - - bool attrs_fetched; - MonoCustomAttrInfo *attributes = nullptr; - - // This contains both the original method names and remapped method names from the native Godot identifiers to the C# functions. - // Most method-related functions refer to this and it's possible this is unintuitive for outside users; this may be a prime location for refactoring or renaming. - bool methods_fetched; - HashMap<MethodKey, GDMonoMethod *, MethodKey::Hasher> methods; - - bool method_list_fetched; - Vector<GDMonoMethod *> method_list; - - bool fields_fetched; - HashMap<StringName, GDMonoField *> fields; - Vector<GDMonoField *> fields_list; - - bool properties_fetched; - HashMap<StringName, GDMonoProperty *> properties; - Vector<GDMonoProperty *> properties_list; - - bool delegates_fetched; - HashMap<StringName, GDMonoClass *> delegates; - Vector<GDMonoClass *> delegates_list; - - friend class GDMonoAssembly; - GDMonoClass(const StringName &p_namespace, const StringName &p_name, MonoClass *p_class, GDMonoAssembly *p_assembly); - -public: - static String get_full_name(MonoClass *p_mono_class); - static MonoType *get_mono_type(MonoClass *p_mono_class); - - String get_full_name() const; - String get_type_desc() const; - MonoType *get_mono_type() const; - - uint32_t get_flags() const; - bool is_static() const; - - bool is_assignable_from(GDMonoClass *p_from) const; - - StringName get_namespace() const; - _FORCE_INLINE_ StringName get_name() const { return class_name; } - String get_name_for_lookup() const; - - _FORCE_INLINE_ MonoClass *get_mono_ptr() const { return mono_class; } - _FORCE_INLINE_ const GDMonoAssembly *get_assembly() const { return assembly; } - - GDMonoClass *get_parent_class() const; - GDMonoClass *get_nesting_class() const; - -#ifdef TOOLS_ENABLED - Vector<MonoClassField *> get_enum_fields(); -#endif - - GDMonoMethod *get_fetched_method_unknown_params(const StringName &p_name); - bool has_fetched_method_unknown_params(const StringName &p_name); - - bool has_attribute(GDMonoClass *p_attr_class); - MonoObject *get_attribute(GDMonoClass *p_attr_class); - - void fetch_attributes(); - void fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base); - - bool implements_interface(GDMonoClass *p_interface); - bool has_public_parameterless_ctor(); - - GDMonoMethod *get_method(const StringName &p_name, uint16_t p_params_count = 0); - GDMonoMethod *get_method(MonoMethod *p_raw_method); - GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name); - GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name, uint16_t p_params_count); - GDMonoMethod *get_method_with_desc(const String &p_description, bool p_include_namespace); - - GDMonoField *get_field(const StringName &p_name); - const Vector<GDMonoField *> &get_all_fields(); - - GDMonoProperty *get_property(const StringName &p_name); - const Vector<GDMonoProperty *> &get_all_properties(); - - const Vector<GDMonoClass *> &get_all_delegates(); - - const Vector<GDMonoMethod *> &get_all_methods(); - - ~GDMonoClass(); -}; - -#endif // GD_MONO_CLASS_H diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp deleted file mode 100644 index 6beeca79c3..0000000000 --- a/modules/mono/mono_gd/gd_mono_field.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/*************************************************************************/ -/* gd_mono_field.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "gd_mono_field.h" - -#include <mono/metadata/attrdefs.h> - -#include "gd_mono_cache.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" -#include "gd_mono_utils.h" - -void GDMonoField::set_value(MonoObject *p_object, MonoObject *p_value) { - mono_field_set_value(p_object, mono_field, p_value); -} - -void GDMonoField::set_value_raw(MonoObject *p_object, void *p_ptr) { - mono_field_set_value(p_object, mono_field, &p_ptr); -} - -void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_value) { - MonoReflectionField *reflfield = mono_field_get_object(mono_domain_get(), owner->get_mono_ptr(), mono_field); - - MonoException *exc = nullptr; - CACHED_METHOD_THUNK(Marshaling, SetFieldValue) - .invoke(reflfield, p_object, &p_value, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - } -} - -MonoObject *GDMonoField::get_value(MonoObject *p_object) { - return mono_field_get_value_object(mono_domain_get(), mono_field, p_object); -} - -bool GDMonoField::get_bool_value(MonoObject *p_object) { - return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object)); -} - -int GDMonoField::get_int_value(MonoObject *p_object) { - return GDMonoMarshal::unbox<int32_t>(get_value(p_object)); -} - -String GDMonoField::get_string_value(MonoObject *p_object) { - MonoObject *val = get_value(p_object); - return GDMonoMarshal::mono_string_to_godot((MonoString *)val); -} - -bool GDMonoField::has_attribute(GDMonoClass *p_attr_class) { - ERR_FAIL_NULL_V(p_attr_class, false); - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return false; - } - - return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); -} - -MonoObject *GDMonoField::get_attribute(GDMonoClass *p_attr_class) { - ERR_FAIL_NULL_V(p_attr_class, nullptr); - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return nullptr; - } - - return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); -} - -void GDMonoField::fetch_attributes() { - ERR_FAIL_COND(attributes != nullptr); - attributes = mono_custom_attrs_from_field(owner->get_mono_ptr(), mono_field); - attrs_fetched = true; -} - -bool GDMonoField::is_static() { - return mono_field_get_flags(mono_field) & MONO_FIELD_ATTR_STATIC; -} - -IMonoClassMember::Visibility GDMonoField::get_visibility() { - switch (mono_field_get_flags(mono_field) & MONO_FIELD_ATTR_FIELD_ACCESS_MASK) { - case MONO_FIELD_ATTR_PRIVATE: - return IMonoClassMember::PRIVATE; - case MONO_FIELD_ATTR_FAM_AND_ASSEM: - return IMonoClassMember::PROTECTED_AND_INTERNAL; - case MONO_FIELD_ATTR_ASSEMBLY: - return IMonoClassMember::INTERNAL; - case MONO_FIELD_ATTR_FAMILY: - return IMonoClassMember::PROTECTED; - case MONO_FIELD_ATTR_PUBLIC: - return IMonoClassMember::PUBLIC; - default: - ERR_FAIL_V(IMonoClassMember::PRIVATE); - } -} - -GDMonoField::GDMonoField(MonoClassField *p_mono_field, GDMonoClass *p_owner) { - owner = p_owner; - mono_field = p_mono_field; - name = String::utf8(mono_field_get_name(mono_field)); - MonoType *field_type = mono_field_get_type(mono_field); - type.type_encoding = mono_type_get_type(field_type); - MonoClass *field_type_class = mono_class_from_mono_type(field_type); - type.type_class = GDMono::get_singleton()->get_class(field_type_class); - - attrs_fetched = false; - attributes = nullptr; -} - -GDMonoField::~GDMonoField() { - if (attributes) { - mono_custom_attrs_free(attributes); - } -} diff --git a/modules/mono/mono_gd/gd_mono_field.h b/modules/mono/mono_gd/gd_mono_field.h deleted file mode 100644 index 1d30f7a369..0000000000 --- a/modules/mono/mono_gd/gd_mono_field.h +++ /dev/null @@ -1,78 +0,0 @@ -/*************************************************************************/ -/* gd_mono_field.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef GD_MONO_FIELD_H -#define GD_MONO_FIELD_H - -#include "gd_mono.h" -#include "gd_mono_header.h" -#include "i_mono_class_member.h" - -class GDMonoField : public IMonoClassMember { - GDMonoClass *owner = nullptr; - MonoClassField *mono_field = nullptr; - - StringName name; - ManagedType type; - - bool attrs_fetched; - MonoCustomAttrInfo *attributes = nullptr; - -public: - virtual GDMonoClass *get_enclosing_class() const final { return owner; } - - virtual MemberType get_member_type() const final { return MEMBER_TYPE_FIELD; } - - virtual StringName get_name() const final { return name; } - - virtual bool is_static() final; - virtual Visibility get_visibility() final; - - virtual bool has_attribute(GDMonoClass *p_attr_class) final; - virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) final; - void fetch_attributes(); - - _FORCE_INLINE_ ManagedType get_type() const { return type; } - - void set_value(MonoObject *p_object, MonoObject *p_value); - void set_value_raw(MonoObject *p_object, void *p_ptr); - void set_value_from_variant(MonoObject *p_object, const Variant &p_value); - - MonoObject *get_value(MonoObject *p_object); - - bool get_bool_value(MonoObject *p_object); - int get_int_value(MonoObject *p_object); - String get_string_value(MonoObject *p_object); - - GDMonoField(MonoClassField *p_mono_field, GDMonoClass *p_owner); - ~GDMonoField(); -}; - -#endif // GD_MONO_FIELD_H diff --git a/modules/mono/mono_gd/gd_mono_header.h b/modules/mono/mono_gd/gd_mono_header.h deleted file mode 100644 index bf21283080..0000000000 --- a/modules/mono/mono_gd/gd_mono_header.h +++ /dev/null @@ -1,52 +0,0 @@ -/*************************************************************************/ -/* gd_mono_header.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef GD_MONO_HEADER_H -#define GD_MONO_HEADER_H - -#include <cstdint> - -#ifdef WIN32 -#define GD_MONO_STDCALL __stdcall -#else -#define GD_MONO_STDCALL -#endif - -class GDMonoAssembly; -class GDMonoClass; -class GDMonoField; -class GDMonoMethod; -class GDMonoProperty; - -class IMonoClassMember; - -#include "managed_type.h" - -#endif // GD_MONO_HEADER_H diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp index d206b0dfc3..7b5fdef8a3 100644 --- a/modules/mono/mono_gd/gd_mono_internals.cpp +++ b/modules/mono/mono_gd/gd_mono_internals.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ @@ -31,10 +31,7 @@ #include "gd_mono_internals.h" #include "../csharp_script.h" -#include "../mono_gc_handle.h" #include "../utils/macros.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" #include "gd_mono_utils.h" #include "core/debugger/engine_debugger.h" @@ -43,77 +40,6 @@ #include <mono/metadata/exception.h> namespace GDMonoInternals { -void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { - // This method should not fail - - CRASH_COND(!unmanaged); - - // All mono objects created from the managed world (e.g.: 'new Player()') - // need to have a CSharpScript in order for their methods to be callable from the unmanaged side - - RefCounted *rc = Object::cast_to<RefCounted>(unmanaged); - - GDMonoClass *klass = GDMonoUtils::get_object_class(managed); - - CRASH_COND(!klass); - - GDMonoClass *native = GDMonoUtils::get_class_native_base(klass); - - CRASH_COND(native == nullptr); - - if (native == klass) { - // If it's just a wrapper Godot class and not a custom inheriting class, then attach a - // script binding instead. One of the advantages of this is that if a script is attached - // later and it's not a C# script, then the managed object won't have to be disposed. - // Another reason for doing this is that this instance could outlive CSharpLanguage, which would - // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621 - - CSharpScriptBinding script_binding; - - script_binding.inited = true; - script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass); - script_binding.wrapper_class = klass; - script_binding.gchandle = rc ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); - script_binding.owner = unmanaged; - - if (rc) { - // Unsafe refcount increment. The managed instance also counts as a reference. - // This way if the unmanaged world has no references to our owner - // but the managed instance is alive, the refcount will be 1 instead of 0. - // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr) - - // May not me referenced yet, so we must use init_ref() instead of reference() - if (rc->init_ref()) { - CSharpLanguage::get_singleton()->post_unsafe_reference(rc); - } - } - - // The object was just created, no script instance binding should have been attached - CRASH_COND(CSharpLanguage::has_instance_binding(unmanaged)); - - void *data; - { - MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex()); - data = (void *)CSharpLanguage::get_singleton()->insert_script_binding(unmanaged, script_binding); - } - - // Should be thread safe because the object was just created and nothing else should be referencing it - CSharpLanguage::set_instance_binding(unmanaged, data); - - return; - } - - MonoGCHandleData gchandle = rc ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); - - Ref<CSharpScript> script = CSharpScript::create_for_managed_type(klass, native); - - CRASH_COND(script.is_null()); - - CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(unmanaged, script.ptr(), gchandle); - - unmanaged->set_script_and_instance(script, csharp_instance); -} - void unhandled_exception(MonoException *p_exc) { mono_print_unhandled_exception((MonoObject *)p_exc); gd_unhandled_exception_event(p_exc); @@ -137,7 +63,7 @@ void gd_unhandled_exception_event(MonoException *p_exc) { MonoImage *mono_image = GDMono::get_singleton()->get_core_api_assembly()->get_image(); MonoClass *gd_klass = mono_class_from_name(mono_image, "Godot", "GD"); - MonoMethod *unhandled_exception_method = mono_class_get_method_from_name(gd_klass, "OnUnhandledException", -1); + MonoMethod *unhandled_exception_method = mono_class_get_method_from_name(gd_klass, "OnUnhandledException", 1); void *args[1]; args[0] = p_exc; mono_runtime_invoke(unhandled_exception_method, nullptr, (void **)args, nullptr); diff --git a/modules/mono/mono_gd/gd_mono_internals.h b/modules/mono/mono_gd/gd_mono_internals.h index a8f9cfa3ca..858c395b78 100644 --- a/modules/mono/mono_gd/gd_mono_internals.h +++ b/modules/mono/mono_gd/gd_mono_internals.h @@ -37,9 +37,9 @@ #include "core/object/class_db.h" -namespace GDMonoInternals { -void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged); +class CSharpScript; +namespace GDMonoInternals { /** * Do not call this function directly. * Use GDMonoUtils::debug_unhandled_exception(MonoException *) instead. diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp deleted file mode 100644 index 8828ec588b..0000000000 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/*************************************************************************/ -/* gd_mono_marshal.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "gd_mono_marshal.h" - -#include "../signal_awaiter_utils.h" -#include "gd_mono.h" -#include "gd_mono_cache.h" -#include "gd_mono_class.h" - -namespace GDMonoMarshal { - -// TODO: Those are just temporary until the code that needs them is moved to C# - -Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_variant) { - CRASH_COND(p_type.type_class == nullptr); - - MonoReflectionType *refltype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type()); - MonoBoolean nil_is_variant = false; - - MonoException *exc = nullptr; - int32_t ret = CACHED_METHOD_THUNK(Marshaling, managed_to_variant_type) - .invoke(refltype, &nil_is_variant, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - return Variant::NIL; - } - - if (r_nil_is_variant) { - *r_nil_is_variant = (bool)nil_is_variant; - } - - return (Variant::Type)ret; -} - -bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type) { - MonoReflectionType *array_refltype = mono_type_get_object(mono_domain_get(), p_array_type.type_class->get_mono_type()); - MonoReflectionType *elem_refltype = nullptr; - - MonoException *exc = nullptr; - MonoBoolean ret = CACHED_METHOD_THUNK(Marshaling, try_get_array_element_type) - .invoke(array_refltype, &elem_refltype, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - return Variant::NIL; - } - - r_elem_type = ManagedType::from_reftype(elem_refltype); - return ret; -} - -MonoObject *variant_to_mono_object_of_type(const Variant &p_var, const ManagedType &p_type) { - MonoReflectionType *refltype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type()); - - MonoException *exc = nullptr; - MonoObject *ret = CACHED_METHOD_THUNK(Marshaling, variant_to_mono_object_of_type) - .invoke(&p_var, refltype, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - return nullptr; - } - - return ret; -} - -MonoObject *variant_to_mono_object(const Variant &p_var) { - MonoException *exc = nullptr; - MonoObject *ret = CACHED_METHOD_THUNK(Marshaling, variant_to_mono_object) - .invoke(&p_var, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - return nullptr; - } - - return ret; -} - -static Variant mono_object_to_variant_impl(MonoObject *p_obj, bool p_fail_with_err) { - if (!p_obj) { - return Variant(); - } - - MonoBoolean fail_with_error = p_fail_with_err; - - Variant ret; - - MonoException *exc = nullptr; - CACHED_METHOD_THUNK(Marshaling, mono_object_to_variant_out) - .invoke(p_obj, fail_with_error, &ret, &exc); - - if (exc) { - GDMonoUtils::debug_print_unhandled_exception(exc); - return Variant(); - } - - return ret; -} - -Variant mono_object_to_variant(MonoObject *p_obj) { - return mono_object_to_variant_impl(p_obj, /* fail_with_err: */ true); -} - -Variant mono_object_to_variant_no_err(MonoObject *p_obj) { - return mono_object_to_variant_impl(p_obj, /* fail_with_err: */ false); -} - -MonoArray *PackedStringArray_to_mono_array(const PackedStringArray &p_array) { - const String *r = p_array.ptr(); - int length = p_array.size(); - - MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), length); - - for (int i = 0; i < length; i++) { - MonoString *boxed = mono_string_from_godot(r[i]); - mono_array_setref(ret, i, boxed); - } - - return ret; -} -} // namespace GDMonoMarshal diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h deleted file mode 100644 index fbe5795df5..0000000000 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ /dev/null @@ -1,97 +0,0 @@ -/*************************************************************************/ -/* gd_mono_marshal.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef GD_MONO_MARSHAL_H -#define GD_MONO_MARSHAL_H - -#include "core/variant/variant.h" - -#include "gd_mono.h" -#include "gd_mono_utils.h" - -namespace GDMonoMarshal { - -template <typename T> -T unbox(MonoObject *p_obj) { - return *(T *)mono_object_unbox(p_obj); -} - -Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_variant = nullptr); - -bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type); - -// String - -_FORCE_INLINE_ String mono_string_to_godot_not_null(MonoString *p_mono_string) { - char32_t *utf32 = (char32_t *)mono_string_to_utf32(p_mono_string); - String ret = String(utf32); - mono_free(utf32); - return ret; -} - -_FORCE_INLINE_ String mono_string_to_godot(MonoString *p_mono_string) { - if (p_mono_string == nullptr) { - return String(); - } - - return mono_string_to_godot_not_null(p_mono_string); -} - -_FORCE_INLINE_ MonoString *mono_string_from_godot(const String &p_string) { - return mono_string_from_utf32((mono_unichar4 *)(p_string.get_data())); -} - -// Variant - -MonoObject *variant_to_mono_object_of_type(const Variant &p_var, const ManagedType &p_type); - -MonoObject *variant_to_mono_object(const Variant &p_var); - -// These overloads were added to avoid passing a `const Variant *` to the `const Variant &` -// parameter. That would result in the `Variant(bool)` copy constructor being called as -// pointers are implicitly converted to bool. Implicit conversions are f-ing evil. - -_FORCE_INLINE_ MonoObject *variant_to_mono_object_of_type(const Variant *p_var, const ManagedType &p_type) { - return variant_to_mono_object_of_type(*p_var, p_type); -} -_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant *p_var) { - return variant_to_mono_object(*p_var); -} - -Variant mono_object_to_variant(MonoObject *p_obj); -Variant mono_object_to_variant_no_err(MonoObject *p_obj); - -// PackedStringArray - -MonoArray *PackedStringArray_to_mono_array(const PackedStringArray &p_array); - -} // namespace GDMonoMarshal - -#endif // GD_MONO_MARSHAL_H diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp deleted file mode 100644 index 97d3c82230..0000000000 --- a/modules/mono/mono_gd/gd_mono_method.cpp +++ /dev/null @@ -1,295 +0,0 @@ -/*************************************************************************/ -/* gd_mono_method.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "gd_mono_method.h" - -#include <mono/metadata/attrdefs.h> -#include <mono/metadata/debug-helpers.h> - -#include "gd_mono_cache.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" -#include "gd_mono_utils.h" - -void GDMonoMethod::_update_signature() { - // Apparently MonoMethodSignature needs not to be freed. - // mono_method_signature caches the result, we don't need to cache it ourselves. - - MonoMethodSignature *method_sig = mono_method_signature(mono_method); - _update_signature(method_sig); -} - -void GDMonoMethod::_update_signature(MonoMethodSignature *p_method_sig) { - params_count = mono_signature_get_param_count(p_method_sig); - - MonoType *ret_type = mono_signature_get_return_type(p_method_sig); - if (ret_type) { - return_type.type_encoding = mono_type_get_type(ret_type); - - if (return_type.type_encoding != MONO_TYPE_VOID) { - MonoClass *ret_type_class = mono_class_from_mono_type(ret_type); - return_type.type_class = GDMono::get_singleton()->get_class(ret_type_class); - } - } - - void *iter = nullptr; - MonoType *param_raw_type; - while ((param_raw_type = mono_signature_get_params(p_method_sig, &iter)) != nullptr) { - ManagedType param_type; - - param_type.type_encoding = mono_type_get_type(param_raw_type); - - MonoClass *param_type_class = mono_class_from_mono_type(param_raw_type); - param_type.type_class = GDMono::get_singleton()->get_class(param_type_class); - - param_types.push_back(param_type); - } - - // clear the cache - method_info_fetched = false; - method_info = MethodInfo(); -} - -GDMonoClass *GDMonoMethod::get_enclosing_class() const { - return GDMono::get_singleton()->get_class(mono_method_get_class(mono_method)); -} - -bool GDMonoMethod::is_static() { - return mono_method_get_flags(mono_method, nullptr) & MONO_METHOD_ATTR_STATIC; -} - -IMonoClassMember::Visibility GDMonoMethod::get_visibility() { - switch (mono_method_get_flags(mono_method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK) { - case MONO_METHOD_ATTR_PRIVATE: - return IMonoClassMember::PRIVATE; - case MONO_METHOD_ATTR_FAM_AND_ASSEM: - return IMonoClassMember::PROTECTED_AND_INTERNAL; - case MONO_METHOD_ATTR_ASSEM: - return IMonoClassMember::INTERNAL; - case MONO_METHOD_ATTR_FAMILY: - return IMonoClassMember::PROTECTED; - case MONO_METHOD_ATTR_PUBLIC: - return IMonoClassMember::PUBLIC; - default: - ERR_FAIL_V(IMonoClassMember::PRIVATE); - } -} - -MonoObject *GDMonoMethod::invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc) const { - MonoException *exc = nullptr; - MonoObject *ret; - - if (params_count > 0) { - MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), get_parameters_count()); - - for (int i = 0; i < params_count; i++) { - MonoObject *boxed_param = GDMonoMarshal::variant_to_mono_object_of_type(p_params[i], param_types[i]); - mono_array_setref(params, i, boxed_param); - } - - ret = GDMonoUtils::runtime_invoke_array(mono_method, p_object, params, &exc); - } else { - ret = GDMonoUtils::runtime_invoke(mono_method, p_object, nullptr, &exc); - } - - if (exc) { - ret = nullptr; - if (r_exc) { - *r_exc = exc; - } else { - GDMonoUtils::set_pending_exception(exc); - } - } - - return ret; -} - -MonoObject *GDMonoMethod::invoke(MonoObject *p_object, MonoException **r_exc) const { - ERR_FAIL_COND_V(get_parameters_count() > 0, nullptr); - return invoke_raw(p_object, nullptr, r_exc); -} - -MonoObject *GDMonoMethod::invoke_raw(MonoObject *p_object, void **p_params, MonoException **r_exc) const { - MonoException *exc = nullptr; - MonoObject *ret = GDMonoUtils::runtime_invoke(mono_method, p_object, p_params, &exc); - - if (exc) { - ret = nullptr; - if (r_exc) { - *r_exc = exc; - } else { - GDMonoUtils::set_pending_exception(exc); - } - } - - return ret; -} - -bool GDMonoMethod::has_attribute(GDMonoClass *p_attr_class) { - ERR_FAIL_NULL_V(p_attr_class, false); - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return false; - } - - return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); -} - -MonoObject *GDMonoMethod::get_attribute(GDMonoClass *p_attr_class) { - ERR_FAIL_NULL_V(p_attr_class, nullptr); - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return nullptr; - } - - return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); -} - -void GDMonoMethod::fetch_attributes() { - ERR_FAIL_COND(attributes != nullptr); - attributes = mono_custom_attrs_from_method(mono_method); - attrs_fetched = true; -} - -String GDMonoMethod::get_full_name(bool p_signature) const { - char *res = mono_method_full_name(mono_method, p_signature); - String full_name(res); - mono_free(res); - return full_name; -} - -String GDMonoMethod::get_full_name_no_class() const { - String res; - - MonoMethodSignature *method_sig = mono_method_signature(mono_method); - - char *ret_str = mono_type_full_name(mono_signature_get_return_type(method_sig)); - res += ret_str; - mono_free(ret_str); - - res += " "; - res += name; - res += "("; - - char *sig_desc = mono_signature_get_desc(method_sig, true); - res += sig_desc; - mono_free(sig_desc); - - res += ")"; - - return res; -} - -String GDMonoMethod::get_ret_type_full_name() const { - MonoMethodSignature *method_sig = mono_method_signature(mono_method); - char *ret_str = mono_type_full_name(mono_signature_get_return_type(method_sig)); - String res = ret_str; - mono_free(ret_str); - return res; -} - -String GDMonoMethod::get_signature_desc(bool p_namespaces) const { - MonoMethodSignature *method_sig = mono_method_signature(mono_method); - char *sig_desc = mono_signature_get_desc(method_sig, p_namespaces); - String res = sig_desc; - mono_free(sig_desc); - return res; -} - -void GDMonoMethod::get_parameter_names(Vector<StringName> &names) const { - if (params_count > 0) { - const char **_names = memnew_arr(const char *, params_count); - mono_method_get_param_names(mono_method, _names); - for (int i = 0; i < params_count; ++i) { - names.push_back(StringName(_names[i])); - } - memdelete_arr(_names); - } -} - -void GDMonoMethod::get_parameter_types(Vector<ManagedType> &types) const { - for (int i = 0; i < params_count; ++i) { - types.push_back(param_types[i]); - } -} - -const MethodInfo &GDMonoMethod::get_method_info() { - if (!method_info_fetched) { - method_info.name = name; - - bool nil_is_variant = false; - if (return_type.type_encoding == MONO_TYPE_VOID) { - method_info.return_val = PropertyInfo(Variant::NIL, ""); - } else { - method_info.return_val = PropertyInfo(GDMonoMarshal::managed_to_variant_type(return_type, &nil_is_variant), ""); - if (method_info.return_val.type == Variant::NIL && nil_is_variant) { - method_info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; - } - } - - Vector<StringName> names; - get_parameter_names(names); - - for (int i = 0; i < params_count; ++i) { - nil_is_variant = false; - PropertyInfo arg_info = PropertyInfo(GDMonoMarshal::managed_to_variant_type(param_types[i], &nil_is_variant), names[i]); - if (arg_info.type == Variant::NIL && nil_is_variant) { - arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; - } - - method_info.arguments.push_back(arg_info); - } - - // TODO: default arguments - - method_info_fetched = true; - } - - return method_info; -} - -GDMonoMethod::GDMonoMethod(StringName p_name, MonoMethod *p_method) : - name(p_name), mono_method(p_method) { - _update_signature(); -} - -GDMonoMethod::~GDMonoMethod() { - if (attributes) { - mono_custom_attrs_free(attributes); - } -} diff --git a/modules/mono/mono_gd/gd_mono_method.h b/modules/mono/mono_gd/gd_mono_method.h deleted file mode 100644 index 5398f34103..0000000000 --- a/modules/mono/mono_gd/gd_mono_method.h +++ /dev/null @@ -1,96 +0,0 @@ -/*************************************************************************/ -/* gd_mono_method.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef GD_MONO_METHOD_H -#define GD_MONO_METHOD_H - -#include "gd_mono.h" -#include "gd_mono_header.h" -#include "i_mono_class_member.h" - -class GDMonoMethod : public IMonoClassMember { - StringName name; - - uint16_t params_count; - ManagedType return_type; - Vector<ManagedType> param_types; - - bool method_info_fetched = false; - MethodInfo method_info; - - bool attrs_fetched = false; - MonoCustomAttrInfo *attributes = nullptr; - - void _update_signature(); - void _update_signature(MonoMethodSignature *p_method_sig); - - friend class GDMonoClass; - - MonoMethod *mono_method = nullptr; - -public: - virtual GDMonoClass *get_enclosing_class() const final; - - virtual MemberType get_member_type() const final { return MEMBER_TYPE_METHOD; } - - virtual StringName get_name() const final { return name; } - - virtual bool is_static() final; - - virtual Visibility get_visibility() final; - - virtual bool has_attribute(GDMonoClass *p_attr_class) final; - virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) final; - void fetch_attributes(); - - _FORCE_INLINE_ MonoMethod *get_mono_ptr() const { return mono_method; } - - _FORCE_INLINE_ uint16_t get_parameters_count() const { return params_count; } - _FORCE_INLINE_ ManagedType get_return_type() const { return return_type; } - - MonoObject *invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc = nullptr) const; - MonoObject *invoke(MonoObject *p_object, MonoException **r_exc = nullptr) const; - MonoObject *invoke_raw(MonoObject *p_object, void **p_params, MonoException **r_exc = nullptr) const; - - String get_full_name(bool p_signature = false) const; - String get_full_name_no_class() const; - String get_ret_type_full_name() const; - String get_signature_desc(bool p_namespaces = false) const; - - void get_parameter_names(Vector<StringName> &names) const; - void get_parameter_types(Vector<ManagedType> &types) const; - - const MethodInfo &get_method_info(); - - GDMonoMethod(StringName p_name, MonoMethod *p_method); - ~GDMonoMethod(); -}; - -#endif // GD_MONO_METHOD_H diff --git a/modules/mono/mono_gd/gd_mono_method_thunk.h b/modules/mono/mono_gd/gd_mono_method_thunk.h index 0180dee3ea..aa84a7f2d0 100644 --- a/modules/mono/mono_gd/gd_mono_method_thunk.h +++ b/modules/mono/mono_gd/gd_mono_method_thunk.h @@ -31,20 +31,19 @@ #ifndef GD_MONO_METHOD_THUNK_H #define GD_MONO_METHOD_THUNK_H +#include <mono/jit/jit.h> +#include <mono/metadata/attrdefs.h> #include <type_traits> -#include "gd_mono_class.h" -#include "gd_mono_header.h" -#include "gd_mono_marshal.h" -#include "gd_mono_method.h" +#include "core/error/error_macros.h" #include "gd_mono_utils.h" -#if !defined(JAVASCRIPT_ENABLED) && !defined(IOS_ENABLED) -#define HAVE_METHOD_THUNKS +#ifdef WIN32 +#define GD_MONO_STDCALL __stdcall +#else +#define GD_MONO_STDCALL #endif -#ifdef HAVE_METHOD_THUNKS - template <class... ParamTypes> struct GDMonoMethodThunk { typedef void(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **); @@ -58,33 +57,30 @@ public: GD_MONO_END_RUNTIME_INVOKE; } - _FORCE_INLINE_ bool is_null() { + bool is_null() { return mono_method_thunk == nullptr; } - _FORCE_INLINE_ void nullify() { - mono_method_thunk = nullptr; - } - - _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { + void set_from_method(MonoMethod *p_mono_method) { #ifdef DEBUG_ENABLED CRASH_COND(p_mono_method == nullptr); - CRASH_COND(p_mono_method->get_return_type().type_encoding != MONO_TYPE_VOID); - if (p_mono_method->is_static()) { - CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); - } else { - CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); - } + MonoMethodSignature *method_sig = mono_method_signature(p_mono_method); + MonoType *ret_type = mono_signature_get_return_type(method_sig); + int ret_type_encoding = ret_type ? mono_type_get_type(ret_type) : MONO_TYPE_VOID; + + CRASH_COND(ret_type_encoding != MONO_TYPE_VOID); + + bool is_static = mono_method_get_flags(p_mono_method, nullptr) & MONO_METHOD_ATTR_STATIC; + CRASH_COND(!is_static); + + uint32_t parameters_count = mono_signature_get_param_count(method_sig); + CRASH_COND(parameters_count != sizeof...(ParamTypes)); #endif - mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr()); + mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method); } GDMonoMethodThunk() {} - - explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) { - set_from_method(p_mono_method); - } }; template <class R, class... ParamTypes> @@ -101,220 +97,30 @@ public: return r; } - _FORCE_INLINE_ bool is_null() { + bool is_null() { return mono_method_thunk == nullptr; } - _FORCE_INLINE_ void nullify() { - mono_method_thunk = nullptr; - } - - _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { -#ifdef DEBUG_ENABLED - CRASH_COND(p_mono_method == nullptr); - CRASH_COND(p_mono_method->get_return_type().type_encoding == MONO_TYPE_VOID); - - if (p_mono_method->is_static()) { - CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); - } else { - CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); - } -#endif - mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr()); - } - - GDMonoMethodThunkR() {} - - explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) { -#ifdef DEBUG_ENABLED - CRASH_COND(p_mono_method == nullptr); -#endif - mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr()); - } -}; - -#else - -template <unsigned int ThunkParamCount, class P1, class... ParamTypes> -struct VariadicInvokeMonoMethodImpl { - static void invoke(GDMonoMethod *p_mono_method, P1 p_arg1, ParamTypes... p_args, MonoException **r_exc) { - if (p_mono_method->is_static()) { - void *args[ThunkParamCount] = { p_arg1, p_args... }; - p_mono_method->invoke_raw(nullptr, args, r_exc); - } else { - void *args[ThunkParamCount] = { p_args... }; - p_mono_method->invoke_raw((MonoObject *)p_arg1, args, r_exc); - } - } -}; - -template <unsigned int ThunkParamCount, class... ParamTypes> -struct VariadicInvokeMonoMethod { - static void invoke(GDMonoMethod *p_mono_method, ParamTypes... p_args, MonoException **r_exc) { - VariadicInvokeMonoMethodImpl<ThunkParamCount, ParamTypes...>::invoke(p_mono_method, p_args..., r_exc); - } -}; - -template <> -struct VariadicInvokeMonoMethod<0> { - static void invoke(GDMonoMethod *p_mono_method, MonoException **r_exc) { -#ifdef DEBUG_ENABLED - CRASH_COND(!p_mono_method->is_static()); -#endif - p_mono_method->invoke_raw(nullptr, nullptr, r_exc); - } -}; - -template <class P1> -struct VariadicInvokeMonoMethod<1, P1> { - static void invoke(GDMonoMethod *p_mono_method, P1 p_arg1, MonoException **r_exc) { - if (p_mono_method->is_static()) { - void *args[1] = { p_arg1 }; - p_mono_method->invoke_raw(nullptr, args, r_exc); - } else { - p_mono_method->invoke_raw((MonoObject *)p_arg1, nullptr, r_exc); - } - } -}; - -template <class R> -R unbox_if_needed(MonoObject *p_val, const ManagedType &, typename std::enable_if<!std::is_pointer<R>::value>::type * = 0) { - return GDMonoMarshal::unbox<R>(p_val); -} - -template <class R> -R unbox_if_needed(MonoObject *p_val, const ManagedType &p_type, typename std::enable_if<std::is_pointer<R>::value>::type * = 0) { - if (mono_class_is_valuetype(p_type.type_class->get_mono_ptr())) { - return GDMonoMarshal::unbox<R>(p_val); - } else { - // If it's not a value type, we assume 'R' is a pointer to 'MonoObject' or a compatible type, like 'MonoException'. - return (R)p_val; - } -} - -template <unsigned int ThunkParamCount, class R, class P1, class... ParamTypes> -struct VariadicInvokeMonoMethodRImpl { - static R invoke(GDMonoMethod *p_mono_method, P1 p_arg1, ParamTypes... p_args, MonoException **r_exc) { - if (p_mono_method->is_static()) { - void *args[ThunkParamCount] = { p_arg1, p_args... }; - MonoObject *r = p_mono_method->invoke_raw(nullptr, args, r_exc); - return unbox_if_needed<R>(r, p_mono_method->get_return_type()); - } else { - void *args[ThunkParamCount] = { p_args... }; - MonoObject *r = p_mono_method->invoke_raw((MonoObject *)p_arg1, args, r_exc); - return unbox_if_needed<R>(r, p_mono_method->get_return_type()); - } - } -}; - -template <unsigned int ThunkParamCount, class R, class... ParamTypes> -struct VariadicInvokeMonoMethodR { - static R invoke(GDMonoMethod *p_mono_method, ParamTypes... p_args, MonoException **r_exc) { - return VariadicInvokeMonoMethodRImpl<ThunkParamCount, R, ParamTypes...>::invoke(p_mono_method, p_args..., r_exc); - } -}; - -template <class R> -struct VariadicInvokeMonoMethodR<0, R> { - static R invoke(GDMonoMethod *p_mono_method, MonoException **r_exc) { -#ifdef DEBUG_ENABLED - CRASH_COND(!p_mono_method->is_static()); -#endif - MonoObject *r = p_mono_method->invoke_raw(nullptr, nullptr, r_exc); - return unbox_if_needed<R>(r, p_mono_method->get_return_type()); - } -}; - -template <class R, class P1> -struct VariadicInvokeMonoMethodR<1, R, P1> { - static R invoke(GDMonoMethod *p_mono_method, P1 p_arg1, MonoException **r_exc) { - if (p_mono_method->is_static()) { - void *args[1] = { p_arg1 }; - MonoObject *r = p_mono_method->invoke_raw(nullptr, args, r_exc); - return unbox_if_needed<R>(r, p_mono_method->get_return_type()); - } else { - MonoObject *r = p_mono_method->invoke_raw((MonoObject *)p_arg1, nullptr, r_exc); - return unbox_if_needed<R>(r, p_mono_method->get_return_type()); - } - } -}; - -template <class... ParamTypes> -struct GDMonoMethodThunk { - GDMonoMethod *mono_method = nullptr; - -public: - _FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) { - VariadicInvokeMonoMethod<sizeof...(ParamTypes), ParamTypes...>::invoke(mono_method, p_args..., r_exc); - } - - _FORCE_INLINE_ bool is_null() { - return mono_method == nullptr; - } - - _FORCE_INLINE_ void nullify() { - mono_method = nullptr; - } - - _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { + void set_from_method(MonoMethod *p_mono_method) { #ifdef DEBUG_ENABLED CRASH_COND(p_mono_method == nullptr); - CRASH_COND(p_mono_method->get_return_type().type_encoding != MONO_TYPE_VOID); - if (p_mono_method->is_static()) { - CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); - } else { - CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); - } -#endif - mono_method = p_mono_method; - } - - GDMonoMethodThunk() {} - - explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) { - set_from_method(p_mono_method); - } -}; + MonoMethodSignature *method_sig = mono_method_signature(p_mono_method); + MonoType *ret_type = mono_signature_get_return_type(method_sig); + int ret_type_encoding = ret_type ? mono_type_get_type(ret_type) : MONO_TYPE_VOID; -template <class R, class... ParamTypes> -struct GDMonoMethodThunkR { - GDMonoMethod *mono_method = nullptr; + CRASH_COND(ret_type_encoding == MONO_TYPE_VOID); -public: - _FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) { - return VariadicInvokeMonoMethodR<sizeof...(ParamTypes), R, ParamTypes...>::invoke(mono_method, p_args..., r_exc); - } + bool is_static = mono_method_get_flags(p_mono_method, nullptr) & MONO_METHOD_ATTR_STATIC; + CRASH_COND(!is_static); - _FORCE_INLINE_ bool is_null() { - return mono_method == nullptr; - } - - _FORCE_INLINE_ void nullify() { - mono_method = nullptr; - } - - _FORCE_INLINE_ void set_from_method(GDMonoMethod *p_mono_method) { -#ifdef DEBUG_ENABLED - CRASH_COND(p_mono_method == nullptr); - CRASH_COND(p_mono_method->get_return_type().type_encoding == MONO_TYPE_VOID); - - if (p_mono_method->is_static()) { - CRASH_COND(p_mono_method->get_parameters_count() != sizeof...(ParamTypes)); - } else { - CRASH_COND(p_mono_method->get_parameters_count() != (sizeof...(ParamTypes) - 1)); - } + uint32_t parameters_count = mono_signature_get_param_count(method_sig); + CRASH_COND(parameters_count != sizeof...(ParamTypes)); #endif - mono_method = p_mono_method; + mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method); } GDMonoMethodThunkR() {} - - explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) { - set_from_method(p_mono_method); - } }; -#endif - #endif // GD_MONO_METHOD_THUNK_H diff --git a/modules/mono/mono_gd/gd_mono_property.cpp b/modules/mono/mono_gd/gd_mono_property.cpp deleted file mode 100644 index 7cbf5be151..0000000000 --- a/modules/mono/mono_gd/gd_mono_property.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/*************************************************************************/ -/* gd_mono_property.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "gd_mono_property.h" - -#include "gd_mono_cache.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" -#include "gd_mono_utils.h" - -#include <mono/metadata/attrdefs.h> - -GDMonoProperty::GDMonoProperty(MonoProperty *p_mono_property, GDMonoClass *p_owner) { - owner = p_owner; - mono_property = p_mono_property; - name = String::utf8(mono_property_get_name(mono_property)); - - MonoMethod *prop_method = mono_property_get_get_method(mono_property); - - if (prop_method) { - MonoMethodSignature *getter_sig = mono_method_signature(prop_method); - - MonoType *ret_type = mono_signature_get_return_type(getter_sig); - - type.type_encoding = mono_type_get_type(ret_type); - MonoClass *ret_type_class = mono_class_from_mono_type(ret_type); - type.type_class = GDMono::get_singleton()->get_class(ret_type_class); - } else { - prop_method = mono_property_get_set_method(mono_property); - - MonoMethodSignature *setter_sig = mono_method_signature(prop_method); - - void *iter = nullptr; - MonoType *param_raw_type = mono_signature_get_params(setter_sig, &iter); - - type.type_encoding = mono_type_get_type(param_raw_type); - MonoClass *param_type_class = mono_class_from_mono_type(param_raw_type); - type.type_class = GDMono::get_singleton()->get_class(param_type_class); - } - - attrs_fetched = false; - attributes = nullptr; -} - -GDMonoProperty::~GDMonoProperty() { - if (attributes) { - mono_custom_attrs_free(attributes); - } -} - -bool GDMonoProperty::is_static() { - MonoMethod *prop_method = mono_property_get_get_method(mono_property); - if (prop_method == nullptr) { - prop_method = mono_property_get_set_method(mono_property); - } - return mono_method_get_flags(prop_method, nullptr) & MONO_METHOD_ATTR_STATIC; -} - -IMonoClassMember::Visibility GDMonoProperty::get_visibility() { - MonoMethod *prop_method = mono_property_get_get_method(mono_property); - if (prop_method == nullptr) { - prop_method = mono_property_get_set_method(mono_property); - } - - switch (mono_method_get_flags(prop_method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK) { - case MONO_METHOD_ATTR_PRIVATE: - return IMonoClassMember::PRIVATE; - case MONO_METHOD_ATTR_FAM_AND_ASSEM: - return IMonoClassMember::PROTECTED_AND_INTERNAL; - case MONO_METHOD_ATTR_ASSEM: - return IMonoClassMember::INTERNAL; - case MONO_METHOD_ATTR_FAMILY: - return IMonoClassMember::PROTECTED; - case MONO_METHOD_ATTR_PUBLIC: - return IMonoClassMember::PUBLIC; - default: - ERR_FAIL_V(IMonoClassMember::PRIVATE); - } -} - -bool GDMonoProperty::has_attribute(GDMonoClass *p_attr_class) { - ERR_FAIL_NULL_V(p_attr_class, false); - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return false; - } - - return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr()); -} - -MonoObject *GDMonoProperty::get_attribute(GDMonoClass *p_attr_class) { - ERR_FAIL_NULL_V(p_attr_class, nullptr); - - if (!attrs_fetched) { - fetch_attributes(); - } - - if (!attributes) { - return nullptr; - } - - return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr()); -} - -void GDMonoProperty::fetch_attributes() { - ERR_FAIL_COND(attributes != nullptr); - attributes = mono_custom_attrs_from_property(owner->get_mono_ptr(), mono_property); - attrs_fetched = true; -} - -bool GDMonoProperty::has_getter() { - return mono_property_get_get_method(mono_property) != nullptr; -} - -bool GDMonoProperty::has_setter() { - return mono_property_get_set_method(mono_property) != nullptr; -} - -void GDMonoProperty::set_value_from_variant(MonoObject *p_object, const Variant &p_value, MonoException **r_exc) { - MonoMethod *set_method = mono_property_get_set_method(mono_property); - ERR_FAIL_COND(set_method == nullptr); - - // Temporary solution, while moving code to C# - MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), 1); - MonoObject *boxed_param = GDMonoMarshal::variant_to_mono_object_of_type(p_value, type); - mono_array_setref(params, 0, boxed_param); - - MonoException *exc = nullptr; - GDMonoUtils::runtime_invoke_array(set_method, p_object, params, &exc); - if (exc) { - if (r_exc) { - *r_exc = exc; - } else { - GDMonoUtils::set_pending_exception(exc); - } - } -} - -MonoObject *GDMonoProperty::get_value(MonoObject *p_object, MonoException **r_exc) { - MonoException *exc = nullptr; - MonoObject *ret = GDMonoUtils::property_get_value(mono_property, p_object, nullptr, &exc); - - if (exc) { - ret = nullptr; - if (r_exc) { - *r_exc = exc; - } else { - GDMonoUtils::set_pending_exception(exc); - } - } - - return ret; -} - -bool GDMonoProperty::get_bool_value(MonoObject *p_object) { - return (bool)GDMonoMarshal::unbox<MonoBoolean>(get_value(p_object)); -} - -int GDMonoProperty::get_int_value(MonoObject *p_object) { - return GDMonoMarshal::unbox<int32_t>(get_value(p_object)); -} - -String GDMonoProperty::get_string_value(MonoObject *p_object) { - MonoObject *val = get_value(p_object); - return GDMonoMarshal::mono_string_to_godot((MonoString *)val); -} diff --git a/modules/mono/mono_gd/gd_mono_property.h b/modules/mono/mono_gd/gd_mono_property.h deleted file mode 100644 index 885ea8f011..0000000000 --- a/modules/mono/mono_gd/gd_mono_property.h +++ /dev/null @@ -1,78 +0,0 @@ -/*************************************************************************/ -/* gd_mono_property.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef GD_MONO_PROPERTY_H -#define GD_MONO_PROPERTY_H - -#include "gd_mono.h" -#include "gd_mono_header.h" -#include "i_mono_class_member.h" - -class GDMonoProperty : public IMonoClassMember { - GDMonoClass *owner = nullptr; - MonoProperty *mono_property = nullptr; - - StringName name; - ManagedType type; - - bool attrs_fetched; - MonoCustomAttrInfo *attributes = nullptr; - -public: - virtual GDMonoClass *get_enclosing_class() const final { return owner; } - - virtual MemberType get_member_type() const final { return MEMBER_TYPE_PROPERTY; } - - virtual StringName get_name() const final { return name; } - - virtual bool is_static() final; - virtual Visibility get_visibility() final; - - virtual bool has_attribute(GDMonoClass *p_attr_class) final; - virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) final; - void fetch_attributes(); - - bool has_getter(); - bool has_setter(); - - _FORCE_INLINE_ ManagedType get_type() const { return type; } - - void set_value_from_variant(MonoObject *p_object, const Variant &p_value, MonoException **r_exc = nullptr); - MonoObject *get_value(MonoObject *p_object, MonoException **r_exc = nullptr); - - bool get_bool_value(MonoObject *p_object); - int get_int_value(MonoObject *p_object); - String get_string_value(MonoObject *p_object); - - GDMonoProperty(MonoProperty *p_mono_property, GDMonoClass *p_owner); - ~GDMonoProperty(); -}; - -#endif // GD_MONO_PROPERTY_H diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index e240381112..3e2f4b05d5 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -48,68 +48,9 @@ #include "../utils/macros.h" #include "gd_mono.h" #include "gd_mono_cache.h" -#include "gd_mono_class.h" -#include "gd_mono_marshal.h" namespace GDMonoUtils { -MonoObject *unmanaged_get_managed(Object *unmanaged) { - if (!unmanaged) { - return nullptr; - } - - if (unmanaged->get_script_instance()) { - CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(unmanaged->get_script_instance()); - - if (cs_instance) { - return cs_instance->get_mono_object(); - } - } - - // If the owner does not have a CSharpInstance... - - void *data = CSharpLanguage::get_instance_binding(unmanaged); - ERR_FAIL_NULL_V(data, nullptr); - CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->value(); - ERR_FAIL_COND_V(!script_binding.inited, nullptr); - - MonoGCHandleData &gchandle = script_binding.gchandle; - - MonoObject *target = gchandle.get_target(); - - if (target) { - return target; - } - - CSharpLanguage::get_singleton()->release_script_gchandle(gchandle); - - // Create a new one - -#ifdef DEBUG_ENABLED - CRASH_COND(script_binding.type_name == StringName()); - CRASH_COND(script_binding.wrapper_class == nullptr); -#endif - - MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(script_binding.wrapper_class, script_binding.type_name, unmanaged); - ERR_FAIL_NULL_V(mono_object, nullptr); - - gchandle = MonoGCHandleData::new_strong_handle(mono_object); - - // Tie managed to unmanaged - RefCounted *rc = Object::cast_to<RefCounted>(unmanaged); - - if (rc) { - // Unsafe refcount increment. The managed instance also counts as a reference. - // This way if the unmanaged world has no references to our owner - // but the managed instance is alive, the refcount will be 1 instead of 0. - // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr) - rc->reference(); - CSharpLanguage::get_singleton()->post_unsafe_reference(rc); - } - - return mono_object; -} - void set_main_thread(MonoThread *p_thread) { mono_thread_set_main(p_thread); } @@ -148,90 +89,6 @@ bool is_thread_attached() { return mono_domain_get() != nullptr; } -uint32_t new_strong_gchandle(MonoObject *p_object) { - return mono_gchandle_new(p_object, /* pinned: */ false); -} - -uint32_t new_strong_gchandle_pinned(MonoObject *p_object) { - return mono_gchandle_new(p_object, /* pinned: */ true); -} - -uint32_t new_weak_gchandle(MonoObject *p_object) { - return mono_gchandle_new_weakref(p_object, /* track_resurrection: */ false); -} - -void free_gchandle(uint32_t p_gchandle) { - mono_gchandle_free(p_gchandle); -} - -void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc) { - GDMonoMethod *ctor = p_class->get_method(".ctor", 0); - ERR_FAIL_NULL(ctor); - ctor->invoke_raw(p_this_obj, nullptr, r_exc); -} - -GDMonoClass *get_object_class(MonoObject *p_object) { - return GDMono::get_singleton()->get_class(mono_object_get_class(p_object)); -} - -GDMonoClass *type_get_proxy_class(const StringName &p_type) { - String class_name = p_type; - - if (class_name[0] == '_') { - class_name = class_name.substr(1, class_name.length()); - } - - GDMonoClass *klass = GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name); - - if (klass && klass->is_static()) { - // A static class means this is a Godot singleton class. If an instance is needed we use Godot.Object. - return GDMonoCache::cached_data.class_GodotObject; - } - -#ifdef TOOLS_ENABLED - if (!klass) { - return GDMono::get_singleton()->get_editor_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name); - } -#endif - - return klass; -} - -GDMonoClass *get_class_native_base(GDMonoClass *p_class) { - GDMonoClass *klass = p_class; - - do { - const GDMonoAssembly *assembly = klass->get_assembly(); - - if (assembly == GDMono::get_singleton()->get_core_api_assembly()) { - return klass; - } -#ifdef TOOLS_ENABLED - if (assembly == GDMono::get_singleton()->get_editor_api_assembly()) { - return klass; - } -#endif - } while ((klass = klass->get_parent_class()) != nullptr); - - return nullptr; -} - -MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object) { - bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), p_native); - ERR_FAIL_COND_V_MSG(!parent_is_object_class, nullptr, - "Type inherits from native type '" + p_native + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'."); - - MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr()); - ERR_FAIL_NULL_V(mono_object, nullptr); - - CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, p_object); - - // Construct - GDMonoUtils::runtime_object_init(mono_object, p_class); - - return mono_object; -} - MonoDomain *create_domain(const String &p_friendly_name) { print_verbose("Mono: Creating domain '" + p_friendly_name + "'..."); @@ -247,14 +104,12 @@ MonoDomain *create_domain(const String &p_friendly_name) { return domain; } -String get_type_desc(MonoType *p_type) { - return mono_type_full_name(p_type); -} - -String get_type_desc(MonoReflectionType *p_reftype) { - return get_type_desc(mono_reflection_type_get_type(p_reftype)); -} +// TODO: +// Implement all of the disabled exception logging below. Once we move to .NET 6. +// It will have to be done from C# as UnmanagedCallersOnly doesn't allow throwing. +#warning TODO +#if 0 String get_exception_name_and_message(MonoException *p_exc) { String res; @@ -273,6 +128,7 @@ String get_exception_name_and_message(MonoException *p_exc) { return res; } +#endif void debug_print_unhandled_exception(MonoException *p_exc) { print_unhandled_exception(p_exc); @@ -284,7 +140,10 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) { if (!EngineDebugger::is_active()) { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { +#warning TODO +#if 0 ERR_PRINT(GDMonoUtils::get_exception_name_and_message(p_exc)); +#endif } #endif return; @@ -305,6 +164,8 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) { Vector<ScriptLanguage::StackInfo> si; String exc_msg; +#warning TODO +#if 0 while (p_exc != nullptr) { GDMonoClass *st_klass = CACHED_CLASS(System_Diagnostics_StackTrace); MonoObject *stack_trace = mono_object_new(mono_domain_get(), st_klass->get_mono_ptr()); @@ -341,6 +202,7 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) { p_exc = (MonoException *)inner_exc; } +#endif String file = si.size() ? si[0].file : __FILE__; String func = si.size() ? si[0].func : FUNCTION_STR; @@ -377,101 +239,6 @@ void set_pending_exception(MonoException *p_exc) { thread_local int current_invoke_count = 0; -MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, MonoException **r_exc) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - MonoObject *ret = mono_runtime_invoke(p_method, p_obj, p_params, (MonoObject **)r_exc); - GD_MONO_END_RUNTIME_INVOKE; - return ret; -} - -MonoObject *runtime_invoke_array(MonoMethod *p_method, void *p_obj, MonoArray *p_params, MonoException **r_exc) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - MonoObject *ret = mono_runtime_invoke_array(p_method, p_obj, p_params, (MonoObject **)r_exc); - GD_MONO_END_RUNTIME_INVOKE; - return ret; -} - -MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - MonoString *ret = mono_object_to_string(p_obj, (MonoObject **)r_exc); - GD_MONO_END_RUNTIME_INVOKE; - return ret; -} - -void property_set_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - mono_property_set_value(p_prop, p_obj, p_params, (MonoObject **)r_exc); - GD_MONO_END_RUNTIME_INVOKE; -} - -MonoObject *property_get_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc) { - GD_MONO_BEGIN_RUNTIME_INVOKE; - MonoObject *ret = mono_property_get_value(p_prop, p_obj, p_params, (MonoObject **)r_exc); - GD_MONO_END_RUNTIME_INVOKE; - return ret; -} - -uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool &r_error) { - r_error = false; - switch (mono_type_get_type(p_enum_basetype)) { - case MONO_TYPE_BOOLEAN: - return (bool)GDMonoMarshal::unbox<MonoBoolean>(p_boxed) ? 1 : 0; - case MONO_TYPE_CHAR: - return GDMonoMarshal::unbox<uint16_t>(p_boxed); - case MONO_TYPE_U1: - return GDMonoMarshal::unbox<uint8_t>(p_boxed); - case MONO_TYPE_U2: - return GDMonoMarshal::unbox<uint16_t>(p_boxed); - case MONO_TYPE_U4: - return GDMonoMarshal::unbox<uint32_t>(p_boxed); - case MONO_TYPE_U8: - return GDMonoMarshal::unbox<uint64_t>(p_boxed); - case MONO_TYPE_I1: - return GDMonoMarshal::unbox<int8_t>(p_boxed); - case MONO_TYPE_I2: - return GDMonoMarshal::unbox<int16_t>(p_boxed); - case MONO_TYPE_I4: - return GDMonoMarshal::unbox<int32_t>(p_boxed); - case MONO_TYPE_I8: - return GDMonoMarshal::unbox<int64_t>(p_boxed); - default: - r_error = true; - return 0; - } -} - -void dispose(MonoObject *p_mono_object, MonoException **r_exc) { - CACHED_METHOD_THUNK(GodotObject, Dispose).invoke(p_mono_object, r_exc); -} - -namespace Marshal { - -#ifdef MONO_GLUE_ENABLED -#ifdef TOOLS_ENABLED -#define NO_GLUE_RET(m_ret) \ - { \ - if (!GDMonoCache::cached_data.godot_api_cache_updated) \ - return m_ret; \ - } -#else -#define NO_GLUE_RET(m_ret) \ - {} -#endif -#else -#define NO_GLUE_RET(m_ret) \ - { return m_ret; } -#endif - -bool type_has_flags_attribute(MonoReflectionType *p_reftype) { - NO_GLUE_RET(false); - MonoException *exc = nullptr; - MonoBoolean res = CACHED_METHOD_THUNK(MarshalUtils, TypeHasFlagsAttribute).invoke(p_reftype, &exc); - UNHANDLED_EXCEPTION(exc); - return (bool)res; -} - -} // namespace Marshal - ScopeThreadAttach::ScopeThreadAttach() { if (likely(GDMono::get_singleton()->is_runtime_initialized()) && unlikely(!mono_domain_get())) { mono_thread = GDMonoUtils::attach_current_thread(); @@ -483,9 +250,4 @@ ScopeThreadAttach::~ScopeThreadAttach() { GDMonoUtils::detach_current_thread(mono_thread); } } - -StringName get_native_godot_class_name(GDMonoClass *p_class) { - MonoObject *native_name_obj = p_class->get_field(BINDINGS_NATIVE_NAME_FIELD)->get_value(nullptr); - return (StringName)GDMonoMarshal::mono_object_to_variant(native_name_obj); -} } // namespace GDMonoUtils diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index ee1be979e7..16fc3cc757 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -35,7 +35,6 @@ #include "../mono_gc_handle.h" #include "../utils/macros.h" -#include "gd_mono_header.h" #ifdef JAVASCRIPT_ENABLED #include "gd_mono_wasm_m2n.h" #endif @@ -60,13 +59,6 @@ _FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) p_hash ^= p_with_hash + 0x9e3779b9 + (p_hash << 6) + (p_hash >> 2); } -/** - * If the object has a csharp script, returns the target of the gchandle stored in the script instance - * Otherwise returns a newly constructed MonoObject* which is attached to the object - * Returns nullptr on error - */ -MonoObject *unmanaged_get_managed(Object *unmanaged); - void set_main_thread(MonoThread *p_thread); MonoThread *attach_current_thread(); void detach_current_thread(); @@ -74,24 +66,8 @@ void detach_current_thread(MonoThread *p_mono_thread); MonoThread *get_current_thread(); bool is_thread_attached(); -uint32_t new_strong_gchandle(MonoObject *p_object); -uint32_t new_strong_gchandle_pinned(MonoObject *p_object); -uint32_t new_weak_gchandle(MonoObject *p_object); -void free_gchandle(uint32_t p_gchandle); - -void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc = nullptr); - -GDMonoClass *get_object_class(MonoObject *p_object); -GDMonoClass *type_get_proxy_class(const StringName &p_type); -GDMonoClass *get_class_native_base(GDMonoClass *p_class); - -MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object); - MonoDomain *create_domain(const String &p_friendly_name); -String get_type_desc(MonoType *p_type); -String get_type_desc(MonoReflectionType *p_reftype); - String get_exception_name_and_message(MonoException *p_exc); void debug_print_unhandled_exception(MonoException *p_exc); @@ -116,18 +92,8 @@ _FORCE_INLINE_ int &get_runtime_invoke_count_ref() { return current_invoke_count; } -MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, MonoException **r_exc); -MonoObject *runtime_invoke_array(MonoMethod *p_method, void *p_obj, MonoArray *p_params, MonoException **r_exc); - -MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc); - -void property_set_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc); -MonoObject *property_get_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc); - uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool &r_error); -void dispose(MonoObject *p_mono_object, MonoException **r_exc); - struct ScopeThreadAttach { ScopeThreadAttach(); ~ScopeThreadAttach(); @@ -136,8 +102,6 @@ private: MonoThread *mono_thread = nullptr; }; -StringName get_native_godot_class_name(GDMonoClass *p_class); - template <typename... P> void add_internal_call(const char *p_name, void (*p_func)(P...)) { #ifdef JAVASCRIPT_ENABLED @@ -155,8 +119,6 @@ void add_internal_call(const char *p_name, R (*p_func)(P...)) { } } // namespace GDMonoUtils -#define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoUtils::get_native_godot_class_name(m_class)) - #define GD_MONO_BEGIN_RUNTIME_INVOKE \ int &_runtime_invoke_count_ref = GDMonoUtils::get_runtime_invoke_count_ref(); \ _runtime_invoke_count_ref += 1; \ diff --git a/modules/mono/mono_gd/i_mono_class_member.h b/modules/mono/mono_gd/i_mono_class_member.h deleted file mode 100644 index 14e8ca82b9..0000000000 --- a/modules/mono/mono_gd/i_mono_class_member.h +++ /dev/null @@ -1,70 +0,0 @@ -/*************************************************************************/ -/* i_mono_class_member.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef I_MONO_CLASS_MEMBER_H -#define I_MONO_CLASS_MEMBER_H - -#include "gd_mono_header.h" - -#include <mono/metadata/object.h> - -class IMonoClassMember { -public: - enum Visibility { - PRIVATE, - PROTECTED_AND_INTERNAL, // FAM_AND_ASSEM - INTERNAL, // ASSEMBLY - PROTECTED, // FAMILY - PUBLIC - }; - - enum MemberType { - MEMBER_TYPE_FIELD, - MEMBER_TYPE_PROPERTY, - MEMBER_TYPE_METHOD - }; - - virtual ~IMonoClassMember() {} - - virtual GDMonoClass *get_enclosing_class() const = 0; - - virtual MemberType get_member_type() const = 0; - - virtual StringName get_name() const = 0; - - virtual bool is_static() = 0; - - virtual Visibility get_visibility() = 0; - - virtual bool has_attribute(GDMonoClass *p_attr_class) = 0; - virtual MonoObject *get_attribute(GDMonoClass *p_attr_class) = 0; -}; - -#endif // I_MONO_CLASS_MEMBER_H diff --git a/modules/mono/mono_gd/managed_type.cpp b/modules/mono/mono_gd/managed_type.cpp deleted file mode 100644 index 5860d7db1e..0000000000 --- a/modules/mono/mono_gd/managed_type.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/*************************************************************************/ -/* managed_type.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "managed_type.h" - -#include "gd_mono.h" -#include "gd_mono_class.h" - -ManagedType ManagedType::from_class(GDMonoClass *p_class) { - return ManagedType(mono_type_get_type(p_class->get_mono_type()), p_class); -} - -ManagedType ManagedType::from_class(MonoClass *p_mono_class) { - GDMonoClass *tclass = GDMono::get_singleton()->get_class(p_mono_class); - ERR_FAIL_COND_V(!tclass, ManagedType()); - - return ManagedType(mono_type_get_type(tclass->get_mono_type()), tclass); -} - -ManagedType ManagedType::from_type(MonoType *p_mono_type) { - MonoClass *mono_class = mono_class_from_mono_type(p_mono_type); - GDMonoClass *tclass = GDMono::get_singleton()->get_class(mono_class); - ERR_FAIL_COND_V(!tclass, ManagedType()); - - return ManagedType(mono_type_get_type(p_mono_type), tclass); -} - -ManagedType ManagedType::from_reftype(MonoReflectionType *p_mono_reftype) { - MonoType *mono_type = mono_reflection_type_get_type(p_mono_reftype); - return from_type(mono_type); -} diff --git a/modules/mono/mono_gd/managed_type.h b/modules/mono/mono_gd/managed_type.h deleted file mode 100644 index 603ff3aca1..0000000000 --- a/modules/mono/mono_gd/managed_type.h +++ /dev/null @@ -1,55 +0,0 @@ -/*************************************************************************/ -/* managed_type.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef MANAGED_TYPE_H -#define MANAGED_TYPE_H - -#include <mono/metadata/object.h> - -#include "gd_mono_header.h" - -struct ManagedType { - int type_encoding = 0; - GDMonoClass *type_class = nullptr; - - static ManagedType from_class(GDMonoClass *p_class); - static ManagedType from_class(MonoClass *p_mono_class); - static ManagedType from_type(MonoType *p_mono_type); - static ManagedType from_reftype(MonoReflectionType *p_mono_reftype); - - ManagedType() {} - - ManagedType(int p_type_encoding, GDMonoClass *p_type_class) : - type_encoding(p_type_encoding), - type_class(p_type_class) { - } -}; - -#endif // MANAGED_TYPE_H diff --git a/modules/mono/mono_gd/support/android_support.cpp b/modules/mono/mono_gd/support/android_support.cpp index 4797d5dae1..7fb983cd37 100644 --- a/modules/mono/mono_gd/support/android_support.cpp +++ b/modules/mono/mono_gd/support/android_support.cpp @@ -359,7 +359,7 @@ MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) { ScopedLocalRef<jbyteArray> encoded(env, (jbyteArray)env->CallObjectMethod(certificate, getEncoded)); jsize encodedLength = env->GetArrayLength(encoded); - MonoArray *encoded_ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), encodedLength); + MonoArray *encoded_ret = mono_array_new(mono_domain_get(), mono_get_byte_class(), encodedLength); uint8_t *dest = (uint8_t *)mono_array_addr(encoded_ret, uint8_t, 0); env->GetByteArrayRegion(encoded, 0, encodedLength, reinterpret_cast<jbyte *>(dest)); |