2
0

gdnative.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. /*************************************************************************/
  2. /* gdnative.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "gdnative.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/core_constants.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/file_access_encrypted.h"
  36. #include "core/os/os.h"
  37. #include "scene/main/scene_tree.h"
  38. static const String init_symbol = "gdnative_init";
  39. static const String terminate_symbol = "gdnative_terminate";
  40. static const String default_symbol_prefix = "godot_";
  41. static const bool default_singleton = false;
  42. static const bool default_load_once = true;
  43. static const bool default_reloadable = true;
  44. // Defined in gdnative_api_struct.gen.cpp
  45. extern const godot_gdnative_core_api_struct api_struct;
  46. Map<String, Vector<Ref<GDNative>>> GDNativeLibrary::loaded_libraries;
  47. GDNativeLibrary::GDNativeLibrary() {
  48. config_file.instantiate();
  49. symbol_prefix = default_symbol_prefix;
  50. load_once = default_load_once;
  51. singleton = default_singleton;
  52. reloadable = default_reloadable;
  53. }
  54. GDNativeLibrary::~GDNativeLibrary() {
  55. }
  56. bool GDNativeLibrary::_set(const StringName &p_name, const Variant &p_property) {
  57. String name = p_name;
  58. if (name.begins_with("entry/")) {
  59. String key = name.substr(6, name.length() - 6);
  60. config_file->set_value("entry", key, p_property);
  61. set_config_file(config_file);
  62. return true;
  63. }
  64. if (name.begins_with("dependency/")) {
  65. String key = name.substr(11, name.length() - 11);
  66. config_file->set_value("dependencies", key, p_property);
  67. set_config_file(config_file);
  68. return true;
  69. }
  70. return false;
  71. }
  72. bool GDNativeLibrary::_get(const StringName &p_name, Variant &r_property) const {
  73. String name = p_name;
  74. if (name.begins_with("entry/")) {
  75. String key = name.substr(6, name.length() - 6);
  76. r_property = config_file->get_value("entry", key);
  77. return true;
  78. }
  79. if (name.begins_with("dependency/")) {
  80. String key = name.substr(11, name.length() - 11);
  81. r_property = config_file->get_value("dependencies", key);
  82. return true;
  83. }
  84. return false;
  85. }
  86. void GDNativeLibrary::reset_state() {
  87. config_file.instantiate();
  88. current_library_path = "";
  89. current_dependencies.clear();
  90. symbol_prefix = default_symbol_prefix;
  91. load_once = default_load_once;
  92. singleton = default_singleton;
  93. reloadable = default_reloadable;
  94. }
  95. void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const {
  96. // set entries
  97. List<String> entry_key_list;
  98. if (config_file->has_section("entry")) {
  99. config_file->get_section_keys("entry", &entry_key_list);
  100. }
  101. for (const String &key : entry_key_list) {
  102. PropertyInfo prop;
  103. prop.type = Variant::STRING;
  104. prop.name = "entry/" + key;
  105. p_list->push_back(prop);
  106. }
  107. // set dependencies
  108. List<String> dependency_key_list;
  109. if (config_file->has_section("dependencies")) {
  110. config_file->get_section_keys("dependencies", &dependency_key_list);
  111. }
  112. for (const String &key : dependency_key_list) {
  113. PropertyInfo prop;
  114. prop.type = Variant::STRING;
  115. prop.name = "dependency/" + key;
  116. p_list->push_back(prop);
  117. }
  118. }
  119. void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) {
  120. ERR_FAIL_COND(p_config_file.is_null());
  121. set_singleton(p_config_file->get_value("general", "singleton", default_singleton));
  122. set_load_once(p_config_file->get_value("general", "load_once", default_load_once));
  123. set_symbol_prefix(p_config_file->get_value("general", "symbol_prefix", default_symbol_prefix));
  124. set_reloadable(p_config_file->get_value("general", "reloadable", default_reloadable));
  125. String entry_lib_path;
  126. {
  127. List<String> entry_keys;
  128. if (p_config_file->has_section("entry")) {
  129. p_config_file->get_section_keys("entry", &entry_keys);
  130. }
  131. for (const String &key : entry_keys) {
  132. Vector<String> tags = key.split(".");
  133. bool skip = false;
  134. for (int i = 0; i < tags.size(); i++) {
  135. bool has_feature = OS::get_singleton()->has_feature(tags[i]);
  136. if (!has_feature) {
  137. skip = true;
  138. break;
  139. }
  140. }
  141. if (skip) {
  142. continue;
  143. }
  144. entry_lib_path = p_config_file->get_value("entry", key);
  145. break;
  146. }
  147. }
  148. Vector<String> dependency_paths;
  149. {
  150. List<String> dependency_keys;
  151. if (p_config_file->has_section("dependencies")) {
  152. p_config_file->get_section_keys("dependencies", &dependency_keys);
  153. }
  154. for (const String &key : dependency_keys) {
  155. Vector<String> tags = key.split(".");
  156. bool skip = false;
  157. for (int i = 0; i < tags.size(); i++) {
  158. bool has_feature = OS::get_singleton()->has_feature(tags[i]);
  159. if (!has_feature) {
  160. skip = true;
  161. break;
  162. }
  163. }
  164. if (skip) {
  165. continue;
  166. }
  167. dependency_paths = p_config_file->get_value("dependencies", key);
  168. break;
  169. }
  170. }
  171. current_library_path = entry_lib_path;
  172. current_dependencies = dependency_paths;
  173. }
  174. void GDNativeLibrary::_bind_methods() {
  175. ClassDB::bind_method(D_METHOD("get_config_file"), &GDNativeLibrary::get_config_file);
  176. ClassDB::bind_method(D_METHOD("set_config_file", "config_file"), &GDNativeLibrary::set_config_file);
  177. ClassDB::bind_method(D_METHOD("get_current_library_path"), &GDNativeLibrary::get_current_library_path);
  178. ClassDB::bind_method(D_METHOD("get_current_dependencies"), &GDNativeLibrary::get_current_dependencies);
  179. ClassDB::bind_method(D_METHOD("should_load_once"), &GDNativeLibrary::should_load_once);
  180. ClassDB::bind_method(D_METHOD("is_singleton"), &GDNativeLibrary::is_singleton);
  181. ClassDB::bind_method(D_METHOD("get_symbol_prefix"), &GDNativeLibrary::get_symbol_prefix);
  182. ClassDB::bind_method(D_METHOD("is_reloadable"), &GDNativeLibrary::is_reloadable);
  183. ClassDB::bind_method(D_METHOD("set_load_once", "load_once"), &GDNativeLibrary::set_load_once);
  184. ClassDB::bind_method(D_METHOD("set_singleton", "singleton"), &GDNativeLibrary::set_singleton);
  185. ClassDB::bind_method(D_METHOD("set_symbol_prefix", "symbol_prefix"), &GDNativeLibrary::set_symbol_prefix);
  186. ClassDB::bind_method(D_METHOD("set_reloadable", "reloadable"), &GDNativeLibrary::set_reloadable);
  187. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config_file", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile", PROPERTY_USAGE_NONE), "set_config_file", "get_config_file");
  188. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "load_once"), "set_load_once", "should_load_once");
  189. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "singleton"), "set_singleton", "is_singleton");
  190. ADD_PROPERTY(PropertyInfo(Variant::STRING, "symbol_prefix"), "set_symbol_prefix", "get_symbol_prefix");
  191. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reloadable"), "set_reloadable", "is_reloadable");
  192. }
  193. GDNative::GDNative() {
  194. native_handle = nullptr;
  195. initialized = false;
  196. }
  197. GDNative::~GDNative() {
  198. }
  199. void GDNative::_bind_methods() {
  200. ClassDB::bind_method(D_METHOD("set_library", "library"), &GDNative::set_library);
  201. ClassDB::bind_method(D_METHOD("get_library"), &GDNative::get_library);
  202. ClassDB::bind_method(D_METHOD("initialize"), &GDNative::initialize);
  203. ClassDB::bind_method(D_METHOD("terminate"), &GDNative::terminate);
  204. ClassDB::bind_method(D_METHOD("call_native", "calling_type", "procedure_name", "arguments"), &GDNative::call_native);
  205. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "library", PROPERTY_HINT_RESOURCE_TYPE, "GDNativeLibrary"), "set_library", "get_library");
  206. }
  207. void GDNative::set_library(Ref<GDNativeLibrary> p_library) {
  208. ERR_FAIL_COND_MSG(library.is_valid(), "Tried to change library of GDNative when it is already set.");
  209. library = p_library;
  210. }
  211. Ref<GDNativeLibrary> GDNative::get_library() const {
  212. return library;
  213. }
  214. extern "C" void _gdnative_report_version_mismatch(const godot_object *p_library, const char *p_ext, godot_gdnative_api_version p_want, godot_gdnative_api_version p_have);
  215. extern "C" void _gdnative_report_loading_error(const godot_object *p_library, const char *p_what);
  216. bool GDNative::initialize() {
  217. if (library.is_null()) {
  218. ERR_PRINT("No library set, can't initialize GDNative object");
  219. return false;
  220. }
  221. String lib_path = library->get_current_library_path();
  222. if (lib_path.is_empty()) {
  223. ERR_PRINT("No library set for this platform");
  224. return false;
  225. }
  226. #ifdef IPHONE_ENABLED
  227. // On iOS we use static linking by default.
  228. String path = "";
  229. // On iOS dylibs is not allowed, but can be replaced with .framework or .xcframework.
  230. // If they are used, we can run dlopen on them.
  231. // They should be located under Frameworks directory, so we need to replace library path.
  232. if (!lib_path.ends_with(".a")) {
  233. path = ProjectSettings::get_singleton()->globalize_path(lib_path);
  234. if (!FileAccess::exists(path)) {
  235. String lib_name = lib_path.get_basename().get_file();
  236. String framework_path_format = "Frameworks/$name.framework/$name";
  237. Dictionary format_dict;
  238. format_dict["name"] = lib_name;
  239. String framework_path = framework_path_format.format(format_dict, "$_");
  240. path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file(framework_path);
  241. }
  242. }
  243. #elif defined(ANDROID_ENABLED)
  244. // On Android dynamic libraries are located separately from resource assets,
  245. // we should pass library name to dlopen(). The library name is flattened
  246. // during export.
  247. String path = lib_path.get_file();
  248. #elif defined(UWP_ENABLED)
  249. // On UWP we use a relative path from the app
  250. String path = lib_path.replace("res://", "");
  251. #elif defined(OSX_ENABLED)
  252. // On OSX the exported libraries are located under the Frameworks directory.
  253. // So we need to replace the library path.
  254. String path = ProjectSettings::get_singleton()->globalize_path(lib_path);
  255. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  256. if (!da->file_exists(path) && !da->dir_exists(path)) {
  257. path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(lib_path.get_file());
  258. }
  259. if (da->dir_exists(path)) { // Target library is a ".framework", add library base name to the path.
  260. path = path.plus_file(path.get_file().get_basename());
  261. }
  262. memdelete(da);
  263. #else
  264. String path = ProjectSettings::get_singleton()->globalize_path(lib_path);
  265. #endif
  266. if (library->should_load_once()) {
  267. if (GDNativeLibrary::loaded_libraries.has(lib_path)) {
  268. // already loaded. Don't load again.
  269. // copy some of the stuff instead
  270. this->native_handle = GDNativeLibrary::loaded_libraries[lib_path][0]->native_handle;
  271. initialized = true;
  272. return true;
  273. }
  274. }
  275. Error err = OS::get_singleton()->open_dynamic_library(path, native_handle, true);
  276. if (err != OK) {
  277. return false;
  278. }
  279. void *library_init;
  280. // we cheat here a little bit. you saw nothing
  281. initialized = true;
  282. err = get_symbol(library->get_symbol_prefix() + init_symbol, library_init, false);
  283. initialized = false;
  284. if (err || !library_init) {
  285. OS::get_singleton()->close_dynamic_library(native_handle);
  286. native_handle = nullptr;
  287. ERR_PRINT("Failed to obtain " + library->get_symbol_prefix() + "gdnative_init symbol");
  288. return false;
  289. }
  290. godot_gdnative_init_fn library_init_fpointer;
  291. library_init_fpointer = (godot_gdnative_init_fn)library_init;
  292. static uint64_t core_api_hash = 0;
  293. static uint64_t editor_api_hash = 0;
  294. static uint64_t no_api_hash = 0;
  295. if (!(core_api_hash || editor_api_hash || no_api_hash)) {
  296. core_api_hash = ClassDB::get_api_hash(ClassDB::API_CORE);
  297. editor_api_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR);
  298. no_api_hash = ClassDB::get_api_hash(ClassDB::API_NONE);
  299. }
  300. godot_gdnative_init_options options;
  301. options.api_struct = &api_struct;
  302. options.in_editor = Engine::get_singleton()->is_editor_hint();
  303. options.core_api_hash = core_api_hash;
  304. options.editor_api_hash = editor_api_hash;
  305. options.no_api_hash = no_api_hash;
  306. options.report_version_mismatch = &_gdnative_report_version_mismatch;
  307. options.report_loading_error = &_gdnative_report_loading_error;
  308. options.gd_native_library = (godot_object *)(get_library().ptr());
  309. options.active_library_path = (godot_string *)&path;
  310. library_init_fpointer(&options);
  311. initialized = true;
  312. if (library->should_load_once() && !GDNativeLibrary::loaded_libraries.has(lib_path)) {
  313. Vector<Ref<GDNative>> gdnatives;
  314. gdnatives.resize(1);
  315. gdnatives.write[0] = Ref<GDNative>(this);
  316. GDNativeLibrary::loaded_libraries.insert(lib_path, gdnatives);
  317. }
  318. return true;
  319. }
  320. bool GDNative::terminate() {
  321. if (!initialized) {
  322. ERR_PRINT("No valid library handle, can't terminate GDNative object");
  323. return false;
  324. }
  325. if (library->should_load_once()) {
  326. Vector<Ref<GDNative>> *gdnatives = &GDNativeLibrary::loaded_libraries[library->get_current_library_path()];
  327. if (gdnatives->size() > 1) {
  328. // there are other GDNative's still using this library, so we actually don't terminate
  329. gdnatives->erase(Ref<GDNative>(this));
  330. initialized = false;
  331. return true;
  332. } else if (gdnatives->size() == 1) {
  333. // we're the last one, terminate!
  334. gdnatives->clear();
  335. // whew this looks scary, but all it does is remove the entry completely
  336. GDNativeLibrary::loaded_libraries.erase(GDNativeLibrary::loaded_libraries.find(library->get_current_library_path()));
  337. }
  338. }
  339. void *library_terminate;
  340. Error error = get_symbol(library->get_symbol_prefix() + terminate_symbol, library_terminate);
  341. if (error || !library_terminate) {
  342. OS::get_singleton()->close_dynamic_library(native_handle);
  343. native_handle = nullptr;
  344. initialized = false;
  345. return true;
  346. }
  347. godot_gdnative_terminate_fn library_terminate_pointer;
  348. library_terminate_pointer = (godot_gdnative_terminate_fn)library_terminate;
  349. godot_gdnative_terminate_options options;
  350. options.in_editor = Engine::get_singleton()->is_editor_hint();
  351. library_terminate_pointer(&options);
  352. initialized = false;
  353. // GDNativeScriptLanguage::get_singleton()->initialized_libraries.erase(p_native_lib->path);
  354. OS::get_singleton()->close_dynamic_library(native_handle);
  355. native_handle = nullptr;
  356. return true;
  357. }
  358. bool GDNative::is_initialized() const {
  359. return initialized;
  360. }
  361. void GDNativeCallRegistry::register_native_call_type(StringName p_call_type, native_call_cb p_callback) {
  362. native_calls.insert(p_call_type, p_callback);
  363. }
  364. Vector<StringName> GDNativeCallRegistry::get_native_call_types() {
  365. Vector<StringName> call_types;
  366. call_types.resize(native_calls.size());
  367. size_t idx = 0;
  368. for (Map<StringName, native_call_cb>::Element *E = native_calls.front(); E; E = E->next(), idx++) {
  369. call_types.write[idx] = E->key();
  370. }
  371. return call_types;
  372. }
  373. Variant GDNative::call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments) {
  374. Map<StringName, native_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_calls.find(p_native_call_type);
  375. if (!E) {
  376. ERR_PRINT((String("No handler for native call type \"" + p_native_call_type) + "\" found").utf8().get_data());
  377. return Variant();
  378. }
  379. void *procedure_handle;
  380. Error err = OS::get_singleton()->get_dynamic_library_symbol_handle(
  381. native_handle,
  382. p_procedure_name,
  383. procedure_handle);
  384. if (err != OK || procedure_handle == nullptr) {
  385. return Variant();
  386. }
  387. godot_variant result = E->get()(procedure_handle, (godot_array *)&p_arguments);
  388. Variant res = *(Variant *)&result;
  389. godot_variant_destroy(&result);
  390. return res;
  391. }
  392. Error GDNative::get_symbol(StringName p_procedure_name, void *&r_handle, bool p_optional) const {
  393. if (!initialized) {
  394. ERR_PRINT("No valid library handle, can't get symbol from GDNative object");
  395. return ERR_CANT_OPEN;
  396. }
  397. Error result = OS::get_singleton()->get_dynamic_library_symbol_handle(
  398. native_handle,
  399. p_procedure_name,
  400. r_handle,
  401. p_optional);
  402. return result;
  403. }
  404. RES GDNativeLibraryResourceLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  405. Ref<GDNativeLibrary> lib;
  406. lib.instantiate();
  407. Ref<ConfigFile> config = lib->get_config_file();
  408. Error err = config->load(p_path);
  409. if (r_error) {
  410. *r_error = err;
  411. }
  412. lib->set_config_file(config);
  413. return lib;
  414. }
  415. void GDNativeLibraryResourceLoader::get_recognized_extensions(List<String> *p_extensions) const {
  416. p_extensions->push_back("gdnlib");
  417. }
  418. bool GDNativeLibraryResourceLoader::handles_type(const String &p_type) const {
  419. return p_type == "GDNativeLibrary";
  420. }
  421. String GDNativeLibraryResourceLoader::get_resource_type(const String &p_path) const {
  422. String el = p_path.get_extension().to_lower();
  423. if (el == "gdnlib") {
  424. return "GDNativeLibrary";
  425. }
  426. return "";
  427. }
  428. Error GDNativeLibraryResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  429. Ref<GDNativeLibrary> lib = p_resource;
  430. if (lib.is_null()) {
  431. return ERR_INVALID_DATA;
  432. }
  433. Ref<ConfigFile> config = lib->get_config_file();
  434. config->set_value("general", "singleton", lib->is_singleton());
  435. config->set_value("general", "load_once", lib->should_load_once());
  436. config->set_value("general", "symbol_prefix", lib->get_symbol_prefix());
  437. config->set_value("general", "reloadable", lib->is_reloadable());
  438. return config->save(p_path);
  439. }
  440. bool GDNativeLibraryResourceSaver::recognize(const RES &p_resource) const {
  441. return Object::cast_to<GDNativeLibrary>(*p_resource) != nullptr;
  442. }
  443. void GDNativeLibraryResourceSaver::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  444. if (Object::cast_to<GDNativeLibrary>(*p_resource) != nullptr) {
  445. p_extensions->push_back("gdnlib");
  446. }
  447. }