| 1 | // Copyright (C) 2016 The Qt Company Ltd. |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #include "qv4compilationunitmapper_p.h" |
| 5 | |
| 6 | #include <private/qv4compileddata_p.h> |
| 7 | |
| 8 | #include <QtCore/qdatetime.h> |
| 9 | #include <QtCore/qmutex.h> |
| 10 | #include <QtCore/qhash.h> |
| 11 | |
| 12 | QT_BEGIN_NAMESPACE |
| 13 | |
| 14 | using namespace QV4; |
| 15 | |
| 16 | class StaticUnitCache |
| 17 | { |
| 18 | public: |
| 19 | StaticUnitCache() : m_lock(&s_mutex) {} |
| 20 | |
| 21 | CompilationUnitMapper get(const QString &file) |
| 22 | { |
| 23 | const auto it = s_staticUnits.constFind(key: file); |
| 24 | return it == s_staticUnits.constEnd() ? CompilationUnitMapper() : *it; |
| 25 | } |
| 26 | |
| 27 | void set(const QString &file, const CompilationUnitMapper &staticUnit) { |
| 28 | s_staticUnits.insert(key: file, value: staticUnit); |
| 29 | } |
| 30 | |
| 31 | void remove(const QString &file) |
| 32 | { |
| 33 | s_staticUnits.remove(key: file); |
| 34 | } |
| 35 | |
| 36 | private: |
| 37 | QMutexLocker<QMutex> m_lock; |
| 38 | |
| 39 | static QMutex s_mutex; |
| 40 | |
| 41 | // We can copy the mappers around because they're all static. |
| 42 | // We never unmap the files. |
| 43 | static QHash<QString, CompilationUnitMapper> s_staticUnits; |
| 44 | }; |
| 45 | |
| 46 | QHash<QString, CompilationUnitMapper> StaticUnitCache::s_staticUnits; |
| 47 | QMutex StaticUnitCache::s_mutex; |
| 48 | |
| 49 | CompiledData::Unit *CompilationUnitMapper::get( |
| 50 | const QString &cacheFilePath, const QDateTime &sourceTimeStamp, QString *errorString) |
| 51 | { |
| 52 | StaticUnitCache cache; |
| 53 | |
| 54 | CompilationUnitMapper mapper = cache.get(file: cacheFilePath); |
| 55 | if (mapper.dataPtr) { |
| 56 | auto *unit = reinterpret_cast<CompiledData::Unit *>(mapper.dataPtr); |
| 57 | if (unit->verifyHeader(expectedSourceTimeStamp: sourceTimeStamp, errorString)) { |
| 58 | *this = mapper; |
| 59 | return unit; |
| 60 | } |
| 61 | |
| 62 | return nullptr; |
| 63 | } |
| 64 | |
| 65 | CompiledData::Unit *data = open(cacheFilePath, sourceTimeStamp, errorString); |
| 66 | if (data && (data->flags & CompiledData::Unit::StaticData)) { |
| 67 | cache.set(file: cacheFilePath, staticUnit: *this); |
| 68 | return data; |
| 69 | } else { |
| 70 | close(); |
| 71 | return nullptr; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | void CompilationUnitMapper::invalidate(const QString &cacheFilePath) |
| 76 | { |
| 77 | StaticUnitCache cache; |
| 78 | cache.remove(file: cacheFilePath); |
| 79 | } |
| 80 | |
| 81 | QT_END_NAMESPACE |
| 82 | |