gd_mono_utils.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /*************************************************************************/
  2. /* gd_mono_utils.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "gd_mono_utils.h"
  31. #include <mono/metadata/exception.h>
  32. #include "core/os/dir_access.h"
  33. #include "core/os/os.h"
  34. #include "core/project_settings.h"
  35. #include "core/reference.h"
  36. #include "../csharp_script.h"
  37. #include "../utils/macros.h"
  38. #include "../utils/mutex_utils.h"
  39. #include "gd_mono.h"
  40. #include "gd_mono_class.h"
  41. #include "gd_mono_marshal.h"
  42. namespace GDMonoUtils {
  43. MonoCache mono_cache;
  44. #define CACHE_AND_CHECK(m_var, m_val) \
  45. { \
  46. m_var = m_val; \
  47. if (!m_var) { \
  48. ERR_EXPLAIN("Mono Cache: Member " #m_var " is null"); \
  49. ERR_FAIL(); \
  50. } \
  51. }
  52. #define CACHE_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.class_##m_class, m_val)
  53. #define CACHE_NS_CLASS_AND_CHECK(m_ns, m_class, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.class_##m_ns##_##m_class, m_val)
  54. #define CACHE_RAW_MONO_CLASS_AND_CHECK(m_class, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.rawclass_##m_class, m_val)
  55. #define CACHE_FIELD_AND_CHECK(m_class, m_field, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.field_##m_class##_##m_field, m_val)
  56. #define CACHE_METHOD_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.method_##m_class##_##m_method, m_val)
  57. #define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.methodthunk_##m_class##_##m_method, m_val)
  58. #define CACHE_PROPERTY_AND_CHECK(m_class, m_property, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.property_##m_class##_##m_property, m_val)
  59. void MonoCache::clear_members() {
  60. class_MonoObject = NULL;
  61. class_bool = NULL;
  62. class_int8_t = NULL;
  63. class_int16_t = NULL;
  64. class_int32_t = NULL;
  65. class_int64_t = NULL;
  66. class_uint8_t = NULL;
  67. class_uint16_t = NULL;
  68. class_uint32_t = NULL;
  69. class_uint64_t = NULL;
  70. class_float = NULL;
  71. class_double = NULL;
  72. class_String = NULL;
  73. class_IntPtr = NULL;
  74. class_System_Collections_IEnumerable = NULL;
  75. class_System_Collections_IDictionary = NULL;
  76. #ifdef DEBUG_ENABLED
  77. class_System_Diagnostics_StackTrace = NULL;
  78. methodthunk_System_Diagnostics_StackTrace_GetFrames = NULL;
  79. method_System_Diagnostics_StackTrace_ctor_bool = NULL;
  80. method_System_Diagnostics_StackTrace_ctor_Exception_bool = NULL;
  81. #endif
  82. class_KeyNotFoundException = NULL;
  83. rawclass_Dictionary = NULL;
  84. class_Vector2 = NULL;
  85. class_Rect2 = NULL;
  86. class_Transform2D = NULL;
  87. class_Vector3 = NULL;
  88. class_Basis = NULL;
  89. class_Quat = NULL;
  90. class_Transform = NULL;
  91. class_AABB = NULL;
  92. class_Color = NULL;
  93. class_Plane = NULL;
  94. class_NodePath = NULL;
  95. class_RID = NULL;
  96. class_GodotObject = NULL;
  97. class_GodotReference = NULL;
  98. class_Node = NULL;
  99. class_Control = NULL;
  100. class_Spatial = NULL;
  101. class_WeakRef = NULL;
  102. class_Array = NULL;
  103. class_Dictionary = NULL;
  104. class_MarshalUtils = NULL;
  105. #ifdef DEBUG_ENABLED
  106. class_DebuggingUtils = NULL;
  107. methodthunk_DebuggingUtils_GetStackFrameInfo = NULL;
  108. #endif
  109. class_ExportAttribute = NULL;
  110. field_ExportAttribute_hint = NULL;
  111. field_ExportAttribute_hintString = NULL;
  112. class_SignalAttribute = NULL;
  113. class_ToolAttribute = NULL;
  114. class_RemoteAttribute = NULL;
  115. class_SyncAttribute = NULL;
  116. class_MasterAttribute = NULL;
  117. class_PuppetAttribute = NULL;
  118. class_SlaveAttribute = NULL;
  119. class_RemoteSyncAttribute = NULL;
  120. class_MasterSyncAttribute = NULL;
  121. class_PuppetSyncAttribute = NULL;
  122. class_GodotMethodAttribute = NULL;
  123. field_GodotMethodAttribute_methodName = NULL;
  124. field_GodotObject_ptr = NULL;
  125. field_NodePath_ptr = NULL;
  126. field_Image_ptr = NULL;
  127. field_RID_ptr = NULL;
  128. methodthunk_GodotObject_Dispose = NULL;
  129. methodthunk_Array_GetPtr = NULL;
  130. methodthunk_Dictionary_GetPtr = NULL;
  131. methodthunk_SignalAwaiter_SignalCallback = NULL;
  132. methodthunk_SignalAwaiter_FailureCallback = NULL;
  133. methodthunk_GodotTaskScheduler_Activate = NULL;
  134. methodthunk_MarshalUtils_TypeIsGenericArray = NULL;
  135. methodthunk_MarshalUtils_TypeIsGenericDictionary = NULL;
  136. methodthunk_MarshalUtils_ArrayGetElementType = NULL;
  137. methodthunk_MarshalUtils_DictionaryGetKeyValueTypes = NULL;
  138. methodthunk_MarshalUtils_EnumerableToArray = NULL;
  139. methodthunk_MarshalUtils_IDictionaryToDictionary = NULL;
  140. task_scheduler_handle = Ref<MonoGCHandle>();
  141. }
  142. void MonoCache::cleanup() {
  143. corlib_cache_updated = false;
  144. godot_api_cache_updated = false;
  145. }
  146. #define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class))
  147. #define GODOT_API_NS_CLAS(m_ns, m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(m_ns, #m_class))
  148. void update_corlib_cache() {
  149. CACHE_CLASS_AND_CHECK(MonoObject, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_object_class()));
  150. CACHE_CLASS_AND_CHECK(bool, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_boolean_class()));
  151. CACHE_CLASS_AND_CHECK(int8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_sbyte_class()));
  152. CACHE_CLASS_AND_CHECK(int16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int16_class()));
  153. CACHE_CLASS_AND_CHECK(int32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int32_class()));
  154. CACHE_CLASS_AND_CHECK(int64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_int64_class()));
  155. CACHE_CLASS_AND_CHECK(uint8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_byte_class()));
  156. CACHE_CLASS_AND_CHECK(uint16_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint16_class()));
  157. CACHE_CLASS_AND_CHECK(uint32_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint32_class()));
  158. CACHE_CLASS_AND_CHECK(uint64_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_uint64_class()));
  159. CACHE_CLASS_AND_CHECK(float, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_single_class()));
  160. CACHE_CLASS_AND_CHECK(double, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_double_class()));
  161. CACHE_CLASS_AND_CHECK(String, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_string_class()));
  162. CACHE_CLASS_AND_CHECK(IntPtr, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_intptr_class()));
  163. CACHE_CLASS_AND_CHECK(System_Collections_IEnumerable, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IEnumerable"));
  164. CACHE_CLASS_AND_CHECK(System_Collections_IDictionary, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections", "IDictionary"));
  165. #ifdef DEBUG_ENABLED
  166. CACHE_CLASS_AND_CHECK(System_Diagnostics_StackTrace, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Diagnostics", "StackTrace"));
  167. CACHE_METHOD_THUNK_AND_CHECK(System_Diagnostics_StackTrace, GetFrames, (StackTrace_GetFrames)CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_thunk("GetFrames"));
  168. CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(bool)", true));
  169. 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));
  170. #endif
  171. CACHE_CLASS_AND_CHECK(KeyNotFoundException, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections.Generic", "KeyNotFoundException"));
  172. mono_cache.corlib_cache_updated = true;
  173. }
  174. void update_godot_api_cache() {
  175. CACHE_CLASS_AND_CHECK(Vector2, GODOT_API_CLASS(Vector2));
  176. CACHE_CLASS_AND_CHECK(Rect2, GODOT_API_CLASS(Rect2));
  177. CACHE_CLASS_AND_CHECK(Transform2D, GODOT_API_CLASS(Transform2D));
  178. CACHE_CLASS_AND_CHECK(Vector3, GODOT_API_CLASS(Vector3));
  179. CACHE_CLASS_AND_CHECK(Basis, GODOT_API_CLASS(Basis));
  180. CACHE_CLASS_AND_CHECK(Quat, GODOT_API_CLASS(Quat));
  181. CACHE_CLASS_AND_CHECK(Transform, GODOT_API_CLASS(Transform));
  182. CACHE_CLASS_AND_CHECK(AABB, GODOT_API_CLASS(AABB));
  183. CACHE_CLASS_AND_CHECK(Color, GODOT_API_CLASS(Color));
  184. CACHE_CLASS_AND_CHECK(Plane, GODOT_API_CLASS(Plane));
  185. CACHE_CLASS_AND_CHECK(NodePath, GODOT_API_CLASS(NodePath));
  186. CACHE_CLASS_AND_CHECK(RID, GODOT_API_CLASS(RID));
  187. CACHE_CLASS_AND_CHECK(GodotObject, GODOT_API_CLASS(Object));
  188. CACHE_CLASS_AND_CHECK(GodotReference, GODOT_API_CLASS(Reference));
  189. CACHE_CLASS_AND_CHECK(Node, GODOT_API_CLASS(Node));
  190. CACHE_CLASS_AND_CHECK(Control, GODOT_API_CLASS(Control));
  191. CACHE_CLASS_AND_CHECK(Spatial, GODOT_API_CLASS(Spatial));
  192. CACHE_CLASS_AND_CHECK(WeakRef, GODOT_API_CLASS(WeakRef));
  193. CACHE_CLASS_AND_CHECK(Array, GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Array));
  194. CACHE_CLASS_AND_CHECK(Dictionary, GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary));
  195. CACHE_CLASS_AND_CHECK(MarshalUtils, GODOT_API_CLASS(MarshalUtils));
  196. #ifdef DEBUG_ENABLED
  197. CACHE_CLASS_AND_CHECK(DebuggingUtils, GODOT_API_CLASS(DebuggingUtils));
  198. #endif
  199. // Attributes
  200. CACHE_CLASS_AND_CHECK(ExportAttribute, GODOT_API_CLASS(ExportAttribute));
  201. CACHE_FIELD_AND_CHECK(ExportAttribute, hint, CACHED_CLASS(ExportAttribute)->get_field("hint"));
  202. CACHE_FIELD_AND_CHECK(ExportAttribute, hintString, CACHED_CLASS(ExportAttribute)->get_field("hintString"));
  203. CACHE_CLASS_AND_CHECK(SignalAttribute, GODOT_API_CLASS(SignalAttribute));
  204. CACHE_CLASS_AND_CHECK(ToolAttribute, GODOT_API_CLASS(ToolAttribute));
  205. CACHE_CLASS_AND_CHECK(RemoteAttribute, GODOT_API_CLASS(RemoteAttribute));
  206. CACHE_CLASS_AND_CHECK(SyncAttribute, GODOT_API_CLASS(SyncAttribute));
  207. CACHE_CLASS_AND_CHECK(MasterAttribute, GODOT_API_CLASS(MasterAttribute));
  208. CACHE_CLASS_AND_CHECK(PuppetAttribute, GODOT_API_CLASS(PuppetAttribute));
  209. CACHE_CLASS_AND_CHECK(SlaveAttribute, GODOT_API_CLASS(SlaveAttribute));
  210. CACHE_CLASS_AND_CHECK(RemoteSyncAttribute, GODOT_API_CLASS(RemoteSyncAttribute));
  211. CACHE_CLASS_AND_CHECK(MasterSyncAttribute, GODOT_API_CLASS(MasterSyncAttribute));
  212. CACHE_CLASS_AND_CHECK(PuppetSyncAttribute, GODOT_API_CLASS(PuppetSyncAttribute));
  213. CACHE_CLASS_AND_CHECK(GodotMethodAttribute, GODOT_API_CLASS(GodotMethodAttribute));
  214. CACHE_FIELD_AND_CHECK(GodotMethodAttribute, methodName, CACHED_CLASS(GodotMethodAttribute)->get_field("methodName"));
  215. CACHE_FIELD_AND_CHECK(GodotObject, ptr, CACHED_CLASS(GodotObject)->get_field(BINDINGS_PTR_FIELD));
  216. CACHE_FIELD_AND_CHECK(NodePath, ptr, CACHED_CLASS(NodePath)->get_field(BINDINGS_PTR_FIELD));
  217. CACHE_FIELD_AND_CHECK(RID, ptr, CACHED_CLASS(RID)->get_field(BINDINGS_PTR_FIELD));
  218. CACHE_METHOD_THUNK_AND_CHECK(GodotObject, Dispose, (GodotObject_Dispose)CACHED_CLASS(GodotObject)->get_method_thunk("Dispose", 0));
  219. CACHE_METHOD_THUNK_AND_CHECK(Array, GetPtr, (Array_GetPtr)GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Array)->get_method_thunk("GetPtr", 0));
  220. CACHE_METHOD_THUNK_AND_CHECK(Dictionary, GetPtr, (Dictionary_GetPtr)GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary)->get_method_thunk("GetPtr", 0));
  221. CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, (SignalAwaiter_SignalCallback)GODOT_API_CLASS(SignalAwaiter)->get_method_thunk("SignalCallback", 1));
  222. CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, FailureCallback, (SignalAwaiter_FailureCallback)GODOT_API_CLASS(SignalAwaiter)->get_method_thunk("FailureCallback", 0));
  223. CACHE_METHOD_THUNK_AND_CHECK(GodotTaskScheduler, Activate, (GodotTaskScheduler_Activate)GODOT_API_CLASS(GodotTaskScheduler)->get_method_thunk("Activate", 0));
  224. CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericArray, (TypeIsGenericArray)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("TypeIsGenericArray", 1));
  225. CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, TypeIsGenericDictionary, (TypeIsGenericDictionary)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("TypeIsGenericDictionary", 1));
  226. CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArrayGetElementType, (ArrayGetElementType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("ArrayGetElementType", 2));
  227. CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryGetKeyValueTypes, (DictionaryGetKeyValueTypes)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("DictionaryGetKeyValueTypes", 3));
  228. CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, EnumerableToArray, (EnumerableToArray)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("EnumerableToArray", 2));
  229. CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, IDictionaryToDictionary, (IDictionaryToDictionary)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("IDictionaryToDictionary", 2));
  230. #ifdef DEBUG_ENABLED
  231. CACHE_METHOD_THUNK_AND_CHECK(DebuggingUtils, GetStackFrameInfo, (DebugUtils_StackFrameInfo)GODOT_API_CLASS(DebuggingUtils)->get_method_thunk("GetStackFrameInfo", 4));
  232. #endif
  233. // TODO Move to CSharpLanguage::init() and do handle disposal
  234. MonoObject *task_scheduler = mono_object_new(SCRIPTS_DOMAIN, GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr());
  235. GDMonoUtils::runtime_object_init(task_scheduler);
  236. mono_cache.task_scheduler_handle = MonoGCHandle::create_strong(task_scheduler);
  237. mono_cache.godot_api_cache_updated = true;
  238. }
  239. void clear_cache() {
  240. mono_cache.cleanup();
  241. mono_cache.clear_members();
  242. }
  243. MonoObject *unmanaged_get_managed(Object *unmanaged) {
  244. if (!unmanaged)
  245. return NULL;
  246. if (unmanaged->get_script_instance()) {
  247. CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(unmanaged->get_script_instance());
  248. if (cs_instance) {
  249. return cs_instance->get_mono_object();
  250. }
  251. }
  252. // If the owner does not have a CSharpInstance...
  253. void *data = unmanaged->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  254. ERR_FAIL_NULL_V(data, NULL);
  255. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->value();
  256. if (!script_binding.inited) {
  257. SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  258. if (!script_binding.inited) { // Other thread may have set it up
  259. // Already had a binding that needs to be setup
  260. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, unmanaged);
  261. ERR_FAIL_COND_V(!script_binding.inited, NULL);
  262. }
  263. }
  264. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  265. ERR_FAIL_COND_V(gchandle.is_null(), NULL);
  266. MonoObject *target = gchandle->get_target();
  267. if (target)
  268. return target;
  269. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  270. // Create a new one
  271. #ifdef DEBUG_ENABLED
  272. CRASH_COND(script_binding.type_name == StringName());
  273. CRASH_COND(script_binding.wrapper_class == NULL);
  274. #endif
  275. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(script_binding.wrapper_class, script_binding.type_name, unmanaged);
  276. ERR_FAIL_NULL_V(mono_object, NULL);
  277. gchandle->set_handle(MonoGCHandle::new_strong_handle(mono_object), MonoGCHandle::STRONG_HANDLE);
  278. // Tie managed to unmanaged
  279. Reference *ref = Object::cast_to<Reference>(unmanaged);
  280. if (ref) {
  281. // Unsafe refcount increment. The managed instance also counts as a reference.
  282. // This way if the unmanaged world has no references to our owner
  283. // but the managed instance is alive, the refcount will be 1 instead of 0.
  284. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
  285. ref->reference();
  286. }
  287. return mono_object;
  288. }
  289. void set_main_thread(MonoThread *p_thread) {
  290. mono_thread_set_main(p_thread);
  291. }
  292. void attach_current_thread() {
  293. ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
  294. MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
  295. ERR_FAIL_NULL(mono_thread);
  296. }
  297. void detach_current_thread() {
  298. ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
  299. MonoThread *mono_thread = mono_thread_current();
  300. ERR_FAIL_NULL(mono_thread);
  301. mono_thread_detach(mono_thread);
  302. }
  303. MonoThread *get_current_thread() {
  304. return mono_thread_current();
  305. }
  306. void runtime_object_init(MonoObject *p_this_obj) {
  307. GD_MONO_BEGIN_RUNTIME_INVOKE;
  308. // FIXME: Do not use mono_runtime_object_init, it aborts if an exception is thrown
  309. mono_runtime_object_init(p_this_obj);
  310. GD_MONO_END_RUNTIME_INVOKE;
  311. }
  312. GDMonoClass *get_object_class(MonoObject *p_object) {
  313. return GDMono::get_singleton()->get_class(mono_object_get_class(p_object));
  314. }
  315. GDMonoClass *type_get_proxy_class(const StringName &p_type) {
  316. String class_name = p_type;
  317. if (class_name[0] == '_')
  318. class_name = class_name.substr(1, class_name.length());
  319. GDMonoClass *klass = GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name);
  320. if (klass && klass->is_static()) {
  321. // A static class means this is a Godot singleton class. If an instance is needed we use Godot.Object.
  322. return mono_cache.class_GodotObject;
  323. }
  324. #ifdef TOOLS_ENABLED
  325. if (!klass) {
  326. return GDMono::get_singleton()->get_editor_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name);
  327. }
  328. #endif
  329. return klass;
  330. }
  331. GDMonoClass *get_class_native_base(GDMonoClass *p_class) {
  332. GDMonoClass *klass = p_class;
  333. do {
  334. const GDMonoAssembly *assembly = klass->get_assembly();
  335. if (assembly == GDMono::get_singleton()->get_core_api_assembly())
  336. return klass;
  337. #ifdef TOOLS_ENABLED
  338. if (assembly == GDMono::get_singleton()->get_editor_api_assembly())
  339. return klass;
  340. #endif
  341. } while ((klass = klass->get_parent_class()) != NULL);
  342. return NULL;
  343. }
  344. MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object) {
  345. String object_type = p_object->get_class_name();
  346. if (object_type[0] == '_')
  347. object_type = object_type.substr(1, object_type.length());
  348. if (!ClassDB::is_parent_class(object_type, p_native)) {
  349. ERR_EXPLAIN("Type inherits from native type '" + p_native + "', so it can't be instanced in object of type: '" + p_object->get_class() + "'");
  350. ERR_FAIL_V(NULL);
  351. }
  352. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr());
  353. ERR_FAIL_NULL_V(mono_object, NULL);
  354. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, p_object);
  355. // Construct
  356. GDMonoUtils::runtime_object_init(mono_object);
  357. return mono_object;
  358. }
  359. MonoObject *create_managed_from(const NodePath &p_from) {
  360. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(NodePath));
  361. ERR_FAIL_NULL_V(mono_object, NULL);
  362. // Construct
  363. GDMonoUtils::runtime_object_init(mono_object);
  364. CACHED_FIELD(NodePath, ptr)->set_value_raw(mono_object, memnew(NodePath(p_from)));
  365. return mono_object;
  366. }
  367. MonoObject *create_managed_from(const RID &p_from) {
  368. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(RID));
  369. ERR_FAIL_NULL_V(mono_object, NULL);
  370. // Construct
  371. GDMonoUtils::runtime_object_init(mono_object);
  372. CACHED_FIELD(RID, ptr)->set_value_raw(mono_object, memnew(RID(p_from)));
  373. return mono_object;
  374. }
  375. MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class) {
  376. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr());
  377. ERR_FAIL_NULL_V(mono_object, NULL);
  378. // Search constructor that takes a pointer as parameter
  379. MonoMethod *m;
  380. void *iter = NULL;
  381. while ((m = mono_class_get_methods(p_class->get_mono_ptr(), &iter))) {
  382. if (strcmp(mono_method_get_name(m), ".ctor") == 0) {
  383. MonoMethodSignature *sig = mono_method_signature(m);
  384. void *front = NULL;
  385. if (mono_signature_get_param_count(sig) == 1 &&
  386. mono_class_from_mono_type(mono_signature_get_params(sig, &front)) == CACHED_CLASS(IntPtr)->get_mono_ptr()) {
  387. break;
  388. }
  389. }
  390. }
  391. CRASH_COND(m == NULL);
  392. Array *new_array = memnew(Array(p_from));
  393. void *args[1] = { &new_array };
  394. MonoException *exc = NULL;
  395. GDMonoUtils::runtime_invoke(m, mono_object, args, &exc);
  396. UNLIKELY_UNHANDLED_EXCEPTION(exc);
  397. return mono_object;
  398. }
  399. MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class) {
  400. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr());
  401. ERR_FAIL_NULL_V(mono_object, NULL);
  402. // Search constructor that takes a pointer as parameter
  403. MonoMethod *m;
  404. void *iter = NULL;
  405. while ((m = mono_class_get_methods(p_class->get_mono_ptr(), &iter))) {
  406. if (strcmp(mono_method_get_name(m), ".ctor") == 0) {
  407. MonoMethodSignature *sig = mono_method_signature(m);
  408. void *front = NULL;
  409. if (mono_signature_get_param_count(sig) == 1 &&
  410. mono_class_from_mono_type(mono_signature_get_params(sig, &front)) == CACHED_CLASS(IntPtr)->get_mono_ptr()) {
  411. break;
  412. }
  413. }
  414. }
  415. CRASH_COND(m == NULL);
  416. Dictionary *new_dict = memnew(Dictionary(p_from));
  417. void *args[1] = { &new_dict };
  418. MonoException *exc = NULL;
  419. GDMonoUtils::runtime_invoke(m, mono_object, args, &exc);
  420. UNLIKELY_UNHANDLED_EXCEPTION(exc);
  421. return mono_object;
  422. }
  423. MonoDomain *create_domain(const String &p_friendly_name) {
  424. MonoDomain *domain = mono_domain_create_appdomain((char *)p_friendly_name.utf8().get_data(), NULL);
  425. if (domain) {
  426. // Workaround to avoid this exception:
  427. // System.Configuration.ConfigurationErrorsException: Error Initializing the configuration system.
  428. // ---> System.ArgumentException: The 'ExeConfigFilename' argument cannot be null.
  429. mono_domain_set_config(domain, ".", "");
  430. }
  431. return domain;
  432. }
  433. String get_exception_name_and_message(MonoException *p_exc) {
  434. String res;
  435. MonoClass *klass = mono_object_get_class((MonoObject *)p_exc);
  436. MonoType *type = mono_class_get_type(klass);
  437. char *full_name = mono_type_full_name(type);
  438. res += full_name;
  439. mono_free(full_name);
  440. res += ": ";
  441. MonoProperty *prop = mono_class_get_property_from_name(klass, "Message");
  442. MonoString *msg = (MonoString *)property_get_value(prop, (MonoObject *)p_exc, NULL, NULL);
  443. res += GDMonoMarshal::mono_string_to_godot(msg);
  444. return res;
  445. }
  446. void set_exception_message(MonoException *p_exc, String message) {
  447. MonoClass *klass = mono_object_get_class((MonoObject *)p_exc);
  448. MonoProperty *prop = mono_class_get_property_from_name(klass, "Message");
  449. MonoString *msg = GDMonoMarshal::mono_string_from_godot(message);
  450. void *params[1] = { msg };
  451. property_set_value(prop, (MonoObject *)p_exc, params, NULL);
  452. }
  453. void debug_print_unhandled_exception(MonoException *p_exc) {
  454. print_unhandled_exception(p_exc);
  455. debug_send_unhandled_exception_error(p_exc);
  456. }
  457. void debug_send_unhandled_exception_error(MonoException *p_exc) {
  458. #ifdef DEBUG_ENABLED
  459. if (!ScriptDebugger::get_singleton())
  460. return;
  461. _TLS_RECURSION_GUARD_;
  462. ScriptLanguage::StackInfo separator;
  463. separator.file = String();
  464. separator.func = "--- " + RTR("End of inner exception stack trace") + " ---";
  465. separator.line = 0;
  466. Vector<ScriptLanguage::StackInfo> si;
  467. String exc_msg;
  468. while (p_exc != NULL) {
  469. GDMonoClass *st_klass = CACHED_CLASS(System_Diagnostics_StackTrace);
  470. MonoObject *stack_trace = mono_object_new(mono_domain_get(), st_klass->get_mono_ptr());
  471. MonoBoolean need_file_info = true;
  472. void *ctor_args[2] = { p_exc, &need_file_info };
  473. MonoException *unexpected_exc = NULL;
  474. CACHED_METHOD(System_Diagnostics_StackTrace, ctor_Exception_bool)->invoke_raw(stack_trace, ctor_args, &unexpected_exc);
  475. if (unexpected_exc) {
  476. GDMonoInternals::unhandled_exception(unexpected_exc);
  477. GD_UNREACHABLE();
  478. }
  479. Vector<ScriptLanguage::StackInfo> _si;
  480. if (stack_trace != NULL) {
  481. _si = CSharpLanguage::get_singleton()->stack_trace_get_info(stack_trace);
  482. for (int i = _si.size() - 1; i >= 0; i--)
  483. si.insert(0, _si[i]);
  484. }
  485. exc_msg += (exc_msg.length() > 0 ? " ---> " : "") + GDMonoUtils::get_exception_name_and_message(p_exc);
  486. GDMonoClass *exc_class = GDMono::get_singleton()->get_class(mono_get_exception_class());
  487. GDMonoProperty *inner_exc_prop = exc_class->get_property("InnerException");
  488. CRASH_COND(inner_exc_prop == NULL);
  489. MonoObject *inner_exc = inner_exc_prop->get_value((MonoObject *)p_exc);
  490. if (inner_exc != NULL)
  491. si.insert(0, separator);
  492. p_exc = (MonoException *)inner_exc;
  493. }
  494. String file = si.size() ? si[0].file : __FILE__;
  495. String func = si.size() ? si[0].func : FUNCTION_STR;
  496. int line = si.size() ? si[0].line : __LINE__;
  497. String error_msg = "Unhandled exception";
  498. ScriptDebugger::get_singleton()->send_error(func, file, line, error_msg, exc_msg, ERR_HANDLER_ERROR, si);
  499. #endif
  500. }
  501. void debug_unhandled_exception(MonoException *p_exc) {
  502. GDMonoInternals::unhandled_exception(p_exc); // prints the exception as well
  503. GD_UNREACHABLE();
  504. }
  505. void print_unhandled_exception(MonoException *p_exc) {
  506. mono_print_unhandled_exception((MonoObject *)p_exc);
  507. }
  508. void set_pending_exception(MonoException *p_exc) {
  509. #ifdef HAS_PENDING_EXCEPTIONS
  510. if (get_runtime_invoke_count() == 0) {
  511. debug_unhandled_exception(p_exc);
  512. GD_UNREACHABLE();
  513. }
  514. if (!mono_runtime_set_pending_exception(p_exc, false)) {
  515. ERR_PRINTS("Exception thrown from managed code, but it could not be set as pending:");
  516. GDMonoUtils::debug_print_unhandled_exception(p_exc);
  517. }
  518. #else
  519. debug_unhandled_exception(p_exc);
  520. GD_UNREACHABLE();
  521. #endif
  522. }
  523. _THREAD_LOCAL_(int)
  524. current_invoke_count = 0;
  525. MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, MonoException **r_exc) {
  526. GD_MONO_BEGIN_RUNTIME_INVOKE;
  527. MonoObject *ret = mono_runtime_invoke(p_method, p_obj, p_params, (MonoObject **)r_exc);
  528. GD_MONO_END_RUNTIME_INVOKE;
  529. return ret;
  530. }
  531. MonoObject *runtime_invoke_array(MonoMethod *p_method, void *p_obj, MonoArray *p_params, MonoException **r_exc) {
  532. GD_MONO_BEGIN_RUNTIME_INVOKE;
  533. MonoObject *ret = mono_runtime_invoke_array(p_method, p_obj, p_params, (MonoObject **)r_exc);
  534. GD_MONO_END_RUNTIME_INVOKE;
  535. return ret;
  536. }
  537. MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc) {
  538. GD_MONO_BEGIN_RUNTIME_INVOKE;
  539. MonoString *ret = mono_object_to_string(p_obj, (MonoObject **)r_exc);
  540. GD_MONO_END_RUNTIME_INVOKE;
  541. return ret;
  542. }
  543. void property_set_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc) {
  544. GD_MONO_BEGIN_RUNTIME_INVOKE;
  545. mono_property_set_value(p_prop, p_obj, p_params, (MonoObject **)r_exc);
  546. GD_MONO_END_RUNTIME_INVOKE;
  547. }
  548. MonoObject *property_get_value(MonoProperty *p_prop, void *p_obj, void **p_params, MonoException **r_exc) {
  549. GD_MONO_BEGIN_RUNTIME_INVOKE;
  550. MonoObject *ret = mono_property_get_value(p_prop, p_obj, p_params, (MonoObject **)r_exc);
  551. GD_MONO_END_RUNTIME_INVOKE;
  552. return ret;
  553. }
  554. uint64_t unbox_enum_value(MonoObject *p_boxed, MonoType *p_enum_basetype, bool &r_error) {
  555. r_error = false;
  556. switch (mono_type_get_type(p_enum_basetype)) {
  557. case MONO_TYPE_BOOLEAN:
  558. return (bool)GDMonoMarshal::unbox<MonoBoolean>(p_boxed) ? 1 : 0;
  559. case MONO_TYPE_CHAR:
  560. return GDMonoMarshal::unbox<uint16_t>(p_boxed);
  561. case MONO_TYPE_U1:
  562. return GDMonoMarshal::unbox<uint8_t>(p_boxed);
  563. case MONO_TYPE_U2:
  564. return GDMonoMarshal::unbox<uint16_t>(p_boxed);
  565. case MONO_TYPE_U4:
  566. return GDMonoMarshal::unbox<uint32_t>(p_boxed);
  567. case MONO_TYPE_U8:
  568. return GDMonoMarshal::unbox<uint64_t>(p_boxed);
  569. case MONO_TYPE_I1:
  570. return GDMonoMarshal::unbox<int8_t>(p_boxed);
  571. case MONO_TYPE_I2:
  572. return GDMonoMarshal::unbox<int16_t>(p_boxed);
  573. case MONO_TYPE_I4:
  574. return GDMonoMarshal::unbox<int32_t>(p_boxed);
  575. case MONO_TYPE_I8:
  576. return GDMonoMarshal::unbox<int64_t>(p_boxed);
  577. default:
  578. r_error = true;
  579. return 0;
  580. }
  581. }
  582. void dispose(MonoObject *p_mono_object, MonoException **r_exc) {
  583. invoke_method_thunk(CACHED_METHOD_THUNK(GodotObject, Dispose), p_mono_object, r_exc);
  584. }
  585. } // namespace GDMonoUtils