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/dom/ipc/StructuredCloneData.h"
13 #include "mozilla/ipc/SharedMemory.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"
21 class nsIGlobalObject
;
23 namespace mozilla::dom
{
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()
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 SharedMemory
= mozilla::ipc::SharedMemory
;
57 using SharedMemoryHandle
= mozilla::ipc::SharedMemoryHandle
;
62 SharedMap(nsIGlobalObject
* aGlobal
, SharedMemoryHandle
&&, size_t,
63 nsTArray
<RefPtr
<BlobImpl
>>&& aBlobs
);
65 // Returns true if the map contains the given (UTF-8) key.
66 bool Has(const nsACString
& name
);
68 // If the map contains the given (UTF-8) key, decodes and returns a new copy
69 // of its value. Otherwise returns null.
70 void Get(JSContext
* cx
, const nsACString
& name
,
71 JS::MutableHandle
<JS::Value
> aRetVal
, ErrorResult
& aRv
);
73 // Conversion helpers for WebIDL callers
74 bool Has(const nsAString
& aName
) { return Has(NS_ConvertUTF16toUTF8(aName
)); }
76 void Get(JSContext
* aCx
, const nsAString
& aName
,
77 JS::MutableHandle
<JS::Value
> aRetVal
, ErrorResult
& aRv
) {
78 return Get(aCx
, NS_ConvertUTF16toUTF8(aName
), aRetVal
, aRv
);
82 * WebIDL iterator glue.
84 uint32_t GetIterableLength() const { return EntryArray().Length(); }
87 * These functions return the key or value, respectively, at the given index.
88 * The index *must* be less than the value returned by GetIterableLength(), or
89 * the program will crash.
91 const nsString
GetKeyAtIndex(uint32_t aIndex
) const;
92 bool GetValueAtIndex(JSContext
* aCx
, uint32_t aIndex
,
93 JS::MutableHandle
<JS::Value
> aResult
) const;
96 * Returns a copy of the read-only file descriptor which backs the shared
97 * memory region for this map. The file descriptor may be passed between
98 * processes, and used to update corresponding instances in child processes.
100 SharedMemoryHandle
CloneHandle() const;
103 * Returns the size of the memory mapped region that backs this map. Must be
104 * passed to the SharedMap() constructor or Update() method along with the
105 * descriptor returned by CloneMapFile() in order to initialize or update a
108 size_t MapSize() const { return mMap
->Size(); }
111 * Updates this instance to reflect the contents of the shared memory region
112 * in the given map handle, and broadcasts a change event for the given set of
113 * changed (UTF-8-encoded) keys.
115 void Update(SharedMemoryHandle
&& aMapHandle
, size_t aMapSize
,
116 nsTArray
<RefPtr
<BlobImpl
>>&& aBlobs
,
117 nsTArray
<nsCString
>&& aChangedKeys
);
119 JSObject
* WrapObject(JSContext
* aCx
,
120 JS::Handle
<JSObject
*> aGivenProto
) override
;
123 ~SharedMap() override
= default;
127 Entry(Entry
&&) = delete;
129 explicit Entry(SharedMap
& aMap
, const nsACString
& aName
= ""_ns
)
130 : mMap(aMap
), mName(aName
), mData(AsVariant(uint32_t(0))) {}
135 * Encodes or decodes this entry into or from the given OutputBuffer or
138 template <typename Buffer
>
139 void Code(Buffer
& buffer
) {
140 DebugOnly
<size_t> startOffset
= buffer
.cursor();
142 buffer
.codeString(mName
);
143 buffer
.codeUint32(DataOffset());
144 buffer
.codeUint32(mSize
);
145 buffer
.codeUint16(mBlobOffset
);
146 buffer
.codeUint16(mBlobCount
);
148 MOZ_ASSERT(buffer
.cursor() == startOffset
+ HeaderSize());
152 * Returns the size that this entry will take up in the map header. This
153 * must be equal to the number of bytes encoded by Code().
155 size_t HeaderSize() const {
156 return (sizeof(uint16_t) + mName
.Length() + sizeof(DataOffset()) +
157 sizeof(mSize
) + sizeof(mBlobOffset
) + sizeof(mBlobCount
));
161 * Updates the value of this entry to the given structured clone data, of
162 * which it takes ownership. The passed StructuredCloneData object must not
163 * be used after this call.
165 void TakeData(StructuredCloneData
&&);
168 * This is called while building a new snapshot of the SharedMap. aDestPtr
169 * must point to a buffer within the new snapshot with Size() bytes reserved
170 * for it, and `aNewOffset` must be the offset of that buffer from the start
171 * of the snapshot's memory region.
173 * This function copies the raw structured clone data for the entry's value
174 * to the new buffer, and updates its internal state for use with the new
175 * data. Its offset is updated to aNewOffset, and any StructuredCloneData
176 * object it holds is destroyed.
178 * After this call, the entry is only valid in reference to the new
179 * snapshot, and must not be accessed again until the SharedMap mMap has
180 * been updated to point to it.
182 void ExtractData(char* aDestPtr
, uint32_t aNewOffset
,
183 uint16_t aNewBlobOffset
);
185 // Returns the UTF-8-encoded name of the entry, which is used as its key in
187 const nsCString
& Name() const { return mName
; }
189 // Decodes the entry's value into the current Realm of the given JS context
190 // and puts the result in aRetVal on success.
191 void Read(JSContext
* aCx
, JS::MutableHandle
<JS::Value
> aRetVal
,
194 // Returns the byte size of the entry's raw structured clone data.
195 uint32_t Size() const { return mSize
; }
198 // Returns a pointer to the entry value's structured clone data within the
199 // SharedMap's mapped memory region. This is *only* valid shen mData
200 // contains a uint32_t.
201 const char* Data() const { return mMap
.Data() + DataOffset(); }
203 // Returns the offset of the entry value's structured clone data within the
204 // SharedMap's mapped memory region. This is *only* valid shen mData
205 // contains a uint32_t.
206 uint32_t& DataOffset() { return mData
.as
<uint32_t>(); }
207 const uint32_t& DataOffset() const { return mData
.as
<uint32_t>(); }
210 uint16_t BlobOffset() const { return mBlobOffset
; }
211 uint16_t BlobCount() const { return mBlobCount
; }
213 Span
<const RefPtr
<BlobImpl
>> Blobs() {
214 if (mData
.is
<StructuredCloneData
>()) {
215 return mData
.as
<StructuredCloneData
>().BlobImpls();
217 return {&mMap
.mBlobImpls
[mBlobOffset
], BlobCount()};
221 // Returns the temporary StructuredCloneData object containing the entry's
222 // value. This is *only* value when mData contains a StructuredCloneDAta
224 const StructuredCloneData
& Holder() const {
225 return mData
.as
<StructuredCloneData
>();
230 // The entry's (UTF-8 encoded) name, which serves as its key in the map.
234 * This member provides a reference to the entry's structured clone data.
235 * Its type varies depending on the state of the entry:
237 * - For entries which have been snapshotted into a shared memory region,
238 * this is a uint32_t offset into the parent SharedMap's Data() buffer.
240 * - For entries which have been changed in a WritableSharedMap instance,
241 * but not serialized to a shared memory snapshot yet, this is a
242 * StructuredCloneData instance, containing a process-local copy of the
243 * data. This will be discarded the next time the map is serialized, and
244 * replaced with a buffer offset, as described above.
246 Variant
<uint32_t, StructuredCloneData
> mData
;
248 // The size, in bytes, of the entry's structured clone data.
251 uint16_t mBlobOffset
= 0;
252 uint16_t mBlobCount
= 0;
255 const nsTArray
<Entry
*>& EntryArray() const;
257 nsTArray
<RefPtr
<BlobImpl
>> mBlobImpls
;
259 // Rebuilds the entry hashtable mEntries from the values serialized in the
260 // current snapshot, if necessary. The hashtable is rebuilt lazily after
261 // construction and after every Update() call, so this function must be called
262 // before any attempt to access mEntries.
263 Result
<Ok
, nsresult
> MaybeRebuild();
264 void MaybeRebuild() const;
266 SharedMemoryHandle mMapHandle
;
267 // The size of the memory-mapped region backed by mMap, in bytes.
270 mutable nsClassHashtable
<nsCStringHashKey
, Entry
> mEntries
;
271 mutable Maybe
<nsTArray
<Entry
*>> mEntryArray
;
273 // Manages the memory mapping of the current snapshot. This is initialized
274 // lazily after each SharedMap construction or updated, based on the values in
275 // mMapFile and mMapSize.
276 RefPtr
<SharedMemory
> mMap
= MakeRefPtr
<SharedMemory
>();
278 bool mWritable
= false;
280 // Returns a pointer to the beginning of the memory mapped snapshot. Entry
281 // offsets are relative to this pointer, and Entry objects access their
282 // structured clone data by indexing this pointer.
283 char* Data() { return static_cast<char*>(mMap
->Memory()); }
286 class WritableSharedMap final
: public SharedMap
{
288 NS_DECL_ISUPPORTS_INHERITED
289 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(WritableSharedMap
, SharedMap
)
293 // Sets the value of the given (UTF-8 encoded) key to a structured clone
294 // snapshot of the given value.
295 void Set(JSContext
* cx
, const nsACString
& name
, JS::Handle
<JS::Value
> value
,
298 // Deletes the given (UTF-8 encoded) key from the map.
299 void Delete(const nsACString
& name
);
301 // Conversion helpers for WebIDL callers
302 void Set(JSContext
* aCx
, const nsAString
& aName
, JS::Handle
<JS::Value
> aValue
,
304 return Set(aCx
, NS_ConvertUTF16toUTF8(aName
), aValue
, aRv
);
307 void Delete(const nsAString
& aName
) {
308 return Delete(NS_ConvertUTF16toUTF8(aName
));
311 // Flushes any queued changes to a new snapshot, and broadcasts it to all
312 // child SharedMap instances.
315 // Sends the current set of shared map data to the given content process.
316 void SendTo(ContentParent
* aContentParent
) const;
319 * Returns the read-only SharedMap instance corresponding to this
320 * WritableSharedMap for use in the parent process.
322 SharedMap
* GetReadOnly();
324 JSObject
* WrapObject(JSContext
* aCx
,
325 JS::Handle
<JSObject
*> aGivenProto
) override
;
328 ~WritableSharedMap() override
= default;
331 // The set of (UTF-8 encoded) keys which have changed, or been deleted, since
332 // the last snapshot.
333 nsTArray
<nsCString
> mChangedKeys
;
335 RefPtr
<SharedMap
> mReadOnly
;
337 bool mPendingFlush
= false;
339 // Creates a new snapshot of the map, and updates all Entry instance to
340 // reference its data.
341 Result
<Ok
, nsresult
> Serialize();
345 // If there have been any changes since the last snapshot, creates a new
346 // serialization and broadcasts it to all child SharedMap instances.
347 void BroadcastChanges();
349 // Marks the given (UTF-8 encoded) key as having changed. This adds it to
350 // mChangedKeys, if not already present, and schedules a flush for the next
351 // time the event loop is idle.
352 nsresult
KeyChanged(const nsACString
& aName
);
356 } // namespace mozilla::dom
358 #endif // dom_ipc_SharedMap_h