Bug 1832033: change `CheckPopoverValidity` to match spec more closely. r=emilio
[gecko.git] / startupcache / StartupCache.cpp
blobe38439fb71e6682f1893d4dcf90766189a1a5231
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 MutexAutoLock lock(mTableLock);
69 MOZ_COLLECT_REPORT(
70 "explicit/startup-cache/mapping", KIND_NONHEAP, UNITS_BYTES,
71 mCacheData.nonHeapSizeOfExcludingThis(),
72 "Memory used to hold the mapping of the startup cache from file. "
73 "This memory is likely to be swapped out shortly after start-up.");
75 MOZ_COLLECT_REPORT("explicit/startup-cache/data", KIND_HEAP, UNITS_BYTES,
76 HeapSizeOfIncludingThis(StartupCacheMallocSizeOf),
77 "Memory used by the startup cache for things other than "
78 "the file mapping.");
80 return NS_OK;
83 static const uint8_t MAGIC[] = "startupcache0002";
84 // This is a heuristic value for how much to reserve for mTable to avoid
85 // rehashing. This is not a hard limit in release builds, but it is in
86 // debug builds as it should be stable. If we exceed this number we should
87 // just increase it.
88 static const size_t STARTUP_CACHE_RESERVE_CAPACITY = 450;
89 // This is a hard limit which we will assert on, to ensure that we don't
90 // have some bug causing runaway cache growth.
91 static const size_t STARTUP_CACHE_MAX_CAPACITY = 5000;
93 // Not const because we change it for gtests.
94 static uint8_t STARTUP_CACHE_WRITE_TIMEOUT = 60;
96 #define STARTUP_CACHE_NAME "startupCache." SC_WORDSIZE "." SC_ENDIAN
98 static inline Result<Ok, nsresult> Write(PRFileDesc* fd, const void* data,
99 int32_t len) {
100 if (PR_Write(fd, data, len) != len) {
101 return Err(NS_ERROR_FAILURE);
103 return Ok();
106 static inline Result<Ok, nsresult> Seek(PRFileDesc* fd, int32_t offset) {
107 if (PR_Seek(fd, offset, PR_SEEK_SET) == -1) {
108 return Err(NS_ERROR_FAILURE);
110 return Ok();
113 static nsresult MapLZ4ErrorToNsresult(size_t aError) {
114 return NS_ERROR_FAILURE;
117 StartupCache* StartupCache::GetSingletonNoInit() {
118 return StartupCache::gStartupCache;
121 StartupCache* StartupCache::GetSingleton() {
122 #ifdef MOZ_BACKGROUNDTASKS
123 if (BackgroundTasks::IsBackgroundTaskMode()) {
124 return nullptr;
126 #endif
128 if (!gStartupCache) {
129 if (!XRE_IsParentProcess()) {
130 return nullptr;
132 #ifdef MOZ_DISABLE_STARTUPCACHE
133 return nullptr;
134 #else
135 StartupCache::InitSingleton();
136 #endif
139 return StartupCache::gStartupCache;
142 void StartupCache::DeleteSingleton() { StartupCache::gStartupCache = nullptr; }
144 nsresult StartupCache::InitSingleton() {
145 nsresult rv;
146 StartupCache::gStartupCache = new StartupCache();
148 rv = StartupCache::gStartupCache->Init();
149 if (NS_FAILED(rv)) {
150 StartupCache::gStartupCache = nullptr;
152 return rv;
155 StaticRefPtr<StartupCache> StartupCache::gStartupCache;
156 bool StartupCache::gShutdownInitiated;
157 bool StartupCache::gIgnoreDiskCache;
158 bool StartupCache::gFoundDiskCacheOnInit;
160 NS_IMPL_ISUPPORTS(StartupCache, nsIMemoryReporter)
162 StartupCache::StartupCache()
163 : mTableLock("StartupCache::mTableLock"),
164 mDirty(false),
165 mWrittenOnce(false),
166 mCurTableReferenced(false),
167 mRequestedCount(0),
168 mCacheEntriesBaseOffset(0) {}
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);
233 MutexAutoLock lock(mTableLock);
234 auto result = LoadArchive();
235 rv = result.isErr() ? result.unwrapErr() : NS_OK;
238 gFoundDiskCacheOnInit = rv != NS_ERROR_FILE_NOT_FOUND;
240 // Sometimes we don't have a cache yet, that's ok.
241 // If it's corrupted, just remove it and start over.
242 if (gIgnoreDiskCache || (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND)) {
243 NS_WARNING("Failed to load startupcache file correctly, removing!");
244 InvalidateCache();
247 RegisterWeakMemoryReporter(this);
248 mDecompressionContext = MakeUnique<LZ4FrameDecompressionContext>(true);
250 return NS_OK;
253 void StartupCache::StartPrefetchMemory() {
255 MonitorAutoLock lock(mPrefetchComplete);
256 mPrefetchInProgress = true;
258 NS_DispatchBackgroundTask(NewRunnableMethod(
259 "StartupCache::ThreadedPrefetch", this, &StartupCache::ThreadedPrefetch));
263 * LoadArchive can only be called from the main thread.
265 Result<Ok, nsresult> StartupCache::LoadArchive() {
266 MOZ_ASSERT(NS_IsMainThread(), "Can only load startup cache on main thread");
267 if (gIgnoreDiskCache) return Err(NS_ERROR_FAILURE);
269 mTableLock.AssertCurrentThreadOwns();
271 MOZ_TRY(mCacheData.init(mFile));
272 auto size = mCacheData.size();
273 if (CanPrefetchMemory()) {
274 StartPrefetchMemory();
277 uint32_t headerSize;
278 if (size < sizeof(MAGIC) + sizeof(headerSize)) {
279 return Err(NS_ERROR_UNEXPECTED);
282 auto data = mCacheData.get<uint8_t>();
283 auto end = data + size;
285 MMAP_FAULT_HANDLER_BEGIN_BUFFER(data.get(), size)
287 if (memcmp(MAGIC, data.get(), sizeof(MAGIC))) {
288 return Err(NS_ERROR_UNEXPECTED);
290 data += sizeof(MAGIC);
292 headerSize = LittleEndian::readUint32(data.get());
293 data += sizeof(headerSize);
295 if (headerSize > end - data) {
296 MOZ_ASSERT(false, "StartupCache file is corrupt.");
297 return Err(NS_ERROR_UNEXPECTED);
300 Range<uint8_t> header(data, data + headerSize);
301 data += headerSize;
303 mCacheEntriesBaseOffset = sizeof(MAGIC) + sizeof(headerSize) + headerSize;
305 if (!mTable.reserve(STARTUP_CACHE_RESERVE_CAPACITY)) {
306 return Err(NS_ERROR_UNEXPECTED);
308 auto cleanup = MakeScopeExit([&]() {
309 mTableLock.AssertCurrentThreadOwns();
310 WaitOnPrefetch();
311 mTable.clear();
312 mCacheData.reset();
314 loader::InputBuffer buf(header);
316 uint32_t currentOffset = 0;
317 while (!buf.finished()) {
318 uint32_t offset = 0;
319 uint32_t compressedSize = 0;
320 uint32_t uncompressedSize = 0;
321 nsCString key;
322 buf.codeUint32(offset);
323 buf.codeUint32(compressedSize);
324 buf.codeUint32(uncompressedSize);
325 buf.codeString(key);
327 if (offset + compressedSize > end - data) {
328 MOZ_ASSERT(false, "StartupCache file is corrupt.");
329 return Err(NS_ERROR_UNEXPECTED);
332 // Make sure offsets match what we'd expect based on script ordering and
333 // size, as a basic sanity check.
334 if (offset != currentOffset) {
335 return Err(NS_ERROR_UNEXPECTED);
337 currentOffset += compressedSize;
339 // We could use mTable.putNew if we knew the file we're loading weren't
340 // corrupt. However, we don't know that, so check if the key already
341 // exists. If it does, we know the file must be corrupt.
342 decltype(mTable)::AddPtr p = mTable.lookupForAdd(key);
343 if (p) {
344 return Err(NS_ERROR_UNEXPECTED);
347 if (!mTable.add(
348 p, key,
349 StartupCacheEntry(offset, compressedSize, uncompressedSize))) {
350 return Err(NS_ERROR_UNEXPECTED);
354 if (buf.error()) {
355 return Err(NS_ERROR_UNEXPECTED);
358 cleanup.release();
361 MMAP_FAULT_HANDLER_CATCH(Err(NS_ERROR_UNEXPECTED))
363 return Ok();
366 bool StartupCache::HasEntry(const char* id) {
367 AUTO_PROFILER_LABEL("StartupCache::HasEntry", OTHER);
369 MOZ_ASSERT(NS_IsMainThread(), "Startup cache only available on main thread");
371 MutexAutoLock lock(mTableLock);
372 return mTable.has(nsDependentCString(id));
375 nsresult StartupCache::GetBuffer(const char* id, const char** outbuf,
376 uint32_t* length)
377 MOZ_NO_THREAD_SAFETY_ANALYSIS {
378 AUTO_PROFILER_LABEL("StartupCache::GetBuffer", OTHER);
380 NS_ASSERTION(NS_IsMainThread(),
381 "Startup cache only available on main thread");
383 Telemetry::LABELS_STARTUP_CACHE_REQUESTS label =
384 Telemetry::LABELS_STARTUP_CACHE_REQUESTS::Miss;
385 auto telemetry =
386 MakeScopeExit([&label] { Telemetry::AccumulateCategorical(label); });
388 MutexAutoLock lock(mTableLock);
389 decltype(mTable)::Ptr p = mTable.lookup(nsDependentCString(id));
390 if (!p) {
391 return NS_ERROR_NOT_AVAILABLE;
394 auto& value = p->value();
395 if (value.mData) {
396 label = Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitMemory;
397 } else {
398 if (!mCacheData.initialized()) {
399 return NS_ERROR_NOT_AVAILABLE;
402 size_t totalRead = 0;
403 size_t totalWritten = 0;
404 Span<const char> compressed = Span(
405 mCacheData.get<char>().get() + mCacheEntriesBaseOffset + value.mOffset,
406 value.mCompressedSize);
407 value.mData = UniqueFreePtr<char[]>(reinterpret_cast<char*>(
408 malloc(sizeof(char) * value.mUncompressedSize)));
409 Span<char> uncompressed = Span(value.mData.get(), value.mUncompressedSize);
410 MMAP_FAULT_HANDLER_BEGIN_BUFFER(uncompressed.Elements(),
411 uncompressed.Length())
412 bool finished = false;
413 while (!finished) {
414 auto result = mDecompressionContext->Decompress(
415 uncompressed.From(totalWritten), compressed.From(totalRead));
416 if (NS_WARN_IF(result.isErr())) {
417 value.mData = nullptr;
418 MutexAutoUnlock unlock(mTableLock);
419 InvalidateCache();
420 return NS_ERROR_FAILURE;
422 auto decompressionResult = result.unwrap();
423 totalRead += decompressionResult.mSizeRead;
424 totalWritten += decompressionResult.mSizeWritten;
425 finished = decompressionResult.mFinished;
428 MMAP_FAULT_HANDLER_CATCH(NS_ERROR_FAILURE)
430 label = Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitDisk;
433 if (!value.mRequested) {
434 value.mRequested = true;
435 value.mRequestedOrder = ++mRequestedCount;
436 MOZ_ASSERT(mRequestedCount <= mTable.count(),
437 "Somehow we requested more StartupCache items than exist.");
438 ResetStartupWriteTimerCheckingReadCount();
441 // Track that something holds a reference into mTable, so we know to hold
442 // onto it in case the cache is invalidated.
443 mCurTableReferenced = true;
444 *outbuf = value.mData.get();
445 *length = value.mUncompressedSize;
446 return NS_OK;
449 // Makes a copy of the buffer, client retains ownership of inbuf.
450 nsresult StartupCache::PutBuffer(const char* id, UniqueFreePtr<char[]>&& inbuf,
451 uint32_t len) MOZ_NO_THREAD_SAFETY_ANALYSIS {
452 NS_ASSERTION(NS_IsMainThread(),
453 "Startup cache only available on main thread");
454 if (StartupCache::gShutdownInitiated) {
455 return NS_ERROR_NOT_AVAILABLE;
458 // Try to gain the table write lock. If the background task to write the
459 // cache is running, this will fail.
460 MutexAutoTryLock lock(mTableLock);
461 if (!lock) {
462 return NS_ERROR_NOT_AVAILABLE;
464 mTableLock.AssertCurrentThreadOwns();
465 bool exists = mTable.has(nsDependentCString(id));
466 if (exists) {
467 NS_WARNING("Existing entry in StartupCache.");
468 // Double-caching is undesirable but not an error.
469 return NS_OK;
472 // putNew returns false on alloc failure - in the very unlikely event we hit
473 // that and aren't going to crash elsewhere, there's no reason we need to
474 // crash here.
475 if (mTable.putNew(nsCString(id), StartupCacheEntry(std::move(inbuf), len,
476 ++mRequestedCount))) {
477 return ResetStartupWriteTimer();
479 MOZ_DIAGNOSTIC_ASSERT(mTable.count() < STARTUP_CACHE_MAX_CAPACITY,
480 "Too many StartupCache entries.");
481 return NS_OK;
484 size_t StartupCache::HeapSizeOfIncludingThis(
485 mozilla::MallocSizeOf aMallocSizeOf) const {
486 // This function could measure more members, but they haven't been found by
487 // DMD to be significant. They can be added later if necessary.
489 size_t n = aMallocSizeOf(this);
491 n += mTable.shallowSizeOfExcludingThis(aMallocSizeOf);
492 for (auto iter = mTable.iter(); !iter.done(); iter.next()) {
493 if (iter.get().value().mData) {
494 n += aMallocSizeOf(iter.get().value().mData.get());
496 n += iter.get().key().SizeOfExcludingThisIfUnshared(aMallocSizeOf);
499 return n;
503 * WriteToDisk writes the cache out to disk. Callers of WriteToDisk need to call
504 * WaitOnWriteComplete to make sure there isn't a write
505 * happening on another thread.
506 * We own the mTableLock here.
508 Result<Ok, nsresult> StartupCache::WriteToDisk() {
509 if (!mDirty || mWrittenOnce) {
510 return Ok();
513 if (!mFile) {
514 return Err(NS_ERROR_UNEXPECTED);
517 AutoFDClose fd;
518 MOZ_TRY(mFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
519 0644, &fd.rwget()));
521 nsTArray<std::pair<const nsCString*, StartupCacheEntry*>> entries;
522 for (auto iter = mTable.iter(); !iter.done(); iter.next()) {
523 if (iter.get().value().mRequested) {
524 entries.AppendElement(
525 std::make_pair(&iter.get().key(), &iter.get().value()));
529 if (entries.IsEmpty()) {
530 return Ok();
533 entries.Sort(StartupCacheEntry::Comparator());
534 loader::OutputBuffer buf;
535 for (auto& e : entries) {
536 auto key = e.first;
537 auto value = e.second;
538 auto uncompressedSize = value->mUncompressedSize;
539 // Set the mHeaderOffsetInFile so we can go back and edit the offset.
540 value->mHeaderOffsetInFile = buf.cursor();
541 // Write a 0 offset/compressed size as a placeholder until we get the real
542 // offset after compressing.
543 buf.codeUint32(0);
544 buf.codeUint32(0);
545 buf.codeUint32(uncompressedSize);
546 buf.codeString(*key);
549 uint8_t headerSize[4];
550 LittleEndian::writeUint32(headerSize, buf.cursor());
552 MOZ_TRY(Write(fd, MAGIC, sizeof(MAGIC)));
553 MOZ_TRY(Write(fd, headerSize, sizeof(headerSize)));
554 size_t headerStart = sizeof(MAGIC) + sizeof(headerSize);
555 size_t dataStart = headerStart + buf.cursor();
556 MOZ_TRY(Seek(fd, dataStart));
558 size_t offset = 0;
560 const size_t chunkSize = 1024 * 16;
561 LZ4FrameCompressionContext ctx(6, /* aCompressionLevel */
562 chunkSize, /* aReadBufLen */
563 true, /* aChecksum */
564 true); /* aStableSrc */
565 size_t writeBufLen = ctx.GetRequiredWriteBufferLength();
566 auto writeBuffer = MakeUnique<char[]>(writeBufLen);
567 auto writeSpan = Span(writeBuffer.get(), writeBufLen);
569 for (auto& e : entries) {
570 auto value = e.second;
571 value->mOffset = offset;
572 Span<const char> result;
573 MOZ_TRY_VAR(result,
574 ctx.BeginCompressing(writeSpan).mapErr(MapLZ4ErrorToNsresult));
575 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
576 offset += result.Length();
578 for (size_t i = 0; i < value->mUncompressedSize; i += chunkSize) {
579 size_t size = std::min(chunkSize, value->mUncompressedSize - i);
580 char* uncompressed = value->mData.get() + i;
581 MOZ_TRY_VAR(result, ctx.ContinueCompressing(Span(uncompressed, size))
582 .mapErr(MapLZ4ErrorToNsresult));
583 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
584 offset += result.Length();
587 MOZ_TRY_VAR(result, ctx.EndCompressing().mapErr(MapLZ4ErrorToNsresult));
588 MOZ_TRY(Write(fd, result.Elements(), result.Length()));
589 offset += result.Length();
590 value->mCompressedSize = offset - value->mOffset;
591 MOZ_TRY(Seek(fd, dataStart + offset));
594 for (auto& e : entries) {
595 auto value = e.second;
596 uint8_t* headerEntry = buf.Get() + value->mHeaderOffsetInFile;
597 LittleEndian::writeUint32(headerEntry, value->mOffset);
598 LittleEndian::writeUint32(headerEntry + sizeof(value->mOffset),
599 value->mCompressedSize);
601 MOZ_TRY(Seek(fd, headerStart));
602 MOZ_TRY(Write(fd, buf.Get(), buf.cursor()));
604 mDirty = false;
605 mWrittenOnce = true;
607 return Ok();
610 void StartupCache::InvalidateCache(bool memoryOnly) {
611 WaitOnPrefetch();
612 // Ensure we're not writing using mTable...
613 MutexAutoLock lock(mTableLock);
615 mWrittenOnce = false;
616 if (memoryOnly) {
617 // This should only be called in tests.
618 auto writeResult = WriteToDisk();
619 if (NS_WARN_IF(writeResult.isErr())) {
620 gIgnoreDiskCache = true;
621 return;
624 if (mCurTableReferenced) {
625 // There should be no way for this assert to fail other than a user manually
626 // sending startupcache-invalidate messages through the Browser Toolbox. If
627 // something knowingly invalidates the cache, the event can be counted with
628 // mAllowedInvalidationsCount.
629 MOZ_DIAGNOSTIC_ASSERT(
630 xpc::IsInAutomation() ||
631 // The allowed invalidations can grow faster than the old tables, so
632 // guard against incorrect unsigned subtraction.
633 mAllowedInvalidationsCount > mOldTables.Length() ||
634 // Now perform the real check.
635 mOldTables.Length() - mAllowedInvalidationsCount < 10,
636 "Startup cache invalidated too many times.");
637 mOldTables.AppendElement(std::move(mTable));
638 mCurTableReferenced = false;
639 } else {
640 mTable.clear();
642 mRequestedCount = 0;
643 if (!memoryOnly) {
644 mCacheData.reset();
645 nsresult rv = mFile->Remove(false);
646 if (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND) {
647 gIgnoreDiskCache = true;
648 return;
651 gIgnoreDiskCache = false;
652 auto result = LoadArchive();
653 if (NS_WARN_IF(result.isErr())) {
654 gIgnoreDiskCache = true;
658 void StartupCache::CountAllowedInvalidation() { mAllowedInvalidationsCount++; }
660 void StartupCache::MaybeInitShutdownWrite() {
661 if (mTimer) {
662 mTimer->Cancel();
664 gShutdownInitiated = true;
666 MaybeWriteOffMainThread();
669 void StartupCache::EnsureShutdownWriteComplete() {
670 MutexAutoLock lock(mTableLock);
671 // If we've already written or there's nothing to write,
672 // we don't need to do anything. This is the common case.
673 if (mWrittenOnce || (mCacheData.initialized() && !ShouldCompactCache())) {
674 return;
676 // Otherwise, ensure the write happens. The timer should have been cancelled
677 // already in MaybeInitShutdownWrite.
679 // We got the lock. Keep the following in sync with
680 // MaybeWriteOffMainThread:
681 WaitOnPrefetch();
682 mDirty = true;
683 mCacheData.reset();
684 // Most of this should be redundant given MaybeWriteOffMainThread should
685 // have run before now.
687 auto writeResult = WriteToDisk();
688 Unused << NS_WARN_IF(writeResult.isErr());
689 // We've had the lock, and `WriteToDisk()` sets mWrittenOnce and mDirty
690 // when done, and checks for them when starting, so we don't need to do
691 // anything else.
694 void StartupCache::IgnoreDiskCache() {
695 gIgnoreDiskCache = true;
696 if (gStartupCache) gStartupCache->InvalidateCache();
699 bool StartupCache::GetIgnoreDiskCache() { return gIgnoreDiskCache; }
701 void StartupCache::WaitOnPrefetch() {
702 // This can't be called from within ThreadedPrefetch()
703 MonitorAutoLock lock(mPrefetchComplete);
704 while (mPrefetchInProgress) {
705 mPrefetchComplete.Wait();
709 void StartupCache::ThreadedPrefetch() {
710 uint8_t* buf;
711 size_t size;
713 MutexAutoLock lock(mTableLock);
714 buf = mCacheData.get<uint8_t>().get();
715 size = mCacheData.size();
717 // PrefetchMemory does madvise/equivalent, but doesn't access the memory
718 // pointed to by buf
719 MMAP_FAULT_HANDLER_BEGIN_BUFFER(buf, size)
720 PrefetchMemory(buf, size);
721 MMAP_FAULT_HANDLER_CATCH()
722 MonitorAutoLock lock(mPrefetchComplete);
723 mPrefetchInProgress = false;
724 mPrefetchComplete.NotifyAll();
727 // mTableLock must be held
728 bool StartupCache::ShouldCompactCache() {
729 // If we've requested less than 4/5 of the startup cache, then we should
730 // probably compact it down. This can happen quite easily after the first run,
731 // which seems to request quite a few more things than subsequent runs.
732 CheckedInt<uint32_t> threshold = CheckedInt<uint32_t>(mTable.count()) * 4 / 5;
733 MOZ_RELEASE_ASSERT(threshold.isValid(), "Runaway StartupCache size");
734 return mRequestedCount < threshold.value();
738 * The write-thread is spawned on a timeout(which is reset with every write).
739 * This can avoid a slow shutdown.
741 void StartupCache::WriteTimeout(nsITimer* aTimer, void* aClosure) {
743 * It is safe to use the pointer passed in aClosure to reference the
744 * StartupCache object because the timer's lifetime is tightly coupled to
745 * the lifetime of the StartupCache object; this timer is canceled in the
746 * StartupCache destructor, guaranteeing that this function runs if and only
747 * if the StartupCache object is valid.
749 StartupCache* startupCacheObj = static_cast<StartupCache*>(aClosure);
750 startupCacheObj->MaybeWriteOffMainThread();
754 * See StartupCache::WriteTimeout above - this is just the non-static body.
756 void StartupCache::MaybeWriteOffMainThread() {
758 MutexAutoLock lock(mTableLock);
759 if (mWrittenOnce || (mCacheData.initialized() && !ShouldCompactCache())) {
760 return;
763 // Keep this code in sync with EnsureShutdownWriteComplete.
764 WaitOnPrefetch();
766 MutexAutoLock lock(mTableLock);
767 mDirty = true;
768 mCacheData.reset();
771 RefPtr<StartupCache> self = this;
772 nsCOMPtr<nsIRunnable> runnable =
773 NS_NewRunnableFunction("StartupCache::Write", [self]() mutable {
774 MutexAutoLock lock(self->mTableLock);
775 auto result = self->WriteToDisk();
776 Unused << NS_WARN_IF(result.isErr());
778 NS_DispatchBackgroundTask(runnable.forget(), NS_DISPATCH_EVENT_MAY_BLOCK);
781 // We don't want to refcount StartupCache, so we'll just
782 // hold a ref to this and pass it to observerService instead.
783 NS_IMPL_ISUPPORTS(StartupCacheListener, nsIObserver)
785 nsresult StartupCacheListener::Observe(nsISupports* subject, const char* topic,
786 const char16_t* data) {
787 StartupCache* sc = StartupCache::GetSingleton();
788 if (!sc) return NS_OK;
790 if (strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
791 // Do not leave the thread running past xpcom shutdown
792 sc->WaitOnPrefetch();
793 StartupCache::gShutdownInitiated = true;
794 // Note that we don't do anything special for the background write
795 // task; we expect the threadpool to finish running any tasks already
796 // posted to it prior to shutdown. FastShutdown will call
797 // EnsureShutdownWriteComplete() to ensure any pending writes happen
798 // in that case.
799 } else if (strcmp(topic, "startupcache-invalidate") == 0) {
800 sc->InvalidateCache(data && nsCRT::strcmp(data, u"memoryOnly") == 0);
801 } else if (strcmp(topic, "intl:app-locales-changed") == 0) {
802 // Live language switching invalidates the startup cache due to the history
803 // sidebar retaining localized strings in its internal SQL query. This
804 // should be a relatively rare event, but a user could do it an arbitrary
805 // number of times.
806 sc->CountAllowedInvalidation();
808 return NS_OK;
811 nsresult StartupCache::GetDebugObjectOutputStream(
812 nsIObjectOutputStream* aStream, nsIObjectOutputStream** aOutStream) {
813 NS_ENSURE_ARG_POINTER(aStream);
814 #ifdef DEBUG
815 auto* stream = new StartupCacheDebugOutputStream(aStream, &mWriteObjectMap);
816 NS_ADDREF(*aOutStream = stream);
817 #else
818 NS_ADDREF(*aOutStream = aStream);
819 #endif
821 return NS_OK;
824 nsresult StartupCache::ResetStartupWriteTimerCheckingReadCount() {
825 nsresult rv = NS_OK;
826 if (!mTimer)
827 mTimer = NS_NewTimer();
828 else
829 rv = mTimer->Cancel();
830 NS_ENSURE_SUCCESS(rv, rv);
831 // Wait for the specified timeout, then write out the cache.
832 mTimer->InitWithNamedFuncCallback(
833 StartupCache::WriteTimeout, this, STARTUP_CACHE_WRITE_TIMEOUT * 1000,
834 nsITimer::TYPE_ONE_SHOT, "StartupCache::WriteTimeout");
835 return NS_OK;
838 // For test code only
839 nsresult StartupCache::ResetStartupWriteTimerAndLock() {
840 MutexAutoLock lock(mTableLock);
841 return ResetStartupWriteTimer();
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 MutexAutoLock lock(mTableLock);
863 return !mDirty && mWrittenOnce;
866 // StartupCacheDebugOutputStream implementation
867 #ifdef DEBUG
868 NS_IMPL_ISUPPORTS(StartupCacheDebugOutputStream, nsIObjectOutputStream,
869 nsIBinaryOutputStream, nsIOutputStream)
871 bool StartupCacheDebugOutputStream::CheckReferences(nsISupports* aObject) {
872 nsresult rv;
874 nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(aObject);
875 if (!classInfo) {
876 NS_ERROR("aObject must implement nsIClassInfo");
877 return false;
880 uint32_t flags;
881 rv = classInfo->GetFlags(&flags);
882 NS_ENSURE_SUCCESS(rv, false);
883 if (flags & nsIClassInfo::SINGLETON) return true;
885 bool inserted = mObjectMap->EnsureInserted(aObject);
886 if (!inserted) {
887 NS_ERROR(
888 "non-singleton aObject is referenced multiple times in this"
889 "serialization, we don't support that.");
892 return inserted;
895 // nsIObjectOutputStream implementation
896 nsresult StartupCacheDebugOutputStream::WriteObject(nsISupports* aObject,
897 bool aIsStrongRef) {
898 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
900 NS_ASSERTION(rootObject.get() == aObject,
901 "bad call to WriteObject -- call WriteCompoundObject!");
902 bool check = CheckReferences(aObject);
903 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
904 return mBinaryStream->WriteObject(aObject, aIsStrongRef);
907 nsresult StartupCacheDebugOutputStream::WriteSingleRefObject(
908 nsISupports* aObject) {
909 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
911 NS_ASSERTION(rootObject.get() == aObject,
912 "bad call to WriteSingleRefObject -- call WriteCompoundObject!");
913 bool check = CheckReferences(aObject);
914 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
915 return mBinaryStream->WriteSingleRefObject(aObject);
918 nsresult StartupCacheDebugOutputStream::WriteCompoundObject(
919 nsISupports* aObject, const nsIID& aIID, bool aIsStrongRef) {
920 nsCOMPtr<nsISupports> rootObject(do_QueryInterface(aObject));
922 nsCOMPtr<nsISupports> roundtrip;
923 rootObject->QueryInterface(aIID, getter_AddRefs(roundtrip));
924 NS_ASSERTION(roundtrip.get() == aObject,
925 "bad aggregation or multiple inheritance detected by call to "
926 "WriteCompoundObject!");
928 bool check = CheckReferences(aObject);
929 NS_ENSURE_TRUE(check, NS_ERROR_FAILURE);
930 return mBinaryStream->WriteCompoundObject(aObject, aIID, aIsStrongRef);
933 nsresult StartupCacheDebugOutputStream::WriteID(nsID const& aID) {
934 return mBinaryStream->WriteID(aID);
937 char* StartupCacheDebugOutputStream::GetBuffer(uint32_t aLength,
938 uint32_t aAlignMask) {
939 return mBinaryStream->GetBuffer(aLength, aAlignMask);
942 void StartupCacheDebugOutputStream::PutBuffer(char* aBuffer, uint32_t aLength) {
943 mBinaryStream->PutBuffer(aBuffer, aLength);
945 #endif // DEBUG
947 } // namespace scache
948 } // namespace mozilla