Bug 1707526 [wpt PR 28685] - [testharness.js] Remove code working around issues in...
[gecko.git] / startupcache / StartupCache.cpp
blobcd527a3debd180c896f1634245b9bbb660c0d367
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/. */
7 #include "prio.h"
8 #include "PLDHashTable.h"
9 #include "mozilla/IOInterposer.h"
10 #include "mozilla/AutoMemMap.h"
11 #include "mozilla/IOBuffers.h"
12 #include "mozilla/MemoryReporting.h"
13 #include "mozilla/MemUtils.h"
14 #include "mozilla/MmapFaultHandler.h"
15 #include "mozilla/ResultExtensions.h"
16 #include "mozilla/scache/StartupCache.h"
17 #include "mozilla/ScopeExit.h"
19 #include "nsClassHashtable.h"
20 #include "nsComponentManagerUtils.h"
21 #include "nsCRT.h"
22 #include "nsDirectoryServiceUtils.h"
23 #include "nsIClassInfo.h"
24 #include "nsIFile.h"
25 #include "nsIObserver.h"
26 #include "nsIOutputStream.h"
27 #include "nsISupports.h"
28 #include "nsITimer.h"
29 #include "mozilla/Omnijar.h"
30 #include "prenv.h"
31 #include "mozilla/Telemetry.h"
32 #include "nsThreadUtils.h"
33 #include "nsXULAppAPI.h"
34 #include "nsIProtocolHandler.h"
35 #include "GeckoProfiler.h"
36 #include "nsAppRunner.h"
37 #include "xpcpublic.h"
38 #ifdef MOZ_BACKGROUNDTASKS
39 # include "mozilla/BackgroundTasks.h"
40 #endif
42 #if defined(XP_WIN)
43 # include <windows.h>
44 #endif
46 #ifdef IS_BIG_ENDIAN
47 # define SC_ENDIAN "big"
48 #else
49 # define SC_ENDIAN "little"
50 #endif
52 #if PR_BYTES_PER_WORD == 4
53 # define SC_WORDSIZE "4"
54 #else
55 # define SC_WORDSIZE "8"
56 #endif
58 using namespace mozilla::Compression;
60 namespace mozilla {
61 namespace scache {
63 MOZ_DEFINE_MALLOC_SIZE_OF(StartupCacheMallocSizeOf)
65 NS_IMETHODIMP
66 StartupCache::CollectReports(nsIHandleReportCallback* aHandleReport,
67 nsISupports* aData, bool aAnonymize) {
68 MOZ_COLLECT_REPORT(
69 "explicit/startup-cache/mapping", KIND_NONHEAP, UNITS_BYTES,
70 mCacheData.nonHeapSizeOfExcludingThis(),
71 "Memory used to hold the mapping of the startup cache from file. "
72 "This memory is likely to be swapped out shortly after start-up.");
74 MOZ_COLLECT_REPORT("explicit/startup-cache/data", KIND_HEAP, UNITS_BYTES,
75 HeapSizeOfIncludingThis(StartupCacheMallocSizeOf),
76 "Memory used by the startup cache for things other than "
77 "the file mapping.");
79 return NS_OK;
82 static const uint8_t MAGIC[] = "startupcache0002";
83 // This is a heuristic value for how much to reserve for mTable to avoid
84 // rehashing. This is not a hard limit in release builds, but it is in
85 // debug builds as it should be stable. If we exceed this number we should
86 // just increase it.
87 static const size_t STARTUP_CACHE_RESERVE_CAPACITY = 450;
88 // This is a hard limit which we will assert on, to ensure that we don't
89 // have some bug causing runaway cache growth.
90 static const size_t STARTUP_CACHE_MAX_CAPACITY = 5000;
92 // Not const because we change it for gtests.
93 static uint8_t STARTUP_CACHE_WRITE_TIMEOUT = 60;
95 #define STARTUP_CACHE_NAME "startupCache." SC_WORDSIZE "." SC_ENDIAN
97 static inline Result<Ok, nsresult> Write(PRFileDesc* fd, const void* data,
98 int32_t len) {
99 if (PR_Write(fd, data, len) != len) {
100 return Err(NS_ERROR_FAILURE);
102 return Ok();
105 static inline Result<Ok, nsresult> Seek(PRFileDesc* fd, int32_t offset) {
106 if (PR_Seek(fd, offset, PR_SEEK_SET) == -1) {
107 return Err(NS_ERROR_FAILURE);
109 return Ok();
112 static nsresult MapLZ4ErrorToNsresult(size_t aError) {
113 return NS_ERROR_FAILURE;
116 StartupCache* StartupCache::GetSingletonNoInit() {
117 return StartupCache::gStartupCache;
120 StartupCache* StartupCache::GetSingleton() {
121 #ifdef MOZ_BACKGROUNDTASKS
122 if (BackgroundTasks::IsBackgroundTaskMode()) {
123 return nullptr;
125 #endif
127 if (!gStartupCache) {
128 if (!XRE_IsParentProcess()) {
129 return nullptr;
131 #ifdef MOZ_DISABLE_STARTUPCACHE
132 return nullptr;
133 #else
134 StartupCache::InitSingleton();
135 #endif
138 return StartupCache::gStartupCache;
141 void StartupCache::DeleteSingleton() { StartupCache::gStartupCache = nullptr; }
143 nsresult StartupCache::InitSingleton() {
144 nsresult rv;
145 StartupCache::gStartupCache = new StartupCache();
147 rv = StartupCache::gStartupCache->Init();
148 if (NS_FAILED(rv)) {
149 StartupCache::gStartupCache = nullptr;
151 return rv;
154 StaticRefPtr<StartupCache> StartupCache::gStartupCache;
155 bool StartupCache::gShutdownInitiated;
156 bool StartupCache::gIgnoreDiskCache;
157 bool StartupCache::gFoundDiskCacheOnInit;
159 NS_IMPL_ISUPPORTS(StartupCache, nsIMemoryReporter)
161 StartupCache::StartupCache()
162 : mTableLock("StartupCache::mTableLock"),
163 mDirty(false),
164 mWrittenOnce(false),
165 mCurTableReferenced(false),
166 mRequestedCount(0),
167 mCacheEntriesBaseOffset(0),
168 mPrefetchThread(nullptr) {}
170 StartupCache::~StartupCache() { UnregisterWeakMemoryReporter(this); }
172 nsresult StartupCache::Init() {
173 // workaround for bug 653936
174 nsCOMPtr<nsIProtocolHandler> jarInitializer(
175 do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "jar"));
177 nsresult rv;
179 if (mozilla::RunningGTest()) {
180 STARTUP_CACHE_WRITE_TIMEOUT = 3;
183 // This allows to override the startup cache filename
184 // which is useful from xpcshell, when there is no ProfLDS directory to keep
185 // cache in.
186 char* env = PR_GetEnv("MOZ_STARTUP_CACHE");
187 if (env && *env) {
188 rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(env), false,
189 getter_AddRefs(mFile));
190 } else {
191 nsCOMPtr<nsIFile> file;
192 rv = NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(file));
193 if (NS_FAILED(rv)) {
194 // return silently, this will fail in mochitests's xpcshell process.
195 return rv;
198 rv = file->AppendNative("startupCache"_ns);
199 NS_ENSURE_SUCCESS(rv, rv);
201 // Try to create the directory if it's not there yet
202 rv = file->Create(nsIFile::DIRECTORY_TYPE, 0777);
203 if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS) return rv;
205 rv = file->AppendNative(nsLiteralCString(STARTUP_CACHE_NAME));
207 NS_ENSURE_SUCCESS(rv, rv);
209 mFile = file;
212 NS_ENSURE_TRUE(mFile, NS_ERROR_UNEXPECTED);
214 mObserverService = do_GetService("@mozilla.org/observer-service;1");
216 if (!mObserverService) {
217 NS_WARNING("Could not get observerService.");
218 return NS_ERROR_UNEXPECTED;
221 mListener = new StartupCacheListener();
222 rv = mObserverService->AddObserver(mListener, NS_XPCOM_SHUTDOWN_OBSERVER_ID,
223 false);
224 NS_ENSURE_SUCCESS(rv, rv);
225 rv = mObserverService->AddObserver(mListener, "startupcache-invalidate",
226 false);
227 NS_ENSURE_SUCCESS(rv, rv);
228 rv = mObserverService->AddObserver(mListener, "intl:app-locales-changed",
229 false);
230 NS_ENSURE_SUCCESS(rv, rv);
232 auto result = LoadArchive();
233 rv = result.isErr() ? result.unwrapErr() : NS_OK;
235 gFoundDiskCacheOnInit = rv != NS_ERROR_FILE_NOT_FOUND;
237 // Sometimes we don't have a cache yet, that's ok.
238 // If it's corrupted, just remove it and start over.
239 if (gIgnoreDiskCache || (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND)) {
240 NS_WARNING("Failed to load startupcache file correctly, removing!");
241 InvalidateCache();
244 RegisterWeakMemoryReporter(this);
245 mDecompressionContext = MakeUnique<LZ4FrameDecompressionContext>(true);
247 return NS_OK;
250 void StartupCache::StartPrefetchMemoryThread() {
251 // XXX: It would be great for this to not create its own thread, unfortunately
252 // there doesn't seem to be an existing thread that makes sense for this, so
253 // barring a coordinated global scheduling system this is the best we get.
254 mPrefetchThread = PR_CreateThread(
255 PR_USER_THREAD, StartupCache::ThreadedPrefetch, this, PR_PRIORITY_NORMAL,
256 PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 256 * 1024);
260 * LoadArchive can only be called from the main thread.
262 Result<Ok, nsresult> StartupCache::LoadArchive() {
263 MOZ_ASSERT(NS_IsMainThread(), "Can only load startup cache on main thread");
264 if (gIgnoreDiskCache) return Err(NS_ERROR_FAILURE);
266 MOZ_TRY(mCacheData.init(mFile));
267 auto size = mCacheData.size();
268 if (CanPrefetchMemory()) {
269 StartPrefetchMemoryThread();
272 uint32_t headerSize;
273 if (size < sizeof(MAGIC) + sizeof(headerSize)) {
274 return Err(NS_ERROR_UNEXPECTED);
277 auto data = mCacheData.get<uint8_t>();
278 auto end = data + size;
280 MMAP_FAULT_HANDLER_BEGIN_BUFFER(data.get(), size)
282 if (memcmp(MAGIC, data.get(), sizeof(MAGIC))) {
283 return Err(NS_ERROR_UNEXPECTED);
285 data += sizeof(MAGIC);
287 headerSize = LittleEndian::readUint32(data.get());
288 data += sizeof(headerSize);
290 if (headerSize > end - data) {
291 MOZ_ASSERT(false, "StartupCache file is corrupt.");
292 return Err(NS_ERROR_UNEXPECTED);
295 Range<uint8_t> header(data, data + headerSize);
296 data += headerSize;
298 mCacheEntriesBaseOffset = sizeof(MAGIC) + sizeof(headerSize) + headerSize;
300 if (!mTable.reserve(STARTUP_CACHE_RESERVE_CAPACITY)) {
301 return Err(NS_ERROR_UNEXPECTED);
303 auto cleanup = MakeScopeExit([&]() {
304 WaitOnPrefetchThread();
305 mTable.clear();
306 mCacheData.reset();
308 loader::InputBuffer buf(header);
310 uint32_t currentOffset = 0;
311 while (!buf.finished()) {
312 uint32_t offset = 0;
313 uint32_t compressedSize = 0;
314 uint32_t uncompressedSize = 0;
315 nsCString key;
316 buf.codeUint32(offset);
317 buf.codeUint32(compressedSize);
318 buf.codeUint32(uncompressedSize);
319 buf.codeString(key);
321 if (offset + compressedSize > end - data) {
322 MOZ_ASSERT(false, "StartupCache file is corrupt.");
323 return Err(NS_ERROR_UNEXPECTED);
326 // Make sure offsets match what we'd expect based on script ordering and
327 // size, as a basic sanity check.
328 if (offset != currentOffset) {
329 return Err(NS_ERROR_UNEXPECTED);
331 currentOffset += compressedSize;
333 // We could use mTable.putNew if we knew the file we're loading weren't
334 // corrupt. However, we don't know that, so check if the key already
335 // exists. If it does, we know the file must be corrupt.
336 decltype(mTable)::AddPtr p = mTable.lookupForAdd(key);
337 if (p) {
338 return Err(NS_ERROR_UNEXPECTED);
341 if (!mTable.add(
342 p, key,
343 StartupCacheEntry(offset, compressedSize, uncompressedSize))) {
344 return Err(NS_ERROR_UNEXPECTED);
348 if (buf.error()) {
349 return Err(NS_ERROR_UNEXPECTED);
352 cleanup.release();
355 MMAP_FAULT_HANDLER_CATCH(Err(NS_ERROR_UNEXPECTED))
357 return Ok();
360 bool StartupCache::HasEntry(const char* id) {
361 AUTO_PROFILER_LABEL("StartupCache::HasEntry", OTHER);
363 MOZ_ASSERT(NS_IsMainThread(), "Startup cache only available on main thread");
365 return mTable.has(nsDependentCString(id));
368 nsresult StartupCache::GetBuffer(const char* id, const char** outbuf,
369 uint32_t* length) NO_THREAD_SAFETY_ANALYSIS {
370 AUTO_PROFILER_LABEL("StartupCache::GetBuffer", OTHER);
372 NS_ASSERTION(NS_IsMainThread(),
373 "Startup cache only available on main thread");
375 Telemetry::LABELS_STARTUP_CACHE_REQUESTS label =
376 Telemetry::LABELS_STARTUP_CACHE_REQUESTS::Miss;
377 auto telemetry =
378 MakeScopeExit([&label] { Telemetry::AccumulateCategorical(label); });
380 decltype(mTable)::Ptr p = mTable.lookup(nsDependentCString(id));
381 if (!p) {
382 return NS_ERROR_NOT_AVAILABLE;
385 auto& value = p->value();
386 if (value.mData) {
387 label = Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitMemory;
388 } else {
389 if (!mCacheData.initialized()) {
390 return NS_ERROR_NOT_AVAILABLE;
392 #ifdef DEBUG
393 // It should be impossible for a write to be pending here. This is because
394 // we just checked mCacheData.initialized(), and this is reset before
395 // writing to the cache. It's not re-initialized unless we call
396 // LoadArchive(), either from Init() (which must have already happened) or
397 // InvalidateCache(). InvalidateCache() locks the mutex, so a write can't be
398 // happening. Really, we want to MOZ_ASSERT(!mTableLock.IsLocked()) here,
399 // but there is no such method. So we hack around by attempting to gain the
400 // lock. This should always succeed; if it fails, someone's broken the
401 // assumptions.
402 if (!mTableLock.TryLock()) {
403 MOZ_ASSERT(false, "Could not gain mTableLock - should never happen!");
404 return NS_ERROR_NOT_AVAILABLE;
406 mTableLock.Unlock();
407 #endif
409 size_t totalRead = 0;
410 size_t totalWritten = 0;
411 Span<const char> compressed = Span(
412 mCacheData.get<char>().get() + mCacheEntriesBaseOffset + value.mOffset,
413 value.mCompressedSize);
414 value.mData = MakeUnique<char[]>(value.mUncompressedSize);
415 Span<char> uncompressed = Span(value.mData.get(), value.mUncompressedSize);
416 MMAP_FAULT_HANDLER_BEGIN_BUFFER(uncompressed.Elements(),
417 uncompressed.Length())
418 bool finished = false;
419 while (!finished) {
420 auto result = mDecompressionContext->Decompress(
421 uncompressed.From(totalWritten), compressed.From(totalRead));
422 if (NS_WARN_IF(result.isErr())) {
423 value.mData = nullptr;
424 InvalidateCache();
425 return NS_ERROR_FAILURE;
427 auto decompressionResult = result.unwrap();
428 totalRead += decompressionResult.mSizeRead;
429 totalWritten += decompressionResult.mSizeWritten;
430 finished = decompressionResult.mFinished;
433 MMAP_FAULT_HANDLER_CATCH(NS_ERROR_FAILURE)
435 label = Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitDisk;
438 if (!value.mRequested) {
439 value.mRequested = true;
440 value.mRequestedOrder = ++mRequestedCount;
441 MOZ_ASSERT(mRequestedCount <= mTable.count(),
442 "Somehow we requested more StartupCache items than exist.");
443 ResetStartupWriteTimerCheckingReadCount();
446 // Track that something holds a reference into mTable, so we know to hold
447 // onto it in case the cache is invalidated.
448 mCurTableReferenced = true;
449 *outbuf = value.mData.get();
450 *length = value.mUncompressedSize;
451 return NS_OK;
454 // Makes a copy of the buffer, client retains ownership of inbuf.
455 nsresult StartupCache::PutBuffer(const char* id, UniquePtr<char[]>&& inbuf,
456 uint32_t len) NO_THREAD_SAFETY_ANALYSIS {
457 NS_ASSERTION(NS_IsMainThread(),
458 "Startup cache only available on main thread");
459 if (StartupCache::gShutdownInitiated) {
460 return NS_ERROR_NOT_AVAILABLE;
463 bool exists = mTable.has(nsDependentCString(id));
465 if (exists) {
466 NS_WARNING("Existing entry in StartupCache.");
467 // Double-caching is undesirable but not an error.
468 return NS_OK;
470 // Try to gain the table write lock. If the background task to write the
471 // cache is running, this will fail.
472 if (!mTableLock.TryLock()) {
473 return NS_ERROR_NOT_AVAILABLE;
475 auto lockGuard = MakeScopeExit([&] {
476 mTableLock.AssertCurrentThreadOwns();
477 mTableLock.Unlock();
480 // putNew returns false on alloc failure - in the very unlikely event we hit
481 // that and aren't going to crash elsewhere, there's no reason we need to
482 // crash here.
483 if (mTable.putNew(nsCString(id), StartupCacheEntry(std::move(inbuf), len,
484 ++mRequestedCount))) {
485 return ResetStartupWriteTimer();
487 MOZ_DIAGNOSTIC_ASSERT(mTable.count() < STARTUP_CACHE_MAX_CAPACITY,
488 "Too many StartupCache entries.");
489 return NS_OK;
492 size_t StartupCache::HeapSizeOfIncludingThis(
493 mozilla::MallocSizeOf aMallocSizeOf) const {
494 // This function could measure more members, but they haven't been found by
495 // DMD to be significant. They can be added later if necessary.
497 size_t n = aMallocSizeOf(this);
499 n += mTable.shallowSizeOfExcludingThis(aMallocSizeOf);
500 for (auto iter = mTable.iter(); !iter.done(); iter.next()) {
501 if (iter.get().value().mData) {
502 n += aMallocSizeOf(iter.get().value().mData.get());
504 n += iter.get().key().SizeOfExcludingThisIfUnshared(aMallocSizeOf);
507 return n;
511 * WriteToDisk writes the cache out to disk. Callers of WriteToDisk need to call
512 * WaitOnWriteComplete to make sure there isn't a write
513 * happening on another thread
515 Result<Ok, nsresult> StartupCache::WriteToDisk() {
516 mTableLock.AssertCurrentThreadOwns();
518 if (!mDirty || mWrittenOnce) {
519 return Ok();
522 if (!mFile) {
523 return Err(NS_ERROR_UNEXPECTED);
526 AutoFDClose fd;
527 MOZ_TRY(mFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
528 0644, &fd.rwget()));
530 nsTArray<std::pair<const nsCString*, StartupCacheEntry*>> entries;
531 for (auto iter = mTable.iter(); !iter.done(); iter.next()) {
532 if (iter.get().value().mRequested) {
533 entries.AppendElement(
534 std::make_pair(&iter.get().key(), &iter.get().value()));
538 if (entries.IsEmpty()) {
539 return Ok();
542 entries.Sort(StartupCacheEntry::Comparator());
543 loader::OutputBuffer buf;
544 for (auto& e : entries) {
545 auto key = e.first;
546 auto value = e.second;
547 auto uncompressedSize = value->mUncompressedSize;
548 // Set the mHeaderOffsetInFile so we can go back and edit the offset.
549 value->mHeaderOffsetInFile = buf.cursor();
550 // Write a 0 offset/compressed size as a placeholder until we get the real
551 // offset after compressing.
552 buf.codeUint32(0);
553 buf.codeUint32(0);
554 buf.codeUint32(uncompressedSize);
555 buf.codeString(*key);
558 uint8_t headerSize[4];
559 LittleEndian::writeUint32(headerSize, buf.cursor());
561 MOZ_TRY(Write(fd, MAGIC, sizeof(MAGIC)));
562 MOZ_TRY(Write(fd, headerSize, sizeof(headerSize)));
563 size_t headerStart = sizeof(MAGIC) + sizeof(headerSize);
564 size_t dataStart = headerStart + buf.cursor();
565 MOZ_TRY(Seek(fd, dataStart));
567 size_t offset = 0;
569 const size_t chunkSize = 1024 * 16;
570 LZ4FrameCompressionContext ctx(6, /* aCompressionLevel */
571 chunkSize, /* aReadBufLen */
572 true, /* aChecksum */
573 true); /* aStableSrc */
574 size_t writeBufLen = ctx.GetRequiredWriteBufferLength();
575 auto writeBuffer = MakeUnique<char[]>(writeBufLen);
576 auto writeSpan = Span(writeBuffer.get(), writeBufLen);
578 for (auto& e : entries) {
579 auto value = e.second;
580 value->mOffset = offset;
581 Span<const char> result;
582 MOZ_TRY_VAR(result,
583 ctx.BeginCompressing(writeSpan).mapErr(MapLZ4ErrorToNsresult));
584 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
585 offset += result.Length();
587 for (size_t i = 0; i < value->mUncompressedSize; i += chunkSize) {
588 size_t size = std::min(chunkSize, value->mUncompressedSize - i);
589 char* uncompressed = value->mData.get() + i;
590 MOZ_TRY_VAR(result, ctx.ContinueCompressing(Span(uncompressed, size))
591 .mapErr(MapLZ4ErrorToNsresult));
592 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
593 offset += result.Length();
596 MOZ_TRY_VAR(result, ctx.EndCompressing().mapErr(MapLZ4ErrorToNsresult));
597 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
598 offset += result.Length();
599 value->mCompressedSize = offset - value->mOffset;
600 MOZ_TRY(Seek(fd, dataStart + offset));
603 for (auto& e : entries) {
604 auto value = e.second;
605 uint8_t* headerEntry = buf.Get() + value->mHeaderOffsetInFile;
606 LittleEndian::writeUint32(headerEntry, value->mOffset);
607 LittleEndian::writeUint32(headerEntry + sizeof(value->mOffset),
608 value->mCompressedSize);
610 MOZ_TRY(Seek(fd, headerStart));
611 MOZ_TRY(Write(fd, buf.Get(), buf.cursor()));
613 mDirty = false;
614 mWrittenOnce = true;
616 return Ok();
619 void StartupCache::InvalidateCache(bool memoryOnly) {
620 WaitOnPrefetchThread();
621 // Ensure we're not writing using mTable...
622 MutexAutoLock unlock(mTableLock);
624 mWrittenOnce = false;
625 if (memoryOnly) {
626 // This should only be called in tests.
627 auto writeResult = WriteToDisk();
628 if (NS_WARN_IF(writeResult.isErr())) {
629 gIgnoreDiskCache = true;
630 return;
633 if (mCurTableReferenced) {
634 // There should be no way for this assert to fail other than a user manually
635 // sending startupcache-invalidate messages through the Browser Toolbox. If
636 // something knowingly invalidates the cache, the event can be counted with
637 // mAllowedInvalidationsCount.
638 MOZ_DIAGNOSTIC_ASSERT(
639 xpc::IsInAutomation() ||
640 // The allowed invalidations can grow faster than the old tables, so
641 // guard against incorrect unsigned subtraction.
642 mAllowedInvalidationsCount > mOldTables.Length() ||
643 // Now perform the real check.
644 mOldTables.Length() - mAllowedInvalidationsCount < 10,
645 "Startup cache invalidated too many times.");
646 mOldTables.AppendElement(std::move(mTable));
647 mCurTableReferenced = false;
648 } else {
649 mTable.clear();
651 mRequestedCount = 0;
652 if (!memoryOnly) {
653 mCacheData.reset();
654 nsresult rv = mFile->Remove(false);
655 if (NS_FAILED(rv) && rv != NS_ERROR_FILE_TARGET_DOES_NOT_EXIST &&
656 rv != NS_ERROR_FILE_NOT_FOUND) {
657 gIgnoreDiskCache = true;
658 return;
661 gIgnoreDiskCache = false;
662 auto result = LoadArchive();
663 if (NS_WARN_IF(result.isErr())) {
664 gIgnoreDiskCache = true;
668 void StartupCache::CountAllowedInvalidation() { mAllowedInvalidationsCount++; }
670 void StartupCache::MaybeInitShutdownWrite() {
671 if (mTimer) {
672 mTimer->Cancel();
674 gShutdownInitiated = true;
676 MaybeWriteOffMainThread();
679 void StartupCache::EnsureShutdownWriteComplete() {
680 // If we've already written or there's nothing to write,
681 // we don't need to do anything. This is the common case.
682 if (mWrittenOnce || (mCacheData.initialized() && !ShouldCompactCache())) {
683 return;
685 // Otherwise, ensure the write happens. The timer should have been cancelled
686 // already in MaybeInitShutdownWrite.
687 if (!mTableLock.TryLock()) {
688 // Uh oh, we're writing away from the main thread. Wait to gain the lock,
689 // to ensure the write completes.
690 mTableLock.Lock();
691 } else {
692 // We got the lock. Keep the following in sync with
693 // MaybeWriteOffMainThread:
694 WaitOnPrefetchThread();
695 mDirty = true;
696 mCacheData.reset();
697 // Most of this should be redundant given MaybeWriteOffMainThread should
698 // have run before now.
700 auto writeResult = WriteToDisk();
701 Unused << NS_WARN_IF(writeResult.isErr());
702 // We've had the lock, and `WriteToDisk()` sets mWrittenOnce and mDirty
703 // when done, and checks for them when starting, so we don't need to do
704 // anything else.
706 mTableLock.Unlock();
709 void StartupCache::IgnoreDiskCache() {
710 gIgnoreDiskCache = true;
711 if (gStartupCache) gStartupCache->InvalidateCache();
714 void StartupCache::WaitOnPrefetchThread() {
715 if (!mPrefetchThread || mPrefetchThread == PR_GetCurrentThread()) return;
717 PR_JoinThread(mPrefetchThread);
718 mPrefetchThread = nullptr;
721 void StartupCache::ThreadedPrefetch(void* aClosure) {
722 AUTO_PROFILER_REGISTER_THREAD("StartupCache");
723 NS_SetCurrentThreadName("StartupCache");
724 mozilla::IOInterposer::RegisterCurrentThread();
725 StartupCache* startupCacheObj = static_cast<StartupCache*>(aClosure);
726 uint8_t* buf = startupCacheObj->mCacheData.get<uint8_t>().get();
727 size_t size = startupCacheObj->mCacheData.size();
728 MMAP_FAULT_HANDLER_BEGIN_BUFFER(buf, size)
729 PrefetchMemory(buf, size);
730 MMAP_FAULT_HANDLER_CATCH()
731 mozilla::IOInterposer::UnregisterCurrentThread();
734 bool StartupCache::ShouldCompactCache() {
735 // If we've requested less than 4/5 of the startup cache, then we should
736 // probably compact it down. This can happen quite easily after the first run,
737 // which seems to request quite a few more things than subsequent runs.
738 CheckedInt<uint32_t> threshold = CheckedInt<uint32_t>(mTable.count()) * 4 / 5;
739 MOZ_RELEASE_ASSERT(threshold.isValid(), "Runaway StartupCache size");
740 return mRequestedCount < threshold.value();
744 * The write-thread is spawned on a timeout(which is reset with every write).
745 * This can avoid a slow shutdown.
747 void StartupCache::WriteTimeout(nsITimer* aTimer, void* aClosure) {
749 * It is safe to use the pointer passed in aClosure to reference the
750 * StartupCache object because the timer's lifetime is tightly coupled to
751 * the lifetime of the StartupCache object; this timer is canceled in the
752 * StartupCache destructor, guaranteeing that this function runs if and only
753 * if the StartupCache object is valid.
755 StartupCache* startupCacheObj = static_cast<StartupCache*>(aClosure);
756 startupCacheObj->MaybeWriteOffMainThread();
760 * See StartupCache::WriteTimeout above - this is just the non-static body.
762 void StartupCache::MaybeWriteOffMainThread() {
763 if (mWrittenOnce) {
764 return;
767 if (mCacheData.initialized() && !ShouldCompactCache()) {
768 return;
771 // Keep this code in sync with EnsureShutdownWriteComplete.
772 WaitOnPrefetchThread();
773 mDirty = true;
774 mCacheData.reset();
776 RefPtr<StartupCache> self = this;
777 nsCOMPtr<nsIRunnable> runnable =
778 NS_NewRunnableFunction("StartupCache::Write", [self]() mutable {
779 MutexAutoLock unlock(self->mTableLock);
780 auto result = self->WriteToDisk();
781 Unused << NS_WARN_IF(result.isErr());
783 NS_DispatchBackgroundTask(runnable.forget(), NS_DISPATCH_EVENT_MAY_BLOCK);
786 // We don't want to refcount StartupCache, so we'll just
787 // hold a ref to this and pass it to observerService instead.
788 NS_IMPL_ISUPPORTS(StartupCacheListener, nsIObserver)
790 nsresult StartupCacheListener::Observe(nsISupports* subject, const char* topic,
791 const char16_t* data) {
792 StartupCache* sc = StartupCache::GetSingleton();
793 if (!sc) return NS_OK;
795 if (strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
796 // Do not leave the thread running past xpcom shutdown
797 sc->WaitOnPrefetchThread();
798 StartupCache::gShutdownInitiated = true;
799 // Note that we don't do anything special for the background write
800 // task; we expect the threadpool to finish running any tasks already
801 // posted to it prior to shutdown. FastShutdown will call
802 // EnsureShutdownWriteComplete() to ensure any pending writes happen
803 // in that case.
804 } else if (strcmp(topic, "startupcache-invalidate") == 0) {
805 sc->InvalidateCache(data && nsCRT::strcmp(data, u"memoryOnly") == 0);
806 } else if (strcmp(topic, "intl:app-locales-changed") == 0) {
807 // Live language switching invalidates the startup cache due to the history
808 // sidebar retaining localized strings in its internal SQL query. This
809 // should be a relatively rare event, but a user could do it an arbitrary
810 // number of times.
811 sc->CountAllowedInvalidation();
813 return NS_OK;
816 nsresult StartupCache::GetDebugObjectOutputStream(
817 nsIObjectOutputStream* aStream, nsIObjectOutputStream** aOutStream) {
818 NS_ENSURE_ARG_POINTER(aStream);
819 #ifdef DEBUG
820 auto* stream = new StartupCacheDebugOutputStream(aStream, &mWriteObjectMap);
821 NS_ADDREF(*aOutStream = stream);
822 #else
823 NS_ADDREF(*aOutStream = aStream);
824 #endif
826 return NS_OK;
829 nsresult StartupCache::ResetStartupWriteTimerCheckingReadCount() {
830 nsresult rv = NS_OK;
831 if (!mTimer)
832 mTimer = NS_NewTimer();
833 else
834 rv = mTimer->Cancel();
835 NS_ENSURE_SUCCESS(rv, rv);
836 // Wait for the specified timeout, then write out the cache.
837 mTimer->InitWithNamedFuncCallback(
838 StartupCache::WriteTimeout, this, STARTUP_CACHE_WRITE_TIMEOUT * 1000,
839 nsITimer::TYPE_ONE_SHOT, "StartupCache::WriteTimeout");
840 return NS_OK;
843 nsresult StartupCache::ResetStartupWriteTimer() {
844 mDirty = true;
845 nsresult rv = NS_OK;
846 if (!mTimer)
847 mTimer = NS_NewTimer();
848 else
849 rv = mTimer->Cancel();
850 NS_ENSURE_SUCCESS(rv, rv);
851 // Wait for the specified timeout, then write out the cache.
852 mTimer->InitWithNamedFuncCallback(
853 StartupCache::WriteTimeout, this, STARTUP_CACHE_WRITE_TIMEOUT * 1000,
854 nsITimer::TYPE_ONE_SHOT, "StartupCache::WriteTimeout");
855 return NS_OK;
858 // Used only in tests:
859 bool StartupCache::StartupWriteComplete() {
860 // Need to have written to disk and not added new things since;
861 return !mDirty && mWrittenOnce;
864 // StartupCacheDebugOutputStream implementation
865 #ifdef DEBUG
866 NS_IMPL_ISUPPORTS(StartupCacheDebugOutputStream, nsIObjectOutputStream,
867 nsIBinaryOutputStream, nsIOutputStream)
869 bool StartupCacheDebugOutputStream::CheckReferences(nsISupports* aObject) {
870 nsresult rv;
872 nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(aObject);
873 if (!classInfo) {
874 NS_ERROR("aObject must implement nsIClassInfo");
875 return false;
878 uint32_t flags;
879 rv = classInfo->GetFlags(&flags);
880 NS_ENSURE_SUCCESS(rv, false);
881 if (flags & nsIClassInfo::SINGLETON) return true;
883 bool inserted = mObjectMap->EnsureInserted(aObject);
884 if (!inserted) {
885 NS_ERROR(
886 "non-singleton aObject is referenced multiple times in this"
887 "serialization, we don't support that.");
890 return inserted;
893 // nsIObjectOutputStream implementation
894 nsresult StartupCacheDebugOutputStream::WriteObject(nsISupports* aObject,
895 bool aIsStrongRef) {
896 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
898 NS_ASSERTION(rootObject.get() == aObject,
899 "bad call to WriteObject -- call WriteCompoundObject!");
900 bool check = CheckReferences(aObject);
901 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
902 return mBinaryStream->WriteObject(aObject, aIsStrongRef);
905 nsresult StartupCacheDebugOutputStream::WriteSingleRefObject(
906 nsISupports* aObject) {
907 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
909 NS_ASSERTION(rootObject.get() == aObject,
910 "bad call to WriteSingleRefObject -- call WriteCompoundObject!");
911 bool check = CheckReferences(aObject);
912 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
913 return mBinaryStream->WriteSingleRefObject(aObject);
916 nsresult StartupCacheDebugOutputStream::WriteCompoundObject(
917 nsISupports* aObject, const nsIID& aIID, bool aIsStrongRef) {
918 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
920 nsCOMPtr<nsISupports> roundtrip;
921 rootObject->QueryInterface(aIID, getter_AddRefs(roundtrip));
922 NS_ASSERTION(roundtrip.get() == aObject,
923 "bad aggregation or multiple inheritance detected by call to "
924 "WriteCompoundObject!");
926 bool check = CheckReferences(aObject);
927 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
928 return mBinaryStream->WriteCompoundObject(aObject, aIID, aIsStrongRef);
931 nsresult StartupCacheDebugOutputStream::WriteID(nsID const& aID) {
932 return mBinaryStream->WriteID(aID);
935 char* StartupCacheDebugOutputStream::GetBuffer(uint32_t aLength,
936 uint32_t aAlignMask) {
937 return mBinaryStream->GetBuffer(aLength, aAlignMask);
940 void StartupCacheDebugOutputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
941 mBinaryStream->PutBuffer(aBuffer, aLength);
943 #endif // DEBUG
945 } // namespace scache
946 } // namespace mozilla