gd_mono_assembly.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*************************************************************************/
  2. /* gd_mono_assembly.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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_assembly.h"
  31. #include <mono/metadata/mono-debug.h>
  32. #include <mono/metadata/tokentype.h>
  33. #include "core/list.h"
  34. #include "core/os/file_access.h"
  35. #include "core/os/os.h"
  36. #include "core/project_settings.h"
  37. #include "../godotsharp_dirs.h"
  38. #include "gd_mono_cache.h"
  39. #include "gd_mono_class.h"
  40. Vector<String> GDMonoAssembly::search_dirs;
  41. void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config, const String &p_custom_bcl_dir) {
  42. String framework_dir;
  43. if (!p_custom_bcl_dir.empty()) {
  44. framework_dir = p_custom_bcl_dir;
  45. } else if (mono_assembly_getrootdir()) {
  46. framework_dir = String::utf8(mono_assembly_getrootdir()).plus_file("mono").plus_file("4.5");
  47. }
  48. if (!framework_dir.empty()) {
  49. r_search_dirs.push_back(framework_dir);
  50. r_search_dirs.push_back(framework_dir.plus_file("Facades"));
  51. }
  52. #if !defined(TOOLS_ENABLED)
  53. String data_game_assemblies_dir = GodotSharpDirs::get_data_game_assemblies_dir();
  54. if (!data_game_assemblies_dir.empty()) {
  55. r_search_dirs.push_back(data_game_assemblies_dir);
  56. }
  57. #endif
  58. if (p_custom_config.length()) {
  59. r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(p_custom_config));
  60. } else {
  61. r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_dir());
  62. }
  63. if (p_custom_config.empty()) {
  64. r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir());
  65. } else {
  66. String api_config = p_custom_config == "ExportRelease" ? "Release" : "Debug";
  67. r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir().plus_file(api_config));
  68. }
  69. r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir());
  70. r_search_dirs.push_back(OS::get_singleton()->get_resource_dir());
  71. r_search_dirs.push_back(OS::get_singleton()->get_executable_path().get_base_dir());
  72. #ifdef TOOLS_ENABLED
  73. r_search_dirs.push_back(GodotSharpDirs::get_data_editor_tools_dir());
  74. // For GodotTools to find the api assemblies
  75. r_search_dirs.push_back(GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug"));
  76. #endif
  77. }
  78. // This is how these assembly loading hooks work:
  79. //
  80. // - The 'search' hook checks if the assembly has already been loaded, to avoid loading again.
  81. // - The 'preload' hook does the actual loading and is only called if the
  82. // 'search' hook didn't find the assembly in the list of loaded assemblies.
  83. // - The 'load' hook is called after the assembly has been loaded. Its job is to add the
  84. // assembly to the list of loaded assemblies so that the 'search' hook can look it up.
  85. void GDMonoAssembly::assembly_load_hook(MonoAssembly *assembly, void *user_data) {
  86. String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly)));
  87. MonoImage *image = mono_assembly_get_image(assembly);
  88. GDMonoAssembly *gdassembly = memnew(GDMonoAssembly(name, image, assembly));
  89. #ifdef GD_MONO_HOT_RELOAD
  90. const char *path = mono_image_get_filename(image);
  91. if (FileAccess::exists(path))
  92. gdassembly->modified_time = FileAccess::get_modified_time(path);
  93. #endif
  94. MonoDomain *domain = mono_domain_get();
  95. GDMono::get_singleton()->add_assembly(domain ? mono_domain_get_id(domain) : 0, gdassembly);
  96. }
  97. MonoAssembly *GDMonoAssembly::assembly_search_hook(MonoAssemblyName *aname, void *user_data) {
  98. return GDMonoAssembly::_search_hook(aname, user_data, false);
  99. }
  100. MonoAssembly *GDMonoAssembly::assembly_refonly_search_hook(MonoAssemblyName *aname, void *user_data) {
  101. return GDMonoAssembly::_search_hook(aname, user_data, true);
  102. }
  103. MonoAssembly *GDMonoAssembly::assembly_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data) {
  104. return GDMonoAssembly::_preload_hook(aname, assemblies_path, user_data, false);
  105. }
  106. MonoAssembly *GDMonoAssembly::assembly_refonly_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data) {
  107. return GDMonoAssembly::_preload_hook(aname, assemblies_path, user_data, true);
  108. }
  109. MonoAssembly *GDMonoAssembly::_search_hook(MonoAssemblyName *aname, void *user_data, bool refonly) {
  110. (void)user_data; // UNUSED
  111. String name = String::utf8(mono_assembly_name_get_name(aname));
  112. bool has_extension = name.ends_with(".dll") || name.ends_with(".exe");
  113. GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(has_extension ? name.get_basename() : name);
  114. if (loaded_asm)
  115. return loaded_asm->get_assembly();
  116. return nullptr;
  117. }
  118. MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, void *user_data, bool refonly) {
  119. (void)user_data; // UNUSED
  120. String name = String::utf8(mono_assembly_name_get_name(aname));
  121. return _load_assembly_search(name, search_dirs, refonly);
  122. }
  123. MonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, const Vector<String> &p_search_dirs, bool p_refonly) {
  124. MonoAssembly *res = nullptr;
  125. String path;
  126. bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe");
  127. for (int i = 0; i < p_search_dirs.size(); i++) {
  128. const String &search_dir = p_search_dirs[i];
  129. if (has_extension) {
  130. path = search_dir.plus_file(p_name);
  131. if (FileAccess::exists(path)) {
  132. res = _real_load_assembly_from(path, p_refonly);
  133. if (res != nullptr)
  134. return res;
  135. }
  136. } else {
  137. path = search_dir.plus_file(p_name + ".dll");
  138. if (FileAccess::exists(path)) {
  139. res = _real_load_assembly_from(path, p_refonly);
  140. if (res != nullptr)
  141. return res;
  142. }
  143. path = search_dir.plus_file(p_name + ".exe");
  144. if (FileAccess::exists(path)) {
  145. res = _real_load_assembly_from(path, p_refonly);
  146. if (res != nullptr)
  147. return res;
  148. }
  149. }
  150. }
  151. return nullptr;
  152. }
  153. String GDMonoAssembly::find_assembly(const String &p_name) {
  154. String path;
  155. bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe");
  156. for (int i = 0; i < search_dirs.size(); i++) {
  157. const String &search_dir = search_dirs[i];
  158. if (has_extension) {
  159. path = search_dir.plus_file(p_name);
  160. if (FileAccess::exists(path))
  161. return path;
  162. } else {
  163. path = search_dir.plus_file(p_name + ".dll");
  164. if (FileAccess::exists(path))
  165. return path;
  166. path = search_dir.plus_file(p_name + ".exe");
  167. if (FileAccess::exists(path))
  168. return path;
  169. }
  170. }
  171. return String();
  172. }
  173. void GDMonoAssembly::initialize() {
  174. fill_search_dirs(search_dirs);
  175. mono_install_assembly_search_hook(&assembly_search_hook, nullptr);
  176. mono_install_assembly_refonly_search_hook(&assembly_refonly_search_hook, nullptr);
  177. mono_install_assembly_preload_hook(&assembly_preload_hook, nullptr);
  178. mono_install_assembly_refonly_preload_hook(&assembly_refonly_preload_hook, nullptr);
  179. mono_install_assembly_load_hook(&assembly_load_hook, nullptr);
  180. }
  181. MonoAssembly *GDMonoAssembly::_real_load_assembly_from(const String &p_path, bool p_refonly) {
  182. Vector<uint8_t> data = FileAccess::get_file_as_array(p_path);
  183. ERR_FAIL_COND_V_MSG(data.empty(), nullptr, "Could read the assembly in the specified location");
  184. String image_filename;
  185. #ifdef ANDROID_ENABLED
  186. if (p_path.begins_with("res://")) {
  187. image_filename = p_path.substr(6, p_path.length());
  188. } else {
  189. image_filename = ProjectSettings::get_singleton()->globalize_path(p_path);
  190. }
  191. #else
  192. // FIXME: globalize_path does not work on exported games
  193. image_filename = ProjectSettings::get_singleton()->globalize_path(p_path);
  194. #endif
  195. MonoImageOpenStatus status = MONO_IMAGE_OK;
  196. MonoImage *image = mono_image_open_from_data_with_name(
  197. (char *)&data[0], data.size(),
  198. true, &status, p_refonly,
  199. image_filename.utf8());
  200. ERR_FAIL_COND_V_MSG(status != MONO_IMAGE_OK || !image, nullptr, "Failed to open assembly image from the loaded data");
  201. #ifdef DEBUG_ENABLED
  202. Vector<uint8_t> pdb_data;
  203. String pdb_path(p_path + ".pdb");
  204. if (!FileAccess::exists(pdb_path)) {
  205. pdb_path = p_path.get_basename() + ".pdb"; // without .dll
  206. if (!FileAccess::exists(pdb_path))
  207. goto no_pdb;
  208. }
  209. pdb_data = FileAccess::get_file_as_array(pdb_path);
  210. // mono_debug_close_image doesn't seem to be needed
  211. mono_debug_open_image_from_memory(image, &pdb_data[0], pdb_data.size());
  212. no_pdb:
  213. #endif
  214. bool need_manual_load_hook = mono_image_get_assembly(image) != nullptr; // Re-using an existing image with an assembly loaded
  215. status = MONO_IMAGE_OK;
  216. MonoAssembly *assembly = mono_assembly_load_from_full(image, image_filename.utf8().get_data(), &status, p_refonly);
  217. ERR_FAIL_COND_V_MSG(status != MONO_IMAGE_OK || !assembly, nullptr, "Failed to load assembly for image");
  218. if (need_manual_load_hook) {
  219. // For some reason if an assembly survived domain reloading (maybe because it's referenced somewhere else),
  220. // the mono internal search hook don't detect it, yet mono_image_open_from_data_with_name re-uses the image
  221. // and assembly, and mono_assembly_load_from_full doesn't call the load hook. We need to call it manually.
  222. String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly)));
  223. bool has_extension = name.ends_with(".dll") || name.ends_with(".exe");
  224. GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(has_extension ? name.get_basename() : name);
  225. if (!loaded_asm)
  226. assembly_load_hook(assembly, nullptr);
  227. }
  228. // Decrement refcount which was previously incremented by mono_image_open_from_data_with_name
  229. mono_image_close(image);
  230. return assembly;
  231. }
  232. void GDMonoAssembly::unload() {
  233. ERR_FAIL_NULL(image); // Should not be called if already unloaded
  234. for (Map<MonoClass *, GDMonoClass *>::Element *E = cached_raw.front(); E; E = E->next()) {
  235. memdelete(E->value());
  236. }
  237. cached_classes.clear();
  238. cached_raw.clear();
  239. assembly = nullptr;
  240. image = nullptr;
  241. }
  242. String GDMonoAssembly::get_path() const {
  243. return String::utf8(mono_image_get_filename(image));
  244. }
  245. GDMonoClass *GDMonoAssembly::get_class(const StringName &p_namespace, const StringName &p_name) {
  246. ERR_FAIL_NULL_V(image, nullptr);
  247. ClassKey key(p_namespace, p_name);
  248. GDMonoClass **match = cached_classes.getptr(key);
  249. if (match)
  250. return *match;
  251. MonoClass *mono_class = mono_class_from_name(image, String(p_namespace).utf8(), String(p_name).utf8());
  252. if (!mono_class)
  253. return nullptr;
  254. GDMonoClass *wrapped_class = memnew(GDMonoClass(p_namespace, p_name, mono_class, this));
  255. cached_classes[key] = wrapped_class;
  256. cached_raw[mono_class] = wrapped_class;
  257. return wrapped_class;
  258. }
  259. GDMonoClass *GDMonoAssembly::get_class(MonoClass *p_mono_class) {
  260. ERR_FAIL_NULL_V(image, nullptr);
  261. Map<MonoClass *, GDMonoClass *>::Element *match = cached_raw.find(p_mono_class);
  262. if (match)
  263. return match->value();
  264. StringName namespace_name = mono_class_get_namespace(p_mono_class);
  265. StringName class_name = mono_class_get_name(p_mono_class);
  266. GDMonoClass *wrapped_class = memnew(GDMonoClass(namespace_name, class_name, p_mono_class, this));
  267. cached_classes[ClassKey(namespace_name, class_name)] = wrapped_class;
  268. cached_raw[p_mono_class] = wrapped_class;
  269. return wrapped_class;
  270. }
  271. GDMonoClass *GDMonoAssembly::get_object_derived_class(const StringName &p_class) {
  272. GDMonoClass *match = nullptr;
  273. if (gdobject_class_cache_updated) {
  274. Map<StringName, GDMonoClass *>::Element *result = gdobject_class_cache.find(p_class);
  275. if (result)
  276. match = result->get();
  277. } else {
  278. List<GDMonoClass *> nested_classes;
  279. int rows = mono_image_get_table_rows(image, MONO_TABLE_TYPEDEF);
  280. for (int i = 1; i < rows; i++) {
  281. MonoClass *mono_class = mono_class_get(image, (i + 1) | MONO_TOKEN_TYPE_DEF);
  282. if (!mono_class_is_assignable_from(CACHED_CLASS_RAW(GodotObject), mono_class))
  283. continue;
  284. GDMonoClass *current = get_class(mono_class);
  285. if (!current)
  286. continue;
  287. nested_classes.push_back(current);
  288. if (!match && current->get_name() == p_class)
  289. match = current;
  290. while (!nested_classes.empty()) {
  291. GDMonoClass *current_nested = nested_classes.front()->get();
  292. nested_classes.pop_back();
  293. void *iter = nullptr;
  294. while (true) {
  295. MonoClass *raw_nested = mono_class_get_nested_types(current_nested->get_mono_ptr(), &iter);
  296. if (!raw_nested)
  297. break;
  298. GDMonoClass *nested_class = get_class(raw_nested);
  299. if (nested_class) {
  300. gdobject_class_cache.insert(nested_class->get_name(), nested_class);
  301. nested_classes.push_back(nested_class);
  302. }
  303. }
  304. }
  305. gdobject_class_cache.insert(current->get_name(), current);
  306. }
  307. gdobject_class_cache_updated = true;
  308. }
  309. return match;
  310. }
  311. GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_path, bool p_refonly) {
  312. if (p_name == "mscorlib" || p_name == "mscorlib.dll")
  313. return GDMono::get_singleton()->get_corlib_assembly();
  314. // We need to manually call the search hook in this case, as it won't be called in the next step
  315. MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
  316. MonoAssembly *assembly = mono_assembly_invoke_search_hook(aname);
  317. mono_assembly_name_free(aname);
  318. mono_free(aname);
  319. if (!assembly) {
  320. assembly = _real_load_assembly_from(p_path, p_refonly);
  321. ERR_FAIL_NULL_V(assembly, nullptr);
  322. }
  323. GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(p_name);
  324. ERR_FAIL_NULL_V_MSG(loaded_asm, nullptr, "Loaded assembly missing from table. Did we not receive the load hook?");
  325. return loaded_asm;
  326. }
  327. GDMonoAssembly::GDMonoAssembly(const String &p_name, MonoImage *p_image, MonoAssembly *p_assembly) :
  328. name(p_name),
  329. image(p_image),
  330. assembly(p_assembly),
  331. #ifdef GD_MONO_HOT_RELOAD
  332. modified_time(0),
  333. #endif
  334. gdobject_class_cache_updated(false) {
  335. }
  336. GDMonoAssembly::~GDMonoAssembly() {
  337. if (image)
  338. unload();
  339. }