Path: blob/master/modules/gdscript/gdscript_cache.cpp
20844 views
/**************************************************************************/1/* gdscript_cache.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 "gdscript_cache.h"3132#include "gdscript.h"33#include "gdscript_analyzer.h"34#include "gdscript_compiler.h"35#include "gdscript_parser.h"3637#include "core/io/file_access.h"38#include "core/templates/vector.h"3940GDScriptParserRef::Status GDScriptParserRef::get_status() const {41return status;42}4344String GDScriptParserRef::get_path() const {45return path;46}4748uint32_t GDScriptParserRef::get_source_hash() const {49return source_hash;50}5152GDScriptParser *GDScriptParserRef::get_parser() {53if (parser == nullptr) {54parser = memnew(GDScriptParser);55}56return parser;57}5859GDScriptAnalyzer *GDScriptParserRef::get_analyzer() {60if (analyzer == nullptr) {61analyzer = memnew(GDScriptAnalyzer(get_parser()));62}63return analyzer;64}6566Error GDScriptParserRef::raise_status(Status p_new_status) {67ERR_FAIL_COND_V(clearing, ERR_BUG);68ERR_FAIL_COND_V(parser == nullptr && status != EMPTY, ERR_BUG);6970if (p_new_status < status) {71return OK;72}7374while (result == OK && p_new_status > status) {75switch (status) {76case EMPTY: {77// Calling parse will clear the parser, which can destruct another GDScriptParserRef which can clear the last reference to the script with this path, calling remove_script, which clears this GDScriptParserRef.78// It's ok if its the first thing done here.79get_parser()->clear();80status = PARSED;81String remapped_path = ResourceLoader::path_remap(path);82if (remapped_path.has_extension("gdc")) {83Vector<uint8_t> tokens = GDScriptCache::get_binary_tokens(remapped_path);84source_hash = hash_djb2_buffer(tokens.ptr(), tokens.size());85result = get_parser()->parse_binary(tokens, path);86} else {87String source = GDScriptCache::get_source_code(remapped_path);88source_hash = source.hash();89result = get_parser()->parse(source, path, false);90}91} break;92case PARSED: {93status = INHERITANCE_SOLVED;94result = get_analyzer()->resolve_inheritance();95} break;96case INHERITANCE_SOLVED: {97status = INTERFACE_SOLVED;98result = get_analyzer()->resolve_interface();99} break;100case INTERFACE_SOLVED: {101status = FULLY_SOLVED;102result = get_analyzer()->resolve_body();103} break;104case FULLY_SOLVED: {105return result;106}107}108}109110return result;111}112113void GDScriptParserRef::clear() {114if (clearing) {115return;116}117clearing = true;118119GDScriptParser *lparser = parser;120GDScriptAnalyzer *lanalyzer = analyzer;121122parser = nullptr;123analyzer = nullptr;124status = EMPTY;125result = OK;126source_hash = 0;127128clearing = false;129130if (lanalyzer != nullptr) {131memdelete(lanalyzer);132}133134if (lparser != nullptr) {135memdelete(lparser);136}137}138139GDScriptParserRef::~GDScriptParserRef() {140clear();141142if (!abandoned) {143MutexLock lock(GDScriptCache::singleton->mutex);144GDScriptCache::singleton->parser_map.erase(path);145}146}147148GDScriptCache *GDScriptCache::singleton = nullptr;149150SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> &_get_gdscript_cache_mutex() {151return GDScriptCache::mutex;152}153154template <>155thread_local SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG>::tls_data(_get_gdscript_cache_mutex());156SafeBinaryMutex<GDScriptCache::BINARY_MUTEX_TAG> GDScriptCache::mutex;157158void GDScriptCache::move_script(const String &p_from, const String &p_to) {159if (singleton == nullptr || p_from == p_to || p_from.is_empty()) {160return;161}162163MutexLock lock(singleton->mutex);164165if (singleton->cleared) {166return;167}168169remove_parser(p_from);170171if (singleton->shallow_gdscript_cache.has(p_from) && !p_from.is_empty()) {172singleton->shallow_gdscript_cache[p_to] = singleton->shallow_gdscript_cache[p_from];173}174singleton->shallow_gdscript_cache.erase(p_from);175176if (singleton->full_gdscript_cache.has(p_from) && !p_from.is_empty()) {177singleton->full_gdscript_cache[p_to] = singleton->full_gdscript_cache[p_from];178}179singleton->full_gdscript_cache.erase(p_from);180}181182void GDScriptCache::remove_script(const String &p_path) {183if (singleton == nullptr) {184return;185}186187MutexLock lock(singleton->mutex);188189if (singleton->cleared) {190return;191}192193if (HashMap<String, Vector<ObjectID>>::Iterator E = singleton->abandoned_parser_map.find(p_path)) {194for (ObjectID parser_ref_id : E->value) {195Ref<GDScriptParserRef> parser_ref = { ObjectDB::get_instance(parser_ref_id) };196if (parser_ref.is_valid()) {197parser_ref->clear();198}199}200}201202singleton->abandoned_parser_map.erase(p_path);203204if (singleton->parser_map.has(p_path)) {205singleton->parser_map[p_path]->clear();206}207208remove_parser(p_path);209210singleton->dependencies.erase(p_path);211singleton->shallow_gdscript_cache.erase(p_path);212singleton->full_gdscript_cache.erase(p_path);213}214215Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) {216MutexLock lock(singleton->mutex);217Ref<GDScriptParserRef> ref;218if (!p_owner.is_empty() && p_path != p_owner) {219singleton->dependencies[p_owner].insert(p_path);220singleton->parser_inverse_dependencies[p_path].insert(p_owner);221}222if (singleton->parser_map.has(p_path)) {223ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]);224if (ref.is_null()) {225r_error = ERR_INVALID_DATA;226return ref;227}228} else {229String remapped_path = ResourceLoader::path_remap(p_path);230if (!FileAccess::exists(remapped_path)) {231r_error = ERR_FILE_NOT_FOUND;232return ref;233}234ref.instantiate();235ref->path = p_path;236singleton->parser_map[p_path] = ref.ptr();237}238r_error = ref->raise_status(p_status);239240return ref;241}242243bool GDScriptCache::has_parser(const String &p_path) {244MutexLock lock(singleton->mutex);245return singleton->parser_map.has(p_path);246}247248void GDScriptCache::remove_parser(const String &p_path) {249MutexLock lock(singleton->mutex);250251if (singleton->parser_map.has(p_path)) {252GDScriptParserRef *parser_ref = singleton->parser_map[p_path];253parser_ref->abandoned = true;254singleton->abandoned_parser_map[p_path].push_back(parser_ref->get_instance_id());255}256257// Can't clear the parser because some other parser might be currently using it in the chain of calls.258singleton->parser_map.erase(p_path);259260// Have to copy while iterating, because parser_inverse_dependencies is modified.261HashSet<String> ideps = singleton->parser_inverse_dependencies[p_path];262singleton->parser_inverse_dependencies.erase(p_path);263for (String idep_path : ideps) {264remove_parser(idep_path);265}266}267268String GDScriptCache::get_source_code(const String &p_path) {269Vector<uint8_t> source_file;270Error err;271Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);272ERR_FAIL_COND_V(err, "");273274uint64_t len = f->get_length();275source_file.resize(len + 1);276uint64_t r = f->get_buffer(source_file.ptrw(), len);277ERR_FAIL_COND_V(r != len, "");278source_file.write[len] = 0;279280String source;281if (source.append_utf8((const char *)source_file.ptr(), len) != OK) {282ERR_FAIL_V_MSG("", "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");283}284return source;285}286287Vector<uint8_t> GDScriptCache::get_binary_tokens(const String &p_path) {288Vector<uint8_t> buffer;289Error err = OK;290Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);291ERR_FAIL_COND_V_MSG(err != OK, buffer, "Failed to open binary GDScript file '" + p_path + "'.");292293uint64_t len = f->get_length();294buffer.resize(len);295uint64_t read = f->get_buffer(buffer.ptrw(), buffer.size());296ERR_FAIL_COND_V_MSG(read != len, Vector<uint8_t>(), "Failed to read binary GDScript file '" + p_path + "'.");297298return buffer;299}300301Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, Error &r_error, const String &p_owner) {302MutexLock lock(singleton->mutex);303304if (!p_owner.is_empty() && p_path != p_owner) {305singleton->dependencies[p_owner].insert(p_path);306}307if (singleton->full_gdscript_cache.has(p_path)) {308return singleton->full_gdscript_cache[p_path];309}310if (singleton->shallow_gdscript_cache.has(p_path)) {311return singleton->shallow_gdscript_cache[p_path];312}313314const String remapped_path = ResourceLoader::path_remap(p_path);315316Ref<GDScript> script;317script.instantiate();318319script->set_path_cache(p_path);320if (remapped_path.has_extension("gdc")) {321Vector<uint8_t> buffer = get_binary_tokens(remapped_path);322if (buffer.is_empty()) {323r_error = ERR_FILE_CANT_READ;324}325script->set_binary_tokens_source(buffer);326} else {327r_error = script->load_source_code(remapped_path);328}329330if (r_error) {331return Ref<GDScript>(); // Returns null and does not cache when the script fails to load.332}333334Ref<GDScriptParserRef> parser_ref = get_parser(p_path, GDScriptParserRef::PARSED, r_error);335if (r_error == OK) {336GDScriptCompiler::make_scripts(script.ptr(), parser_ref->get_parser()->get_tree(), true);337}338339singleton->shallow_gdscript_cache[p_path] = script;340341return script;342}343344Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner, bool p_update_from_disk) {345MutexLock lock(singleton->mutex);346347if (!p_owner.is_empty() && p_path != p_owner) {348singleton->dependencies[p_owner].insert(p_path);349}350351Ref<GDScript> script;352r_error = OK;353if (singleton->full_gdscript_cache.has(p_path)) {354script = singleton->full_gdscript_cache[p_path];355if (!p_update_from_disk) {356return script;357}358}359360if (script.is_null()) {361script = get_shallow_script(p_path, r_error);362// Only exit early if script failed to load, otherwise let reload report errors.363if (script.is_null()) {364return script;365}366}367368const String remapped_path = ResourceLoader::path_remap(p_path);369370if (p_update_from_disk) {371if (remapped_path.has_extension("gdc")) {372Vector<uint8_t> buffer = get_binary_tokens(remapped_path);373if (buffer.is_empty()) {374r_error = ERR_FILE_CANT_READ;375goto finish;376}377script->set_binary_tokens_source(buffer);378} else {379r_error = script->load_source_code(remapped_path);380if (r_error) {381goto finish;382}383}384}385386// Allowing lifting the lock might cause a script to be reloaded multiple times,387// which, as a last resort deadlock prevention strategy, is a good tradeoff.388{389uint32_t allowance_id = WorkerThreadPool::thread_enter_unlock_allowance_zone(singleton->mutex);390r_error = script->reload(true);391WorkerThreadPool::thread_exit_unlock_allowance_zone(allowance_id);392}393394finish:395singleton->full_gdscript_cache[p_path] = script;396singleton->shallow_gdscript_cache.erase(p_path);397398// Add the script to the resource cache. Usually ResourceLoader would take care of it, but cyclic references can break that sometimes so we do it ourselves.399// Resources don't know whether they are cached, so using `set_path()` after `set_path_cache()` does not add the resource to the cache if the path is the same.400// We reset the cached path from `get_shallow_script()` so that the subsequent call to `set_path()` caches everything correctly.401script->set_path_cache(String());402script->set_path(p_path, true);403404return script;405}406407Ref<GDScript> GDScriptCache::get_cached_script(const String &p_path) {408MutexLock lock(singleton->mutex);409410if (singleton->full_gdscript_cache.has(p_path)) {411return singleton->full_gdscript_cache[p_path];412}413414if (singleton->shallow_gdscript_cache.has(p_path)) {415return singleton->shallow_gdscript_cache[p_path];416}417418return Ref<GDScript>();419}420421Error GDScriptCache::finish_compiling(const String &p_owner) {422MutexLock lock(singleton->mutex);423424// Mark this as compiled.425Ref<GDScript> script = get_cached_script(p_owner);426singleton->full_gdscript_cache[p_owner] = script;427singleton->shallow_gdscript_cache.erase(p_owner);428429HashSet<String> depends = singleton->dependencies[p_owner];430431Error err = OK;432for (const String &E : depends) {433Error this_err = OK;434// No need to save the script. We assume it's already referenced in the owner.435get_full_script(E, this_err);436437if (this_err != OK) {438err = this_err;439}440}441442singleton->dependencies.erase(p_owner);443444return err;445}446447void GDScriptCache::add_static_script(Ref<GDScript> p_script) {448ERR_FAIL_COND_MSG(p_script.is_null(), "Trying to cache empty script as static.");449ERR_FAIL_COND_MSG(!p_script->is_valid(), "Trying to cache non-compiled script as static.");450singleton->static_gdscript_cache[p_script->get_fully_qualified_name()] = p_script;451}452453void GDScriptCache::remove_static_script(const String &p_fqcn) {454singleton->static_gdscript_cache.erase(p_fqcn);455}456457void GDScriptCache::clear() {458if (singleton == nullptr) {459return;460}461462MutexLock lock(singleton->mutex);463464if (singleton->cleared) {465return;466}467singleton->cleared = true;468469singleton->parser_inverse_dependencies.clear();470471for (const KeyValue<String, Vector<ObjectID>> &KV : singleton->abandoned_parser_map) {472for (ObjectID parser_ref_id : KV.value) {473Ref<GDScriptParserRef> parser_ref = { ObjectDB::get_instance(parser_ref_id) };474if (parser_ref.is_valid()) {475parser_ref->clear();476}477}478}479480singleton->abandoned_parser_map.clear();481482RBSet<Ref<GDScriptParserRef>> parser_map_refs;483for (KeyValue<String, GDScriptParserRef *> &E : singleton->parser_map) {484parser_map_refs.insert(E.value);485}486487singleton->parser_map.clear();488489for (Ref<GDScriptParserRef> &E : parser_map_refs) {490if (E.is_valid()) {491E->clear();492}493}494495parser_map_refs.clear();496singleton->shallow_gdscript_cache.clear();497singleton->full_gdscript_cache.clear();498singleton->static_gdscript_cache.clear();499}500501GDScriptCache::GDScriptCache() {502singleton = this;503}504505GDScriptCache::~GDScriptCache() {506if (!cleared) {507clear();508}509singleton = nullptr;510}511512513