diff options
Diffstat (limited to 'modules/mono/mono_gd')
30 files changed, 1074 insertions, 229 deletions
diff --git a/modules/mono/mono_gd/android_mono_config.h b/modules/mono/mono_gd/android_mono_config.h index c5cc244aec..93f708bba0 100644 --- a/modules/mono/mono_gd/android_mono_config.h +++ b/modules/mono/mono_gd/android_mono_config.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 384ef08cd0..895393537f 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -102,33 +102,23 @@ void gd_mono_profiler_init() { bool profiler_enabled = GLOBAL_DEF("mono/profiler/enabled", false); if (profiler_enabled) { mono_profiler_load(profiler_args.utf8()); + return; } -} - -#if defined(DEBUG_ENABLED) - -bool gd_mono_wait_for_debugger_msecs(uint32_t p_msecs) { - do { - if (mono_is_debugger_attached()) - return true; - - int last_tick = OS::get_singleton()->get_ticks_msec(); - - OS::get_singleton()->delay_usec((p_msecs < 25 ? p_msecs : 25) * 1000); - - uint32_t tdiff = OS::get_singleton()->get_ticks_msec() - last_tick; - - if (tdiff > p_msecs) { - p_msecs = 0; - } else { - p_msecs -= tdiff; + const String env_var_name = "MONO_ENV_OPTIONS"; + if (OS::get_singleton()->has_environment(env_var_name)) { + const auto mono_env_ops = OS::get_singleton()->get_environment(env_var_name); + // Usually MONO_ENV_OPTIONS looks like: --profile=jb:prof=timeline,ctl=remote,host=127.0.0.1:55467 + const String prefix = "--profile="; + if (mono_env_ops.begins_with(prefix)) { + const auto ops = mono_env_ops.substr(prefix.length(), mono_env_ops.length()); + mono_profiler_load(ops.utf8()); } - } while (p_msecs > 0); - - return mono_is_debugger_attached(); + } } +#if defined(DEBUG_ENABLED) + void gd_mono_debug_init() { mono_debug_init(MONO_DEBUG_FORMAT_MONO); @@ -239,35 +229,22 @@ void GDMono::add_mono_shared_libs_dir_to_path() { #endif // WINDOWS_ENABLED || UNIX_ENABLED } -void GDMono::initialize() { - - ERR_FAIL_NULL(Engine::get_singleton()); - - print_verbose("Mono: Initializing module..."); - - char *runtime_build_info = mono_get_runtime_build_info(); - print_verbose("Mono JIT compiler version " + String(runtime_build_info)); - mono_free(runtime_build_info); - -#ifdef DEBUG_METHODS_ENABLED - _initialize_and_check_api_hashes(); -#endif - - GDMonoLog::get_singleton()->initialize(); +void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir) { - String assembly_rootdir; - String config_dir; + String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir(); + String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir(); #ifdef TOOLS_ENABLED + #if defined(WINDOWS_ENABLED) mono_reg_info = MonoRegUtils::find_mono(); if (mono_reg_info.assembly_dir.length() && DirAccess::exists(mono_reg_info.assembly_dir)) { - assembly_rootdir = mono_reg_info.assembly_dir; + r_assembly_rootdir = mono_reg_info.assembly_dir; } if (mono_reg_info.config_dir.length() && DirAccess::exists(mono_reg_info.config_dir)) { - config_dir = mono_reg_info.config_dir; + r_config_dir = mono_reg_info.config_dir; } #elif defined(OSX_ENABLED) const char *c_assembly_rootdir = mono_assembly_getrootdir(); @@ -284,29 +261,24 @@ void GDMono::initialize() { String hint_config_dir = path::join(locations[i], "etc"); if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) { - assembly_rootdir = hint_assembly_rootdir; - config_dir = hint_config_dir; + r_assembly_rootdir = hint_assembly_rootdir; + r_config_dir = hint_config_dir; break; } } } #endif -#endif // TOOLS_ENABLED - String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir(); - String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir(); - -#ifdef TOOLS_ENABLED if (DirAccess::exists(bundled_assembly_rootdir)) { - assembly_rootdir = bundled_assembly_rootdir; + r_assembly_rootdir = bundled_assembly_rootdir; } if (DirAccess::exists(bundled_config_dir)) { - config_dir = bundled_config_dir; + r_config_dir = bundled_config_dir; } #ifdef WINDOWS_ENABLED - if (assembly_rootdir.empty() || config_dir.empty()) { + if (r_assembly_rootdir.empty() || r_config_dir.empty()) { ERR_PRINT("Cannot find Mono in the registry."); // Assertion: if they are not set, then they weren't found in the registry CRASH_COND(mono_reg_info.assembly_dir.length() > 0 || mono_reg_info.config_dir.length() > 0); @@ -314,12 +286,32 @@ void GDMono::initialize() { #endif // WINDOWS_ENABLED #else - // These are always the directories in export templates - assembly_rootdir = bundled_assembly_rootdir; - config_dir = bundled_config_dir; -#endif // TOOLS_ENABLED + // Export templates always use the bundled directories + r_assembly_rootdir = bundled_assembly_rootdir; + r_config_dir = bundled_config_dir; +#endif +} + +void GDMono::initialize() { + + ERR_FAIL_NULL(Engine::get_singleton()); + + print_verbose("Mono: Initializing module..."); + + char *runtime_build_info = mono_get_runtime_build_info(); + print_verbose("Mono JIT compiler version " + String(runtime_build_info)); + mono_free(runtime_build_info); + + _init_godot_api_hashes(); + _init_exception_policy(); + + GDMonoLog::get_singleton()->initialize(); #if !defined(JAVASCRIPT_ENABLED) + String assembly_rootdir; + String config_dir; + determine_mono_dirs(assembly_rootdir, config_dir); + // Leak if we call mono_set_dirs more than once mono_set_dirs(assembly_rootdir.length() ? assembly_rootdir.utf8().get_data() : NULL, config_dir.length() ? config_dir.utf8().get_data() : NULL); @@ -328,21 +320,9 @@ void GDMono::initialize() { #endif #if defined(ANDROID_ENABLED) - GDMonoAndroid::register_android_dl_fallback(); + GDMonoAndroid::initialize(); #endif - { - PropertyInfo exc_policy_prop = PropertyInfo(Variant::INT, "mono/unhandled_exception_policy", PROPERTY_HINT_ENUM, - vformat("Terminate Application:%s,Log Error:%s", (int)POLICY_TERMINATE_APP, (int)POLICY_LOG_ERROR)); - unhandled_exception_policy = (UnhandledExceptionPolicy)(int)GLOBAL_DEF(exc_policy_prop.name, (int)POLICY_TERMINATE_APP); - ProjectSettings::get_singleton()->set_custom_property_info(exc_policy_prop.name, exc_policy_prop); - - if (Engine::get_singleton()->is_editor_hint()) { - // Unhandled exceptions should not terminate the editor - unhandled_exception_policy = POLICY_LOG_ERROR; - } - } - GDMonoAssembly::initialize(); #if !defined(JAVASCRIPT_ENABLED) @@ -358,18 +338,24 @@ void GDMono::initialize() { mono_install_unhandled_exception_hook(&unhandled_exception_hook, NULL); #ifndef TOOLS_ENABLED - // Export templates only load the Mono runtime if the project uses it - if (!DirAccess::exists("res://.mono")) + // Exported games that don't use C# must still work. They likely don't ship with mscorlib. + // We only initialize the Mono runtime if we can find mscorlib. Otherwise it would crash. + if (GDMonoAssembly::find_assembly("mscorlib.dll").empty()) { + print_verbose("Mono: Skipping runtime initialization because 'mscorlib.dll' could not be found"); return; + } #endif -#if !defined(WINDOWS_ENABLED) && !defined(NO_MONO_THREADS_SUSPEND_WORKAROUND) +#if !defined(NO_MONO_THREADS_SUSPEND_WORKAROUND) // FIXME: Temporary workaround. See: https://github.com/godotengine/godot/issues/29812 if (!OS::get_singleton()->has_environment("MONO_THREADS_SUSPEND")) { OS::get_singleton()->set_environment("MONO_THREADS_SUSPEND", "preemptive"); } #endif + // NOTE: Internal calls must be registered after the Mono runtime initialization. + // Otherwise registration fails with the error: 'assertion 'hash != NULL' failed'. + root_domain = gd_initialize_mono_runtime(); ERR_FAIL_NULL_MSG(root_domain, "Mono: Failed to initialize runtime."); @@ -383,6 +369,10 @@ void GDMono::initialize() { print_verbose("Mono: Runtime initialized"); +#if defined(ANDROID_ENABLED) + GDMonoAndroid::register_internal_calls(); +#endif + // mscorlib assembly MUST be present at initialization bool corlib_loaded = _load_corlib_assembly(); ERR_FAIL_COND_MSG(!corlib_loaded, "Mono: Failed to load mscorlib assembly."); @@ -390,12 +380,6 @@ void GDMono::initialize() { Error domain_load_err = _load_scripts_domain(); ERR_FAIL_COND_MSG(domain_load_err != OK, "Mono: Failed to load scripts domain."); -#if defined(DEBUG_ENABLED) && !defined(JAVASCRIPT_ENABLED) - bool debugger_attached = gd_mono_wait_for_debugger_msecs(500); - if (!debugger_attached && OS::get_singleton()->is_stdout_verbose()) - print_error("Mono: Debugger wait timeout"); -#endif - _register_internal_calls(); print_verbose("Mono: INITIALIZED"); @@ -475,9 +459,8 @@ void GDMono::_register_internal_calls() { GodotSharpBindings::register_generated_icalls(); } -void GDMono::_initialize_and_check_api_hashes() { -#ifdef MONO_GLUE_ENABLED -#ifdef DEBUG_METHODS_ENABLED +void GDMono::_init_godot_api_hashes() { +#if defined(MONO_GLUE_ENABLED) && defined(DEBUG_METHODS_ENABLED) if (get_api_core_hash() != GodotSharpBindings::get_core_api_hash()) { ERR_PRINT("Mono: Core API hash mismatch."); } @@ -487,8 +470,19 @@ void GDMono::_initialize_and_check_api_hashes() { ERR_PRINT("Mono: Editor API hash mismatch."); } #endif // TOOLS_ENABLED -#endif // DEBUG_METHODS_ENABLED -#endif // MONO_GLUE_ENABLED +#endif // MONO_GLUE_ENABLED && DEBUG_METHODS_ENABLED +} + +void GDMono::_init_exception_policy() { + PropertyInfo exc_policy_prop = PropertyInfo(Variant::INT, "mono/unhandled_exception_policy", PROPERTY_HINT_ENUM, + vformat("Terminate Application:%s,Log Error:%s", (int)POLICY_TERMINATE_APP, (int)POLICY_LOG_ERROR)); + unhandled_exception_policy = (UnhandledExceptionPolicy)(int)GLOBAL_DEF(exc_policy_prop.name, (int)POLICY_TERMINATE_APP); + ProjectSettings::get_singleton()->set_custom_property_info(exc_policy_prop.name, exc_policy_prop); + + if (Engine::get_singleton()->is_editor_hint()) { + // Unhandled exceptions should not terminate the editor + unhandled_exception_policy = POLICY_LOG_ERROR; + } } void GDMono::add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly) { @@ -627,7 +621,7 @@ bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const memdelete(da); if (err != OK) { - ERR_PRINTS("Failed to create destination directory for the API assemblies. Error: " + itos(err) + "."); + ERR_PRINT("Failed to create destination directory for the API assemblies. Error: " + itos(err) + "."); return false; } } @@ -636,15 +630,15 @@ bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String xml_file = assembly_name + ".xml"; if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK) - WARN_PRINTS("Failed to copy '" + xml_file + "'."); + 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_PRINTS("Failed to copy '" + pdb_file + "'."); + 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_PRINTS("Failed to copy '" + assembly_file + "'."); + ERR_PRINT("Failed to copy '" + assembly_file + "'."); return false; } @@ -1121,7 +1115,7 @@ Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) { mono_domain_try_unload(p_domain, (MonoObject **)&exc); if (exc) { - ERR_PRINTS("Exception thrown when unloading domain '" + domain_name + "'."); + ERR_PRINT("Exception thrown when unloading domain '" + domain_name + "'."); GDMonoUtils::debug_print_unhandled_exception(exc); return FAILED; } @@ -1250,6 +1244,10 @@ GDMono::~GDMono() { mono_jit_cleanup(root_domain); +#if defined(ANDROID_ENABLED) + GDMonoAndroid::cleanup(); +#endif + print_verbose("Mono: Finalized"); runtime_initialized = false; diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index e14a0d8409..306fa15f12 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -153,7 +153,8 @@ private: #ifdef TOOLS_ENABLED uint64_t api_editor_hash; #endif - void _initialize_and_check_api_hashes(); + void _init_godot_api_hashes(); + void _init_exception_policy(); GDMonoLog *gdmono_log; @@ -162,6 +163,7 @@ private: #endif void add_mono_shared_libs_dir_to_path(); + void determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir); protected: static GDMono *singleton; diff --git a/modules/mono/mono_gd/gd_mono_android.cpp b/modules/mono/mono_gd/gd_mono_android.cpp index 42983e1821..761368878f 100644 --- a/modules/mono/mono_gd/gd_mono_android.cpp +++ b/modules/mono/mono_gd/gd_mono_android.cpp @@ -1,41 +1,131 @@ +/*************************************************************************/ +/* gd_mono_android.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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_android.h" #if defined(ANDROID_ENABLED) #include <dlfcn.h> // dlopen, dlsym #include <mono/utils/mono-dl-fallback.h> +#include <sys/system_properties.h> +#include <cstddef> + +#if __ANDROID_API__ < 24 +#include "thirdparty/misc/ifaddrs-android.h" +#else +#include <ifaddrs.h> +#endif #include "core/os/os.h" #include "core/ustring.h" +#include "platform/android/java_godot_wrapper.h" +#include "platform/android/os_android.h" #include "platform/android/thread_jandroid.h" #include "../utils/path_utils.h" #include "../utils/string_utils.h" +#include "gd_mono_cache.h" +#include "gd_mono_marshal.h" + +// Warning: JNI boilerplate ahead... continue at your own risk namespace GDMonoAndroid { +template <typename T> +struct ScopedLocalRef { + JNIEnv *env; + T local_ref; + + _FORCE_INLINE_ T get() const { return local_ref; } + _FORCE_INLINE_ operator T() const { return local_ref; } + _FORCE_INLINE_ operator jvalue() const { return (jvalue)local_ref; } + + _FORCE_INLINE_ operator bool() const { return local_ref != NULL; } + + _FORCE_INLINE_ bool operator==(std::nullptr_t) const { + return local_ref == nullptr; + } + + _FORCE_INLINE_ bool operator!=(std::nullptr_t) const { + return local_ref != nullptr; + } + + ScopedLocalRef(const ScopedLocalRef &) = delete; + ScopedLocalRef &operator=(const ScopedLocalRef &) = delete; + + ScopedLocalRef(JNIEnv *p_env, T p_local_ref) : + env(p_env), + local_ref(p_local_ref) { + } + + ~ScopedLocalRef() { + if (local_ref) { + env->DeleteLocalRef(local_ref); + } + } +}; + +bool jni_exception_check(JNIEnv *p_env) { + if (p_env->ExceptionCheck()) { + // Print the exception to logcat + p_env->ExceptionDescribe(); + + p_env->ExceptionClear(); + return true; + } + + return false; +} + String app_native_lib_dir_cache; String determine_app_native_lib_dir() { JNIEnv *env = ThreadAndroid::get_env(); - jclass activityThreadClass = env->FindClass("android/app/ActivityThread"); + ScopedLocalRef<jclass> activityThreadClass(env, env->FindClass("android/app/ActivityThread")); jmethodID currentActivityThread = env->GetStaticMethodID(activityThreadClass, "currentActivityThread", "()Landroid/app/ActivityThread;"); - jobject activityThread = env->CallStaticObjectMethod(activityThreadClass, currentActivityThread); + ScopedLocalRef<jobject> activityThread(env, env->CallStaticObjectMethod(activityThreadClass, currentActivityThread)); jmethodID getApplication = env->GetMethodID(activityThreadClass, "getApplication", "()Landroid/app/Application;"); - jobject ctx = env->CallObjectMethod(activityThread, getApplication); + ScopedLocalRef<jobject> ctx(env, env->CallObjectMethod(activityThread, getApplication)); jmethodID getApplicationInfo = env->GetMethodID(env->GetObjectClass(ctx), "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;"); - jobject applicationInfo = env->CallObjectMethod(ctx, getApplicationInfo); + ScopedLocalRef<jobject> applicationInfo(env, env->CallObjectMethod(ctx, getApplicationInfo)); jfieldID nativeLibraryDirField = env->GetFieldID(env->GetObjectClass(applicationInfo), "nativeLibraryDir", "Ljava/lang/String;"); - jstring nativeLibraryDir = (jstring)env->GetObjectField(applicationInfo, nativeLibraryDirField); + ScopedLocalRef<jstring> nativeLibraryDir(env, (jstring)env->GetObjectField(applicationInfo, nativeLibraryDirField)); String result; - const char *const nativeLibraryDir_utf8 = env->GetStringUTFChars(nativeLibraryDir, NULL); - if (nativeLibraryDir_utf8) { - result.parse_utf8(nativeLibraryDir_utf8); - env->ReleaseStringUTFChars(nativeLibraryDir, nativeLibraryDir_utf8); + const char *const nativeLibraryDirUtf8 = env->GetStringUTFChars(nativeLibraryDir, NULL); + if (nativeLibraryDirUtf8) { + result.parse_utf8(nativeLibraryDirUtf8); + env->ReleaseStringUTFChars(nativeLibraryDir, nativeLibraryDirUtf8); } return result; @@ -60,7 +150,53 @@ int gd_mono_convert_dl_flags(int flags) { return lflags; } +#ifndef GD_MONO_ANDROID_SO_NAME +#define GD_MONO_ANDROID_SO_NAME "libmonosgen-2.0.so" +#endif + +const char *mono_so_name = GD_MONO_ANDROID_SO_NAME; +const char *godot_so_name = "libgodot_android.so"; + +void *mono_dl_handle = NULL; +void *godot_dl_handle = NULL; + +void *try_dlopen(const String &p_so_path, int p_flags) { + if (!FileAccess::exists(p_so_path)) { + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Cannot find shared library: '%s'\n", p_so_path.utf8().get_data()); + return NULL; + } + + int lflags = gd_mono_convert_dl_flags(p_flags); + + void *handle = dlopen(p_so_path.utf8().get_data(), lflags); + + if (!handle) { + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Failed to open shared library: '%s'. Error: '%s'\n", p_so_path.utf8().get_data(), dlerror()); + return NULL; + } + + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Successfully loaded shared library: '%s'\n", p_so_path.utf8().get_data()); + + return handle; +} + void *gd_mono_android_dlopen(const char *p_name, int p_flags, char **r_err, void *p_user_data) { + if (p_name == NULL) { + // __Internal + + if (!mono_dl_handle) { + String app_native_lib_dir = get_app_native_lib_dir(); + String so_path = path::join(app_native_lib_dir, mono_so_name); + + mono_dl_handle = try_dlopen(so_path, p_flags); + } + + return mono_dl_handle; + } + String name = String::utf8(p_name); if (name.ends_with(".dll.so") || name.ends_with(".exe.so")) { @@ -70,26 +206,7 @@ void *gd_mono_android_dlopen(const char *p_name, int p_flags, char **r_err, void String so_name = "lib-aot-" + orig_so_name; String so_path = path::join(app_native_lib_dir, so_name); - if (!FileAccess::exists(so_path)) { - if (OS::get_singleton()->is_stdout_verbose()) - OS::get_singleton()->print("Cannot find shared library: '%s'\n", so_path.utf8().get_data()); - return NULL; - } - - int lflags = gd_mono_convert_dl_flags(p_flags); - - void *handle = dlopen(so_path.utf8().get_data(), lflags); - - if (!handle) { - if (OS::get_singleton()->is_stdout_verbose()) - OS::get_singleton()->print("Failed to open shared library: '%s'. Error: '%s'\n", so_path.utf8().get_data(), dlerror()); - return NULL; - } - - if (OS::get_singleton()->is_stdout_verbose()) - OS::get_singleton()->print("Successfully loaded AOT shared library: '%s'\n", so_path.utf8().get_data()); - - return handle; + return try_dlopen(so_path, p_flags); } return NULL; @@ -101,16 +218,469 @@ void *gd_mono_android_dlsym(void *p_handle, const char *p_name, char **r_err, vo if (sym_addr) return sym_addr; + if (p_handle == mono_dl_handle && godot_dl_handle) { + // Looking up for '__Internal' P/Invoke. We want to search in both the Mono and Godot shared libraries. + // This is needed to resolve the monodroid P/Invoke functions that are defined at the bottom of the file. + sym_addr = dlsym(godot_dl_handle, p_name); + + if (sym_addr) + return sym_addr; + } + if (r_err) *r_err = str_format_new("%s\n", dlerror()); return NULL; } -void register_android_dl_fallback() { - mono_dl_fallback_register(gd_mono_android_dlopen, gd_mono_android_dlsym, NULL, NULL); +void *gd_mono_android_dlclose(void *p_handle, void *p_user_data) { + dlclose(p_handle); + + // Not sure if this ever happens. Does Mono close the handle for the main module? + if (p_handle == mono_dl_handle) + mono_dl_handle = NULL; + + return NULL; +} + +int32_t build_version_sdk_int = 0; + +int32_t get_build_version_sdk_int() { + // The JNI code is the equivalent of: + // + // android.os.Build.VERSION.SDK_INT + + if (build_version_sdk_int == 0) { + JNIEnv *env = ThreadAndroid::get_env(); + + jclass versionClass = env->FindClass("android/os/Build$VERSION"); + ERR_FAIL_NULL_V(versionClass, 0); + + jfieldID sdkIntField = env->GetStaticFieldID(versionClass, "SDK_INT", "I"); + ERR_FAIL_NULL_V(sdkIntField, 0); + + build_version_sdk_int = (int32_t)env->GetStaticIntField(versionClass, sdkIntField); + } + + return build_version_sdk_int; +} + +jobject certStore = NULL; // KeyStore + +MonoBoolean _gd_mono_init_cert_store() { + // The JNI code is the equivalent of: + // + // try { + // certStoreLocal = KeyStore.getInstance("AndroidCAStore"); + // certStoreLocal.load(null); + // certStore = certStoreLocal; + // return true; + // } catch (Exception e) { + // return false; + // } + + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jclass> keyStoreClass(env, env->FindClass("java/security/KeyStore")); + + jmethodID getInstance = env->GetStaticMethodID(keyStoreClass, "getInstance", "(Ljava/lang/String;)Ljava/security/KeyStore;"); + jmethodID load = env->GetMethodID(keyStoreClass, "load", "(Ljava/security/KeyStore$LoadStoreParameter;)V"); + + ScopedLocalRef<jstring> androidCAStoreString(env, env->NewStringUTF("AndroidCAStore")); + + ScopedLocalRef<jobject> certStoreLocal(env, env->CallStaticObjectMethod(keyStoreClass, getInstance, androidCAStoreString.get())); + + if (jni_exception_check(env)) + return 0; + + env->CallVoidMethod(certStoreLocal, load, NULL); + + if (jni_exception_check(env)) + return 0; + + certStore = env->NewGlobalRef(certStoreLocal); + + return 1; +} + +MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) { + // The JNI code is the equivalent of: + // + // Certificate certificate = certStore.getCertificate(alias); + // if (certificate == null) + // return null; + // return certificate.getEncoded(); + + MonoError mono_error; + char *alias_utf8 = mono_string_to_utf8_checked(p_alias, &mono_error); + + if (!mono_error_ok(&mono_error)) { + ERR_PRINT(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&mono_error) + "'."); + mono_error_cleanup(&mono_error); + return NULL; + } + + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jstring> js_alias(env, env->NewStringUTF(alias_utf8)); + mono_free(alias_utf8); + + ScopedLocalRef<jclass> keyStoreClass(env, env->FindClass("java/security/KeyStore")); + ERR_FAIL_NULL_V(keyStoreClass, NULL); + ScopedLocalRef<jclass> certificateClass(env, env->FindClass("java/security/cert/Certificate")); + ERR_FAIL_NULL_V(certificateClass, NULL); + + jmethodID getCertificate = env->GetMethodID(keyStoreClass, "getCertificate", "(Ljava/lang/String;)Ljava/security/cert/Certificate;"); + ERR_FAIL_NULL_V(getCertificate, NULL); + + jmethodID getEncoded = env->GetMethodID(certificateClass, "getEncoded", "()[B"); + ERR_FAIL_NULL_V(getEncoded, NULL); + + ScopedLocalRef<jobject> certificate(env, env->CallObjectMethod(certStore, getCertificate, js_alias.get())); + + if (!certificate) + return NULL; + + 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); + uint8_t *dest = (uint8_t *)mono_array_addr(encoded_ret, uint8_t, 0); + + env->GetByteArrayRegion(encoded, 0, encodedLength, reinterpret_cast<jbyte *>(dest)); + + return encoded_ret; +} + +void initialize() { + // We need to set this environment variable to make the monodroid BCL use btls instead of legacy as the default provider + OS::get_singleton()->set_environment("XA_TLS_PROVIDER", "btls"); + + mono_dl_fallback_register(gd_mono_android_dlopen, gd_mono_android_dlsym, gd_mono_android_dlclose, NULL); + + String app_native_lib_dir = get_app_native_lib_dir(); + String so_path = path::join(app_native_lib_dir, godot_so_name); + + godot_dl_handle = try_dlopen(so_path, gd_mono_convert_dl_flags(MONO_DL_LAZY)); +} + +void register_internal_calls() { + mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_init_cert_store", (void *)_gd_mono_init_cert_store); + mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_android_cert_store_lookup", (void *)_gd_mono_android_cert_store_lookup); +} + +void cleanup() { + // This is called after shutting down the Mono runtime + + if (mono_dl_handle) + gd_mono_android_dlclose(mono_dl_handle, NULL); + + if (godot_dl_handle) + gd_mono_android_dlclose(godot_dl_handle, NULL); + + JNIEnv *env = ThreadAndroid::get_env(); + + if (certStore) { + env->DeleteGlobalRef(certStore); + certStore = NULL; + } } } // namespace GDMonoAndroid +using namespace GDMonoAndroid; + +// The following are P/Invoke functions required by the monodroid profile of the BCL. +// These are P/Invoke functions and not internal calls, hence why they use +// 'mono_bool' and 'const char*' instead of 'MonoBoolean' and 'MonoString*'. + +#define GD_PINVOKE_EXPORT extern "C" __attribute__((visibility("default"))) + +GD_PINVOKE_EXPORT int32_t _monodroid_get_android_api_level() { + return get_build_version_sdk_int(); +} + +GD_PINVOKE_EXPORT void monodroid_free(void *ptr) { + free(ptr); +} + +GD_PINVOKE_EXPORT int32_t monodroid_get_system_property(const char *p_name, char **r_value) { + char prop_value_str[PROP_VALUE_MAX + 1] = { 0 }; + + int len = __system_property_get(p_name, prop_value_str); + + if (r_value) { + if (len >= 0) { + *r_value = (char *)malloc(len + 1); + if (!*r_value) + return -1; + memcpy(*r_value, prop_value_str, len); + (*r_value)[len] = '\0'; + } else { + *r_value = NULL; + } + } + + return len; +} + +GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_up_state(const char *p_ifname, mono_bool *r_is_up) { + // The JNI code is the equivalent of: + // + // NetworkInterface.getByName(p_ifname).isUp() + + if (!r_is_up || !p_ifname || strlen(p_ifname) == 0) + return 0; + + *r_is_up = 0; + + JNIEnv *env = ThreadAndroid::get_env(); + + jclass networkInterfaceClass = env->FindClass("java/net/NetworkInterface"); + ERR_FAIL_NULL_V(networkInterfaceClass, 0); + + jmethodID getByName = env->GetStaticMethodID(networkInterfaceClass, "getByName", "(Ljava/lang/String;)Ljava/net/NetworkInterface;"); + ERR_FAIL_NULL_V(getByName, 0); + + jmethodID isUp = env->GetMethodID(networkInterfaceClass, "isUp", "()Z"); + ERR_FAIL_NULL_V(isUp, 0); + + ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname)); + ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get())); + + if (!networkInterface) + return 0; + + *r_is_up = (mono_bool)env->CallBooleanMethod(networkInterface, isUp); + + return 1; +} + +GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_supports_multicast(const char *p_ifname, mono_bool *r_supports_multicast) { + // The JNI code is the equivalent of: + // + // NetworkInterface.getByName(p_ifname).supportsMulticast() + + if (!r_supports_multicast || !p_ifname || strlen(p_ifname) == 0) + return 0; + + *r_supports_multicast = 0; + + JNIEnv *env = ThreadAndroid::get_env(); + + jclass networkInterfaceClass = env->FindClass("java/net/NetworkInterface"); + ERR_FAIL_NULL_V(networkInterfaceClass, 0); + + jmethodID getByName = env->GetStaticMethodID(networkInterfaceClass, "getByName", "(Ljava/lang/String;)Ljava/net/NetworkInterface;"); + ERR_FAIL_NULL_V(getByName, 0); + + jmethodID supportsMulticast = env->GetMethodID(networkInterfaceClass, "supportsMulticast", "()Z"); + ERR_FAIL_NULL_V(supportsMulticast, 0); + + ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname)); + ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get())); + + if (!networkInterface) + return 0; + + *r_supports_multicast = (mono_bool)env->CallBooleanMethod(networkInterface, supportsMulticast); + + return 1; +} + +static const int dns_servers_len = 8; + +static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dns_servers_count) { + // The JNI code is the equivalent of: + // + // ConnectivityManager connectivityManager = (ConnectivityManager)getApplicationContext() + // .getSystemService(Context.CONNECTIVITY_SERVICE); + // Network activeNerwork = connectivityManager.getActiveNetwork(); + // LinkProperties linkProperties = connectivityManager.getLinkProperties(activeNerwork); + // List<String> dnsServers = linkProperties.getDnsServers().stream() + // .map(inetAddress -> inetAddress.getHostAddress()).collect(Collectors.toList()); + +#ifdef DEBUG_ENABLED + CRASH_COND(get_build_version_sdk_int() < 23); +#endif + + JNIEnv *env = ThreadAndroid::get_env(); + + GodotJavaWrapper *godot_java = ((OS_Android *)OS::get_singleton())->get_godot_java(); + jobject activity = godot_java->get_activity(); + + ScopedLocalRef<jclass> activityClass(env, env->GetObjectClass(activity)); + ERR_FAIL_NULL(activityClass); + + jmethodID getApplicationContext = env->GetMethodID(activityClass, "getApplicationContext", "()Landroid/content/Context;"); + + ScopedLocalRef<jobject> applicationContext(env, env->CallObjectMethod(activity, getApplicationContext)); + + ScopedLocalRef<jclass> contextClass(env, env->FindClass("android/content/Context")); + ERR_FAIL_NULL(contextClass); + + jfieldID connectivityServiceField = env->GetStaticFieldID(contextClass, "CONNECTIVITY_SERVICE", "Ljava/lang/String;"); + ScopedLocalRef<jstring> connectivityServiceString(env, (jstring)env->GetStaticObjectField(contextClass, connectivityServiceField)); + + jmethodID getSystemService = env->GetMethodID(contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); + + ScopedLocalRef<jobject> connectivityManager(env, env->CallObjectMethod(applicationContext, getSystemService, connectivityServiceString.get())); + + if (!connectivityManager) + return; + + ScopedLocalRef<jclass> connectivityManagerClass(env, env->FindClass("android/net/ConnectivityManager")); + ERR_FAIL_NULL(connectivityManagerClass); + + jmethodID getActiveNetwork = env->GetMethodID(connectivityManagerClass, "getActiveNetwork", "()Landroid/net/Network;"); + ERR_FAIL_NULL(getActiveNetwork); + + ScopedLocalRef<jobject> activeNetwork(env, env->CallObjectMethod(connectivityManager, getActiveNetwork)); + + if (!activeNetwork) + return; + + jmethodID getLinkProperties = env->GetMethodID(connectivityManagerClass, + "getLinkProperties", "(Landroid/net/Network;)Landroid/net/LinkProperties;"); + ERR_FAIL_NULL(getLinkProperties); + + ScopedLocalRef<jobject> linkProperties(env, env->CallObjectMethod(connectivityManager, getLinkProperties, activeNetwork.get())); + + if (!linkProperties) + return; + + ScopedLocalRef<jclass> linkPropertiesClass(env, env->FindClass("android/net/LinkProperties")); + ERR_FAIL_NULL(linkPropertiesClass); + + jmethodID getDnsServers = env->GetMethodID(linkPropertiesClass, "getDnsServers", "()Ljava/util/List;"); + ERR_FAIL_NULL(getDnsServers); + + ScopedLocalRef<jobject> dnsServers(env, env->CallObjectMethod(linkProperties, getDnsServers)); + + if (!dnsServers) + return; + + ScopedLocalRef<jclass> listClass(env, env->FindClass("java/util/List")); + ERR_FAIL_NULL(listClass); + + jmethodID listSize = env->GetMethodID(listClass, "size", "()I"); + ERR_FAIL_NULL(listSize); + + int dnsServersCount = env->CallIntMethod(dnsServers, listSize); + + if (dnsServersCount > dns_servers_len) + dnsServersCount = dns_servers_len; + + if (dnsServersCount <= 0) + return; + + jmethodID listGet = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;"); + ERR_FAIL_NULL(listGet); + + ScopedLocalRef<jclass> inetAddressClass(env, env->FindClass("java/net/InetAddress")); + ERR_FAIL_NULL(inetAddressClass); + + jmethodID getHostAddress = env->GetMethodID(inetAddressClass, "getHostAddress", "()Ljava/lang/String;"); + ERR_FAIL_NULL(getHostAddress); + + for (int i = 0; i < dnsServersCount; i++) { + ScopedLocalRef<jobject> dnsServer(env, env->CallObjectMethod(dnsServers, listGet, (jint)i)); + if (!dnsServer) + continue; + + ScopedLocalRef<jstring> hostAddress(env, (jstring)env->CallObjectMethod(dnsServer, getHostAddress)); + const char *host_address = env->GetStringUTFChars(hostAddress, 0); + + r_dns_servers[i] = strdup(host_address); // freed by the BCL + (*dns_servers_count)++; + + env->ReleaseStringUTFChars(hostAddress, host_address); + } + + // jesus... +} + +GD_PINVOKE_EXPORT int32_t _monodroid_get_dns_servers(void **r_dns_servers_array) { + if (!r_dns_servers_array) + return -1; + + *r_dns_servers_array = NULL; + + char *dns_servers[dns_servers_len]; + int dns_servers_count = 0; + + if (_monodroid_get_android_api_level() < 26) { + // The 'net.dns*' system properties are no longer available in Android 8.0 (API level 26) and greater: + // https://developer.android.com/about/versions/oreo/android-8.0-changes.html#o-pri + + char prop_name[] = "net.dns*"; + + for (int i = 0; i < dns_servers_len; i++) { + prop_name[7] = (char)(i + 0x31); + char *prop_value; + int32_t len = monodroid_get_system_property(prop_name, &prop_value); + + if (len > 0) { + dns_servers[dns_servers_count] = strndup(prop_value, (size_t)len); // freed by the BCL + dns_servers_count++; + free(prop_value); + } + } + } else { + // Alternative for Oreo and greater + interop_get_active_network_dns_servers(dns_servers, &dns_servers_count); + } + + if (dns_servers_count > 0) { + size_t ret_size = sizeof(char *) * (size_t)dns_servers_count; + *r_dns_servers_array = malloc(ret_size); // freed by the BCL + memcpy(*r_dns_servers_array, dns_servers, ret_size); + } + + return dns_servers_count; +} + +GD_PINVOKE_EXPORT const char *_monodroid_timezone_get_default_id() { + // The JNI code is the equivalent of: + // + // TimeZone.getDefault().getID() + + JNIEnv *env = ThreadAndroid::get_env(); + + ScopedLocalRef<jclass> timeZoneClass(env, env->FindClass("java/util/TimeZone")); + ERR_FAIL_NULL_V(timeZoneClass, NULL); + + jmethodID getDefault = env->GetStaticMethodID(timeZoneClass, "getDefault", "()Ljava/util/TimeZone;"); + ERR_FAIL_NULL_V(getDefault, NULL); + + jmethodID getID = env->GetMethodID(timeZoneClass, "getID", "()Ljava/lang/String;"); + ERR_FAIL_NULL_V(getID, NULL); + + ScopedLocalRef<jobject> defaultTimeZone(env, env->CallStaticObjectMethod(timeZoneClass, getDefault)); + + if (!defaultTimeZone) + return NULL; + + ScopedLocalRef<jstring> defaultTimeZoneID(env, (jstring)env->CallObjectMethod(defaultTimeZone, getID)); + + if (!defaultTimeZoneID) + return NULL; + + const char *default_time_zone_id = env->GetStringUTFChars(defaultTimeZoneID, 0); + + char *result = strdup(default_time_zone_id); // freed by the BCL + + env->ReleaseStringUTFChars(defaultTimeZoneID, default_time_zone_id); + + return result; +} + +GD_PINVOKE_EXPORT int32_t _monodroid_getifaddrs(struct ifaddrs **p_ifap) { + return getifaddrs(p_ifap); +} + +GD_PINVOKE_EXPORT void _monodroid_freeifaddrs(struct ifaddrs *p_ifap) { + freeifaddrs(p_ifap); +} + #endif diff --git a/modules/mono/mono_gd/gd_mono_android.h b/modules/mono/mono_gd/gd_mono_android.h index 52705fbd2d..0e04847924 100644 --- a/modules/mono/mono_gd/gd_mono_android.h +++ b/modules/mono/mono_gd/gd_mono_android.h @@ -1,3 +1,33 @@ +/*************************************************************************/ +/* gd_mono_android.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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_ANDROID_H #define GD_MONO_ANDROID_H @@ -9,7 +39,11 @@ namespace GDMonoAndroid { String get_app_native_lib_dir(); -void register_android_dl_fallback(); +void initialize(); + +void register_internal_calls(); + +void cleanup(); } // namespace GDMonoAndroid diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index 91842420b7..6cf5377e2c 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -62,6 +62,13 @@ void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const Strin r_search_dirs.push_back(framework_dir.plus_file("Facades")); } +#if !defined(TOOLS_ENABLED) + String data_game_assemblies_dir = GodotSharpDirs::get_data_game_assemblies_dir(); + if (!data_game_assemblies_dir.empty()) { + r_search_dirs.push_back(data_game_assemblies_dir); + } +#endif + if (p_custom_config.length()) { r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(p_custom_config)); } else { @@ -122,7 +129,7 @@ MonoAssembly *GDMonoAssembly::_search_hook(MonoAssemblyName *aname, void *user_d (void)user_data; // UNUSED - String name = mono_assembly_name_get_name(aname); + String name = String::utf8(mono_assembly_name_get_name(aname)); bool has_extension = name.ends_with(".dll") || name.ends_with(".exe"); if (no_search) @@ -147,10 +154,6 @@ MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, vo (void)user_data; // UNUSED - if (search_dirs.empty()) { - fill_search_dirs(search_dirs); - } - { // If we find the assembly here, we load it with 'mono_assembly_load_from_full', // which in turn invokes load hooks before returning the MonoAssembly to us. @@ -173,7 +176,7 @@ MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, vo no_search = true; in_preload = true; - String name = mono_assembly_name_get_name(aname); + String name = String::utf8(mono_assembly_name_get_name(aname)); bool has_extension = name.ends_with(".dll"); GDMonoAssembly *res = NULL; @@ -228,6 +231,33 @@ GDMonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, cons return NULL; } +String GDMonoAssembly::find_assembly(const String &p_name) { + + String path; + + bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe"); + + for (int i = 0; i < search_dirs.size(); i++) { + const String &search_dir = search_dirs[i]; + + if (has_extension) { + path = search_dir.plus_file(p_name); + if (FileAccess::exists(path)) + return path; + } else { + path = search_dir.plus_file(p_name + ".dll"); + if (FileAccess::exists(path)) + return path; + + path = search_dir.plus_file(p_name + ".exe"); + if (FileAccess::exists(path)) + return path; + } + } + + return String(); +} + GDMonoAssembly *GDMonoAssembly::_load_assembly_from(const String &p_name, const String &p_path, bool p_refonly) { GDMonoAssembly *assembly = memnew(GDMonoAssembly(p_name, p_path)); @@ -246,7 +276,7 @@ GDMonoAssembly *GDMonoAssembly::_load_assembly_from(const String &p_name, const } void GDMonoAssembly::_wrap_mono_assembly(MonoAssembly *assembly) { - String name = mono_assembly_name_get_name(mono_assembly_get_name(assembly)); + String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly))); MonoImage *image = mono_assembly_get_image(assembly); @@ -264,6 +294,8 @@ void GDMonoAssembly::_wrap_mono_assembly(MonoAssembly *assembly) { void GDMonoAssembly::initialize() { + fill_search_dirs(search_dirs); + mono_install_assembly_search_hook(&assembly_search_hook, NULL); mono_install_assembly_refonly_search_hook(&assembly_refonly_search_hook, NULL); mono_install_assembly_preload_hook(&assembly_preload_hook, NULL); diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h index 39749dfc1d..4740e10339 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.h +++ b/modules/mono/mono_gd/gd_mono_assembly.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -122,6 +122,8 @@ public: GDMonoClass *get_object_derived_class(const StringName &p_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()); static GDMonoAssembly *load_from(const String &p_name, const String &p_path, bool p_refonly); diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp index 3422e4ff58..f1f6524cd2 100644 --- a/modules/mono/mono_gd/gd_mono_cache.cpp +++ b/modules/mono/mono_gd/gd_mono_cache.cpp @@ -1,3 +1,33 @@ +/*************************************************************************/ +/* gd_mono_cache.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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_cache.h" #include "gd_mono.h" diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index 0ad7fb607c..1dc6b70479 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -1,3 +1,33 @@ +/*************************************************************************/ +/* gd_mono_cache.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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_CACHE_H #define GD_MONO_CACHE_H @@ -12,20 +42,20 @@ struct CachedData { // corlib classes // Let's use the no-namespace format for these too - GDMonoClass *class_MonoObject; - GDMonoClass *class_bool; - GDMonoClass *class_int8_t; - GDMonoClass *class_int16_t; - GDMonoClass *class_int32_t; - GDMonoClass *class_int64_t; - GDMonoClass *class_uint8_t; - GDMonoClass *class_uint16_t; - GDMonoClass *class_uint32_t; - GDMonoClass *class_uint64_t; - GDMonoClass *class_float; - GDMonoClass *class_double; - GDMonoClass *class_String; - GDMonoClass *class_IntPtr; + GDMonoClass *class_MonoObject; // object + GDMonoClass *class_bool; // bool + GDMonoClass *class_int8_t; // sbyte + GDMonoClass *class_int16_t; // short + GDMonoClass *class_int32_t; // int + GDMonoClass *class_int64_t; // long + GDMonoClass *class_uint8_t; // byte + GDMonoClass *class_uint16_t; // ushort + GDMonoClass *class_uint32_t; // uint + GDMonoClass *class_uint64_t; // ulong + GDMonoClass *class_float; // float + GDMonoClass *class_double; // double + GDMonoClass *class_String; // string + GDMonoClass *class_IntPtr; // System.IntPtr GDMonoClass *class_System_Collections_IEnumerable; GDMonoClass *class_System_Collections_IDictionary; diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp index fb9b6be3d4..648f5f6c6b 100644 --- a/modules/mono/mono_gd/gd_mono_class.cpp +++ b/modules/mono/mono_gd/gd_mono_class.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -166,8 +166,8 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base #ifdef DEBUG_ENABLED String fullname = method->get_ret_type_full_name() + " " + name + "(" + method->get_signature_desc(true) + ")"; - WARN_PRINTS("Method '" + fullname + "' is hidden by Godot API method. Should be '" + - method->get_full_name_no_class() + "'. In class '" + namespace_name + "." + class_name + "'."); + 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; } @@ -185,8 +185,8 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base if (m && m->get_name() != name) { // found String fullname = m->get_ret_type_full_name() + " " + name + "(" + m->get_signature_desc(true) + ")"; - WARN_PRINTS("Method '" + fullname + "' should be '" + m->get_full_name_no_class() + - "'. In class '" + namespace_name + "." + class_name + "'."); + WARN_PRINT("Method '" + fullname + "' should be '" + m->get_full_name_no_class() + + "'. In class '" + namespace_name + "." + class_name + "'."); break; } diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h index 562c337822..0c9a8cdafe 100644 --- a/modules/mono/mono_gd/gd_mono_class.h +++ b/modules/mono/mono_gd/gd_mono_class.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp index d84359b1ab..178647b968 100644 --- a/modules/mono/mono_gd/gd_mono_field.cpp +++ b/modules/mono/mono_gd/gd_mono_field.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -110,8 +110,14 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ } break; case MONO_TYPE_STRING: { - MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value); - mono_field_set_value(p_object, mono_field, mono_string); + if (p_value.get_type() == Variant::NIL) { + // Otherwise, Variant -> String would return the string "Null" + MonoString *mono_string = NULL; + mono_field_set_value(p_object, mono_field, mono_string); + } else { + MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value); + mono_field_set_value(p_object, mono_field, mono_string); + } } break; case MONO_TYPE_VALUETYPE: { @@ -506,7 +512,7 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ } break; default: { - ERR_PRINTS("Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding) + "."); + ERR_PRINT("Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding) + "."); } break; } diff --git a/modules/mono/mono_gd/gd_mono_field.h b/modules/mono/mono_gd/gd_mono_field.h index a7727ddf34..76ee0963c4 100644 --- a/modules/mono/mono_gd/gd_mono_field.h +++ b/modules/mono/mono_gd/gd_mono_field.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_header.h b/modules/mono/mono_gd/gd_mono_header.h index 173e1613bf..0f4f888546 100644 --- a/modules/mono/mono_gd/gd_mono_header.h +++ b/modules/mono/mono_gd/gd_mono_header.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp index 3324ecb3a8..75aa77c7b0 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-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -73,7 +73,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { script_binding.inited = true; script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass); script_binding.wrapper_class = klass; - script_binding.gchandle = MonoGCHandle::create_strong(managed); + script_binding.gchandle = ref ? MonoGCHandle::create_weak(managed) : MonoGCHandle::create_strong(managed); script_binding.owner = unmanaged; if (ref) { @@ -81,7 +81,11 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { // 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_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) - ref->reference(); + + // May not me referenced yet, so we must use init_ref() instead of reference() + if (ref->init_ref()) { + CSharpLanguage::get_singleton()->post_unsafe_reference(ref); + } } // The object was just created, no script instance binding should have been attached diff --git a/modules/mono/mono_gd/gd_mono_internals.h b/modules/mono/mono_gd/gd_mono_internals.h index 0d82723913..038d17f782 100644 --- a/modules/mono/mono_gd/gd_mono_internals.h +++ b/modules/mono/mono_gd/gd_mono_internals.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_log.cpp b/modules/mono/mono_gd/gd_mono_log.cpp index 261b800619..76828a66e0 100644 --- a/modules/mono/mono_gd/gd_mono_log.cpp +++ b/modules/mono/mono_gd/gd_mono_log.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -83,7 +83,7 @@ void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, } if (fatal) { - ERR_PRINTS("Mono: FATAL ERROR, ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'."); + ERR_PRINT("Mono: FATAL ERROR, ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'."); // Make sure to flush before aborting f->flush(); f->close(); @@ -139,7 +139,7 @@ void GDMonoLog::initialize() { CharString log_level = OS::get_singleton()->get_environment("GODOT_MONO_LOG_LEVEL").utf8(); if (log_level.length() != 0 && get_log_level_id(log_level.get_data()) == -1) { - ERR_PRINTS(String() + "Mono: Ignoring invalid log level (GODOT_MONO_LOG_LEVEL): '" + log_level.get_data() + "'."); + ERR_PRINT(String() + "Mono: Ignoring invalid log level (GODOT_MONO_LOG_LEVEL): '" + log_level.get_data() + "'."); log_level = CharString(); } @@ -167,7 +167,7 @@ void GDMonoLog::initialize() { log_file = FileAccess::open(log_file_path, FileAccess::WRITE); if (!log_file) { - ERR_PRINTS("Mono: Cannot create log file at: " + log_file_path); + ERR_PRINT("Mono: Cannot create log file at: " + log_file_path); } } diff --git a/modules/mono/mono_gd/gd_mono_log.h b/modules/mono/mono_gd/gd_mono_log.h index 4cd5a662fb..ecf4c78b1a 100644 --- a/modules/mono/mono_gd/gd_mono_log.h +++ b/modules/mono/mono_gd/gd_mono_log.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp index 3827960e6b..19d627218e 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ b/modules/mono/mono_gd/gd_mono_marshal.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -277,7 +277,7 @@ String mono_to_utf8_string(MonoString *p_mono_string) { char *utf8 = mono_string_to_utf8_checked(p_mono_string, &error); if (!mono_error_ok(&error)) { - ERR_PRINTS(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&error) + "'."); + ERR_PRINT(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&error) + "'."); mono_error_cleanup(&error); return String(); } @@ -374,6 +374,8 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty } case MONO_TYPE_STRING: { + if (p_var->get_type() == Variant::NIL) + return NULL; // Otherwise, Variant -> String would return the string "Null" return (MonoObject *)mono_string_from_godot(p_var->operator String()); } break; @@ -698,15 +700,11 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty p_type.type_class->get_name() + "' Encoding: " + itos(p_type.type_encoding) + "."); } -Variant mono_object_to_variant(MonoObject *p_obj) { - if (!p_obj) - return Variant(); +Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type, bool p_fail_with_err = true) { - ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj)); - - ERR_FAIL_COND_V(!type.type_class, Variant()); + ERR_FAIL_COND_V(!p_type.type_class, Variant()); - switch (type.type_encoding) { + switch (p_type.type_encoding) { case MONO_TYPE_BOOLEAN: return (bool)unbox<MonoBoolean>(p_obj); @@ -743,7 +741,7 @@ Variant mono_object_to_variant(MonoObject *p_obj) { } break; case MONO_TYPE_VALUETYPE: { - GDMonoClass *vtclass = type.type_class; + GDMonoClass *vtclass = p_type.type_class; if (vtclass == CACHED_CLASS(Vector2)) return MARSHALLED_IN(Vector2, (GDMonoMarshal::M_Vector2 *)mono_object_unbox(p_obj)); @@ -781,7 +779,7 @@ Variant mono_object_to_variant(MonoObject *p_obj) { case MONO_TYPE_ARRAY: case MONO_TYPE_SZARRAY: { - MonoArrayType *array_type = mono_type_get_array_type(type.type_class->get_mono_type()); + MonoArrayType *array_type = mono_type_get_array_type(p_type.type_class->get_mono_type()); if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) return mono_array_to_Array((MonoArray *)p_obj); @@ -807,11 +805,15 @@ Variant mono_object_to_variant(MonoObject *p_obj) { if (array_type->eklass == CACHED_CLASS_RAW(Color)) return mono_array_to_PoolColorArray((MonoArray *)p_obj); - ERR_FAIL_V_MSG(Variant(), "Attempted to convert a managed array of unmarshallable element type to Variant."); + if (p_fail_with_err) { + ERR_FAIL_V_MSG(Variant(), "Attempted to convert a managed array of unmarshallable element type to Variant."); + } else { + return Variant(); + } } break; case MONO_TYPE_CLASS: { - GDMonoClass *type_class = type.type_class; + GDMonoClass *type_class = p_type.type_class; // GodotObject if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) { @@ -869,18 +871,18 @@ Variant mono_object_to_variant(MonoObject *p_obj) { } break; case MONO_TYPE_GENERICINST: { - MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type()); + MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type()); if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) { MonoException *exc = NULL; - MonoObject *ret = type.type_class->get_method("GetPtr")->invoke(p_obj, &exc); + MonoObject *ret = p_type.type_class->get_method("GetPtr")->invoke(p_obj, &exc); UNHANDLED_EXCEPTION(exc); return *unbox<Dictionary *>(ret); } if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) { MonoException *exc = NULL; - MonoObject *ret = type.type_class->get_method("GetPtr")->invoke(p_obj, &exc); + MonoObject *ret = p_type.type_class->get_method("GetPtr")->invoke(p_obj, &exc); UNHANDLED_EXCEPTION(exc); return *unbox<Array *>(ret); } @@ -891,7 +893,7 @@ Variant mono_object_to_variant(MonoObject *p_obj) { return GDMonoUtils::Marshal::generic_idictionary_to_dictionary(p_obj); } - if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { + if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IDictionary))) { return GDMonoUtils::Marshal::idictionary_to_dictionary(p_obj); } @@ -899,14 +901,62 @@ Variant mono_object_to_variant(MonoObject *p_obj) { return GDMonoUtils::Marshal::enumerable_to_array(p_obj); } - if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { + if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) { return GDMonoUtils::Marshal::enumerable_to_array(p_obj); } } break; } - ERR_FAIL_V_MSG(Variant(), "Attempted to convert an unmarshallable managed type to Variant. Name: '" + - type.type_class->get_name() + "' Encoding: " + itos(type.type_encoding) + "."); + if (p_fail_with_err) { + ERR_FAIL_V_MSG(Variant(), "Attempted to convert an unmarshallable managed type to Variant. Name: '" + + p_type.type_class->get_name() + "' Encoding: " + itos(p_type.type_encoding) + "."); + } else { + return Variant(); + } +} + +Variant mono_object_to_variant(MonoObject *p_obj) { + if (!p_obj) + return Variant(); + + ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj)); + + return mono_object_to_variant_impl(p_obj, type); +} + +Variant mono_object_to_variant(MonoObject *p_obj, const ManagedType &p_type) { + if (!p_obj) + return Variant(); + + return mono_object_to_variant_impl(p_obj, p_type); +} + +Variant mono_object_to_variant_no_err(MonoObject *p_obj, const ManagedType &p_type) { + if (!p_obj) + return Variant(); + + return mono_object_to_variant_impl(p_obj, p_type, /* fail_with_err: */ false); +} + +String mono_object_to_variant_string(MonoObject *p_obj, MonoException **r_exc) { + ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj)); + Variant var = GDMonoMarshal::mono_object_to_variant_no_err(p_obj, type); + + if (var.get_type() == Variant::NIL && p_obj != NULL) { + // Cannot convert MonoObject* to Variant; fallback to 'ToString()'. + MonoException *exc = NULL; + MonoString *mono_str = GDMonoUtils::object_to_string(p_obj, &exc); + + if (exc) { + if (r_exc) + *r_exc = exc; + return String(); + } + + return GDMonoMarshal::mono_string_to_godot(mono_str); + } else { + return var.operator String(); + } } MonoArray *Array_to_mono_array(const Array &p_array) { @@ -935,6 +985,8 @@ Array mono_array_to_Array(MonoArray *p_array) { return ret; } +// TODO: Use memcpy where possible + MonoArray *PoolIntArray_to_mono_array(const PoolIntArray &p_array) { PoolIntArray::Read r = p_array.read(); diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index 53eae45320..e662e7814e 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -115,6 +115,12 @@ _FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant &p_var, const Ma } Variant mono_object_to_variant(MonoObject *p_obj); +Variant mono_object_to_variant(MonoObject *p_obj, const ManagedType &p_type); +Variant mono_object_to_variant_no_err(MonoObject *p_obj, const ManagedType &p_type); + +/// Tries to convert the MonoObject* to Variant and then convert the Variant to String. +/// If the MonoObject* cannot be converted to Variant, then 'ToString()' is called instead. +String mono_object_to_variant_string(MonoObject *p_obj, MonoException **r_exc); // Array diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp index 080b3a676a..971c5ac737 100644 --- a/modules/mono/mono_gd/gd_mono_method.cpp +++ b/modules/mono/mono_gd/gd_mono_method.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_method.h b/modules/mono/mono_gd/gd_mono_method.h index abbae92e29..b47e42dec2 100644 --- a/modules/mono/mono_gd/gd_mono_method.h +++ b/modules/mono/mono_gd/gd_mono_method.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_method_thunk.h b/modules/mono/mono_gd/gd_mono_method_thunk.h index 9fe9e724f2..d8c9a5eb02 100644 --- a/modules/mono/mono_gd/gd_mono_method_thunk.h +++ b/modules/mono/mono_gd/gd_mono_method_thunk.h @@ -1,3 +1,33 @@ +/*************************************************************************/ +/* gd_mono_method_thunk.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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_THUNK_H #define 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 index 277fe10087..3b5ce58d80 100644 --- a/modules/mono/mono_gd/gd_mono_property.cpp +++ b/modules/mono/mono_gd/gd_mono_property.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_property.h b/modules/mono/mono_gd/gd_mono_property.h index d6efa60412..692037f76a 100644 --- a/modules/mono/mono_gd/gd_mono_property.h +++ b/modules/mono/mono_gd/gd_mono_property.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index 8d7aaa97f2..05077a00c4 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -115,6 +115,7 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) { // but the managed instance is alive, the refcount will be 1 instead of 0. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) ref->reference(); + CSharpLanguage::get_singleton()->post_unsafe_reference(ref); } return mono_object; @@ -124,10 +125,12 @@ void set_main_thread(MonoThread *p_thread) { mono_thread_set_main(p_thread); } -void attach_current_thread() { - ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized()); - MonoThread *mono_thread = mono_thread_attach(mono_get_root_domain()); - ERR_FAIL_NULL(mono_thread); +MonoThread *attach_current_thread() { + ERR_FAIL_COND_V(!GDMono::get_singleton()->is_runtime_initialized(), NULL); + MonoDomain *scripts_domain = GDMono::get_singleton()->get_scripts_domain(); + MonoThread *mono_thread = mono_thread_attach(scripts_domain ? scripts_domain : mono_get_root_domain()); + ERR_FAIL_NULL_V(mono_thread, NULL); + return mono_thread; } void detach_current_thread() { @@ -137,10 +140,20 @@ void detach_current_thread() { mono_thread_detach(mono_thread); } +void detach_current_thread(MonoThread *p_mono_thread) { + ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized()); + ERR_FAIL_NULL(p_mono_thread); + mono_thread_detach(p_mono_thread); +} + MonoThread *get_current_thread() { return mono_thread_current(); } +bool is_thread_attached() { + return mono_domain_get() != NULL; +} + 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); @@ -341,7 +354,7 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) { if (!ScriptDebugger::get_singleton()) { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { - ERR_PRINTS(GDMonoUtils::get_exception_name_and_message(p_exc)); + ERR_PRINT(GDMonoUtils::get_exception_name_and_message(p_exc)); } #endif return; @@ -418,7 +431,7 @@ void set_pending_exception(MonoException *p_exc) { } if (!mono_runtime_set_pending_exception(p_exc, false)) { - ERR_PRINTS("Exception thrown from managed code, but it could not be set as pending:"); + ERR_PRINT("Exception thrown from managed code, but it could not be set as pending:"); GDMonoUtils::debug_print_unhandled_exception(p_exc); } #endif @@ -616,4 +629,19 @@ GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, Mon } // namespace Marshal +ScopeThreadAttach::ScopeThreadAttach() : + mono_thread(NULL) { + if (likely(GDMono::get_singleton()->is_runtime_initialized()) && unlikely(!mono_domain_get())) { + mono_thread = GDMonoUtils::attach_current_thread(); + } +} + +ScopeThreadAttach::~ScopeThreadAttach() { + if (unlikely(mono_thread)) { + GDMonoUtils::detach_current_thread(mono_thread); + } +} + +// namespace Marshal + } // namespace GDMonoUtils diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index 848df843fe..db9f99bfdc 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ @@ -83,9 +83,11 @@ _FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) MonoObject *unmanaged_get_managed(Object *unmanaged); void set_main_thread(MonoThread *p_thread); -void attach_current_thread(); +MonoThread *attach_current_thread(); void detach_current_thread(); +void detach_current_thread(MonoThread *p_mono_thread); MonoThread *get_current_thread(); +bool is_thread_attached(); _FORCE_INLINE_ bool is_main_thread() { return mono_domain_get() != NULL && mono_thread_get_main() == mono_thread_current(); @@ -142,6 +144,14 @@ uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool & void dispose(MonoObject *p_mono_object, MonoException **r_exc); +struct ScopeThreadAttach { + ScopeThreadAttach(); + ~ScopeThreadAttach(); + +private: + MonoThread *mono_thread; +}; + } // namespace GDMonoUtils #define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoMarshal::mono_string_to_godot((MonoString *)m_class->get_field(BINDINGS_NATIVE_NAME_FIELD)->get_value(NULL))) @@ -153,4 +163,15 @@ void dispose(MonoObject *p_mono_object, MonoException **r_exc); #define GD_MONO_END_RUNTIME_INVOKE \ _runtime_invoke_count_ref -= 1; +#define GD_MONO_SCOPE_THREAD_ATTACH \ + GDMonoUtils::ScopeThreadAttach __gdmono__scope__thread__attach__; \ + (void)__gdmono__scope__thread__attach__; + +#ifdef DEBUG_ENABLED +#define GD_MONO_ASSERT_THREAD_ATTACHED \ + { CRASH_COND(!GDMonoUtils::is_thread_attached()); } +#else +#define GD_MONO_ASSERT_THREAD_ATTACHED +#endif + #endif // GD_MONOUTILS_H diff --git a/modules/mono/mono_gd/i_mono_class_member.h b/modules/mono/mono_gd/i_mono_class_member.h index f4de4e3230..2e8e01c80e 100644 --- a/modules/mono/mono_gd/i_mono_class_member.h +++ b/modules/mono/mono_gd/i_mono_class_member.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/managed_type.cpp b/modules/mono/mono_gd/managed_type.cpp index 9f736b71cd..3e971efece 100644 --- a/modules/mono/mono_gd/managed_type.cpp +++ b/modules/mono/mono_gd/managed_type.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ diff --git a/modules/mono/mono_gd/managed_type.h b/modules/mono/mono_gd/managed_type.h index a537e56aea..11b832d0cc 100644 --- a/modules/mono/mono_gd/managed_type.h +++ b/modules/mono/mono_gd/managed_type.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 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 */ |