Repository navigation
Expand file tree
/
Copy pathCodeCacheTest.cpp
More file actions
507 lines (452 loc) · 17.6 KB
/
Copy pathCodeCacheTest.cpp
File metadata and controls
507 lines (452 loc) · 17.6 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <optional>
#include <string>
#include <thread>
#include <vector>
#include "FakePlatform.h"
#include "loader/CodeCacheFormat.h"
#include "ns/AppFiles.h"
#include "ns/LoaderConfig.h"
#include "ns/loader/CodeCache.h"
using namespace nativescript::common;
using namespace nativescript::common::loader;
namespace {
int failures = 0;
void Check(bool ok, const char* what) {
if (!ok) {
failures++;
std::fprintf(stderr, "FAIL %s\n", what);
}
}
std::string tempRoot;
std::string MakeTempDir() {
const char* base = std::getenv("TMPDIR");
std::string pattern = std::string(base != nullptr && *base ? base : "/tmp");
if (pattern.back() != '/') {
pattern += '/';
}
pattern += "ns-code-cache-XXXXXX";
if (mkdtemp(pattern.data()) == nullptr) {
std::perror("mkdtemp");
std::exit(1);
}
return pattern;
}
void RemoveTree(const std::string& path) {
struct stat st;
if (lstat(path.c_str(), &st) != 0) {
return;
}
if (S_ISDIR(st.st_mode)) {
chmod(path.c_str(), 0700);
if (DIR* dir = opendir(path.c_str())) {
while (dirent* item = readdir(dir)) {
const std::string name = item->d_name;
if (name != "." && name != "..") {
RemoveTree(path + "/" + name);
}
}
closedir(dir);
}
rmdir(path.c_str());
} else {
unlink(path.c_str());
}
}
std::vector<std::string> ListDir(const std::string& path) {
std::vector<std::string> names;
if (DIR* dir = opendir(path.c_str())) {
while (dirent* item = readdir(dir)) {
const std::string name = item->d_name;
if (name != "." && name != "..") {
names.push_back(name);
}
}
closedir(dir);
}
return names;
}
std::string ReadAll(const std::string& path) {
std::ifstream in(path, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>());
}
void WriteAll(const std::string& path, const std::string& bytes) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
out.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
}
void Configure(bool enabled, const std::string& dir) {
LoaderConfig& config = fake_platform::MutableLoaderConfig();
config.appRoot = "/root/app";
config.codeCacheEnabled = enabled;
config.codeCacheDir = dir;
}
FileInfo Info(uint64_t size, const std::string& token) {
return FileInfo{true, size, token};
}
CodeCacheEntry EntryFor(const std::string& path, CodeCacheKind kind,
const FileInfo& info) {
std::optional<CodeCacheEntry> entry =
CodeCacheEntryFor(path, kind, info, fake_platform::MutableLoaderConfig());
if (!entry) {
std::fprintf(stderr, "no entry for %s\n", path.c_str());
std::exit(1);
}
return *entry;
}
const std::vector<uint8_t> kPayload = {1, 2, 3, 4, 5, 6, 7, 8, 9};
bool Write(const CodeCacheEntry& entry,
const std::vector<uint8_t>& payload = kPayload) {
return WriteCodeCache(entry, payload.data(), payload.size());
}
bool LoadsPayload(const CodeCacheEntry& entry,
const std::vector<uint8_t>& payload = kPayload) {
std::optional<CodeCacheBytes> bytes = LoadCodeCache(entry);
return bytes && bytes->length == static_cast<int>(payload.size()) &&
std::memcmp(bytes->data.get(), payload.data(), payload.size()) == 0;
}
// The fixed header as raw bytes, the key and token after it, then the
// payload: exactly what WriteCodeCache writes.
std::string ValidFile(const CodeCacheEntry& entry) {
return EncodeCodeCacheHeader(entry, kPayload.size()) +
std::string(kPayload.begin(), kPayload.end());
}
void PutU32At(std::string& bytes, size_t offset, uint32_t value) {
for (int i = 0; i < 4; i++) {
bytes[offset + i] = static_cast<char>((value >> (8 * i)) & 0xff);
}
}
void TestNaming() {
Check(CodeCacheKey("/root/app/a/b.mjs", "/root/app") == "a/b.mjs",
"key: app files are relative to the app root");
Check(CodeCacheKey("/root/apple/b.mjs", "/root/app") == "/root/apple/b.mjs",
"key: a sibling sharing the prefix stays absolute");
Check(CodeCacheKey("/root/app", "/root/app") == "/root/app",
"key: the root itself stays absolute");
Check(CodeCacheKey("/other/x.js", "/root/app") == "/other/x.js",
"key: outside the app root stays absolute");
Check(CodeCacheKey("/other/x.js", "") == "/other/x.js", "key: no app root");
// FNV-1a 64 reference values.
Check(CodeCacheFileName("", CodeCacheKind::kEsModule) ==
"cbf29ce484222325.mcache",
"name: FNV-1a of the empty key");
Check(CodeCacheFileName("a", CodeCacheKind::kClassicScript) ==
"af63dc4c8601ec8c.cache",
"name: FNV-1a of 'a', classic suffix");
Check(CodeCacheFileName("x.js", CodeCacheKind::kEsModule) !=
CodeCacheFileName("x.js", CodeCacheKind::kClassicScript),
"name: the kinds get different files");
Check(CodeCacheFileName("a/b-c.js", CodeCacheKind::kClassicScript) !=
CodeCacheFileName("a-b/c.js", CodeCacheKind::kClassicScript),
"name: no flattening collision");
Check(CodeCacheFileName("a/b.js", CodeCacheKind::kClassicScript).size() ==
16 + 6,
"name: 16 hex digits");
}
void TestEntryFor() {
const FileInfo info = Info(10, "t1");
Configure(false, tempRoot + "/cache");
Check(!CodeCacheEntryFor("/root/app/a.mjs", CodeCacheKind::kEsModule, info,
fake_platform::MutableLoaderConfig()),
"entry: off when disabled");
Configure(true, "");
Check(!CodeCacheEntryFor("/root/app/a.mjs", CodeCacheKind::kEsModule, info,
fake_platform::MutableLoaderConfig()),
"entry: off without a directory");
Configure(true, tempRoot + "/cache");
Check(!CodeCacheEntryFor("/root/app/a.mjs", CodeCacheKind::kEsModule,
Info(10, ""), fake_platform::MutableLoaderConfig()),
"entry: off without a freshness token");
Check(!CodeCacheEntryFor("/root/app/a.mjs", CodeCacheKind::kEsModule,
FileInfo{false, 0, "t1"},
fake_platform::MutableLoaderConfig()),
"entry: off for a non-file");
std::optional<CodeCacheEntry> entry =
CodeCacheEntryFor("/root/app/a.mjs", CodeCacheKind::kEsModule, info,
fake_platform::MutableLoaderConfig());
Check(entry.has_value(), "entry: on");
if (entry) {
Check(entry->key == "a.mjs", "entry: relative key");
Check(entry->sourcePath == "/root/app/a.mjs", "entry: source path");
Check(
entry->file == tempRoot + "/cache/" +
CodeCacheFileName("a.mjs", CodeCacheKind::kEsModule),
"entry: file under the cache dir");
Check(entry->source.size == 10 && entry->source.freshnessToken == "t1",
"entry: the decided Stat");
}
}
void TestRoundTrip() {
const std::string dir = tempRoot + "/round/nested/v8";
Configure(true, dir);
const CodeCacheEntry entry =
EntryFor("/root/app/m.mjs", CodeCacheKind::kEsModule, Info(42, "100.5"));
Check(!HasFreshCodeCache(entry), "round trip: nothing before the write");
Check(!LoadCodeCache(entry), "round trip: no load before the write");
Check(Write(entry), "round trip: write creates the directories");
Check(HasFreshCodeCache(entry), "round trip: fresh after the write");
Check(LoadsPayload(entry), "round trip: the payload comes back");
Check(ReadAll(entry.file) == ValidFile(entry),
"round trip: the layout on disk");
const std::vector<uint8_t> other = {9, 9, 9};
Check(Write(entry, other), "round trip: rewrite");
Check(LoadsPayload(entry, other), "round trip: the rewrite replaced it");
Check(ListDir(dir).size() == 1, "round trip: no temporary files left");
Check(!WriteCodeCache(entry, kPayload.data(), 0),
"round trip: an empty payload is not written");
Check(!WriteCodeCache(entry, nullptr, 4), "round trip: no payload");
}
void TestStaleness() {
Configure(true, tempRoot + "/stale");
const CodeCacheEntry entry =
EntryFor("/root/app/s.js", CodeCacheKind::kClassicScript, Info(7, "t1"));
Check(Write(entry), "stale: write");
CodeCacheEntry resized = entry;
resized.source.size = 8;
Check(!HasFreshCodeCache(resized) && !LoadCodeCache(resized),
"stale: the size changed");
CodeCacheEntry retokened = entry;
retokened.source.freshnessToken = "t2";
Check(!HasFreshCodeCache(retokened) && !LoadCodeCache(retokened),
"stale: the token changed");
CodeCacheEntry longerToken = entry;
longerToken.source.freshnessToken = "t1x";
Check(!HasFreshCodeCache(longerToken), "stale: a longer token");
// Two keys whose names collide share one file; the stored key tells them
// apart, even at the same length.
CodeCacheEntry collided = entry;
collided.key = "t.js";
Check(!HasFreshCodeCache(collided) && !LoadCodeCache(collided),
"stale: another key in the same file");
CodeCacheEntry otherKind = entry;
otherKind.kind = CodeCacheKind::kEsModule;
Check(!HasFreshCodeCache(otherKind), "stale: the other kind");
Check(HasFreshCodeCache(entry) && LoadsPayload(entry),
"stale: the original still matches");
}
void TestModuleFormat() {
Configure(true, tempRoot + "/format");
const CodeCacheEntry esm =
EntryFor("/root/app/f.js", CodeCacheKind::kEsModule, Info(5, "t1"));
const CodeCacheEntry script =
EntryFor("/root/app/f.js", CodeCacheKind::kClassicScript, Info(5, "t1"));
Check(esm.format == ModuleFormat::kEsModule &&
script.format == ModuleFormat::kNone,
"format: the entry's default follows its kind");
Check(!FreshModuleFormat(esm), "format: none before a write");
Check(Write(esm), "format: write an ES module cache");
Check(FreshModuleFormat(esm) == ModuleFormat::kEsModule,
"format: an ES module cache records kEsModule");
CodeCacheEntry marker = esm;
marker.format = ModuleFormat::kCommonJs;
Check(!WriteCodeCache(marker, kPayload.data(), kPayload.size()),
"format: a CommonJS marker takes no payload");
Check(WriteCodeCache(marker, nullptr, 0), "format: write a CommonJS marker");
Check(FreshModuleFormat(esm) == ModuleFormat::kCommonJs,
"format: the marker replaced the ES module cache");
Check(!HasFreshCodeCache(esm) && !LoadCodeCache(esm),
"format: a marker is no ES module cache");
Check(HasFreshCodeCache(marker) && !LoadCodeCache(marker),
"format: a marker is fresh but has no payload");
CodeCacheEntry changed = esm;
changed.source.freshnessToken = "t2";
Check(!FreshModuleFormat(changed), "format: a stale marker records nothing");
Check(Write(script), "format: write a classic script cache");
Check(HasFreshCodeCache(script) && LoadsPayload(script),
"format: a classic script cache has no format");
}
void TestCorruption() {
Configure(true, tempRoot + "/corrupt");
const CodeCacheEntry entry =
EntryFor("/root/app/c.mjs", CodeCacheKind::kEsModule, Info(3, "tok"));
Check(Write(entry), "corrupt: write");
const std::string valid = ReadAll(entry.file);
struct Case {
const char* what;
std::string bytes;
};
std::vector<Case> cases;
cases.push_back({"corrupt: empty file", ""});
cases.push_back({"corrupt: short header", valid.substr(0, 20)});
cases.push_back(
{"corrupt: header only", valid.substr(0, kCodeCacheFixedHeaderBytes)});
cases.push_back(
{"corrupt: truncated payload", valid.substr(0, valid.size() - 1)});
cases.push_back({"corrupt: trailing byte", valid + "x"});
{
std::string bytes = valid;
bytes[0] = 'X';
cases.push_back({"corrupt: magic", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 4, kCodeCacheFormatVersion + 1);
cases.push_back({"corrupt: format version", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 12, 0xffffffffu);
cases.push_back({"corrupt: huge key length", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 24, 0xffffffffu);
cases.push_back({"corrupt: huge token length", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 28, 0xffffffffu);
cases.push_back({"corrupt: huge payload length", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 28, 0);
cases.push_back({"corrupt: zero payload length",
bytes.substr(0, bytes.size() - kPayload.size())});
}
{
std::string bytes = valid;
PutU32At(bytes, 32, static_cast<uint32_t>(ModuleFormat::kCommonJs));
cases.push_back({"corrupt: a CommonJS marker with a payload", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 32, static_cast<uint32_t>(ModuleFormat::kNone));
cases.push_back({"corrupt: an ES module cache with no format", bytes});
}
{
std::string bytes = valid;
PutU32At(bytes, 32, 7);
cases.push_back({"corrupt: an unknown format", bytes});
}
{
std::string bytes = valid;
bytes[kCodeCacheFixedHeaderBytes] ^= 1;
cases.push_back({"corrupt: key bytes", bytes});
}
{
std::string bytes = valid;
bytes[kCodeCacheFixedHeaderBytes + entry.key.size()] ^= 1;
cases.push_back({"corrupt: token bytes", bytes});
}
for (const Case& c : cases) {
WriteAll(entry.file, c.bytes);
Check(!HasFreshCodeCache(entry) && !LoadCodeCache(entry) &&
!FreshModuleFormat(entry),
c.what);
}
RemoveTree(entry.file);
mkdir(entry.file.c_str(), 0700);
Check(!HasFreshCodeCache(entry) && !LoadCodeCache(entry),
"corrupt: a directory in its place");
RemoveTree(entry.file);
WriteAll(entry.file, valid);
Check(LoadsPayload(entry), "corrupt: the valid file still loads");
}
void TestFailedWrites() {
// The cache directory's parent is a plain file.
const std::string blocker = tempRoot + "/blocker";
WriteAll(blocker, "x");
Configure(true, blocker + "/v8");
const CodeCacheEntry blocked =
EntryFor("/root/app/b.mjs", CodeCacheKind::kEsModule, Info(1, "t"));
Check(!Write(blocked), "failed write: the directory cannot be created");
// A read-only directory keeps the previous file and gains no temporary.
// Root ignores directory permissions, so this half needs a normal user.
const std::string dir = tempRoot + "/readonly";
Configure(true, dir);
const CodeCacheEntry entry =
EntryFor("/root/app/r.mjs", CodeCacheKind::kEsModule, Info(1, "t"));
Check(Write(entry), "failed write: first write");
if (geteuid() != 0) {
chmod(dir.c_str(), 0500);
Check(!Write(entry, {7, 7}), "failed write: read-only directory");
chmod(dir.c_str(), 0700);
Check(LoadsPayload(entry), "failed write: the previous file survives");
Check(ListDir(dir).size() == 1, "failed write: nothing left behind");
}
}
void TestSourceUnchanged() {
fake_platform::ClearFiles();
fake_platform::SetFile("/root/app/u.mjs", "export {}", "t1");
const FileInfo decided = *platform::Stat("/root/app/u.mjs");
Check(SourceUnchanged("/root/app/u.mjs", decided), "unchanged: same file");
fake_platform::SetFile("/root/app/u.mjs", "export {};", "t1");
Check(!SourceUnchanged("/root/app/u.mjs", decided),
"unchanged: the size changed");
fake_platform::SetFile("/root/app/u.mjs", "export {}", "t2");
Check(!SourceUnchanged("/root/app/u.mjs", decided),
"unchanged: the token changed");
fake_platform::SetFile("/root/app/u.mjs", "export {}", "t1");
Check(SourceUnchanged("/root/app/u.mjs", decided), "unchanged: same again");
fake_platform::RemoveFile("/root/app/u.mjs");
Check(!SourceUnchanged("/root/app/u.mjs", decided),
"unchanged: the file is gone");
}
bool WaitForFile(const std::string& path) {
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::seconds(10);
while (std::chrono::steady_clock::now() < deadline) {
if (access(path.c_str(), F_OK) == 0) {
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
return false;
}
void TestWriter() {
fake_platform::ClearFiles();
Configure(true, tempRoot + "/writer");
fake_platform::SetFile("/root/app/changed.mjs", "aaaa", "t1");
fake_platform::SetFile("/root/app/kept.mjs", "bbbb", "t1");
const CodeCacheEntry changed = EntryFor(
"/root/app/changed.mjs", CodeCacheKind::kEsModule, Info(4, "t1"));
const CodeCacheEntry kept =
EntryFor("/root/app/kept.mjs", CodeCacheKind::kEsModule, Info(4, "t1"));
// Changed after it was read: the writer must skip it.
fake_platform::SetFile("/root/app/changed.mjs", "aaaa", "t2");
const int runJobsBefore = fake_platform::runJobCalls;
for (const CodeCacheEntry* entry : {&changed, &kept}) {
std::unique_ptr<uint8_t[]> payload(new uint8_t[kPayload.size()]);
std::memcpy(payload.get(), kPayload.data(), kPayload.size());
PostCodeCacheWrite(*entry, std::move(payload), kPayload.size());
}
// One serial thread: once the second file exists, the first job is done.
Check(WaitForFile(kept.file), "writer: writes an unchanged source");
Check(LoadsPayload(kept), "writer: the written cache loads");
Check(access(changed.file.c_str(), F_OK) != 0,
"writer: skips a source that changed");
Check(fake_platform::runJobCalls - runJobsBefore >= 1,
"writer: jobs run through platform::RunJob");
Check(fake_platform::threadPriorityCalls >= 1,
"writer: the thread applies its priority");
}
} // namespace
int main() {
tempRoot = MakeTempDir();
TestNaming();
TestEntryFor();
TestRoundTrip();
TestStaleness();
TestModuleFormat();
TestCorruption();
TestFailedWrites();
TestSourceUnchanged();
TestWriter();
RemoveTree(tempRoot);
if (failures != 0) {
std::fprintf(stderr, "%d failure(s)\n", failures);
return 1;
}
std::printf("CodeCacheTest: ok\n");
return 0;
}