Bug 1826620 [wpt PR 39397] - Add WPTs for AuctionConfig, a=testonly
[gecko.git] / startupcache / StartupCache.cpp
blob67d19155eb2de358241f87527bd46ac070a21e7d
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)
370 MOZ_NO_THREAD_SAFETY_ANALYSIS {
371 AUTO_PROFILER_LABEL("StartupCache::GetBuffer", OTHER);
373 NS_ASSERTION(NS_IsMainThread(),
374 "Startup cache only available on main thread");
376 Telemetry::LABELS_STARTUP_CACHE_REQUESTS label =
377 Telemetry::LABELS_STARTUP_CACHE_REQUESTS::Miss;
378 auto telemetry =
379 MakeScopeExit([&label] { Telemetry::AccumulateCategorical(label); });
381 decltype(mTable)::Ptr p = mTable.lookup(nsDependentCString(id));
382 if (!p) {
383 return NS_ERROR_NOT_AVAILABLE;
386 auto& value = p->value();
387 if (value.mData) {
388 label = Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitMemory;
389 } else {
390 if (!mCacheData.initialized()) {
391 return NS_ERROR_NOT_AVAILABLE;
393 #ifdef DEBUG
394 // It should be impossible for a write to be pending here. This is because
395 // we just checked mCacheData.initialized(), and this is reset before
396 // writing to the cache. It's not re-initialized unless we call
397 // LoadArchive(), either from Init() (which must have already happened) or
398 // InvalidateCache(). InvalidateCache() locks the mutex, so a write can't be
399 // happening. Really, we want to MOZ_ASSERT(!mTableLock.IsLocked()) here,
400 // but there is no such method. So we hack around by attempting to gain the
401 // lock. This should always succeed; if it fails, someone's broken the
402 // assumptions.
403 if (!mTableLock.TryLock()) {
404 MOZ_ASSERT(false, "Could not gain mTableLock - should never happen!");
405 return NS_ERROR_NOT_AVAILABLE;
407 mTableLock.Unlock();
408 #endif
410 size_t totalRead = 0;
411 size_t totalWritten = 0;
412 Span<const char> compressed = Span(
413 mCacheData.get<char>().get() + mCacheEntriesBaseOffset + value.mOffset,
414 value.mCompressedSize);
415 value.mData = UniqueFreePtr<char[]>(reinterpret_cast<char*>(
416 malloc(sizeof(char) * value.mUncompressedSize)));
417 Span<char> uncompressed = Span(value.mData.get(), value.mUncompressedSize);
418 MMAP_FAULT_HANDLER_BEGIN_BUFFER(uncompressed.Elements(),
419 uncompressed.Length())
420 bool finished = false;
421 while (!finished) {
422 auto result = mDecompressionContext->Decompress(
423 uncompressed.From(totalWritten), compressed.From(totalRead));
424 if (NS_WARN_IF(result.isErr())) {
425 value.mData = nullptr;
426 InvalidateCache();
427 return NS_ERROR_FAILURE;
429 auto decompressionResult = result.unwrap();
430 totalRead += decompressionResult.mSizeRead;
431 totalWritten += decompressionResult.mSizeWritten;
432 finished = decompressionResult.mFinished;
435 MMAP_FAULT_HANDLER_CATCH(NS_ERROR_FAILURE)
437 label = Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitDisk;
440 if (!value.mRequested) {
441 value.mRequested = true;
442 value.mRequestedOrder = ++mRequestedCount;
443 MOZ_ASSERT(mRequestedCount <= mTable.count(),
444 "Somehow we requested more StartupCache items than exist.");
445 ResetStartupWriteTimerCheckingReadCount();
448 // Track that something holds a reference into mTable, so we know to hold
449 // onto it in case the cache is invalidated.
450 mCurTableReferenced = true;
451 *outbuf = value.mData.get();
452 *length = value.mUncompressedSize;
453 return NS_OK;
456 // Makes a copy of the buffer, client retains ownership of inbuf.
457 nsresult StartupCache::PutBuffer(const char* id, UniqueFreePtr<char[]>&& inbuf,
458 uint32_t len) MOZ_NO_THREAD_SAFETY_ANALYSIS {
459 NS_ASSERTION(NS_IsMainThread(),
460 "Startup cache only available on main thread");
461 if (StartupCache::gShutdownInitiated) {
462 return NS_ERROR_NOT_AVAILABLE;
465 bool exists = mTable.has(nsDependentCString(id));
467 if (exists) {
468 NS_WARNING("Existing entry in StartupCache.");
469 // Double-caching is undesirable but not an error.
470 return NS_OK;
472 // Try to gain the table write lock. If the background task to write the
473 // cache is running, this will fail.
474 if (!mTableLock.TryLock()) {
475 return NS_ERROR_NOT_AVAILABLE;
477 auto lockGuard = MakeScopeExit([&] {
478 mTableLock.AssertCurrentThreadOwns();
479 mTableLock.Unlock();
482 // putNew returns false on alloc failure - in the very unlikely event we hit
483 // that and aren't going to crash elsewhere, there's no reason we need to
484 // crash here.
485 if (mTable.putNew(nsCString(id), StartupCacheEntry(std::move(inbuf), len,
486 ++mRequestedCount))) {
487 return ResetStartupWriteTimer();
489 MOZ_DIAGNOSTIC_ASSERT(mTable.count() < STARTUP_CACHE_MAX_CAPACITY,
490 "Too many StartupCache entries.");
491 return NS_OK;
494 size_t StartupCache::HeapSizeOfIncludingThis(
495 mozilla::MallocSizeOf aMallocSizeOf) const {
496 // This function could measure more members, but they haven't been found by
497 // DMD to be significant. They can be added later if necessary.
499 size_t n = aMallocSizeOf(this);
501 n += mTable.shallowSizeOfExcludingThis(aMallocSizeOf);
502 for (auto iter = mTable.iter(); !iter.done(); iter.next()) {
503 if (iter.get().value().mData) {
504 n += aMallocSizeOf(iter.get().value().mData.get());
506 n += iter.get().key().SizeOfExcludingThisIfUnshared(aMallocSizeOf);
509 return n;
513 * WriteToDisk writes the cache out to disk. Callers of WriteToDisk need to call
514 * WaitOnWriteComplete to make sure there isn't a write
515 * happening on another thread
517 Result<Ok, nsresult> StartupCache::WriteToDisk() {
518 mTableLock.AssertCurrentThreadOwns();
520 if (!mDirty || mWrittenOnce) {
521 return Ok();
524 if (!mFile) {
525 return Err(NS_ERROR_UNEXPECTED);
528 AutoFDClose fd;
529 MOZ_TRY(mFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
530 0644, &fd.rwget()));
532 nsTArray<std::pair<const nsCString*, StartupCacheEntry*>> entries;
533 for (auto iter = mTable.iter(); !iter.done(); iter.next()) {
534 if (iter.get().value().mRequested) {
535 entries.AppendElement(
536 std::make_pair(&iter.get().key(), &iter.get().value()));
540 if (entries.IsEmpty()) {
541 return Ok();
544 entries.Sort(StartupCacheEntry::Comparator());
545 loader::OutputBuffer buf;
546 for (auto& e : entries) {
547 auto key = e.first;
548 auto value = e.second;
549 auto uncompressedSize = value->mUncompressedSize;
550 // Set the mHeaderOffsetInFile so we can go back and edit the offset.
551 value->mHeaderOffsetInFile = buf.cursor();
552 // Write a 0 offset/compressed size as a placeholder until we get the real
553 // offset after compressing.
554 buf.codeUint32(0);
555 buf.codeUint32(0);
556 buf.codeUint32(uncompressedSize);
557 buf.codeString(*key);
560 uint8_t headerSize[4];
561 LittleEndian::writeUint32(headerSize, buf.cursor());
563 MOZ_TRY(Write(fd, MAGIC, sizeof(MAGIC)));
564 MOZ_TRY(Write(fd, headerSize, sizeof(headerSize)));
565 size_t headerStart = sizeof(MAGIC) + sizeof(headerSize);
566 size_t dataStart = headerStart + buf.cursor();
567 MOZ_TRY(Seek(fd, dataStart));
569 size_t offset = 0;
571 const size_t chunkSize = 1024 * 16;
572 LZ4FrameCompressionContext ctx(6, /* aCompressionLevel */
573 chunkSize, /* aReadBufLen */
574 true, /* aChecksum */
575 true); /* aStableSrc */
576 size_t writeBufLen = ctx.GetRequiredWriteBufferLength();
577 auto writeBuffer = MakeUnique<char[]>(writeBufLen);
578 auto writeSpan = Span(writeBuffer.get(), writeBufLen);
580 for (auto& e : entries) {
581 auto value = e.second;
582 value->mOffset = offset;
583 Span<const char> result;
584 MOZ_TRY_VAR(result,
585 ctx.BeginCompressing(writeSpan).mapErr(MapLZ4ErrorToNsresult));
586 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
587 offset += result.Length();
589 for (size_t i = 0; i < value->mUncompressedSize; i += chunkSize) {
590 size_t size = std::min(chunkSize, value->mUncompressedSize - i);
591 char* uncompressed = value->mData.get() + i;
592 MOZ_TRY_VAR(result, ctx.ContinueCompressing(Span(uncompressed, size))
593 .mapErr(MapLZ4ErrorToNsresult));
594 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
595 offset += result.Length();
598 MOZ_TRY_VAR(result, ctx.EndCompressing().mapErr(MapLZ4ErrorToNsresult));
599 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
600 offset += result.Length();
601 value->mCompressedSize = offset - value->mOffset;
602 MOZ_TRY(Seek(fd, dataStart + offset));
605 for (auto& e : entries) {
606 auto value = e.second;
607 uint8_t* headerEntry = buf.Get() + value->mHeaderOffsetInFile;
608 LittleEndian::writeUint32(headerEntry, value->mOffset);
609 LittleEndian::writeUint32(headerEntry + sizeof(value->mOffset),
610 value->mCompressedSize);
612 MOZ_TRY(Seek(fd, headerStart));
613 MOZ_TRY(Write(fd, buf.Get(), buf.cursor()));
615 mDirty = false;
616 mWrittenOnce = true;
618 return Ok();
621 void StartupCache::InvalidateCache(bool memoryOnly) {
622 WaitOnPrefetchThread();
623 // Ensure we're not writing using mTable...
624 MutexAutoLock unlock(mTableLock);
626 mWrittenOnce = false;
627 if (memoryOnly) {
628 // This should only be called in tests.
629 auto writeResult = WriteToDisk();
630 if (NS_WARN_IF(writeResult.isErr())) {
631 gIgnoreDiskCache = true;
632 return;
635 if (mCurTableReferenced) {
636 // There should be no way for this assert to fail other than a user manually
637 // sending startupcache-invalidate messages through the Browser Toolbox. If
638 // something knowingly invalidates the cache, the event can be counted with
639 // mAllowedInvalidationsCount.
640 MOZ_DIAGNOSTIC_ASSERT(
641 xpc::IsInAutomation() ||
642 // The allowed invalidations can grow faster than the old tables, so
643 // guard against incorrect unsigned subtraction.
644 mAllowedInvalidationsCount > mOldTables.Length() ||
645 // Now perform the real check.
646 mOldTables.Length() - mAllowedInvalidationsCount < 10,
647 "Startup cache invalidated too many times.");
648 mOldTables.AppendElement(std::move(mTable));
649 mCurTableReferenced = false;
650 } else {
651 mTable.clear();
653 mRequestedCount = 0;
654 if (!memoryOnly) {
655 mCacheData.reset();
656 nsresult rv = mFile->Remove(false);
657 if (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND) {
658 gIgnoreDiskCache = true;
659 return;
662 gIgnoreDiskCache = false;
663 auto result = LoadArchive();
664 if (NS_WARN_IF(result.isErr())) {
665 gIgnoreDiskCache = true;
669 void StartupCache::CountAllowedInvalidation() { mAllowedInvalidationsCount++; }
671 void StartupCache::MaybeInitShutdownWrite() {
672 if (mTimer) {
673 mTimer->Cancel();
675 gShutdownInitiated = true;
677 MaybeWriteOffMainThread();
680 void StartupCache::EnsureShutdownWriteComplete() {
681 // If we've already written or there's nothing to write,
682 // we don't need to do anything. This is the common case.
683 if (mWrittenOnce || (mCacheData.initialized() && !ShouldCompactCache())) {
684 return;
686 // Otherwise, ensure the write happens. The timer should have been cancelled
687 // already in MaybeInitShutdownWrite.
688 if (!mTableLock.TryLock()) {
689 // Uh oh, we're writing away from the main thread. Wait to gain the lock,
690 // to ensure the write completes.
691 mTableLock.Lock();
692 } else {
693 // We got the lock. Keep the following in sync with
694 // MaybeWriteOffMainThread:
695 WaitOnPrefetchThread();
696 mDirty = true;
697 mCacheData.reset();
698 // Most of this should be redundant given MaybeWriteOffMainThread should
699 // have run before now.
701 auto writeResult = WriteToDisk();
702 Unused << NS_WARN_IF(writeResult.isErr());
703 // We've had the lock, and `WriteToDisk()` sets mWrittenOnce and mDirty
704 // when done, and checks for them when starting, so we don't need to do
705 // anything else.
707 mTableLock.Unlock();
710 void StartupCache::IgnoreDiskCache() {
711 gIgnoreDiskCache = true;
712 if (gStartupCache) gStartupCache->InvalidateCache();
715 void StartupCache::WaitOnPrefetchThread() {
716 if (!mPrefetchThread || mPrefetchThread == PR_GetCurrentThread()) return;
718 PR_JoinThread(mPrefetchThread);
719 mPrefetchThread = nullptr;
722 void StartupCache::ThreadedPrefetch(void* aClosure) {
723 AUTO_PROFILER_REGISTER_THREAD("StartupCache");
724 NS_SetCurrentThreadName("StartupCache");
725 mozilla::IOInterposer::RegisterCurrentThread();
726 StartupCache* startupCacheObj = static_cast<StartupCache*>(aClosure);
727 uint8_t* buf = startupCacheObj->mCacheData.get<uint8_t>().get();
728 size_t size = startupCacheObj->mCacheData.size();
729 MMAP_FAULT_HANDLER_BEGIN_BUFFER(buf, size)
730 PrefetchMemory(buf, size);
731 MMAP_FAULT_HANDLER_CATCH()
732 mozilla::IOInterposer::UnregisterCurrentThread();
735 bool StartupCache::ShouldCompactCache() {
736 // If we've requested less than 4/5 of the startup cache, then we should
737 // probably compact it down. This can happen quite easily after the first run,
738 // which seems to request quite a few more things than subsequent runs.
739 CheckedInt<uint32_t> threshold = CheckedInt<uint32_t>(mTable.count()) * 4 / 5;
740 MOZ_RELEASE_ASSERT(threshold.isValid(), "Runaway StartupCache size");
741 return mRequestedCount < threshold.value();
745 * The write-thread is spawned on a timeout(which is reset with every write).
746 * This can avoid a slow shutdown.
748 void StartupCache::WriteTimeout(nsITimer* aTimer, void* aClosure) {
750 * It is safe to use the pointer passed in aClosure to reference the
751 * StartupCache object because the timer's lifetime is tightly coupled to
752 * the lifetime of the StartupCache object; this timer is canceled in the
753 * StartupCache destructor, guaranteeing that this function runs if and only
754 * if the StartupCache object is valid.
756 StartupCache* startupCacheObj = static_cast<StartupCache*>(aClosure);
757 startupCacheObj->MaybeWriteOffMainThread();
761 * See StartupCache::WriteTimeout above - this is just the non-static body.
763 void StartupCache::MaybeWriteOffMainThread() {
764 if (mWrittenOnce) {
765 return;
768 if (mCacheData.initialized() && !ShouldCompactCache()) {
769 return;
772 // Keep this code in sync with EnsureShutdownWriteComplete.
773 WaitOnPrefetchThread();
774 mDirty = true;
775 mCacheData.reset();
777 RefPtr<StartupCache> self = this;
778 nsCOMPtr<nsIRunnable> runnable =
779 NS_NewRunnableFunction("StartupCache::Write", [self]() mutable {
780 MutexAutoLock unlock(self->mTableLock);
781 auto result = self->WriteToDisk();
782 Unused << NS_WARN_IF(result.isErr());
784 NS_DispatchBackgroundTask(runnable.forget(), NS_DISPATCH_EVENT_MAY_BLOCK);
787 // We don't want to refcount StartupCache, so we'll just
788 // hold a ref to this and pass it to observerService instead.
789 NS_IMPL_ISUPPORTS(StartupCacheListener, nsIObserver)
791 nsresult StartupCacheListener::Observe(nsISupports* subject, const char* topic,
792 const char16_t* data) {
793 StartupCache* sc = StartupCache::GetSingleton();
794 if (!sc) return NS_OK;
796 if (strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
797 // Do not leave the thread running past xpcom shutdown
798 sc->WaitOnPrefetchThread();
799 StartupCache::gShutdownInitiated = true;
800 // Note that we don't do anything special for the background write
801 // task; we expect the threadpool to finish running any tasks already
802 // posted to it prior to shutdown. FastShutdown will call
803 // EnsureShutdownWriteComplete() to ensure any pending writes happen
804 // in that case.
805 } else if (strcmp(topic, "startupcache-invalidate") == 0) {
806 sc->InvalidateCache(data && nsCRT::strcmp(data, u"memoryOnly") == 0);
807 } else if (strcmp(topic, "intl:app-locales-changed") == 0) {
808 // Live language switching invalidates the startup cache due to the history
809 // sidebar retaining localized strings in its internal SQL query. This
810 // should be a relatively rare event, but a user could do it an arbitrary
811 // number of times.
812 sc->CountAllowedInvalidation();
814 return NS_OK;
817 nsresult StartupCache::GetDebugObjectOutputStream(
818 nsIObjectOutputStream* aStream, nsIObjectOutputStream** aOutStream) {
819 NS_ENSURE_ARG_POINTER(aStream);
820 #ifdef DEBUG
821 auto* stream = new StartupCacheDebugOutputStream(aStream, &mWriteObjectMap);
822 NS_ADDREF(*aOutStream = stream);
823 #else
824 NS_ADDREF(*aOutStream = aStream);
825 #endif
827 return NS_OK;
830 nsresult StartupCache::ResetStartupWriteTimerCheckingReadCount() {
831 nsresult rv = NS_OK;
832 if (!mTimer)
833 mTimer = NS_NewTimer();
834 else
835 rv = mTimer->Cancel();
836 NS_ENSURE_SUCCESS(rv, rv);
837 // Wait for the specified timeout, then write out the cache.
838 mTimer->InitWithNamedFuncCallback(
839 StartupCache::WriteTimeout, this, STARTUP_CACHE_WRITE_TIMEOUT * 1000,
840 nsITimer::TYPE_ONE_SHOT, "StartupCache::WriteTimeout");
841 return NS_OK;
844 nsresult StartupCache::ResetStartupWriteTimer() {
845 mDirty = true;
846 nsresult rv = NS_OK;
847 if (!mTimer)
848 mTimer = NS_NewTimer();
849 else
850 rv = mTimer->Cancel();
851 NS_ENSURE_SUCCESS(rv, rv);
852 // Wait for the specified timeout, then write out the cache.
853 mTimer->InitWithNamedFuncCallback(
854 StartupCache::WriteTimeout, this, STARTUP_CACHE_WRITE_TIMEOUT * 1000,
855 nsITimer::TYPE_ONE_SHOT, "StartupCache::WriteTimeout");
856 return NS_OK;
859 // Used only in tests:
860 bool StartupCache::StartupWriteComplete() {
861 // Need to have written to disk and not added new things since;
862 return !mDirty && mWrittenOnce;
865 // StartupCacheDebugOutputStream implementation
866 #ifdef DEBUG
867 NS_IMPL_ISUPPORTS(StartupCacheDebugOutputStream, nsIObjectOutputStream,
868 nsIBinaryOutputStream, nsIOutputStream)
870 bool StartupCacheDebugOutputStream::CheckReferences(nsISupports* aObject) {
871 nsresult rv;
873 nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(aObject);
874 if (!classInfo) {
875 NS_ERROR("aObject must implement nsIClassInfo");
876 return false;
879 uint32_t flags;
880 rv = classInfo->GetFlags(&flags);
881 NS_ENSURE_SUCCESS(rv, false);
882 if (flags & nsIClassInfo::SINGLETON) return true;
884 bool inserted = mObjectMap->EnsureInserted(aObject);
885 if (!inserted) {
886 NS_ERROR(
887 "non-singleton aObject is referenced multiple times in this"
888 "serialization, we don't support that.");
891 return inserted;
894 // nsIObjectOutputStream implementation
895 nsresult StartupCacheDebugOutputStream::WriteObject(nsISupports* aObject,
896 bool aIsStrongRef) {
897 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
899 NS_ASSERTION(rootObject.get() == aObject,
900 "bad call to WriteObject -- call WriteCompoundObject!");
901 bool check = CheckReferences(aObject);
902 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
903 return mBinaryStream->WriteObject(aObject, aIsStrongRef);
906 nsresult StartupCacheDebugOutputStream::WriteSingleRefObject(
907 nsISupports* aObject) {
908 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
910 NS_ASSERTION(rootObject.get() == aObject,
911 "bad call to WriteSingleRefObject -- call WriteCompoundObject!");
912 bool check = CheckReferences(aObject);
913 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
914 return mBinaryStream->WriteSingleRefObject(aObject);
917 nsresult StartupCacheDebugOutputStream::WriteCompoundObject(
918 nsISupports* aObject, const nsIID& aIID, bool aIsStrongRef) {
919 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
921 nsCOMPtr<nsISupports> roundtrip;
922 rootObject->QueryInterface(aIID, getter_AddRefs(roundtrip));
923 NS_ASSERTION(roundtrip.get() == aObject,
924 "bad aggregation or multiple inheritance detected by call to "
925 "WriteCompoundObject!");
927 bool check = CheckReferences(aObject);
928 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
929 return mBinaryStream->WriteCompoundObject(aObject, aIID, aIsStrongRef);
932 nsresult StartupCacheDebugOutputStream::WriteID(nsID const& aID) {
933 return mBinaryStream->WriteID(aID);
936 char* StartupCacheDebugOutputStream::GetBuffer(uint32_t aLength,
937 uint32_t aAlignMask) {
938 return mBinaryStream->GetBuffer(aLength, aAlignMask);
941 void StartupCacheDebugOutputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
942 mBinaryStream->PutBuffer(aBuffer, aLength);
944 #endif // DEBUG
946 } // namespace scache
947 } // namespace mozilla