Bug 1605894 reduce the proliferation of DefaultLoopbackTone to only AudioStreamFlowin...
[gecko.git] / startupcache / StartupCache.h
blob045ad05213fcb2c57b1fa7082abe57cb285017bb
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_
9 #include <utility>
11 #include "nsClassHashtable.h"
12 #include "nsComponentManagerUtils.h"
13 #include "nsTArray.h"
14 #include "nsTHashSet.h"
15 #include "nsTStringHasher.h" // mozilla::DefaultHasher<nsCString>
16 #include "nsZipArchive.h"
17 #include "nsITimer.h"
18 #include "nsIMemoryReporter.h"
19 #include "nsIObserverService.h"
20 #include "nsIObserver.h"
21 #include "nsIObjectOutputStream.h"
22 #include "nsIFile.h"
23 #include "mozilla/Attributes.h"
24 #include "mozilla/AutoMemMap.h"
25 #include "mozilla/Compression.h"
26 #include "mozilla/MemoryReporting.h"
27 #include "mozilla/Monitor.h"
28 #include "mozilla/Mutex.h"
29 #include "mozilla/Result.h"
30 #include "mozilla/UniquePtr.h"
31 #include "mozilla/UniquePtrExtensions.h"
33 /**
34 * The StartupCache is a persistent cache of simple key-value pairs,
35 * where the keys are null-terminated c-strings and the values are
36 * arbitrary data, passed as a (char*, size) tuple.
38 * Clients should use the GetSingleton() static method to access the cache. It
39 * will be available from the end of XPCOM init (NS_InitXPCOM3 in
40 * XPCOMInit.cpp), until XPCOM shutdown begins. The GetSingleton() method will
41 * return null if the cache is unavailable. The cache is only provided for
42 * libxul builds -- it will fail to link in non-libxul builds. The XPCOM
43 * interface is provided only to allow compiled-code tests; clients should avoid
44 * using it.
46 * The API provided is very simple: GetBuffer() returns a buffer that was
47 * previously stored in the cache (if any), and PutBuffer() inserts a buffer
48 * into the cache. GetBuffer returns a new buffer, and the caller must take
49 * ownership of it. PutBuffer will assert if the client attempts to insert a
50 * buffer with the same name as an existing entry. The cache makes a copy of the
51 * passed-in buffer, so client retains ownership.
53 * InvalidateCache() may be called if a client suspects data corruption
54 * or wishes to invalidate for any other reason. This will remove all existing
55 * cache data. Additionally, the static method IgnoreDiskCache() can be called
56 * if it is believed that the on-disk cache file is itself corrupt. This call
57 * implicitly calls InvalidateCache (if the singleton has been initialized) to
58 * ensure any data already read from disk is discarded. The cache will not load
59 * data from the disk file until a successful write occurs.
61 * Finally, getDebugObjectOutputStream() allows debug code to wrap an
62 * objectstream with a debug objectstream, to check for multiply-referenced
63 * objects. These will generally fail to deserialize correctly, unless they are
64 * stateless singletons or the client maintains their own object data map for
65 * deserialization.
67 * Writes before the final-ui-startup notification are placed in an intermediate
68 * cache in memory, then written out to disk at a later time, to get writes off
69 * the startup path. In any case, clients should not rely on being able to
70 * GetBuffer() data that is written to the cache, since it may not have been
71 * written to disk or another client may have invalidated the cache. In other
72 * words, it should be used as a cache only, and not a reliable persistent
73 * store.
75 * Some utility functions are provided in StartupCacheUtils. These functions
76 * wrap the buffers into object streams, which may be useful for serializing
77 * objects. Note the above caution about multiply-referenced objects, though --
78 * the streams are just as 'dumb' as the underlying buffers about
79 * multiply-referenced objects. They just provide some convenience in writing
80 * out data.
83 namespace mozilla {
85 namespace scache {
87 struct StartupCacheEntry {
88 UniqueFreePtr<char[]> mData;
89 uint32_t mOffset;
90 uint32_t mCompressedSize;
91 uint32_t mUncompressedSize;
92 int32_t mHeaderOffsetInFile;
93 int32_t mRequestedOrder;
94 bool mRequested;
96 MOZ_IMPLICIT StartupCacheEntry(uint32_t aOffset, uint32_t aCompressedSize,
97 uint32_t aUncompressedSize)
98 : mData(nullptr),
99 mOffset(aOffset),
100 mCompressedSize(aCompressedSize),
101 mUncompressedSize(aUncompressedSize),
102 mHeaderOffsetInFile(0),
103 mRequestedOrder(0),
104 mRequested(false) {}
106 StartupCacheEntry(UniqueFreePtr<char[]> aData, size_t aLength,
107 int32_t aRequestedOrder)
108 : mData(std::move(aData)),
109 mOffset(0),
110 mCompressedSize(0),
111 mUncompressedSize(aLength),
112 mHeaderOffsetInFile(0),
113 mRequestedOrder(0),
114 mRequested(true) {}
116 struct Comparator {
117 using Value = std::pair<const nsCString*, StartupCacheEntry*>;
119 bool Equals(const Value& a, const Value& b) const {
120 return a.second->mRequestedOrder == b.second->mRequestedOrder;
123 bool LessThan(const Value& a, const Value& b) const {
124 return a.second->mRequestedOrder < b.second->mRequestedOrder;
129 // We don't want to refcount StartupCache, and ObserverService wants to
130 // refcount its listeners, so we'll let it refcount this instead.
131 class StartupCacheListener final : public nsIObserver {
132 ~StartupCacheListener() = default;
133 NS_DECL_THREADSAFE_ISUPPORTS
134 NS_DECL_NSIOBSERVER
137 class StartupCache : public nsIMemoryReporter {
138 friend class StartupCacheListener;
140 public:
141 NS_DECL_THREADSAFE_ISUPPORTS
142 NS_DECL_NSIMEMORYREPORTER
144 // StartupCache methods. See above comments for a more detailed description.
146 // true if the archive has an entry for the buffer or not.
147 bool HasEntry(const char* id);
149 // Returns a buffer that was previously stored, caller does not take ownership
150 nsresult GetBuffer(const char* id, const char** outbuf, uint32_t* length);
152 // Stores a buffer. Caller yields ownership.
153 nsresult PutBuffer(const char* id, UniqueFreePtr<char[]>&& inbuf,
154 uint32_t length);
156 // Removes the cache file.
157 void InvalidateCache(bool memoryOnly = false);
159 // If some event knowingly re-generates the startup cache (like live language
160 // switching) count these events in order to allow them.
161 void CountAllowedInvalidation();
163 // For use during shutdown - this will write the startupcache's data
164 // to disk if the timer hasn't already gone off.
165 void MaybeInitShutdownWrite();
167 // For use during shutdown - ensure we complete the shutdown write
168 // before shutdown, even in the FastShutdown case.
169 void EnsureShutdownWriteComplete();
171 // Signal that data should not be loaded from the cache file
172 static void IgnoreDiskCache();
174 static bool GetIgnoreDiskCache();
176 // In DEBUG builds, returns a stream that will attempt to check for
177 // and disallow multiple writes of the same object.
178 nsresult GetDebugObjectOutputStream(nsIObjectOutputStream* aStream,
179 nsIObjectOutputStream** outStream);
181 static StartupCache* GetSingletonNoInit();
182 static StartupCache* GetSingleton();
183 static void DeleteSingleton();
185 // This measures all the heap memory used by the StartupCache, i.e. it
186 // excludes the mapping.
187 size_t HeapSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const
188 MOZ_REQUIRES(mTableLock);
190 bool ShouldCompactCache() MOZ_REQUIRES(mTableLock);
191 nsresult ResetStartupWriteTimerCheckingReadCount();
192 nsresult ResetStartupWriteTimerAndLock();
193 nsresult ResetStartupWriteTimer() MOZ_REQUIRES(mTableLock);
194 bool StartupWriteComplete();
196 private:
197 StartupCache();
198 virtual ~StartupCache();
200 friend class StartupCacheInfo;
202 Result<Ok, nsresult> LoadArchive();
203 nsresult Init();
205 // Returns a file pointer for the cache file with the given name in the
206 // current profile.
207 Result<nsCOMPtr<nsIFile>, nsresult> GetCacheFile(const nsAString& suffix);
209 // Opens the cache file for reading.
210 Result<Ok, nsresult> OpenCache();
212 // Writes the cache to disk
213 Result<Ok, nsresult> WriteToDisk() MOZ_REQUIRES(mTableLock);
215 void WaitOnPrefetch();
216 void StartPrefetchMemory() MOZ_REQUIRES(mTableLock);
218 static nsresult InitSingleton();
219 static void WriteTimeout(nsITimer* aTimer, void* aClosure);
220 void MaybeWriteOffMainThread();
221 void ThreadedPrefetch(uint8_t* aStart, size_t aSize);
223 Monitor mPrefetchComplete{"StartupCachePrefetch"};
224 bool mPrefetchInProgress MOZ_GUARDED_BY(mPrefetchComplete){false};
226 // This is normally accessed on MainThread, but WriteToDisk() can
227 // access it on other threads
228 HashMap<nsCString, StartupCacheEntry> mTable MOZ_GUARDED_BY(mTableLock);
229 // This owns references to the contents of tables which have been invalidated.
230 // In theory it grows forever if the cache is continually filled and then
231 // invalidated, but this should not happen in practice. Deleting old tables
232 // could create dangling pointers. RefPtrs could be introduced, but it would
233 // be a large amount of error-prone work to change.
234 nsTArray<decltype(mTable)> mOldTables MOZ_GUARDED_BY(mTableLock);
235 size_t mAllowedInvalidationsCount;
236 nsCOMPtr<nsIFile> mFile;
237 loader::AutoMemMap mCacheData MOZ_GUARDED_BY(mTableLock);
238 Mutex mTableLock;
240 nsCOMPtr<nsIObserverService> mObserverService;
241 RefPtr<StartupCacheListener> mListener;
242 nsCOMPtr<nsITimer> mTimer;
244 bool mDirty MOZ_GUARDED_BY(mTableLock);
245 bool mWrittenOnce MOZ_GUARDED_BY(mTableLock);
246 bool mCurTableReferenced MOZ_GUARDED_BY(mTableLock);
248 uint32_t mRequestedCount;
249 size_t mCacheEntriesBaseOffset;
251 static StaticRefPtr<StartupCache> gStartupCache;
252 static bool gShutdownInitiated;
253 static bool gIgnoreDiskCache;
254 static bool gFoundDiskCacheOnInit;
256 UniquePtr<Compression::LZ4FrameDecompressionContext> mDecompressionContext;
257 #ifdef DEBUG
258 nsTHashSet<nsCOMPtr<nsISupports>> mWriteObjectMap;
259 #endif
262 // This debug outputstream attempts to detect if clients are writing multiple
263 // references to the same object. We only support that if that object
264 // is a singleton.
265 #ifdef DEBUG
266 class StartupCacheDebugOutputStream final : public nsIObjectOutputStream {
267 ~StartupCacheDebugOutputStream() = default;
269 NS_DECL_ISUPPORTS
270 NS_DECL_NSIOBJECTOUTPUTSTREAM
272 StartupCacheDebugOutputStream(nsIObjectOutputStream* binaryStream,
273 nsTHashSet<nsCOMPtr<nsISupports>>* objectMap)
274 : mBinaryStream(binaryStream), mObjectMap(objectMap) {}
276 NS_FORWARD_SAFE_NSIBINARYOUTPUTSTREAM(mBinaryStream)
277 NS_FORWARD_SAFE_NSIOUTPUTSTREAM(mBinaryStream)
279 bool CheckReferences(nsISupports* aObject);
281 nsCOMPtr<nsIObjectOutputStream> mBinaryStream;
282 nsTHashSet<nsCOMPtr<nsISupports>>* mObjectMap;
284 #endif // DEBUG
286 } // namespace scache
287 } // namespace mozilla
289 #endif // StartupCache_h_