gdnative.cpp 19 KB

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