Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qv4compilationunitmapper_unix.cpp
Go to the documentation of this file.
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// Qt-Security score:significant
4
6
7#include <private/qcore_unix_p.h>
8#include <private/qv4compileddata_p.h>
9
10#include <QtCore/qscopeguard.h>
11#include <QtCore/qdatetime.h>
12
13#include <functional>
14#include <sys/mman.h>
15
16QT_BEGIN_NAMESPACE
17
18using namespace QV4;
19
20CompiledData::Unit *CompilationUnitMapper::open(const QString &cacheFileName, const QDateTime &sourceTimeStamp, QString *errorString)
21{
22 close();
23
24 int fd = qt_safe_open(QFile::encodeName(cacheFileName).constData(), O_RDONLY);
25 if (fd == -1) {
26 *errorString = qt_error_string(errno);
27 return nullptr;
28 }
29
30 auto cleanup = qScopeGuard([fd]{
31 qt_safe_close(fd) ;
32 });
33
34 CompiledData::Unit header;
35 qint64 bytesRead = qt_safe_read(fd, reinterpret_cast<char *>(&header), sizeof(header));
36
37 if (bytesRead != sizeof(header)) {
38 *errorString = QStringLiteral("File too small for the header fields");
39 return nullptr;
40 }
41
42 if (!header.verifyHeader(sourceTimeStamp, errorString))
43 return nullptr;
44
45 // Data structure and qt version matched, so now we can access the rest of the file safely.
46
47 length = static_cast<size_t>(lseek(fd, 0, SEEK_END));
48 /* Error out early on file corruption. We assume we can read header.unitSize bytes
49 later (even before verifying the checksum), potentially causing out-of-bound
50 reads
51 Also, no need to wait until checksum verification if we know beforehand
52 that the cached unit is bogus
53 */
54 if (length != header.unitSize) {
55 *errorString = QStringLiteral("Potential file corruption, file too small");
56 return nullptr;
57 }
58
59 void *ptr = mmap(nullptr, length, PROT_READ, MAP_SHARED, fd, /*offset*/0);
60 if (ptr == MAP_FAILED) {
61 *errorString = qt_error_string(errno);
62 return nullptr;
63 }
64 dataPtr = ptr;
65
66 return reinterpret_cast<CompiledData::Unit*>(dataPtr);
67}
68
69void CompilationUnitMapper::close()
70{
71 // Do not unmap the data here.
72 if (dataPtr != nullptr) {
73 // Do not unmap cache files that are built with the StaticData flag. That's the majority of
74 // them and it's necessary to benefit from the QString literal optimization. There might
75 // still be QString instances around that point into that memory area. The memory is backed
76 // on the disk, so the kernel is free to release the pages and all that remains is the
77 // address space allocation.
78 if (!(reinterpret_cast<CompiledData::Unit*>(dataPtr)->flags & CompiledData::Unit::StaticData))
79 munmap(dataPtr, length);
80 }
81 dataPtr = nullptr;
82}
83
84QT_END_NAMESPACE
#define MAP_FAILED