Path: blob/master/core/extension/gdextension_manager.cpp
20897 views
/**************************************************************************/1/* gdextension_manager.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gdextension_manager.h"3132#include "core/extension/gdextension_function_loader.h"33#include "core/extension/gdextension_library_loader.h"34#include "core/extension/gdextension_special_compat_hashes.h"35#include "core/io/dir_access.h"36#include "core/io/file_access.h"37#include "core/object/script_language.h"3839GDExtensionManager::LoadStatus GDExtensionManager::_load_extension_internal(const Ref<GDExtension> &p_extension, bool p_first_load) {40if (level >= 0) { // Already initialized up to some level.41int32_t minimum_level = 0;42if (!p_first_load) {43minimum_level = p_extension->get_minimum_library_initialization_level();44if (minimum_level < MIN(level, GDExtension::INITIALIZATION_LEVEL_SCENE)) {45return LOAD_STATUS_NEEDS_RESTART;46}47}48// Initialize up to current level.49for (int32_t i = minimum_level; i <= level; i++) {50p_extension->initialize_library(GDExtension::InitializationLevel(i));51}52}5354for (const KeyValue<String, String> &kv : p_extension->class_icon_paths) {55gdextension_class_icon_paths[kv.key] = kv.value;56}5758return LOAD_STATUS_OK;59}6061void GDExtensionManager::_finish_load_extension(const Ref<GDExtension> &p_extension) {62#ifdef TOOLS_ENABLED63// Signals that a new extension is loaded so GDScript can register new class names.64emit_signal("extension_loaded", p_extension);65#endif6667if (startup_callback_called) {68// Extension is loading after the startup callback has already been called,69// so we call it now for this extension to make sure it doesn't miss it.70if (p_extension->startup_callback) {71p_extension->startup_callback();72}73}74}7576GDExtensionManager::LoadStatus GDExtensionManager::_unload_extension_internal(const Ref<GDExtension> &p_extension) {77#ifdef TOOLS_ENABLED78// Signals that a new extension is unloading so GDScript can unregister class names.79emit_signal("extension_unloading", p_extension);80#endif8182if (!shutdown_callback_called) {83// Extension is unloading before the shutdown callback has been called,84// which means the engine hasn't shutdown yet but we want to make sure85// to call the shutdown callback so it doesn't miss it.86if (p_extension->shutdown_callback) {87p_extension->shutdown_callback();88}89}9091if (level >= 0) { // Already initialized up to some level.92// Deinitialize down from current level.93for (int32_t i = level; i >= GDExtension::INITIALIZATION_LEVEL_CORE; i--) {94p_extension->deinitialize_library(GDExtension::InitializationLevel(i));95}96}9798for (const KeyValue<String, String> &kv : p_extension->class_icon_paths) {99gdextension_class_icon_paths.erase(kv.key);100}101102// Clear main loop callbacks.103p_extension->startup_callback = nullptr;104p_extension->shutdown_callback = nullptr;105p_extension->frame_callback = nullptr;106107return LOAD_STATUS_OK;108}109110GDExtensionManager::LoadStatus GDExtensionManager::load_extension(const String &p_path) {111if (Engine::get_singleton()->is_recovery_mode_hint()) {112return LOAD_STATUS_FAILED;113}114115Ref<GDExtensionLibraryLoader> loader;116loader.instantiate();117return load_extension_with_loader(p_path, loader);118}119120GDExtensionManager::LoadStatus GDExtensionManager::load_extension_from_function(const String &p_path, GDExtensionConstPtr<const GDExtensionInitializationFunction> p_init_func) {121Ref<GDExtensionFunctionLoader> func_loader;122func_loader.instantiate();123func_loader->set_initialization_function((GDExtensionInitializationFunction)*p_init_func.data);124return load_extension_with_loader(p_path, func_loader);125}126127GDExtensionManager::LoadStatus GDExtensionManager::load_extension_with_loader(const String &p_path, const Ref<GDExtensionLoader> &p_loader) {128DEV_ASSERT(p_loader.is_valid());129130if (gdextension_map.has(p_path)) {131return LOAD_STATUS_ALREADY_LOADED;132}133134Ref<GDExtension> extension;135extension.instantiate();136Error err = extension->open_library(p_path, p_loader);137if (err != OK) {138return LOAD_STATUS_FAILED;139}140141LoadStatus status = _load_extension_internal(extension, true);142if (status != LOAD_STATUS_OK) {143return status;144}145146_finish_load_extension(extension);147148extension->set_path(p_path);149gdextension_map[p_path] = extension;150return LOAD_STATUS_OK;151}152153GDExtensionManager::LoadStatus GDExtensionManager::reload_extension(const String &p_path) {154#ifndef TOOLS_ENABLED155ERR_FAIL_V_MSG(LOAD_STATUS_FAILED, "GDExtensions can only be reloaded in an editor build.");156#else157ERR_FAIL_COND_V_MSG(!Engine::get_singleton()->is_extension_reloading_enabled(), LOAD_STATUS_FAILED, "GDExtension reloading is disabled.");158159if (Engine::get_singleton()->is_recovery_mode_hint()) {160return LOAD_STATUS_FAILED;161}162163if (!gdextension_map.has(p_path)) {164return LOAD_STATUS_NOT_LOADED;165}166167Ref<GDExtension> extension = gdextension_map[p_path];168ERR_FAIL_COND_V_MSG(!extension->is_reloadable(), LOAD_STATUS_FAILED, vformat("This GDExtension is not marked as 'reloadable' or doesn't support reloading: %s.", p_path));169170LoadStatus status;171172extension->prepare_reload();173174// Unload library if it's open. It may not be open if the developer made a175// change that broke loading in a previous hot-reload attempt.176if (extension->is_library_open()) {177status = _unload_extension_internal(extension);178if (status != LOAD_STATUS_OK) {179// We need to clear these no matter what.180extension->clear_instance_bindings();181return status;182}183184extension->clear_instance_bindings();185extension->close_library();186}187188Error err = extension->open_library(p_path, extension->loader);189if (err != OK) {190return LOAD_STATUS_FAILED;191}192193status = _load_extension_internal(extension, false);194if (status != LOAD_STATUS_OK) {195return status;196}197198extension->finish_reload();199200// Needs to come after reload is fully finished, so all objects using201// extension classes are in a consistent state.202_finish_load_extension(extension);203204return LOAD_STATUS_OK;205#endif206}207208GDExtensionManager::LoadStatus GDExtensionManager::unload_extension(const String &p_path) {209if (Engine::get_singleton()->is_recovery_mode_hint()) {210return LOAD_STATUS_FAILED;211}212213if (!gdextension_map.has(p_path)) {214return LOAD_STATUS_NOT_LOADED;215}216217Ref<GDExtension> extension = gdextension_map[p_path];218219LoadStatus status = _unload_extension_internal(extension);220if (status != LOAD_STATUS_OK) {221return status;222}223224gdextension_map.erase(p_path);225return LOAD_STATUS_OK;226}227228bool GDExtensionManager::is_extension_loaded(const String &p_path) const {229return gdextension_map.has(p_path);230}231232Vector<String> GDExtensionManager::get_loaded_extensions() const {233Vector<String> ret;234for (const KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {235ret.push_back(E.key);236}237return ret;238}239Ref<GDExtension> GDExtensionManager::get_extension(const String &p_path) {240HashMap<String, Ref<GDExtension>>::Iterator E = gdextension_map.find(p_path);241ERR_FAIL_COND_V(!E, Ref<GDExtension>());242return E->value;243}244245bool GDExtensionManager::class_has_icon_path(const String &p_class) const {246// TODO: Check that the icon belongs to a registered class somehow.247return gdextension_class_icon_paths.has(p_class);248}249250String GDExtensionManager::class_get_icon_path(const String &p_class) const {251// TODO: Check that the icon belongs to a registered class somehow.252if (gdextension_class_icon_paths.has(p_class)) {253return gdextension_class_icon_paths[p_class];254}255return "";256}257258void GDExtensionManager::initialize_extensions(GDExtension::InitializationLevel p_level) {259if (Engine::get_singleton()->is_recovery_mode_hint()) {260return;261}262263ERR_FAIL_COND(int32_t(p_level) - 1 != level);264for (KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {265E.value->initialize_library(p_level);266267if (p_level == GDExtension::INITIALIZATION_LEVEL_EDITOR) {268for (const KeyValue<String, String> &kv : E.value->class_icon_paths) {269gdextension_class_icon_paths[kv.key] = kv.value;270}271}272}273level = p_level;274}275276void GDExtensionManager::deinitialize_extensions(GDExtension::InitializationLevel p_level) {277if (Engine::get_singleton()->is_recovery_mode_hint()) {278return;279}280281ERR_FAIL_COND(int32_t(p_level) != level);282for (KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {283E.value->deinitialize_library(p_level);284}285level = int32_t(p_level) - 1;286}287288#ifdef TOOLS_ENABLED289void GDExtensionManager::track_instance_binding(void *p_token, Object *p_object) {290for (KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {291if (E.value.ptr() == p_token) {292if (E.value->is_reloadable()) {293E.value->track_instance_binding(p_object);294return;295}296}297}298}299300void GDExtensionManager::untrack_instance_binding(void *p_token, Object *p_object) {301for (KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {302if (E.value.ptr() == p_token) {303if (E.value->is_reloadable()) {304E.value->untrack_instance_binding(p_object);305return;306}307}308}309}310311void GDExtensionManager::_reload_all_scripts() {312for (int i = 0; i < ScriptServer::get_language_count(); i++) {313ScriptServer::get_language(i)->reload_all_scripts();314}315}316#endif // TOOLS_ENABLED317318void GDExtensionManager::load_extensions() {319if (Engine::get_singleton()->is_recovery_mode_hint()) {320return;321}322323Ref<FileAccess> f = FileAccess::open(GDExtension::get_extension_list_config_file(), FileAccess::READ);324while (f.is_valid() && !f->eof_reached()) {325String s = f->get_line().strip_edges();326if (!s.is_empty()) {327LoadStatus err = load_extension(s);328ERR_CONTINUE_MSG(err == LOAD_STATUS_FAILED, vformat("Error loading extension: '%s'.", s));329}330}331332OS::get_singleton()->load_platform_gdextensions();333}334335void GDExtensionManager::reload_extensions() {336#ifdef TOOLS_ENABLED337if (Engine::get_singleton()->is_recovery_mode_hint()) {338return;339}340bool reloaded = false;341for (const KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {342if (!E.value->is_reloadable()) {343continue;344}345346if (E.value->has_library_changed()) {347reloaded = true;348reload_extension(E.value->get_path());349}350}351352if (reloaded) {353emit_signal("extensions_reloaded");354355// Reload all scripts to clear out old references.356callable_mp_static(&GDExtensionManager::_reload_all_scripts).call_deferred();357}358#endif359}360361bool GDExtensionManager::ensure_extensions_loaded(const HashSet<String> &p_extensions) {362Vector<String> extensions_added;363Vector<String> extensions_removed;364365for (const String &E : p_extensions) {366if (!is_extension_loaded(E)) {367extensions_added.push_back(E);368}369}370371Vector<String> loaded_extensions = get_loaded_extensions();372for (const String &loaded_extension : loaded_extensions) {373if (!p_extensions.has(loaded_extension)) {374// The extension may not have a .gdextension file.375const Ref<GDExtension> extension = GDExtensionManager::get_singleton()->get_extension(loaded_extension);376if (!extension->get_loader()->library_exists()) {377extensions_removed.push_back(loaded_extension);378}379}380}381382String extension_list_config_file = GDExtension::get_extension_list_config_file();383if (p_extensions.size()) {384if (extensions_added.size() || extensions_removed.size()) {385// Extensions were added or removed.386Ref<FileAccess> f = FileAccess::open(extension_list_config_file, FileAccess::WRITE);387for (const String &E : p_extensions) {388f->store_line(E);389}390}391} else {392if (loaded_extensions.size() || FileAccess::exists(extension_list_config_file)) {393// Extensions were removed.394Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);395da->remove(extension_list_config_file);396}397}398399bool needs_restart = false;400for (const String &extension : extensions_added) {401GDExtensionManager::LoadStatus st = GDExtensionManager::get_singleton()->load_extension(extension);402if (st == GDExtensionManager::LOAD_STATUS_NEEDS_RESTART) {403needs_restart = true;404}405}406407for (const String &extension : extensions_removed) {408GDExtensionManager::LoadStatus st = GDExtensionManager::get_singleton()->unload_extension(extension);409if (st == GDExtensionManager::LOAD_STATUS_NEEDS_RESTART) {410needs_restart = true;411}412}413414#ifdef TOOLS_ENABLED415if (extensions_added.size() || extensions_removed.size()) {416// Emitting extensions_reloaded so EditorNode can reload Inspector and regenerate documentation.417emit_signal("extensions_reloaded");418419// Reload all scripts to clear out old references.420callable_mp_static(&GDExtensionManager::_reload_all_scripts).call_deferred();421}422#endif423424return needs_restart;425}426427void GDExtensionManager::startup() {428startup_callback_called = true;429430for (const KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {431const Ref<GDExtension> &extension = E.value;432if (extension->startup_callback) {433extension->startup_callback();434}435}436}437438void GDExtensionManager::shutdown() {439shutdown_callback_called = true;440441for (const KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {442const Ref<GDExtension> &extension = E.value;443if (extension->shutdown_callback) {444extension->shutdown_callback();445}446}447}448449void GDExtensionManager::frame() {450for (const KeyValue<String, Ref<GDExtension>> &E : gdextension_map) {451const Ref<GDExtension> &extension = E.value;452if (extension->frame_callback) {453extension->frame_callback();454}455}456}457458GDExtensionManager *GDExtensionManager::get_singleton() {459return singleton;460}461462void GDExtensionManager::_bind_methods() {463ClassDB::bind_method(D_METHOD("load_extension", "path"), &GDExtensionManager::load_extension);464ClassDB::bind_method(D_METHOD("load_extension_from_function", "path", "init_func"), &GDExtensionManager::load_extension_from_function);465ClassDB::bind_method(D_METHOD("reload_extension", "path"), &GDExtensionManager::reload_extension);466ClassDB::bind_method(D_METHOD("unload_extension", "path"), &GDExtensionManager::unload_extension);467ClassDB::bind_method(D_METHOD("is_extension_loaded", "path"), &GDExtensionManager::is_extension_loaded);468469ClassDB::bind_method(D_METHOD("get_loaded_extensions"), &GDExtensionManager::get_loaded_extensions);470ClassDB::bind_method(D_METHOD("get_extension", "path"), &GDExtensionManager::get_extension);471472BIND_ENUM_CONSTANT(LOAD_STATUS_OK);473BIND_ENUM_CONSTANT(LOAD_STATUS_FAILED);474BIND_ENUM_CONSTANT(LOAD_STATUS_ALREADY_LOADED);475BIND_ENUM_CONSTANT(LOAD_STATUS_NOT_LOADED);476BIND_ENUM_CONSTANT(LOAD_STATUS_NEEDS_RESTART);477478ADD_SIGNAL(MethodInfo("extensions_reloaded"));479ADD_SIGNAL(MethodInfo("extension_loaded", PropertyInfo(Variant::OBJECT, "extension", PROPERTY_HINT_RESOURCE_TYPE, GDExtension::get_class_static())));480ADD_SIGNAL(MethodInfo("extension_unloading", PropertyInfo(Variant::OBJECT, "extension", PROPERTY_HINT_RESOURCE_TYPE, GDExtension::get_class_static())));481}482483GDExtensionManager::GDExtensionManager() {484ERR_FAIL_COND(singleton != nullptr);485singleton = this;486487#ifndef DISABLE_DEPRECATED488GDExtensionSpecialCompatHashes::initialize();489#endif490}491492GDExtensionManager::~GDExtensionManager() {493if (singleton == this) {494singleton = nullptr;495}496#ifndef DISABLE_DEPRECATED497GDExtensionSpecialCompatHashes::finalize();498#endif499}500501502