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/. */
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"
22 #include "nsDirectoryServiceUtils.h"
23 #include "nsIClassInfo.h"
25 #include "nsIObserver.h"
26 #include "nsIOutputStream.h"
27 #include "nsISupports.h"
29 #include "mozilla/Omnijar.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"
47 # define SC_ENDIAN "big"
49 # define SC_ENDIAN "little"
52 #if PR_BYTES_PER_WORD == 4
53 # define SC_WORDSIZE "4"
55 # define SC_WORDSIZE "8"
58 using namespace mozilla::Compression
;
63 MOZ_DEFINE_MALLOC_SIZE_OF(StartupCacheMallocSizeOf
)
66 StartupCache::CollectReports(nsIHandleReportCallback
* aHandleReport
,
67 nsISupports
* aData
, bool aAnonymize
) {
68 MutexAutoLock
lock(mTableLock
);
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 "
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
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
,
100 if (PR_Write(fd
, data
, len
) != len
) {
101 return Err(NS_ERROR_FAILURE
);
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
);
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()) {
128 if (!gStartupCache
) {
129 if (!XRE_IsParentProcess()) {
132 #ifdef MOZ_DISABLE_STARTUPCACHE
135 StartupCache::InitSingleton();
139 return StartupCache::gStartupCache
;
142 void StartupCache::DeleteSingleton() { StartupCache::gStartupCache
= nullptr; }
144 nsresult
StartupCache::InitSingleton() {
146 StartupCache::gStartupCache
= new StartupCache();
148 rv
= StartupCache::gStartupCache
->Init();
150 StartupCache::gStartupCache
= nullptr;
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"),
166 mCurTableReferenced(false),
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"));
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
186 char* env
= PR_GetEnv("MOZ_STARTUP_CACHE");
188 rv
= NS_NewLocalFile(NS_ConvertUTF8toUTF16(env
), false,
189 getter_AddRefs(mFile
));
191 nsCOMPtr
<nsIFile
> file
;
192 rv
= NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(file
));
194 // return silently, this will fail in mochitests's xpcshell process.
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
);
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
,
224 NS_ENSURE_SUCCESS(rv
, rv
);
225 rv
= mObserverService
->AddObserver(mListener
, "startupcache-invalidate",
227 NS_ENSURE_SUCCESS(rv
, rv
);
228 rv
= mObserverService
->AddObserver(mListener
, "intl:app-locales-changed",
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!");
247 RegisterWeakMemoryReporter(this);
248 mDecompressionContext
= MakeUnique
<LZ4FrameDecompressionContext
>(true);
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();
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
);
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();
314 loader::InputBuffer
buf(header
);
316 uint32_t currentOffset
= 0;
317 while (!buf
.finished()) {
319 uint32_t compressedSize
= 0;
320 uint32_t uncompressedSize
= 0;
322 buf
.codeUint32(offset
);
323 buf
.codeUint32(compressedSize
);
324 buf
.codeUint32(uncompressedSize
);
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
);
344 return Err(NS_ERROR_UNEXPECTED
);
349 StartupCacheEntry(offset
, compressedSize
, uncompressedSize
))) {
350 return Err(NS_ERROR_UNEXPECTED
);
355 return Err(NS_ERROR_UNEXPECTED
);
361 MMAP_FAULT_HANDLER_CATCH(Err(NS_ERROR_UNEXPECTED
))
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
,
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
;
386 MakeScopeExit([&label
] { Telemetry::AccumulateCategorical(label
); });
388 MutexAutoLock
lock(mTableLock
);
389 decltype(mTable
)::Ptr p
= mTable
.lookup(nsDependentCString(id
));
391 return NS_ERROR_NOT_AVAILABLE
;
394 auto& value
= p
->value();
396 label
= Telemetry::LABELS_STARTUP_CACHE_REQUESTS::HitMemory
;
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;
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
);
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
;
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
);
462 return NS_ERROR_NOT_AVAILABLE
;
464 mTableLock
.AssertCurrentThreadOwns();
465 bool exists
= mTable
.has(nsDependentCString(id
));
467 NS_WARNING("Existing entry in StartupCache.");
468 // Double-caching is undesirable but not an error.
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
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.");
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
);
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
) {
514 return Err(NS_ERROR_UNEXPECTED
);
518 MOZ_TRY(mFile
->OpenNSPRFileDesc(PR_WRONLY
| PR_CREATE_FILE
| PR_TRUNCATE
,
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()) {
533 entries
.Sort(StartupCacheEntry::Comparator());
534 loader::OutputBuffer buf
;
535 for (auto& e
: entries
) {
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.
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
));
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
;
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()));
610 void StartupCache::InvalidateCache(bool memoryOnly
) {
612 // Ensure we're not writing using mTable...
613 MutexAutoLock
lock(mTableLock
);
615 mWrittenOnce
= false;
617 // This should only be called in tests.
618 auto writeResult
= WriteToDisk();
619 if (NS_WARN_IF(writeResult
.isErr())) {
620 gIgnoreDiskCache
= true;
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;
645 nsresult rv
= mFile
->Remove(false);
646 if (NS_FAILED(rv
) && rv
!= NS_ERROR_FILE_NOT_FOUND
) {
647 gIgnoreDiskCache
= true;
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() {
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())) {
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:
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
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() {
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
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())) {
763 // Keep this code in sync with EnsureShutdownWriteComplete.
766 MutexAutoLock
lock(mTableLock
);
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
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
806 sc
->CountAllowedInvalidation();
811 nsresult
StartupCache::GetDebugObjectOutputStream(
812 nsIObjectOutputStream
* aStream
, nsIObjectOutputStream
** aOutStream
) {
813 NS_ENSURE_ARG_POINTER(aStream
);
815 auto* stream
= new StartupCacheDebugOutputStream(aStream
, &mWriteObjectMap
);
816 NS_ADDREF(*aOutStream
= stream
);
818 NS_ADDREF(*aOutStream
= aStream
);
824 nsresult
StartupCache::ResetStartupWriteTimerCheckingReadCount() {
827 mTimer
= NS_NewTimer();
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");
838 // For test code only
839 nsresult
StartupCache::ResetStartupWriteTimerAndLock() {
840 MutexAutoLock
lock(mTableLock
);
841 return ResetStartupWriteTimer();
844 nsresult
StartupCache::ResetStartupWriteTimer() {
848 mTimer
= NS_NewTimer();
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");
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
868 NS_IMPL_ISUPPORTS(StartupCacheDebugOutputStream
, nsIObjectOutputStream
,
869 nsIBinaryOutputStream
, nsIOutputStream
)
871 bool StartupCacheDebugOutputStream::CheckReferences(nsISupports
* aObject
) {
874 nsCOMPtr
<nsIClassInfo
> classInfo
= do_QueryInterface(aObject
);
876 NS_ERROR("aObject must implement nsIClassInfo");
881 rv
= classInfo
->GetFlags(&flags
);
882 NS_ENSURE_SUCCESS(rv
, false);
883 if (flags
& nsIClassInfo::SINGLETON
) return true;
885 bool inserted
= mObjectMap
->EnsureInserted(aObject
);
888 "non-singleton aObject is referenced multiple times in this"
889 "serialization, we don't support that.");
895 // nsIObjectOutputStream implementation
896 nsresult
StartupCacheDebugOutputStream::WriteObject(nsISupports
* aObject
,
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
);
947 } // namespace scache
948 } // namespace mozilla