Bug 1886946: Remove incorrect assertion that buffer is not-pinned. r=sfink
[gecko.git] / dom / ipc / SharedMap.h
blob0a5b686c627b45d555b15b8e4f7ff2aef59b01e7
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 #ifndef dom_ipc_SharedMap_h
8 #define dom_ipc_SharedMap_h
10 #include "mozilla/dom/MozSharedMapBinding.h"
12 #include "mozilla/AutoMemMap.h"
13 #include "mozilla/dom/ipc/StructuredCloneData.h"
14 #include "mozilla/DOMEventTargetHelper.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/UniquePtr.h"
17 #include "mozilla/Variant.h"
18 #include "nsClassHashtable.h"
19 #include "nsTArray.h"
21 class nsIGlobalObject;
23 namespace mozilla::dom {
25 class ContentParent;
27 namespace ipc {
29 /**
30 * Together, the SharedMap and WritableSharedMap classes allow sharing a
31 * dynamically-updated, shared-memory key-value store across processes.
33 * The maps may only ever be updated in the parent process, via
34 * WritableSharedMap instances. When that map changes, its entire contents are
35 * serialized into a contiguous shared memory buffer, and broadcast to all child
36 * processes, which in turn update their entire map contents wholesale.
38 * Keys are arbitrary UTF-8 strings (currently exposed to JavaScript as UTF-16),
39 * and values are structured clone buffers. Values are eagerly encoded whenever
40 * they are updated, and lazily decoded each time they're read.
42 * Updates are batched. Rather than each key change triggering an immediate
43 * update, combined updates are broadcast after a delay. Changes are flushed
44 * immediately any time a new process is created. Additionally, any time a key
45 * is changed, a flush task is scheduled for the next time the event loop
46 * becomes idle. Changes can be flushed immediately by calling the flush()
47 * method.
50 * Whenever a read-only SharedMap is updated, it dispatches a "change" event.
51 * The event contains a "changedKeys" property with a list of all keys which
52 * were changed in the last update batch. Change events are never dispatched to
53 * WritableSharedMap instances.
55 class SharedMap : public DOMEventTargetHelper {
56 using FileDescriptor = mozilla::ipc::FileDescriptor;
58 public:
59 SharedMap();
61 SharedMap(nsIGlobalObject* aGlobal, const FileDescriptor&, size_t,
62 nsTArray<RefPtr<BlobImpl>>&& aBlobs);
64 // Returns true if the map contains the given (UTF-8) key.
65 bool Has(const nsACString& name);
67 // If the map contains the given (UTF-8) key, decodes and returns a new copy
68 // of its value. Otherwise returns null.
69 void Get(JSContext* cx, const nsACString& name,
70 JS::MutableHandle<JS::Value> aRetVal, ErrorResult& aRv);
72 // Conversion helpers for WebIDL callers
73 bool Has(const nsAString& aName) { return Has(NS_ConvertUTF16toUTF8(aName)); }
75 void Get(JSContext* aCx, const nsAString& aName,
76 JS::MutableHandle<JS::Value> aRetVal, ErrorResult& aRv) {
77 return Get(aCx, NS_ConvertUTF16toUTF8(aName), aRetVal, aRv);
80 /**
81 * WebIDL iterator glue.
83 uint32_t GetIterableLength() const { return EntryArray().Length(); }
85 /**
86 * These functions return the key or value, respectively, at the given index.
87 * The index *must* be less than the value returned by GetIterableLength(), or
88 * the program will crash.
90 const nsString GetKeyAtIndex(uint32_t aIndex) const;
91 bool GetValueAtIndex(JSContext* aCx, uint32_t aIndex,
92 JS::MutableHandle<JS::Value> aResult) const;
94 /**
95 * Returns a copy of the read-only file descriptor which backs the shared
96 * memory region for this map. The file descriptor may be passed between
97 * processes, and used to update corresponding instances in child processes.
99 FileDescriptor CloneMapFile() const;
102 * Returns the size of the memory mapped region that backs this map. Must be
103 * passed to the SharedMap() constructor or Update() method along with the
104 * descriptor returned by CloneMapFile() in order to initialize or update a
105 * child SharedMap.
107 size_t MapSize() const { return mMap.size(); }
110 * Updates this instance to reflect the contents of the shared memory region
111 * in the given map file, and broadcasts a change event for the given set of
112 * changed (UTF-8-encoded) keys.
114 void Update(const FileDescriptor& aMapFile, size_t aMapSize,
115 nsTArray<RefPtr<BlobImpl>>&& aBlobs,
116 nsTArray<nsCString>&& aChangedKeys);
118 JSObject* WrapObject(JSContext* aCx,
119 JS::Handle<JSObject*> aGivenProto) override;
121 protected:
122 ~SharedMap() override = default;
124 class Entry {
125 public:
126 Entry(Entry&&) = delete;
128 explicit Entry(SharedMap& aMap, const nsACString& aName = ""_ns)
129 : mMap(aMap), mName(aName), mData(AsVariant(uint32_t(0))) {}
131 ~Entry() = default;
134 * Encodes or decodes this entry into or from the given OutputBuffer or
135 * InputBuffer.
137 template <typename Buffer>
138 void Code(Buffer& buffer) {
139 DebugOnly<size_t> startOffset = buffer.cursor();
141 buffer.codeString(mName);
142 buffer.codeUint32(DataOffset());
143 buffer.codeUint32(mSize);
144 buffer.codeUint16(mBlobOffset);
145 buffer.codeUint16(mBlobCount);
147 MOZ_ASSERT(buffer.cursor() == startOffset + HeaderSize());
151 * Returns the size that this entry will take up in the map header. This
152 * must be equal to the number of bytes encoded by Code().
154 size_t HeaderSize() const {
155 return (sizeof(uint16_t) + mName.Length() + sizeof(DataOffset()) +
156 sizeof(mSize) + sizeof(mBlobOffset) + sizeof(mBlobCount));
160 * Updates the value of this entry to the given structured clone data, of
161 * which it takes ownership. The passed StructuredCloneData object must not
162 * be used after this call.
164 void TakeData(StructuredCloneData&&);
167 * This is called while building a new snapshot of the SharedMap. aDestPtr
168 * must point to a buffer within the new snapshot with Size() bytes reserved
169 * for it, and `aNewOffset` must be the offset of that buffer from the start
170 * of the snapshot's memory region.
172 * This function copies the raw structured clone data for the entry's value
173 * to the new buffer, and updates its internal state for use with the new
174 * data. Its offset is updated to aNewOffset, and any StructuredCloneData
175 * object it holds is destroyed.
177 * After this call, the entry is only valid in reference to the new
178 * snapshot, and must not be accessed again until the SharedMap mMap has
179 * been updated to point to it.
181 void ExtractData(char* aDestPtr, uint32_t aNewOffset,
182 uint16_t aNewBlobOffset);
184 // Returns the UTF-8-encoded name of the entry, which is used as its key in
185 // the map.
186 const nsCString& Name() const { return mName; }
188 // Decodes the entry's value into the current Realm of the given JS context
189 // and puts the result in aRetVal on success.
190 void Read(JSContext* aCx, JS::MutableHandle<JS::Value> aRetVal,
191 ErrorResult& aRv);
193 // Returns the byte size of the entry's raw structured clone data.
194 uint32_t Size() const { return mSize; }
196 private:
197 // Returns a pointer to the entry value's structured clone data within the
198 // SharedMap's mapped memory region. This is *only* valid shen mData
199 // contains a uint32_t.
200 const char* Data() const { return mMap.Data() + DataOffset(); }
202 // Returns the offset of the entry value's structured clone data within the
203 // SharedMap's mapped memory region. This is *only* valid shen mData
204 // contains a uint32_t.
205 uint32_t& DataOffset() { return mData.as<uint32_t>(); }
206 const uint32_t& DataOffset() const { return mData.as<uint32_t>(); }
208 public:
209 uint16_t BlobOffset() const { return mBlobOffset; }
210 uint16_t BlobCount() const { return mBlobCount; }
212 Span<const RefPtr<BlobImpl>> Blobs() {
213 if (mData.is<StructuredCloneData>()) {
214 return mData.as<StructuredCloneData>().BlobImpls();
216 return {&mMap.mBlobImpls[mBlobOffset], BlobCount()};
219 private:
220 // Returns the temporary StructuredCloneData object containing the entry's
221 // value. This is *only* value when mData contains a StructuredCloneDAta
222 // object.
223 const StructuredCloneData& Holder() const {
224 return mData.as<StructuredCloneData>();
227 SharedMap& mMap;
229 // The entry's (UTF-8 encoded) name, which serves as its key in the map.
230 nsCString mName;
233 * This member provides a reference to the entry's structured clone data.
234 * Its type varies depending on the state of the entry:
236 * - For entries which have been snapshotted into a shared memory region,
237 * this is a uint32_t offset into the parent SharedMap's Data() buffer.
239 * - For entries which have been changed in a WritableSharedMap instance,
240 * but not serialized to a shared memory snapshot yet, this is a
241 * StructuredCloneData instance, containing a process-local copy of the
242 * data. This will be discarded the next time the map is serialized, and
243 * replaced with a buffer offset, as described above.
245 Variant<uint32_t, StructuredCloneData> mData;
247 // The size, in bytes, of the entry's structured clone data.
248 uint32_t mSize = 0;
250 uint16_t mBlobOffset = 0;
251 uint16_t mBlobCount = 0;
254 const nsTArray<Entry*>& EntryArray() const;
256 nsTArray<RefPtr<BlobImpl>> mBlobImpls;
258 // Rebuilds the entry hashtable mEntries from the values serialized in the
259 // current snapshot, if necessary. The hashtable is rebuilt lazily after
260 // construction and after every Update() call, so this function must be called
261 // before any attempt to access mEntries.
262 Result<Ok, nsresult> MaybeRebuild();
263 void MaybeRebuild() const;
265 // Note: This header is included by WebIDL binding headers, and therefore
266 // can't include "windows.h". Since FileDescriptor.h does include "windows.h"
267 // on Windows, we can only forward declare FileDescriptor, and can't include
268 // it as an inline member.
269 UniquePtr<FileDescriptor> mMapFile;
270 // The size of the memory-mapped region backed by mMapFile, in bytes.
271 size_t mMapSize = 0;
273 mutable nsClassHashtable<nsCStringHashKey, Entry> mEntries;
274 mutable Maybe<nsTArray<Entry*>> mEntryArray;
276 // Manages the memory mapping of the current snapshot. This is initialized
277 // lazily after each SharedMap construction or updated, based on the values in
278 // mMapFile and mMapSize.
279 loader::AutoMemMap mMap;
281 bool mWritable = false;
283 // Returns a pointer to the beginning of the memory mapped snapshot. Entry
284 // offsets are relative to this pointer, and Entry objects access their
285 // structured clone data by indexing this pointer.
286 char* Data() { return mMap.get<char>().get(); }
289 class WritableSharedMap final : public SharedMap {
290 public:
291 NS_DECL_ISUPPORTS_INHERITED
292 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(WritableSharedMap, SharedMap)
294 WritableSharedMap();
296 // Sets the value of the given (UTF-8 encoded) key to a structured clone
297 // snapshot of the given value.
298 void Set(JSContext* cx, const nsACString& name, JS::Handle<JS::Value> value,
299 ErrorResult& aRv);
301 // Deletes the given (UTF-8 encoded) key from the map.
302 void Delete(const nsACString& name);
304 // Conversion helpers for WebIDL callers
305 void Set(JSContext* aCx, const nsAString& aName, JS::Handle<JS::Value> aValue,
306 ErrorResult& aRv) {
307 return Set(aCx, NS_ConvertUTF16toUTF8(aName), aValue, aRv);
310 void Delete(const nsAString& aName) {
311 return Delete(NS_ConvertUTF16toUTF8(aName));
314 // Flushes any queued changes to a new snapshot, and broadcasts it to all
315 // child SharedMap instances.
316 void Flush();
318 // Sends the current set of shared map data to the given content process.
319 void SendTo(ContentParent* aContentParent) const;
322 * Returns the read-only SharedMap instance corresponding to this
323 * WritableSharedMap for use in the parent process.
325 SharedMap* GetReadOnly();
327 JSObject* WrapObject(JSContext* aCx,
328 JS::Handle<JSObject*> aGivenProto) override;
330 protected:
331 ~WritableSharedMap() override = default;
333 private:
334 // The set of (UTF-8 encoded) keys which have changed, or been deleted, since
335 // the last snapshot.
336 nsTArray<nsCString> mChangedKeys;
338 RefPtr<SharedMap> mReadOnly;
340 bool mPendingFlush = false;
342 // Creates a new snapshot of the map, and updates all Entry instance to
343 // reference its data.
344 Result<Ok, nsresult> Serialize();
346 void IdleFlush();
348 // If there have been any changes since the last snapshot, creates a new
349 // serialization and broadcasts it to all child SharedMap instances.
350 void BroadcastChanges();
352 // Marks the given (UTF-8 encoded) key as having changed. This adds it to
353 // mChangedKeys, if not already present, and schedules a flush for the next
354 // time the event loop is idle.
355 nsresult KeyChanged(const nsACString& aName);
358 } // namespace ipc
359 } // namespace mozilla::dom
361 #endif // dom_ipc_SharedMap_h