Godot Engine – Multi-platform 2D and 3D game engine
GDScript: Make language shutdown more crash resilient
HolonProduction546e46d3b6e0
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cppindex 45eb419e38e..47c8f67e915 100644--- a/modules/gdscript/gdscript.cpp+++ b/modules/gdscript/gdscript.cpp@@ -1431,6 +1431,7 @@ void GDScript::clear() {return;}clearing = true;+ ERR_FAIL_NULL_MSG(GDScriptLanguage::singleton, vformat("GDScript bug (please report): GDScript '%s' was not cleared before language shutdown.", fully_qualified_name));RBSet<GDScriptFunction *> functions_to_clear;@@ -1488,33 +1489,33 @@ void GDScript::clear() {base_cache = Ref<GDScript>();#endifbase = Ref<GDScript>();++ cancel_pending_functions(false);++ {+ MutexLock lock(GDScriptLanguage::get_singleton()->mutex);++ script_list.remove_from_list();+ }}void GDScript::cancel_pending_functions(bool warn) {MutexLock lock(GDScriptLanguage::get_singleton()->mutex);while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {- // Order matters since clearing the stack may already cause- // the GDScriptFunctionState to be destroyed and thus removed from the list.- pending_func_states.remove(E);- GDScriptFunctionState *state = E->self();+ Ref<GDScriptFunctionState> state = E->self();+ state->clear();+#ifdef DEBUG_ENABLEDif (warn) {WARN_PRINT("Canceling suspended execution of \"" + state->get_readable_function() + "\" due to a script reload.");}#endif- ObjectID state_id = state->get_instance_id();- state->_clear_connections();- if (ObjectDB::get_instance(state_id)) {- state->_clear_stack();- }}}GDScript::~GDScript() {- if (destructing) {- return;- }+ ERR_FAIL_COND_MSG(destructing, "GDScript bug (please report): Double free on GDScript.");destructing = true;if (is_print_verbose_enabled()) {@@ -1525,14 +1526,6 @@ GDScript::~GDScript() {}clear();-- cancel_pending_functions(false);-- {- MutexLock lock(GDScriptLanguage::get_singleton()->mutex);-- script_list.remove_from_list();- }}//////////////////////////////@@ -2069,20 +2062,11 @@ GDScriptInstance::~GDScriptInstance() {MutexLock lock(GDScriptLanguage::get_singleton()->mutex);while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {- // Order matters since clearing the stack may already cause- // the GDSCriptFunctionState to be destroyed and thus removed from the list.- pending_func_states.remove(E);- GDScriptFunctionState *state = E->self();- ObjectID state_id = state->get_instance_id();- state->_clear_connections();- if (ObjectDB::get_instance(state_id)) {- state->_clear_stack();- }+ Ref<GDScriptFunctionState> state = E->self();+ state->clear();}- if (script.is_valid()) {- script->instances.remove(&script_instance_list);- }+ script_instance_list.remove_from_list();}/************* SCRIPT LANGUAGE **************/@@ -2228,44 +2212,78 @@ String GDScriptLanguage::get_extension() const {}void GDScriptLanguage::finish() {- if (finishing) {- return;- }+ ERR_FAIL_COND_MSG(finishing, "GDScript bug (please report): GDScriptLanguage double finish.");finishing = true;- // Clear the cache before parsing the script_list+ // Clear the cache before parsing the `script_list`. Some `GDScript` instances will drop to a ref count of zero and destruct on their own.+ // TODO: This might lead to issues when trying to load a script from within `NOTIFICATION_PREDELETE`, we ignore this issue for now.GDScriptCache::clear();- // Clear dependencies between scripts, to ensure cyclic references are broken- // (to avoid leaks at exit).- SelfList<GDScript> *s = script_list.first();- while (s) {- // This ensures the current script is not released before we can check- // what's the next one in the list (we can't get the next upfront because we- // don't know if the reference breaking will cause it -or any other after- // it, for that matter- to be released so the next one is not the same as- // before).- Ref<GDScript> scr = s->self();- if (scr.is_valid()) {- for (KeyValue<StringName, GDScriptFunction *> &E : scr->member_functions) {- GDScriptFunction *func = E.value;- for (int i = 0; i < func->argument_types.size(); i++) {- func->argument_types.write[i].script_type_ref = Ref<Script>();- }- func->return_type.script_type_ref = Ref<Script>();+ // All remaining scripts in `script_list` are still referenced. There can be two reasons for this:+ // 1. They have a cyclic dependency among them-selves.+ // 2. They are referenced from another engine component, which shuts down later (e.g. an instance is stored in the metadata of `Engine`).++ // 1. Pass: Gracefully clear static data, so that GDScript instances stored in static variables can react to `NOTIFICATION_PREDELETE`.+ // Due to Static Deinitialization Order Fiasco it is a user error if `NOTIFICATION_PREDELETE` interacts with static data. In this case+ // static data becomes subject to non-graceful clearing.+ {+ // Make a copy of the script list to avoid problems if it is changed during `NOTIFICATION_PREDELETE`.+ LocalVector<Ref<GDScript>> needs_static_data_clear;+ for (const SelfList<GDScript> *E = script_list.first(); E != nullptr; E = E->next()) {+ ERR_CONTINUE_MSG(E->self() == nullptr, "GDScript bug (please report): `nullptr` in `script_list`.");+ needs_static_data_clear.push_back(E->self());+ }+ for (const Ref<GDScript> &script : needs_static_data_clear) {+ script->static_variables_indices.clear();+ script->static_variables.clear();+ }+ }++ // 2. Pass: Ungracefully cancel pending functions and detach dangling instances.+ // We have no obligations towards user-code at this point. We only need to ensure we do not crash.+ {+ // In case the last reference to the script comes from a dangling instance we need to ensure it stays alive till we are done.+ LocalVector<Ref<GDScript>> needs_dangling_clear;+ for (const SelfList<GDScript> *E = script_list.first(); E != nullptr; E = E->next()) {+ ERR_CONTINUE_MSG(E->self() == nullptr, "GDScript bug (please report): `nullptr` in `script_list`.");+ needs_dangling_clear.push_back(E->self());+ }+ for (const Ref<GDScript> &script : needs_dangling_clear) {+ script->cancel_pending_functions(false);+ while (script->instances.first() != nullptr) {+ // Turns instances into core objects that can outlive `GDScriptLanguage`.+ const SelfList<GDScriptInstance> *elem = script->instances.first();+ elem->self()->get_owner()->set_script(Variant());+ ERR_BREAK_MSG(script->instances.first() == elem, "GDScript bug (please report): Detaching a script does not destruct instance.");}- for (KeyValue<StringName, GDScript::MemberInfo> &E : scr->member_indices) {- E.value.data_type.script_type_ref = Ref<Script>();+ }+ }++ // TODO: We might want to clean up `GDScriptLambdaCallables` at this point, to prevent leaks from set & forget lambda setups. See GH-102327.++ // 3. Pass: Clear remaining internal references and turn the scripts into zombies that can outlive `GDScriptLanguage`.+ {+ while (SelfList<GDScript> *s = script_list.first()) {+ Ref<GDScript> scr = s->self();+ if (scr.is_null()) { // Not sure if this can happen. But the original code did check for it, so let's keep for now.+ ERR_PRINT("GDScript bug (please report): `nullptr` in `script_list`.");+ s->remove_from_list();+ continue;}- // Clear backup for scripts that could slip out of the cyclic reference- // checkscr->clear();+ ERR_BREAK_MSG(script_list.first() == s || s->in_list(), "GDScript bug (please report): cleared script in `script_list`.");}- s = s->next();}- script_list.clear();- function_list.clear();++ if (script_list.first() != nullptr) {+ ERR_PRINT("GDScript bug (please report): Dangling script in script_list after language shutdown.");+ script_list.clear();+ }+ if (function_list.first() != nullptr) {+ ERR_PRINT("GDScript bug (please report): Dangling function in function_list after language shutdown.");+ function_list.clear();+ }finishing = false;}diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.hindex a16ef871fc0..c4208462215 100644--- a/modules/gdscript/gdscript.h+++ b/modules/gdscript/gdscript.h@@ -443,6 +443,10 @@ class GDScriptLanguage : public ScriptLanguage {friend class GDScript;+ /**+ * Linked list of all GDScripts.+ * When clearing a script GDScript gives up ownership of that script to whoever is holding the reference alive, thus cleared scripts do not appear in this list.+ */SelfList<GDScript>::List script_list;friend class GDScriptFunction;diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cppindex 364b19b1044..3bfe29ba375 100644--- a/modules/gdscript/gdscript_function.cpp+++ b/modules/gdscript/gdscript_function.cpp@@ -351,9 +351,23 @@ GDScriptFunctionState::GDScriptFunctionState() :instances_list(this) {}-GDScriptFunctionState::~GDScriptFunctionState() {+void GDScriptFunctionState::clear() {+ if (cleared) {+ return;+ }+ ERR_FAIL_NULL_MSG(GDScriptLanguage::singleton, "GDScript bug (please report): Function state was not cleared before language shutdown.");MutexLock lock(GDScriptLanguage::singleton->mutex);+ if (cleared) {+ return;+ }+ cleared = true;++ _clear_connections();scripts_list.remove_from_list();instances_list.remove_from_list();_clear_stack();}++GDScriptFunctionState::~GDScriptFunctionState() {+ clear();+}diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.hindex 86b8b7da6d7..0afdce8d87c 100644--- a/modules/gdscript/gdscript_function.h+++ b/modules/gdscript/gdscript_function.h@@ -516,7 +516,17 @@ class GDScriptFunctionState : public RefCounted {protected:static void _bind_methods();+private:+ bool cleared = false;+public:+ /**+ * Transfers the object into a zombie state, in which it has no functionality anymore and can outlive `GDScriptLanguage`.+ * A cleared function state does not hold any references and thus can not be locked up in a ref cycle.+ * Callers SHOULD hold a reference to the object while calling `clear`.+ */+ void clear();+#ifdef DEBUG_ENABLED// Returns a human-readable representation of the function.String get_readable_function() {