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 <sys/mman.h> |
7 | #include <functional> |
8 | #include <private/qcore_unix_p.h> |
9 | #include <QScopeGuard> |
10 | #include <QDateTime> |
11 | |
12 | #include "qv4executablecompilationunit_p.h" |
13 | |
14 | QT_BEGIN_NAMESPACE |
15 | |
16 | using namespace QV4; |
17 | |
18 | CompiledData::Unit *CompilationUnitMapper::open(const QString &cacheFileName, const QDateTime &sourceTimeStamp, QString *errorString) |
19 | { |
20 | close(); |
21 | |
22 | int fd = qt_safe_open(pathname: QFile::encodeName(fileName: cacheFileName).constData(), O_RDONLY); |
23 | if (fd == -1) { |
24 | *errorString = qt_error_string(errno); |
25 | return nullptr; |
26 | } |
27 | |
28 | auto cleanup = qScopeGuard(f: [fd]{ |
29 | qt_safe_close(fd) ; |
30 | }); |
31 | |
32 | CompiledData::Unit ; |
33 | qint64 bytesRead = qt_safe_read(fd, data: reinterpret_cast<char *>(&header), maxlen: sizeof(header)); |
34 | |
35 | if (bytesRead != sizeof(header)) { |
36 | *errorString = QStringLiteral("File too small for the header fields" ); |
37 | return nullptr; |
38 | } |
39 | |
40 | if (!ExecutableCompilationUnit::verifyHeader(unit: &header, expectedSourceTimeStamp: sourceTimeStamp, errorString)) |
41 | return nullptr; |
42 | |
43 | // Data structure and qt version matched, so now we can access the rest of the file safely. |
44 | |
45 | length = static_cast<size_t>(lseek(fd: fd, offset: 0, SEEK_END)); |
46 | |
47 | void *ptr = mmap(addr: nullptr, len: length, PROT_READ, MAP_SHARED, fd: fd, /*offset*/0); |
48 | if (ptr == MAP_FAILED) { |
49 | *errorString = qt_error_string(errno); |
50 | return nullptr; |
51 | } |
52 | dataPtr = ptr; |
53 | |
54 | return reinterpret_cast<CompiledData::Unit*>(dataPtr); |
55 | } |
56 | |
57 | void CompilationUnitMapper::close() |
58 | { |
59 | // Do not unmap the data here. |
60 | if (dataPtr != nullptr) { |
61 | // Do not unmap cache files that are built with the StaticData flag. That's the majority of |
62 | // them and it's necessary to benefit from the QString literal optimization. There might |
63 | // still be QString instances around that point into that memory area. The memory is backed |
64 | // on the disk, so the kernel is free to release the pages and all that remains is the |
65 | // address space allocation. |
66 | if (!(reinterpret_cast<CompiledData::Unit*>(dataPtr)->flags & CompiledData::Unit::StaticData)) |
67 | munmap(addr: dataPtr, len: length); |
68 | } |
69 | dataPtr = nullptr; |
70 | } |
71 | |
72 | QT_END_NAMESPACE |
73 | |