gd_mono_utils.cpp 27 KB

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