gdnative.cpp 19 KB

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