Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "ScriptPreloader-inl.h"
8
#include "mozilla/ScriptPreloader.h"
9
#include "mozilla/loader/ScriptCacheActors.h"
10
11
#include "mozilla/URLPreloader.h"
12
13
#include "mozilla/ArrayUtils.h"
14
#include "mozilla/ClearOnShutdown.h"
15
#include "mozilla/Components.h"
16
#include "mozilla/FileUtils.h"
17
#include "mozilla/Logging.h"
18
#include "mozilla/ScopeExit.h"
19
#include "mozilla/Services.h"
20
#include "mozilla/Telemetry.h"
21
#include "mozilla/Unused.h"
22
#include "mozilla/dom/ContentChild.h"
23
#include "mozilla/dom/ContentParent.h"
24
25
#include "MainThreadUtils.h"
26
#include "nsDebug.h"
27
#include "nsDirectoryServiceUtils.h"
28
#include "nsIFile.h"
29
#include "nsIObserverService.h"
30
#include "nsJSUtils.h"
31
#include "nsMemoryReporterManager.h"
32
#include "nsNetUtil.h"
33
#include "nsProxyRelease.h"
34
#include "nsThreadUtils.h"
35
#include "nsXULAppAPI.h"
36
#include "xpcpublic.h"
37
38
#define STARTUP_COMPLETE_TOPIC "browser-delayed-startup-finished"
39
#define DOC_ELEM_INSERTED_TOPIC "document-element-inserted"
40
#define CONTENT_DOCUMENT_LOADED_TOPIC "content-document-loaded"
41
#define CACHE_WRITE_TOPIC "browser-idle-startup-tasks-finished"
42
#define CLEANUP_TOPIC "xpcom-shutdown"
43
#define CACHE_INVALIDATE_TOPIC "startupcache-invalidate"
44
45
// The maximum time we'll wait for a child process to finish starting up before
46
// we send its script data back to the parent.
47
constexpr uint32_t CHILD_STARTUP_TIMEOUT_MS = 8000;
48
49
namespace mozilla {
50
namespace {
51
static LazyLogModule gLog("ScriptPreloader");
52
53
#define LOG(level, ...) MOZ_LOG(gLog, LogLevel::level, (__VA_ARGS__))
54
} // namespace
55
56
using mozilla::dom::AutoJSAPI;
57
using mozilla::dom::ContentChild;
58
using mozilla::dom::ContentParent;
59
using namespace mozilla::loader;
60
61
ProcessType ScriptPreloader::sProcessType;
62
63
nsresult ScriptPreloader::CollectReports(nsIHandleReportCallback* aHandleReport,
64
nsISupports* aData, bool aAnonymize) {
65
MOZ_COLLECT_REPORT(
66
"explicit/script-preloader/heap/saved-scripts", KIND_HEAP, UNITS_BYTES,
67
SizeOfHashEntries<ScriptStatus::Saved>(mScripts, MallocSizeOf),
68
"Memory used to hold the scripts which have been executed in this "
69
"session, and will be written to the startup script cache file.");
70
71
MOZ_COLLECT_REPORT(
72
"explicit/script-preloader/heap/restored-scripts", KIND_HEAP, UNITS_BYTES,
73
SizeOfHashEntries<ScriptStatus::Restored>(mScripts, MallocSizeOf),
74
"Memory used to hold the scripts which have been restored from the "
75
"startup script cache file, but have not been executed in this session.");
76
77
MOZ_COLLECT_REPORT("explicit/script-preloader/heap/other", KIND_HEAP,
78
UNITS_BYTES, ShallowHeapSizeOfIncludingThis(MallocSizeOf),
79
"Memory used by the script cache service itself.");
80
81
// Since the mem-mapped cache file is mapped into memory, we want to report
82
// it as explicit memory somewhere. But since the child cache is shared
83
// between all processes, we don't want to report it as explicit memory for
84
// all of them. So we report it as explicit only in the parent process, and
85
// non-explicit everywhere else.
86
if (XRE_IsParentProcess()) {
87
MOZ_COLLECT_REPORT("explicit/script-preloader/non-heap/memmapped-cache",
88
KIND_NONHEAP, UNITS_BYTES,
89
mCacheData.nonHeapSizeOfExcludingThis(),
90
"The memory-mapped startup script cache file.");
91
} else {
92
MOZ_COLLECT_REPORT("script-preloader-memmapped-cache", KIND_NONHEAP,
93
UNITS_BYTES, mCacheData.nonHeapSizeOfExcludingThis(),
94
"The memory-mapped startup script cache file.");
95
}
96
97
return NS_OK;
98
}
99
100
ScriptPreloader& ScriptPreloader::GetSingleton() {
101
static RefPtr<ScriptPreloader> singleton;
102
103
if (!singleton) {
104
if (XRE_IsParentProcess()) {
105
singleton = new ScriptPreloader();
106
singleton->mChildCache = &GetChildSingleton();
107
Unused << singleton->InitCache();
108
} else {
109
singleton = &GetChildSingleton();
110
}
111
112
ClearOnShutdown(&singleton);
113
}
114
115
return *singleton;
116
}
117
118
// The child singleton is available in all processes, including the parent, and
119
// is used for scripts which are expected to be loaded into child processes
120
// (such as process and frame scripts), or scripts that have already been loaded
121
// into a child. The child caches are managed as follows:
122
//
123
// - Every startup, we open the cache file from the last session, move it to a
124
// new location, and begin pre-loading the scripts that are stored in it. There
125
// is a separate cache file for parent and content processes, but the parent
126
// process opens both the parent and content cache files.
127
//
128
// - Once startup is complete, we write a new cache file for the next session,
129
// containing only the scripts that were used during early startup, so we
130
// don't waste pre-loading scripts that may not be needed.
131
//
132
// - For content processes, opening and writing the cache file is handled in the
133
// parent process. The first content process of each type sends back the data
134
// for scripts that were loaded in early startup, and the parent merges them
135
// and writes them to a cache file.
136
//
137
// - Currently, content processes only benefit from the cache data written
138
// during the *previous* session. Ideally, new content processes should
139
// probably use the cache data written during this session if there was no
140
// previous cache file, but I'd rather do that as a follow-up.
141
ScriptPreloader& ScriptPreloader::GetChildSingleton() {
142
static RefPtr<ScriptPreloader> singleton;
143
144
if (!singleton) {
145
singleton = new ScriptPreloader();
146
if (XRE_IsParentProcess()) {
147
Unused << singleton->InitCache(NS_LITERAL_STRING("scriptCache-child"));
148
}
149
ClearOnShutdown(&singleton);
150
}
151
152
return *singleton;
153
}
154
155
void ScriptPreloader::InitContentChild(ContentParent& parent) {
156
auto& cache = GetChildSingleton();
157
158
// We want startup script data from the first process of a given type.
159
// That process sends back its script data before it executes any
160
// untrusted code, and then we never accept further script data for that
161
// type of process for the rest of the session.
162
//
163
// The script data from each process type is merged with the data from the
164
// parent process's frame and process scripts, and shared between all
165
// content process types in the next session.
166
//
167
// Note that if the first process of a given type crashes or shuts down
168
// before sending us its script data, we silently ignore it, and data for
169
// that process type is not included in the next session's cache. This
170
// should be a sufficiently rare occurrence that it's not worth trying to
171
// handle specially.
172
auto processType = GetChildProcessType(parent.GetRemoteType());
173
bool wantScriptData = !cache.mInitializedProcesses.contains(processType);
174
cache.mInitializedProcesses += processType;
175
176
auto fd = cache.mCacheData.cloneFileDescriptor();
177
// Don't send original cache data to new processes if the cache has been
178
// invalidated.
179
if (fd.IsValid() && !cache.mCacheInvalidated) {
180
Unused << parent.SendPScriptCacheConstructor(fd, wantScriptData);
181
} else {
182
Unused << parent.SendPScriptCacheConstructor(NS_ERROR_FILE_NOT_FOUND,
183
wantScriptData);
184
}
185
}
186
187
ProcessType ScriptPreloader::GetChildProcessType(const nsAString& remoteType) {
188
if (remoteType.EqualsLiteral(EXTENSION_REMOTE_TYPE)) {
189
return ProcessType::Extension;
190
}
191
if (remoteType.EqualsLiteral(PRIVILEGEDABOUT_REMOTE_TYPE)) {
192
return ProcessType::PrivilegedAbout;
193
}
194
return ProcessType::Web;
195
}
196
197
namespace {
198
199
static void TraceOp(JSTracer* trc, void* data) {
200
auto preloader = static_cast<ScriptPreloader*>(data);
201
202
preloader->Trace(trc);
203
}
204
205
} // anonymous namespace
206
207
void ScriptPreloader::Trace(JSTracer* trc) {
208
for (auto& script : IterHash(mScripts)) {
209
JS::TraceEdge(trc, &script->mScript,
210
"ScriptPreloader::CachedScript.mScript");
211
}
212
}
213
214
ScriptPreloader::ScriptPreloader()
215
: mMonitor("[ScriptPreloader.mMonitor]"),
216
mSaveMonitor("[ScriptPreloader.mSaveMonitor]") {
217
// We do not set the process type for child processes here because the
218
// remoteType in ContentChild is not ready yet.
219
if (XRE_IsParentProcess()) {
220
sProcessType = ProcessType::Parent;
221
}
222
223
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
224
MOZ_RELEASE_ASSERT(obs);
225
226
if (XRE_IsParentProcess()) {
227
// In the parent process, we want to freeze the script cache as soon
228
// as idle tasks for the first browser window have completed.
229
obs->AddObserver(this, STARTUP_COMPLETE_TOPIC, false);
230
obs->AddObserver(this, CACHE_WRITE_TOPIC, false);
231
}
232
233
obs->AddObserver(this, CLEANUP_TOPIC, false);
234
obs->AddObserver(this, CACHE_INVALIDATE_TOPIC, false);
235
236
AutoSafeJSAPI jsapi;
237
JS_AddExtraGCRootsTracer(jsapi.cx(), TraceOp, this);
238
}
239
240
void ScriptPreloader::Cleanup() {
241
// Wait for any pending parses to finish before clearing the mScripts
242
// hashtable, since the parse tasks depend on memory allocated by those
243
// scripts.
244
{
245
MonitorAutoLock mal(mMonitor);
246
FinishPendingParses(mal);
247
248
mScripts.Clear();
249
}
250
251
AutoSafeJSAPI jsapi;
252
JS_RemoveExtraGCRootsTracer(jsapi.cx(), TraceOp, this);
253
254
UnregisterWeakMemoryReporter(this);
255
}
256
257
void ScriptPreloader::StartCacheWrite() {
258
MOZ_ASSERT(!mSaveThread);
259
260
Unused << NS_NewNamedThread("SaveScripts", getter_AddRefs(mSaveThread), this);
261
262
nsCOMPtr<nsIAsyncShutdownClient> barrier = GetShutdownBarrier();
263
barrier->AddBlocker(this, NS_LITERAL_STRING(__FILE__), __LINE__,
264
EmptyString());
265
}
266
267
void ScriptPreloader::InvalidateCache() {
268
mMonitor.AssertNotCurrentThreadOwns();
269
MonitorAutoLock mal(mMonitor);
270
271
mCacheInvalidated = true;
272
273
// Wait for pending off-thread parses to finish, since they depend on the
274
// memory allocated by our CachedScripts, and can't be canceled
275
// asynchronously.
276
FinishPendingParses(mal);
277
278
// Pending scripts should have been cleared by the above, and new parses
279
// should not have been queued.
280
MOZ_ASSERT(mParsingScripts.empty());
281
MOZ_ASSERT(mParsingSources.empty());
282
MOZ_ASSERT(mPendingScripts.isEmpty());
283
284
for (auto& script : IterHash(mScripts)) {
285
script.Remove();
286
}
287
288
// If we've already finished saving the cache at this point, start a new
289
// delayed save operation. This will write out an empty cache file in place
290
// of any cache file we've already written out this session, which will
291
// prevent us from falling back to the current session's cache file on the
292
// next startup.
293
if (mSaveComplete && mChildCache) {
294
mSaveComplete = false;
295
296
StartCacheWrite();
297
}
298
}
299
300
nsresult ScriptPreloader::Observe(nsISupports* subject, const char* topic,
301
const char16_t* data) {
302
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
303
if (!strcmp(topic, STARTUP_COMPLETE_TOPIC)) {
304
obs->RemoveObserver(this, STARTUP_COMPLETE_TOPIC);
305
306
MOZ_ASSERT(XRE_IsParentProcess());
307
308
mStartupFinished = true;
309
} else if (!strcmp(topic, CACHE_WRITE_TOPIC)) {
310
obs->RemoveObserver(this, CACHE_WRITE_TOPIC);
311
312
MOZ_ASSERT(mStartupFinished);
313
MOZ_ASSERT(XRE_IsParentProcess());
314
315
if (mChildCache) {
316
StartCacheWrite();
317
}
318
} else if (mContentStartupFinishedTopic.Equals(topic)) {
319
// If this is an uninitialized about:blank viewer or a chrome: document
320
// (which should always be an XBL binding document), ignore it. We don't
321
// have to worry about it loading malicious content.
322
if (nsCOMPtr<dom::Document> doc = do_QueryInterface(subject)) {
323
nsCOMPtr<nsIURI> uri = doc->GetDocumentURI();
324
325
if ((NS_IsAboutBlank(uri) &&
326
doc->GetReadyStateEnum() == doc->READYSTATE_UNINITIALIZED) ||
327
uri->SchemeIs("chrome")) {
328
return NS_OK;
329
}
330
}
331
FinishContentStartup();
332
} else if (!strcmp(topic, "timer-callback")) {
333
FinishContentStartup();
334
} else if (!strcmp(topic, CLEANUP_TOPIC)) {
335
Cleanup();
336
} else if (!strcmp(topic, CACHE_INVALIDATE_TOPIC)) {
337
InvalidateCache();
338
}
339
340
return NS_OK;
341
}
342
343
void ScriptPreloader::FinishContentStartup() {
344
MOZ_ASSERT(XRE_IsContentProcess());
345
346
#ifdef DEBUG
347
if (mContentStartupFinishedTopic.Equals(CONTENT_DOCUMENT_LOADED_TOPIC)) {
348
MOZ_ASSERT(sProcessType == ProcessType::PrivilegedAbout);
349
} else {
350
MOZ_ASSERT(sProcessType != ProcessType::PrivilegedAbout);
351
}
352
#endif /* DEBUG */
353
354
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
355
obs->RemoveObserver(this, mContentStartupFinishedTopic.get());
356
357
mSaveTimer = nullptr;
358
359
mStartupFinished = true;
360
361
if (mChildActor) {
362
mChildActor->SendScriptsAndFinalize(mScripts);
363
}
364
365
#ifdef XP_WIN
366
// Record the amount of USS at startup. This is Windows-only for now,
367
// we could turn it on for Linux relatively cheaply. On macOS it can have
368
// a perf impact.
369
mozilla::Telemetry::Accumulate(
370
mozilla::Telemetry::MEMORY_UNIQUE_CONTENT_STARTUP,
371
nsMemoryReporterManager::ResidentUnique() / 1024);
372
#endif
373
}
374
375
bool ScriptPreloader::WillWriteScripts() {
376
return Active() && (XRE_IsParentProcess() || mChildActor);
377
}
378
379
Result<nsCOMPtr<nsIFile>, nsresult> ScriptPreloader::GetCacheFile(
380
const nsAString& suffix) {
381
NS_ENSURE_TRUE(mProfD, Err(NS_ERROR_NOT_INITIALIZED));
382
383
nsCOMPtr<nsIFile> cacheFile;
384
MOZ_TRY(mProfD->Clone(getter_AddRefs(cacheFile)));
385
386
MOZ_TRY(cacheFile->AppendNative(NS_LITERAL_CSTRING("startupCache")));
387
Unused << cacheFile->Create(nsIFile::DIRECTORY_TYPE, 0777);
388
389
MOZ_TRY(cacheFile->Append(mBaseName + suffix));
390
391
return std::move(cacheFile);
392
}
393
394
static const uint8_t MAGIC[] = "mozXDRcachev002";
395
396
Result<Ok, nsresult> ScriptPreloader::OpenCache() {
397
MOZ_TRY(NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(mProfD)));
398
399
nsCOMPtr<nsIFile> cacheFile;
400
MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING(".bin")));
401
402
bool exists;
403
MOZ_TRY(cacheFile->Exists(&exists));
404
if (exists) {
405
MOZ_TRY(cacheFile->MoveTo(nullptr,
406
mBaseName + NS_LITERAL_STRING("-current.bin")));
407
} else {
408
MOZ_TRY(
409
cacheFile->SetLeafName(mBaseName + NS_LITERAL_STRING("-current.bin")));
410
MOZ_TRY(cacheFile->Exists(&exists));
411
if (!exists) {
412
return Err(NS_ERROR_FILE_NOT_FOUND);
413
}
414
}
415
416
MOZ_TRY(mCacheData.init(cacheFile));
417
418
return Ok();
419
}
420
421
// Opens the script cache file for this session, and initializes the script
422
// cache based on its contents. See WriteCache for details of the cache file.
423
Result<Ok, nsresult> ScriptPreloader::InitCache(const nsAString& basePath) {
424
mCacheInitialized = true;
425
mBaseName = basePath;
426
427
RegisterWeakMemoryReporter(this);
428
429
if (!XRE_IsParentProcess()) {
430
return Ok();
431
}
432
433
// Grab the compilation scope before initializing the URLPreloader, since
434
// it's not safe to run component loader code during its critical section.
435
AutoSafeJSAPI jsapi;
436
JS::RootedObject scope(jsapi.cx(), xpc::CompilationScope());
437
438
// Note: Code on the main thread *must not access Omnijar in any way* until
439
// this AutoBeginReading guard is destroyed.
440
URLPreloader::AutoBeginReading abr;
441
442
MOZ_TRY(OpenCache());
443
444
return InitCacheInternal(scope);
445
}
446
447
Result<Ok, nsresult> ScriptPreloader::InitCache(
448
const Maybe<ipc::FileDescriptor>& cacheFile, ScriptCacheChild* cacheChild) {
449
MOZ_ASSERT(XRE_IsContentProcess());
450
451
mCacheInitialized = true;
452
mChildActor = cacheChild;
453
sProcessType =
454
GetChildProcessType(dom::ContentChild::GetSingleton()->GetRemoteType());
455
456
nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
457
MOZ_RELEASE_ASSERT(obs);
458
459
if (sProcessType == ProcessType::PrivilegedAbout) {
460
// Since we control all of the documents loaded in the privileged
461
// content process, we can increase the window of active time for the
462
// ScriptPreloader to include the scripts that are loaded until the
463
// first document finishes loading.
464
mContentStartupFinishedTopic.AssignLiteral(CONTENT_DOCUMENT_LOADED_TOPIC);
465
} else {
466
// In the child process, we need to freeze the script cache before any
467
// untrusted code has been executed. The insertion of the first DOM
468
// document element may sometimes be earlier than is ideal, but at
469
// least it should always be safe.
470
mContentStartupFinishedTopic.AssignLiteral(DOC_ELEM_INSERTED_TOPIC);
471
}
472
obs->AddObserver(this, mContentStartupFinishedTopic.get(), false);
473
474
RegisterWeakMemoryReporter(this);
475
476
auto cleanup = MakeScopeExit([&] {
477
// If the parent is expecting cache data from us, make sure we send it
478
// before it writes out its cache file. For normal proceses, this isn't
479
// a concern, since they begin loading documents quite early. For the
480
// preloaded process, we may end up waiting a long time (or, indeed,
481
// never loading a document), so we need an additional timeout.
482
if (cacheChild) {
483
NS_NewTimerWithObserver(getter_AddRefs(mSaveTimer), this,
484
CHILD_STARTUP_TIMEOUT_MS,
485
nsITimer::TYPE_ONE_SHOT);
486
}
487
});
488
489
if (cacheFile.isNothing()) {
490
return Ok();
491
}
492
493
MOZ_TRY(mCacheData.init(cacheFile.ref()));
494
495
return InitCacheInternal();
496
}
497
498
Result<Ok, nsresult> ScriptPreloader::InitCacheInternal(
499
JS::HandleObject scope) {
500
auto size = mCacheData.size();
501
502
uint32_t headerSize;
503
if (size < sizeof(MAGIC) + sizeof(headerSize)) {
504
return Err(NS_ERROR_UNEXPECTED);
505
}
506
507
auto data = mCacheData.get<uint8_t>();
508
auto end = data + size;
509
510
if (memcmp(MAGIC, data.get(), sizeof(MAGIC))) {
511
return Err(NS_ERROR_UNEXPECTED);
512
}
513
data += sizeof(MAGIC);
514
515
headerSize = LittleEndian::readUint32(data.get());
516
data += sizeof(headerSize);
517
518
if (data + headerSize > end) {
519
return Err(NS_ERROR_UNEXPECTED);
520
}
521
522
{
523
auto cleanup = MakeScopeExit([&]() { mScripts.Clear(); });
524
525
LinkedList<CachedScript> scripts;
526
527
Range<uint8_t> header(data, data + headerSize);
528
data += headerSize;
529
530
InputBuffer buf(header);
531
532
size_t offset = 0;
533
while (!buf.finished()) {
534
auto script = MakeUnique<CachedScript>(*this, buf);
535
MOZ_RELEASE_ASSERT(script);
536
537
auto scriptData = data + script->mOffset;
538
if (scriptData + script->mSize > end) {
539
return Err(NS_ERROR_UNEXPECTED);
540
}
541
542
// Make sure offsets match what we'd expect based on script ordering and
543
// size, as a basic sanity check.
544
if (script->mOffset != offset) {
545
return Err(NS_ERROR_UNEXPECTED);
546
}
547
offset += script->mSize;
548
549
script->mXDRRange.emplace(scriptData, scriptData + script->mSize);
550
551
// Don't pre-decode the script unless it was used in this process type
552
// during the previous session.
553
if (script->mOriginalProcessTypes.contains(CurrentProcessType())) {
554
scripts.insertBack(script.get());
555
} else {
556
script->mReadyToExecute = true;
557
}
558
559
mScripts.Put(script->mCachePath, script.get());
560
Unused << script.release();
561
}
562
563
if (buf.error()) {
564
return Err(NS_ERROR_UNEXPECTED);
565
}
566
567
mPendingScripts = std::move(scripts);
568
cleanup.release();
569
}
570
571
DecodeNextBatch(OFF_THREAD_FIRST_CHUNK_SIZE, scope);
572
return Ok();
573
}
574
575
void ScriptPreloader::PrepareCacheWriteInternal() {
576
MOZ_ASSERT(NS_IsMainThread());
577
578
mMonitor.AssertCurrentThreadOwns();
579
580
auto cleanup = MakeScopeExit([&]() {
581
if (mChildCache) {
582
mChildCache->PrepareCacheWrite();
583
}
584
});
585
586
if (mDataPrepared) {
587
return;
588
}
589
590
AutoSafeJSAPI jsapi;
591
bool found = false;
592
for (auto& script : IterHash(mScripts, Match<ScriptStatus::Saved>())) {
593
// Don't write any scripts that are also in the child cache. They'll be
594
// loaded from the child cache in that case, so there's no need to write
595
// them twice.
596
CachedScript* childScript =
597
mChildCache ? mChildCache->mScripts.Get(script->mCachePath) : nullptr;
598
if (childScript && !childScript->mProcessTypes.isEmpty()) {
599
childScript->UpdateLoadTime(script->mLoadTime);
600
childScript->mProcessTypes += script->mProcessTypes;
601
script.Remove();
602
continue;
603
}
604
605
if (!(script->mProcessTypes == script->mOriginalProcessTypes)) {
606
// Note: EnumSet doesn't support operator!=, hence the weird form above.
607
found = true;
608
}
609
610
if (!script->mSize && !script->XDREncode(jsapi.cx())) {
611
script.Remove();
612
}
613
}
614
615
if (!found) {
616
mSaveComplete = true;
617
return;
618
}
619
620
mDataPrepared = true;
621
}
622
623
void ScriptPreloader::PrepareCacheWrite() {
624
MonitorAutoLock mal(mMonitor);
625
626
PrepareCacheWriteInternal();
627
}
628
629
// Writes out a script cache file for the scripts accessed during early
630
// startup in this session. The cache file is a little-endian binary file with
631
// the following format:
632
//
633
// - A uint32 containing the size of the header block.
634
//
635
// - A header entry for each file stored in the cache containing:
636
// - The URL that the script was originally read from.
637
// - Its cache key.
638
// - The offset of its XDR data within the XDR data block.
639
// - The size of its XDR data in the XDR data block.
640
// - A bit field describing which process types the script is used in.
641
//
642
// - A block of XDR data for the encoded scripts, with each script's data at
643
// an offset from the start of the block, as specified above.
644
Result<Ok, nsresult> ScriptPreloader::WriteCache() {
645
MOZ_ASSERT(!NS_IsMainThread());
646
647
if (!mDataPrepared && !mSaveComplete) {
648
MonitorAutoUnlock mau(mSaveMonitor);
649
650
NS_DispatchToMainThread(
651
NewRunnableMethod("ScriptPreloader::PrepareCacheWrite", this,
652
&ScriptPreloader::PrepareCacheWrite),
653
NS_DISPATCH_SYNC);
654
}
655
656
if (mSaveComplete) {
657
// If we don't have anything we need to save, we're done.
658
return Ok();
659
}
660
661
nsCOMPtr<nsIFile> cacheFile;
662
MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING("-new.bin")));
663
664
bool exists;
665
MOZ_TRY(cacheFile->Exists(&exists));
666
if (exists) {
667
MOZ_TRY(cacheFile->Remove(false));
668
}
669
670
{
671
AutoFDClose fd;
672
MOZ_TRY(cacheFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE, 0644,
673
&fd.rwget()));
674
675
// We also need to hold mMonitor while we're touching scripts in
676
// mScripts, or they may be freed before we're done with them.
677
mMonitor.AssertNotCurrentThreadOwns();
678
MonitorAutoLock mal(mMonitor);
679
680
nsTArray<CachedScript*> scripts;
681
for (auto& script : IterHash(mScripts, Match<ScriptStatus::Saved>())) {
682
scripts.AppendElement(script);
683
}
684
685
// Sort scripts by load time, with async loaded scripts before sync scripts.
686
// Since async scripts are always loaded immediately at startup, it helps to
687
// have them stored contiguously.
688
scripts.Sort(CachedScript::Comparator());
689
690
OutputBuffer buf;
691
size_t offset = 0;
692
for (auto script : scripts) {
693
script->mOffset = offset;
694
script->Code(buf);
695
696
offset += script->mSize;
697
}
698
699
uint8_t headerSize[4];
700
LittleEndian::writeUint32(headerSize, buf.cursor());
701
702
MOZ_TRY(Write(fd, MAGIC, sizeof(MAGIC)));
703
MOZ_TRY(Write(fd, headerSize, sizeof(headerSize)));
704
MOZ_TRY(Write(fd, buf.Get(), buf.cursor()));
705
for (auto script : scripts) {
706
MOZ_TRY(Write(fd, script->Range().begin().get(), script->mSize));
707
708
if (script->mScript) {
709
script->FreeData();
710
}
711
}
712
}
713
714
MOZ_TRY(cacheFile->MoveTo(nullptr, mBaseName + NS_LITERAL_STRING(".bin")));
715
716
return Ok();
717
}
718
719
// Runs in the mSaveThread thread, and writes out the cache file for the next
720
// session after a reasonable delay.
721
nsresult ScriptPreloader::Run() {
722
MonitorAutoLock mal(mSaveMonitor);
723
724
// Ideally wait about 10 seconds before saving, to avoid unnecessary IO
725
// during early startup. But only if the cache hasn't been invalidated,
726
// since that can trigger a new write during shutdown, and we don't want to
727
// cause shutdown hangs.
728
if (!mCacheInvalidated) {
729
mal.Wait(TimeDuration::FromSeconds(10));
730
}
731
732
auto result = URLPreloader::GetSingleton().WriteCache();
733
Unused << NS_WARN_IF(result.isErr());
734
735
result = WriteCache();
736
Unused << NS_WARN_IF(result.isErr());
737
738
result = mChildCache->WriteCache();
739
Unused << NS_WARN_IF(result.isErr());
740
741
NS_DispatchToMainThread(
742
NewRunnableMethod("ScriptPreloader::CacheWriteComplete", this,
743
&ScriptPreloader::CacheWriteComplete),
744
NS_DISPATCH_NORMAL);
745
return NS_OK;
746
}
747
748
void ScriptPreloader::CacheWriteComplete() {
749
mSaveThread->AsyncShutdown();
750
mSaveThread = nullptr;
751
mSaveComplete = true;
752
753
nsCOMPtr<nsIAsyncShutdownClient> barrier = GetShutdownBarrier();
754
barrier->RemoveBlocker(this);
755
}
756
757
void ScriptPreloader::NoteScript(const nsCString& url,
758
const nsCString& cachePath,
759
JS::HandleScript jsscript, bool isRunOnce) {
760
if (!Active()) {
761
if (isRunOnce) {
762
if (auto script = mScripts.Get(cachePath)) {
763
script->mIsRunOnce = true;
764
script->MaybeDropScript();
765
}
766
}
767
return;
768
}
769
770
// Don't bother trying to cache any URLs with cache-busting query
771
// parameters.
772
if (cachePath.FindChar('?') >= 0) {
773
return;
774
}
775
776
// Don't bother caching files that belong to the mochitest harness.
777
NS_NAMED_LITERAL_CSTRING(mochikitPrefix, "chrome://mochikit/");
778
if (StringHead(url, mochikitPrefix.Length()) == mochikitPrefix) {
779
return;
780
}
781
782
auto script =
783
mScripts.LookupOrAdd(cachePath, *this, url, cachePath, jsscript);
784
if (isRunOnce) {
785
script->mIsRunOnce = true;
786
}
787
788
if (!script->MaybeDropScript() && !script->mScript) {
789
MOZ_ASSERT(jsscript);
790
script->mScript = jsscript;
791
script->mReadyToExecute = true;
792
}
793
794
script->UpdateLoadTime(TimeStamp::Now());
795
script->mProcessTypes += CurrentProcessType();
796
}
797
798
void ScriptPreloader::NoteScript(const nsCString& url,
799
const nsCString& cachePath,
800
ProcessType processType,
801
nsTArray<uint8_t>&& xdrData,
802
TimeStamp loadTime) {
803
// After data has been prepared, there's no point in noting further scripts,
804
// since the cache either has already been written, or is about to be
805
// written. Any time prior to the data being prepared, we can safely mutate
806
// mScripts without locking. After that point, the save thread is free to
807
// access it, and we can't alter it without locking.
808
if (mDataPrepared) {
809
return;
810
}
811
812
auto script = mScripts.LookupOrAdd(cachePath, *this, url, cachePath, nullptr);
813
814
if (!script->HasRange()) {
815
MOZ_ASSERT(!script->HasArray());
816
817
script->mSize = xdrData.Length();
818
script->mXDRData.construct<nsTArray<uint8_t>>(
819
std::forward<nsTArray<uint8_t>>(xdrData));
820
821
auto& data = script->Array();
822
script->mXDRRange.emplace(data.Elements(), data.Length());
823
}
824
825
if (!script->mSize && !script->mScript) {
826
// If the content process is sending us a script entry for a script
827
// which was in the cache at startup, it expects us to already have this
828
// script data, so it doesn't send it.
829
//
830
// However, the cache may have been invalidated at this point (usually
831
// due to the add-on manager installing or uninstalling a legacy
832
// extension during very early startup), which means we may no longer
833
// have an entry for this script. Since that means we have no data to
834
// write to the new cache, and no JSScript to generate it from, we need
835
// to discard this entry.
836
mScripts.Remove(cachePath);
837
return;
838
}
839
840
script->UpdateLoadTime(loadTime);
841
script->mProcessTypes += processType;
842
}
843
844
JSScript* ScriptPreloader::GetCachedScript(JSContext* cx,
845
const nsCString& path) {
846
// If a script is used by both the parent and the child, it's stored only
847
// in the child cache.
848
if (mChildCache) {
849
RootedScript script(cx, mChildCache->GetCachedScriptInternal(cx, path));
850
if (script) {
851
Telemetry::AccumulateCategorical(
852
Telemetry::LABELS_SCRIPT_PRELOADER_REQUESTS::HitChild);
853
return script;
854
}
855
}
856
857
RootedScript script(cx, GetCachedScriptInternal(cx, path));
858
Telemetry::AccumulateCategorical(
859
script ? Telemetry::LABELS_SCRIPT_PRELOADER_REQUESTS::Hit
860
: Telemetry::LABELS_SCRIPT_PRELOADER_REQUESTS::Miss);
861
return script;
862
}
863
864
JSScript* ScriptPreloader::GetCachedScriptInternal(JSContext* cx,
865
const nsCString& path) {
866
auto script = mScripts.Get(path);
867
if (script) {
868
return WaitForCachedScript(cx, script);
869
}
870
871
return nullptr;
872
}
873
874
JSScript* ScriptPreloader::WaitForCachedScript(JSContext* cx,
875
CachedScript* script) {
876
// Check for finished operations before locking so that we can move onto
877
// decoding the next batch as soon as possible after the pending batch is
878
// ready. If we wait until we hit an unfinished script, we wind up having at
879
// most one batch of buffered scripts, and occasionally under-running that
880
// buffer.
881
MaybeFinishOffThreadDecode();
882
883
if (!script->mReadyToExecute) {
884
LOG(Info, "Must wait for async script load: %s\n", script->mURL.get());
885
auto start = TimeStamp::Now();
886
887
mMonitor.AssertNotCurrentThreadOwns();
888
MonitorAutoLock mal(mMonitor);
889
890
// Check for finished operations again *after* locking, or we may race
891
// against mToken being set between our last check and the time we
892
// entered the mutex.
893
MaybeFinishOffThreadDecode();
894
895
if (!script->mReadyToExecute &&
896
script->mSize < MAX_MAINTHREAD_DECODE_SIZE) {
897
LOG(Info, "Script is small enough to recompile on main thread\n");
898
899
script->mReadyToExecute = true;
900
Telemetry::ScalarAdd(
901
Telemetry::ScalarID::SCRIPT_PRELOADER_MAINTHREAD_RECOMPILE, 1);
902
} else {
903
while (!script->mReadyToExecute) {
904
mal.Wait();
905
906
MonitorAutoUnlock mau(mMonitor);
907
MaybeFinishOffThreadDecode();
908
}
909
}
910
911
double waitedMS = (TimeStamp::Now() - start).ToMilliseconds();
912
Telemetry::Accumulate(Telemetry::SCRIPT_PRELOADER_WAIT_TIME, int(waitedMS));
913
LOG(Debug, "Waited %fms\n", waitedMS);
914
}
915
916
return script->GetJSScript(cx);
917
}
918
919
/* static */
920
void ScriptPreloader::OffThreadDecodeCallback(JS::OffThreadToken* token,
921
void* context) {
922
auto cache = static_cast<ScriptPreloader*>(context);
923
924
cache->mMonitor.AssertNotCurrentThreadOwns();
925
MonitorAutoLock mal(cache->mMonitor);
926
927
// First notify any tasks that are already waiting on scripts, since they'll
928
// be blocking the main thread, and prevent any runnables from executing.
929
cache->mToken = token;
930
mal.NotifyAll();
931
932
// If nothing processed the token, and we don't already have a pending
933
// runnable, then dispatch a new one to finish the processing on the main
934
// thread as soon as possible.
935
if (cache->mToken && !cache->mFinishDecodeRunnablePending) {
936
cache->mFinishDecodeRunnablePending = true;
937
NS_DispatchToMainThread(
938
NewRunnableMethod("ScriptPreloader::DoFinishOffThreadDecode", cache,
939
&ScriptPreloader::DoFinishOffThreadDecode));
940
}
941
}
942
943
void ScriptPreloader::FinishPendingParses(MonitorAutoLock& aMal) {
944
mMonitor.AssertCurrentThreadOwns();
945
946
mPendingScripts.clear();
947
948
MaybeFinishOffThreadDecode();
949
950
// Loop until all pending decode operations finish.
951
while (!mParsingScripts.empty()) {
952
aMal.Wait();
953
MaybeFinishOffThreadDecode();
954
}
955
}
956
957
void ScriptPreloader::DoFinishOffThreadDecode() {
958
mFinishDecodeRunnablePending = false;
959
MaybeFinishOffThreadDecode();
960
}
961
962
void ScriptPreloader::MaybeFinishOffThreadDecode() {
963
if (!mToken) {
964
return;
965
}
966
967
auto cleanup = MakeScopeExit([&]() {
968
mToken = nullptr;
969
mParsingSources.clear();
970
mParsingScripts.clear();
971
972
DecodeNextBatch(OFF_THREAD_CHUNK_SIZE);
973
});
974
975
AutoSafeJSAPI jsapi;
976
JSContext* cx = jsapi.cx();
977
978
JSAutoRealm ar(cx, xpc::CompilationScope());
979
JS::Rooted<JS::ScriptVector> jsScripts(cx, JS::ScriptVector(cx));
980
981
// If this fails, we still need to mark the scripts as finished. Any that
982
// weren't successfully compiled in this operation (which should never
983
// happen under ordinary circumstances) will be re-decoded on the main
984
// thread, and raise the appropriate errors when they're executed.
985
//
986
// The exception from the off-thread decode operation will be reported when
987
// we pop the AutoJSAPI off the stack.
988
Unused << JS::FinishMultiOffThreadScriptsDecoder(cx, mToken, &jsScripts);
989
990
unsigned i = 0;
991
for (auto script : mParsingScripts) {
992
LOG(Debug, "Finished off-thread decode of %s\n", script->mURL.get());
993
if (i < jsScripts.length()) {
994
script->mScript = jsScripts[i++];
995
}
996
script->mReadyToExecute = true;
997
}
998
}
999
1000
void ScriptPreloader::DecodeNextBatch(size_t chunkSize,
1001
JS::HandleObject scope) {
1002
MOZ_ASSERT(mParsingSources.length() == 0);
1003
MOZ_ASSERT(mParsingScripts.length() == 0);
1004
1005
auto cleanup = MakeScopeExit([&]() {
1006
mParsingScripts.clearAndFree();
1007
mParsingSources.clearAndFree();
1008
});
1009
1010
auto start = TimeStamp::Now();
1011
LOG(Debug, "Off-thread decoding scripts...\n");
1012
1013
size_t size = 0;
1014
for (CachedScript* next = mPendingScripts.getFirst(); next;) {
1015
auto script = next;
1016
next = script->getNext();
1017
1018
// Skip any scripts that we decoded on the main thread rather than
1019
// waiting for an off-thread operation to complete.
1020
if (script->mReadyToExecute) {
1021
script->remove();
1022
continue;
1023
}
1024
// If we have enough data for one chunk and this script would put us
1025
// over our chunk size limit, we're done.
1026
if (size > SMALL_SCRIPT_CHUNK_THRESHOLD &&
1027
size + script->mSize > chunkSize) {
1028
break;
1029
}
1030
if (!mParsingScripts.append(script) ||
1031
!mParsingSources.emplaceBack(script->Range(), script->mURL.get(), 0)) {
1032
break;
1033
}
1034
1035
LOG(Debug, "Beginning off-thread decode of script %s (%u bytes)\n",
1036
script->mURL.get(), script->mSize);
1037
1038
script->remove();
1039
size += script->mSize;
1040
}
1041
1042
if (size == 0 && mPendingScripts.isEmpty()) {
1043
return;
1044
}
1045
1046
AutoSafeJSAPI jsapi;
1047
JSContext* cx = jsapi.cx();
1048
JSAutoRealm ar(cx, scope ? scope : xpc::CompilationScope());
1049
1050
JS::CompileOptions options(cx);
1051
options.setNoScriptRval(true).setSourceIsLazy(true);
1052
1053
if (!JS::CanCompileOffThread(cx, options, size) ||
1054
!JS::DecodeMultiOffThreadScripts(cx, options, mParsingSources,
1055
OffThreadDecodeCallback,
1056
static_cast<void*>(this))) {
1057
// If we fail here, we don't move on to process the next batch, so make
1058
// sure we don't have any other scripts left to process.
1059
MOZ_ASSERT(mPendingScripts.isEmpty());
1060
for (auto script : mPendingScripts) {
1061
script->mReadyToExecute = true;
1062
}
1063
1064
LOG(Info, "Can't decode %lu bytes of scripts off-thread",
1065
(unsigned long)size);
1066
for (auto script : mParsingScripts) {
1067
script->mReadyToExecute = true;
1068
}
1069
return;
1070
}
1071
1072
cleanup.release();
1073
1074
LOG(Debug, "Initialized decoding of %u scripts (%u bytes) in %fms\n",
1075
(unsigned)mParsingSources.length(), (unsigned)size,
1076
(TimeStamp::Now() - start).ToMilliseconds());
1077
}
1078
1079
ScriptPreloader::CachedScript::CachedScript(ScriptPreloader& cache,
1080
InputBuffer& buf)
1081
: mCache(cache) {
1082
Code(buf);
1083
1084
// Swap the mProcessTypes and mOriginalProcessTypes values, since we want to
1085
// start with an empty set of processes loaded into for this session, and
1086
// compare against last session's values later.
1087
mOriginalProcessTypes = mProcessTypes;
1088
mProcessTypes = {};
1089
}
1090
1091
bool ScriptPreloader::CachedScript::XDREncode(JSContext* cx) {
1092
auto cleanup = MakeScopeExit([&]() { MaybeDropScript(); });
1093
1094
JSAutoRealm ar(cx, mScript);
1095
JS::RootedScript jsscript(cx, mScript);
1096
1097
mXDRData.construct<JS::TranscodeBuffer>();
1098
1099
JS::TranscodeResult code = JS::EncodeScript(cx, Buffer(), jsscript);
1100
if (code == JS::TranscodeResult_Ok) {
1101
mXDRRange.emplace(Buffer().begin(), Buffer().length());
1102
mSize = Range().length();
1103
return true;
1104
}
1105
mXDRData.destroy();
1106
JS_ClearPendingException(cx);
1107
return false;
1108
}
1109
1110
JSScript* ScriptPreloader::CachedScript::GetJSScript(JSContext* cx) {
1111
MOZ_ASSERT(mReadyToExecute);
1112
if (mScript) {
1113
return mScript;
1114
}
1115
1116
if (!HasRange()) {
1117
// We've already executed the script, and thrown it away. But it wasn't
1118
// in the cache at startup, so we don't have any data to decode. Give
1119
// up.
1120
return nullptr;
1121
}
1122
1123
// If we have no script at this point, the script was too small to decode
1124
// off-thread, or it was needed before the off-thread compilation was
1125
// finished, and is small enough to decode on the main thread rather than
1126
// wait for the off-thread decoding to finish. In either case, we decode
1127
// it synchronously the first time it's needed.
1128
1129
auto start = TimeStamp::Now();
1130
LOG(Info, "Decoding script %s on main thread...\n", mURL.get());
1131
1132
JS::RootedScript script(cx);
1133
if (JS::DecodeScript(cx, Range(), &script)) {
1134
mScript = script;
1135
1136
if (mCache.mSaveComplete) {
1137
FreeData();
1138
}
1139
}
1140
1141
LOG(Debug, "Finished decoding in %fms",
1142
(TimeStamp::Now() - start).ToMilliseconds());
1143
1144
return mScript;
1145
}
1146
1147
// nsIAsyncShutdownBlocker
1148
1149
nsresult ScriptPreloader::GetName(nsAString& aName) {
1150
aName.AssignLiteral(u"ScriptPreloader: Saving bytecode cache");
1151
return NS_OK;
1152
}
1153
1154
nsresult ScriptPreloader::GetState(nsIPropertyBag** aState) {
1155
*aState = nullptr;
1156
return NS_OK;
1157
}
1158
1159
nsresult ScriptPreloader::BlockShutdown(
1160
nsIAsyncShutdownClient* aBarrierClient) {
1161
// If we're waiting on a timeout to finish saving, interrupt it and just save
1162
// immediately.
1163
mSaveMonitor.NotifyAll();
1164
return NS_OK;
1165
}
1166
1167
already_AddRefed<nsIAsyncShutdownClient> ScriptPreloader::GetShutdownBarrier() {
1168
nsCOMPtr<nsIAsyncShutdownService> svc = components::AsyncShutdown::Service();
1169
MOZ_RELEASE_ASSERT(svc);
1170
1171
nsCOMPtr<nsIAsyncShutdownClient> barrier;
1172
Unused << svc->GetXpcomWillShutdown(getter_AddRefs(barrier));
1173
MOZ_RELEASE_ASSERT(barrier);
1174
1175
return barrier.forget();
1176
}
1177
1178
NS_IMPL_ISUPPORTS(ScriptPreloader, nsIObserver, nsIRunnable, nsIMemoryReporter,
1179
nsIAsyncShutdownBlocker)
1180
1181
#undef LOG
1182
1183
} // namespace mozilla