Repository navigation
Expand file tree
/
Copy pathCodeCache.cpp
More file actions
391 lines (356 loc) · 11.8 KB
/
Copy pathCodeCache.cpp
File metadata and controls
391 lines (356 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#include "ns/loader/CodeCache.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <climits>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <mutex>
#include <utility>
#include "loader/CodeCacheFormat.h"
#include "ns/LoaderConfig.h"
#include "ns/Thread.h"
namespace nativescript::common::loader {
namespace {
constexpr char kMagic[4] = {'N', 'S', 'C', 'C'};
void PutU32(std::string& out, uint32_t value) {
for (int i = 0; i < 4; i++) {
out.push_back(static_cast<char>((value >> (8 * i)) & 0xff));
}
}
void PutU64(std::string& out, uint64_t value) {
for (int i = 0; i < 8; i++) {
out.push_back(static_cast<char>((value >> (8 * i)) & 0xff));
}
}
uint32_t GetU32(const uint8_t* bytes) {
uint32_t value = 0;
for (int i = 3; i >= 0; i--) {
value = (value << 8) | bytes[i];
}
return value;
}
uint64_t GetU64(const uint8_t* bytes) {
uint64_t value = 0;
for (int i = 7; i >= 0; i--) {
value = (value << 8) | bytes[i];
}
return value;
}
uint64_t Fnv1a64(std::string_view text) {
uint64_t hash = 0xcbf29ce484222325ULL;
for (unsigned char c : text) {
hash ^= c;
hash *= 0x100000001b3ULL;
}
return hash;
}
bool ReadFully(int fd, void* dst, size_t length) {
auto* out = static_cast<uint8_t*>(dst);
while (length > 0) {
const ssize_t got = read(fd, out, length);
if (got < 0 && errno == EINTR) {
continue;
}
if (got <= 0) {
return false;
}
out += got;
length -= static_cast<size_t>(got);
}
return true;
}
bool WriteFully(int fd, const void* src, size_t length) {
const auto* in = static_cast<const uint8_t*>(src);
while (length > 0) {
const ssize_t put = write(fd, in, length);
if (put < 0 && errno == EINTR) {
continue;
}
if (put <= 0) {
return false;
}
in += put;
length -= static_cast<size_t>(put);
}
return true;
}
bool IsDirectory(const std::string& path) {
struct stat st;
return stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
// mkdir -p, creating only the missing tail: an app may not be allowed to
// mkdir, or even stat, the ancestors it was given. Another thread or process
// may create a component concurrently.
bool MakeDirectories(const std::string& dir) {
if (dir.empty() || mkdir(dir.c_str(), 0700) == 0) {
return true;
}
if (errno == EEXIST) {
return IsDirectory(dir);
}
if (errno != ENOENT) {
return false;
}
const size_t slash = dir.rfind('/');
if (slash == std::string::npos || slash == 0 ||
!MakeDirectories(dir.substr(0, slash))) {
return false;
}
return (mkdir(dir.c_str(), 0700) == 0 || errno == EEXIST) && IsDirectory(dir);
}
// The open cache file positioned at its payload, or -1 when it is not a cache
// for exactly `entry`, in `entry.format` unless `anyFormat`. `format` is the
// one it records. Every length is checked against the expected values and
// the file's size before anything is allocated from it.
int OpenValidated(const CodeCacheEntry& entry, bool anyFormat,
uint32_t& payloadLength, ModuleFormat& format) {
const int fd = open(entry.file.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return -1;
}
struct stat st;
uint8_t fixed[kCodeCacheFixedHeaderBytes];
CodeCacheHeader header;
bool valid = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
ReadFully(fd, fixed, sizeof(fixed)) &&
DecodeCodeCacheFixedHeader(fixed, header) &&
header.version == kCodeCacheFormatVersion &&
header.kind == static_cast<uint32_t>(entry.kind) &&
header.keyLength == entry.key.size() &&
header.tokenLength == entry.source.freshnessToken.size() &&
header.sourceSize == entry.source.size &&
header.payloadLength <= INT_MAX &&
static_cast<uint64_t>(st.st_size) ==
kCodeCacheFixedHeaderBytes +
static_cast<uint64_t>(header.keyLength) +
header.tokenLength + header.payloadLength;
if (valid) {
const bool marker =
header.format == static_cast<uint32_t>(ModuleFormat::kCommonJs);
const bool known =
entry.kind == CodeCacheKind::kEsModule
? marker || header.format ==
static_cast<uint32_t>(ModuleFormat::kEsModule)
: header.format == static_cast<uint32_t>(ModuleFormat::kNone);
valid = known && (header.payloadLength == 0) == marker &&
(anyFormat || header.format == static_cast<uint32_t>(entry.format));
}
if (valid) {
std::string tail(entry.key.size() + entry.source.freshnessToken.size(),
'\0');
valid = ReadFully(fd, tail.data(), tail.size()) &&
std::string_view(tail).substr(0, entry.key.size()) == entry.key &&
std::string_view(tail).substr(entry.key.size()) ==
entry.source.freshnessToken;
}
if (!valid) {
close(fd);
return -1;
}
payloadLength = header.payloadLength;
format = static_cast<ModuleFormat>(header.format);
return fd;
}
struct WriteJob {
CodeCacheEntry entry;
std::unique_ptr<uint8_t[]> payload;
size_t length = 0;
};
void RunWriteJob(const WriteJob& job) {
if (SourceUnchanged(job.entry.sourcePath, job.entry.source)) {
WriteCodeCache(job.entry, job.payload.get(), job.length);
}
}
// One utility-priority thread that writes caches in the order they were
// posted. Never destroyed: its thread waits on it for the life of the process.
class Writer {
public:
static Writer& Shared() {
static Writer* writer = new Writer();
return *writer;
}
void Post(WriteJob job) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!started_) {
started_ = StartThread(
ThreadSpec{"ns-cache-write", 0, ThreadPriority::kUtility},
[this] { Run(); });
}
if (started_) {
jobs_.push_back(std::move(job));
ready_.notify_one();
return;
}
}
RunWriteJob(job);
}
private:
[[noreturn]] void Run() {
for (;;) {
WriteJob job;
{
std::unique_lock<std::mutex> lock(mutex_);
ready_.wait(lock, [this] { return !jobs_.empty(); });
job = std::move(jobs_.front());
jobs_.pop_front();
}
platform::RunJob([&job] { RunWriteJob(job); });
}
}
std::mutex mutex_;
std::condition_variable ready_;
std::deque<WriteJob> jobs_;
bool started_ = false;
};
} // namespace
std::string EncodeCodeCacheHeader(const CodeCacheEntry& entry,
size_t payloadLength) {
const std::string& token = entry.source.freshnessToken;
if (entry.key.size() > UINT32_MAX || token.size() > UINT32_MAX ||
payloadLength > UINT32_MAX) {
return std::string();
}
std::string out;
out.reserve(kCodeCacheFixedHeaderBytes + entry.key.size() + token.size());
out.append(kMagic, sizeof(kMagic));
PutU32(out, kCodeCacheFormatVersion);
PutU32(out, static_cast<uint32_t>(entry.kind));
PutU32(out, static_cast<uint32_t>(entry.key.size()));
PutU64(out, entry.source.size);
PutU32(out, static_cast<uint32_t>(token.size()));
PutU32(out, static_cast<uint32_t>(payloadLength));
PutU32(out, static_cast<uint32_t>(entry.format));
out += entry.key;
out += token;
return out;
}
bool DecodeCodeCacheFixedHeader(const uint8_t* bytes, CodeCacheHeader& out) {
if (std::memcmp(bytes, kMagic, sizeof(kMagic)) != 0) {
return false;
}
out.version = GetU32(bytes + 4);
out.kind = GetU32(bytes + 8);
out.keyLength = GetU32(bytes + 12);
out.sourceSize = GetU64(bytes + 16);
out.tokenLength = GetU32(bytes + 24);
out.payloadLength = GetU32(bytes + 28);
out.format = GetU32(bytes + 32);
return true;
}
std::string CodeCacheKey(std::string_view logicalPath,
std::string_view appRoot) {
if (!appRoot.empty() && logicalPath.size() > appRoot.size() &&
logicalPath.substr(0, appRoot.size()) == appRoot &&
logicalPath[appRoot.size()] == '/') {
return std::string(logicalPath.substr(appRoot.size() + 1));
}
return std::string(logicalPath);
}
std::string CodeCacheFileName(std::string_view key, CodeCacheKind kind) {
char hex[17];
std::snprintf(hex, sizeof(hex), "%016llx",
static_cast<unsigned long long>(Fnv1a64(key)));
return std::string(hex) +
(kind == CodeCacheKind::kEsModule ? ".mcache" : ".cache");
}
std::optional<CodeCacheEntry> CodeCacheEntryFor(std::string_view logicalPath,
CodeCacheKind kind,
const FileInfo& source,
const LoaderConfig& config) {
if (!config.codeCacheEnabled || config.codeCacheDir.empty() ||
!source.isFile || source.freshnessToken.empty()) {
return std::nullopt;
}
CodeCacheEntry entry;
entry.key = CodeCacheKey(logicalPath, config.appRoot);
entry.file = config.codeCacheDir + "/" + CodeCacheFileName(entry.key, kind);
entry.sourcePath = std::string(logicalPath);
entry.kind = kind;
entry.format = kind == CodeCacheKind::kEsModule ? ModuleFormat::kEsModule
: ModuleFormat::kNone;
entry.source = source;
return entry;
}
bool HasFreshCodeCache(const CodeCacheEntry& entry) {
uint32_t payloadLength = 0;
ModuleFormat format = ModuleFormat::kNone;
const int fd = OpenValidated(entry, false, payloadLength, format);
if (fd < 0) {
return false;
}
close(fd);
return true;
}
std::optional<ModuleFormat> FreshModuleFormat(const CodeCacheEntry& entry) {
uint32_t payloadLength = 0;
ModuleFormat format = ModuleFormat::kNone;
const int fd = OpenValidated(entry, true, payloadLength, format);
if (fd < 0) {
return std::nullopt;
}
close(fd);
return format;
}
std::optional<CodeCacheBytes> LoadCodeCache(const CodeCacheEntry& entry) {
uint32_t payloadLength = 0;
ModuleFormat format = ModuleFormat::kNone;
const int fd = OpenValidated(entry, false, payloadLength, format);
if (fd < 0 || payloadLength == 0) {
if (fd >= 0) {
close(fd);
}
return std::nullopt;
}
CodeCacheBytes bytes;
bytes.data.reset(new uint8_t[payloadLength]);
bytes.length = static_cast<int>(payloadLength);
const bool ok = ReadFully(fd, bytes.data.get(), payloadLength);
close(fd);
if (!ok) {
return std::nullopt;
}
return bytes;
}
bool WriteCodeCache(const CodeCacheEntry& entry, const uint8_t* payload,
size_t length) {
const bool marker = entry.format == ModuleFormat::kCommonJs;
if (marker ? payload != nullptr || length != 0
: payload == nullptr || length == 0 || length > INT_MAX) {
return false;
}
const std::string header = EncodeCodeCacheHeader(entry, length);
const size_t slash = entry.file.rfind('/');
if (header.empty() || slash == std::string::npos ||
!MakeDirectories(entry.file.substr(0, slash))) {
return false;
}
std::string temp = entry.file + ".XXXXXX";
const int fd = mkstemp(temp.data());
if (fd < 0) {
return false;
}
bool ok = WriteFully(fd, header.data(), header.size()) &&
(marker || WriteFully(fd, payload, length));
ok = close(fd) == 0 && ok;
ok = ok && rename(temp.c_str(), entry.file.c_str()) == 0;
if (!ok) {
unlink(temp.c_str());
}
return ok;
}
bool SourceUnchanged(std::string_view logicalPath, const FileInfo& decided) {
const std::optional<FileInfo> now = platform::Stat(logicalPath);
return now && now->isFile == decided.isFile && now->size == decided.size &&
now->freshnessToken == decided.freshnessToken;
}
void PostCodeCacheWrite(CodeCacheEntry entry,
std::unique_ptr<uint8_t[]> payload, size_t length) {
Writer::Shared().Post(WriteJob{std::move(entry), std::move(payload), length});
}
} // namespace nativescript::common::loader