1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef StartupCache_h_
7 #define StartupCache_h_
11 #include "nsClassHashtable.h"
12 #include "nsComponentManagerUtils.h"
14 #include "nsTStringHasher.h" // mozilla::DefaultHasher<nsCString>
15 #include "nsZipArchive.h"
17 #include "nsIMemoryReporter.h"
18 #include "nsIObserverService.h"
19 #include "nsIObserver.h"
20 #include "nsIObjectOutputStream.h"
22 #include "mozilla/Attributes.h"
23 #include "mozilla/AutoMemMap.h"
24 #include "mozilla/Compression.h"
25 #include "mozilla/MemoryReporting.h"
26 #include "mozilla/Mutex.h"
27 #include "mozilla/Result.h"
28 #include "mozilla/UniquePtr.h"
31 * The StartupCache is a persistent cache of simple key-value pairs,
32 * where the keys are null-terminated c-strings and the values are
33 * arbitrary data, passed as a (char*, size) tuple.
35 * Clients should use the GetSingleton() static method to access the cache. It
36 * will be available from the end of XPCOM init (NS_InitXPCOM3 in
37 * XPCOMInit.cpp), until XPCOM shutdown begins. The GetSingleton() method will
38 * return null if the cache is unavailable. The cache is only provided for
39 * libxul builds -- it will fail to link in non-libxul builds. The XPCOM
40 * interface is provided only to allow compiled-code tests; clients should avoid
43 * The API provided is very simple: GetBuffer() returns a buffer that was
44 * previously stored in the cache (if any), and PutBuffer() inserts a buffer
45 * into the cache. GetBuffer returns a new buffer, and the caller must take
46 * ownership of it. PutBuffer will assert if the client attempts to insert a
47 * buffer with the same name as an existing entry. The cache makes a copy of the
48 * passed-in buffer, so client retains ownership.
50 * InvalidateCache() may be called if a client suspects data corruption
51 * or wishes to invalidate for any other reason. This will remove all existing
52 * cache data. Additionally, the static method IgnoreDiskCache() can be called
53 * if it is believed that the on-disk cache file is itself corrupt. This call
54 * implicitly calls InvalidateCache (if the singleton has been initialized) to
55 * ensure any data already read from disk is discarded. The cache will not load
56 * data from the disk file until a successful write occurs.
58 * Finally, getDebugObjectOutputStream() allows debug code to wrap an
59 * objectstream with a debug objectstream, to check for multiply-referenced
60 * objects. These will generally fail to deserialize correctly, unless they are
61 * stateless singletons or the client maintains their own object data map for
64 * Writes before the final-ui-startup notification are placed in an intermediate
65 * cache in memory, then written out to disk at a later time, to get writes off
66 * the startup path. In any case, clients should not rely on being able to
67 * GetBuffer() data that is written to the cache, since it may not have been
68 * written to disk or another client may have invalidated the cache. In other
69 * words, it should be used as a cache only, and not a reliable persistent
72 * Some utility functions are provided in StartupCacheUtils. These functions
73 * wrap the buffers into object streams, which may be useful for serializing
74 * objects. Note the above caution about multiply-referenced objects, though --
75 * the streams are just as 'dumb' as the underlying buffers about
76 * multiply-referenced objects. They just provide some convenience in writing
84 struct StartupCacheEntry
{
85 UniquePtr
<char[]> mData
;
87 uint32_t mCompressedSize
;
88 uint32_t mUncompressedSize
;
89 int32_t mHeaderOffsetInFile
;
90 int32_t mRequestedOrder
;
93 MOZ_IMPLICIT
StartupCacheEntry(uint32_t aOffset
, uint32_t aCompressedSize
,
94 uint32_t aUncompressedSize
)
97 mCompressedSize(aCompressedSize
),
98 mUncompressedSize(aUncompressedSize
),
99 mHeaderOffsetInFile(0),
103 StartupCacheEntry(UniquePtr
<char[]> aData
, size_t aLength
,
104 int32_t aRequestedOrder
)
105 : mData(std::move(aData
)),
108 mUncompressedSize(aLength
),
109 mHeaderOffsetInFile(0),
114 using Value
= std::pair
<const nsCString
*, StartupCacheEntry
*>;
116 bool Equals(const Value
& a
, const Value
& b
) const {
117 return a
.second
->mRequestedOrder
== b
.second
->mRequestedOrder
;
120 bool LessThan(const Value
& a
, const Value
& b
) const {
121 return a
.second
->mRequestedOrder
< b
.second
->mRequestedOrder
;
126 // We don't want to refcount StartupCache, and ObserverService wants to
127 // refcount its listeners, so we'll let it refcount this instead.
128 class StartupCacheListener final
: public nsIObserver
{
129 ~StartupCacheListener() = default;
130 NS_DECL_THREADSAFE_ISUPPORTS
134 class StartupCache
: public nsIMemoryReporter
{
135 friend class StartupCacheListener
;
138 NS_DECL_THREADSAFE_ISUPPORTS
139 NS_DECL_NSIMEMORYREPORTER
141 // StartupCache methods. See above comments for a more detailed description.
143 // true if the archive has an entry for the buffer or not.
144 bool HasEntry(const char* id
);
146 // Returns a buffer that was previously stored, caller does not take ownership
147 nsresult
GetBuffer(const char* id
, const char** outbuf
, uint32_t* length
);
149 // Stores a buffer. Caller yields ownership.
150 nsresult
PutBuffer(const char* id
, UniquePtr
<char[]>&& inbuf
,
153 // Removes the cache file.
154 void InvalidateCache(bool memoryOnly
= false);
156 // For use during shutdown - this will write the startupcache's data
157 // to disk if the timer hasn't already gone off.
158 void MaybeInitShutdownWrite();
160 // For use during shutdown - ensure we complete the shutdown write
161 // before shutdown, even in the FastShutdown case.
162 void EnsureShutdownWriteComplete();
164 // Signal that data should not be loaded from the cache file
165 static void IgnoreDiskCache();
167 // In DEBUG builds, returns a stream that will attempt to check for
168 // and disallow multiple writes of the same object.
169 nsresult
GetDebugObjectOutputStream(nsIObjectOutputStream
* aStream
,
170 nsIObjectOutputStream
** outStream
);
172 static StartupCache
* GetSingletonNoInit();
173 static StartupCache
* GetSingleton();
174 static void DeleteSingleton();
176 // This measures all the heap memory used by the StartupCache, i.e. it
177 // excludes the mapping.
178 size_t HeapSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf
) const;
180 bool ShouldCompactCache();
181 nsresult
ResetStartupWriteTimerCheckingReadCount();
182 nsresult
ResetStartupWriteTimer();
183 bool StartupWriteComplete();
187 virtual ~StartupCache();
189 friend class StartupCacheInfo
;
191 Result
<Ok
, nsresult
> LoadArchive();
194 // Returns a file pointer for the cache file with the given name in the
196 Result
<nsCOMPtr
<nsIFile
>, nsresult
> GetCacheFile(const nsAString
& suffix
);
198 // Opens the cache file for reading.
199 Result
<Ok
, nsresult
> OpenCache();
201 // Writes the cache to disk
202 Result
<Ok
, nsresult
> WriteToDisk();
204 void WaitOnPrefetchThread();
205 void StartPrefetchMemoryThread();
207 static nsresult
InitSingleton();
208 static void WriteTimeout(nsITimer
* aTimer
, void* aClosure
);
209 void MaybeWriteOffMainThread();
210 static void ThreadedPrefetch(void* aClosure
);
212 HashMap
<nsCString
, StartupCacheEntry
> mTable
;
213 // owns references to the contents of tables which have been invalidated.
214 // In theory grows forever if the cache is continually filled and then
215 // invalidated, but this should not happen in practice.
216 nsTArray
<decltype(mTable
)> mOldTables
;
217 nsCOMPtr
<nsIFile
> mFile
;
218 loader::AutoMemMap mCacheData
;
221 nsCOMPtr
<nsIObserverService
> mObserverService
;
222 RefPtr
<StartupCacheListener
> mListener
;
223 nsCOMPtr
<nsITimer
> mTimer
;
226 Atomic
<bool> mWrittenOnce
;
227 bool mCurTableReferenced
;
228 uint32_t mRequestedCount
;
229 size_t mCacheEntriesBaseOffset
;
231 static StaticRefPtr
<StartupCache
> gStartupCache
;
232 static bool gShutdownInitiated
;
233 static bool gIgnoreDiskCache
;
234 static bool gFoundDiskCacheOnInit
;
235 PRThread
* mPrefetchThread
;
236 UniquePtr
<Compression::LZ4FrameDecompressionContext
> mDecompressionContext
;
238 nsTHashtable
<nsISupportsHashKey
> mWriteObjectMap
;
242 // This debug outputstream attempts to detect if clients are writing multiple
243 // references to the same object. We only support that if that object
246 class StartupCacheDebugOutputStream final
: public nsIObjectOutputStream
{
247 ~StartupCacheDebugOutputStream() = default;
250 NS_DECL_NSIOBJECTOUTPUTSTREAM
252 StartupCacheDebugOutputStream(nsIObjectOutputStream
* binaryStream
,
253 nsTHashtable
<nsISupportsHashKey
>* objectMap
)
254 : mBinaryStream(binaryStream
), mObjectMap(objectMap
) {}
256 NS_FORWARD_SAFE_NSIBINARYOUTPUTSTREAM(mBinaryStream
)
257 NS_FORWARD_SAFE_NSIOUTPUTSTREAM(mBinaryStream
)
259 bool CheckReferences(nsISupports
* aObject
);
261 nsCOMPtr
<nsIObjectOutputStream
> mBinaryStream
;
262 nsTHashtable
<nsISupportsHashKey
>* mObjectMap
;
266 } // namespace scache
267 } // namespace mozilla
269 #endif // StartupCache_h_