Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/dom/ipc/SharedMap.h
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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/. */
6
7
#ifndef dom_ipc_SharedMap_h
8
#define dom_ipc_SharedMap_h
9
10
#include "mozilla/dom/MozSharedMapBinding.h"
11
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"
20
21
class nsIGlobalObject;
22
23
namespace mozilla {
24
namespace dom {
25
26
class ContentParent;
27
28
namespace ipc {
29
30
/**
31
 * Together, the SharedMap and WritableSharedMap classes allow sharing a
32
 * dynamically-updated, shared-memory key-value store across processes.
33
 *
34
 * The maps may only ever be updated in the parent process, via
35
 * WritableSharedMap instances. When that map changes, its entire contents are
36
 * serialized into a contiguous shared memory buffer, and broadcast to all child
37
 * processes, which in turn update their entire map contents wholesale.
38
 *
39
 * Keys are arbitrary UTF-8 strings (currently exposed to JavaScript as UTF-16),
40
 * and values are structured clone buffers. Values are eagerly encoded whenever
41
 * they are updated, and lazily decoded each time they're read.
42
 *
43
 * Updates are batched. Rather than each key change triggering an immediate
44
 * update, combined updates are broadcast after a delay. Changes are flushed
45
 * immediately any time a new process is created. Additionally, any time a key
46
 * is changed, a flush task is scheduled for the next time the event loop
47
 * becomes idle. Changes can be flushed immediately by calling the flush()
48
 * method.
49
 *
50
 *
51
 * Whenever a read-only SharedMap is updated, it dispatches a "change" event.
52
 * The event contains a "changedKeys" property with a list of all keys which
53
 * were changed in the last update batch. Change events are never dispatched to
54
 * WritableSharedMap instances.
55
 */
56
class SharedMap : public DOMEventTargetHelper
57
{
58
  using FileDescriptor = mozilla::ipc::FileDescriptor;
59
60
public:
61
62
  SharedMap();
63
64
  SharedMap(nsIGlobalObject* aGlobal, const FileDescriptor&, size_t,
65
            nsTArray<RefPtr<BlobImpl>>&& aBlobs);
66
67
  // Returns true if the map contains the given (UTF-8) key.
68
  bool Has(const nsACString& name);
69
70
  // If the map contains the given (UTF-8) key, decodes and returns a new copy
71
  // of its value. Otherwise returns null.
72
  void Get(JSContext* cx, const nsACString& name, JS::MutableHandleValue aRetVal,
73
           ErrorResult& aRv);
74
75
76
  // Conversion helpers for WebIDL callers
77
  bool Has(const nsAString& aName)
78
  {
79
    return Has(NS_ConvertUTF16toUTF8(aName));
80
  }
81
82
  void Get(JSContext* aCx, const nsAString& aName, JS::MutableHandleValue aRetVal,
83
           ErrorResult& aRv)
84
  {
85
    return Get(aCx, NS_ConvertUTF16toUTF8(aName), aRetVal, aRv);
86
  }
87
88
89
  /**
90
   * WebIDL iterator glue.
91
   */
92
  uint32_t GetIterableLength() const
93
  {
94
    return EntryArray().Length();
95
  }
96
97
  /**
98
   * These functions return the key or value, respectively, at the given index.
99
   * The index *must* be less than the value returned by GetIterableLength(), or
100
   * the program will crash.
101
   */
102
  const nsString GetKeyAtIndex(uint32_t aIndex) const;
103
  bool GetValueAtIndex(JSContext* aCx, uint32_t aIndex,
104
                       JS::MutableHandle<JS::Value> aResult) const;
105
106
107
  /**
108
   * Returns a copy of the read-only file descriptor which backs the shared
109
   * memory region for this map. The file descriptor may be passed between
110
   * processes, and used to update corresponding instances in child processes.
111
   */
112
  FileDescriptor CloneMapFile() const;
113
114
  /**
115
   * Returns the size of the memory mapped region that backs this map. Must be
116
   * passed to the SharedMap() constructor or Update() method along with the
117
   * descriptor returned by CloneMapFile() in order to initialize or update a
118
   * child SharedMap.
119
   */
120
0
  size_t MapSize() const { return mMap.size(); }
121
122
  /**
123
   * Updates this instance to reflect the contents of the shared memory region
124
   * in the given map file, and broadcasts a change event for the given set of
125
   * changed (UTF-8-encoded) keys.
126
   */
127
  void Update(const FileDescriptor& aMapFile, size_t aMapSize,
128
              nsTArray<RefPtr<BlobImpl>>&& aBlobs,
129
              nsTArray<nsCString>&& aChangedKeys);
130
131
132
  JSObject* WrapObject(JSContext* aCx, JS::HandleObject aGivenProto) override;
133
134
protected:
135
0
  ~SharedMap() override = default;
136
137
  class Entry
138
  {
139
  public:
140
    Entry(Entry&&) = delete;
141
142
    explicit Entry(SharedMap& aMap, const nsACString& aName = EmptyCString())
143
      : mMap(aMap)
144
      , mName(aName)
145
      , mData(AsVariant(uint32_t(0)))
146
0
    {
147
0
    }
148
149
0
    ~Entry() = default;
150
151
    /**
152
     * Encodes or decodes this entry into or from the given OutputBuffer or
153
     * InputBuffer.
154
     */
155
    template<typename Buffer>
156
    void Code(Buffer& buffer)
157
0
    {
158
0
      DebugOnly<size_t> startOffset = buffer.cursor();
159
0
160
0
      buffer.codeString(mName);
161
0
      buffer.codeUint32(DataOffset());
162
0
      buffer.codeUint32(mSize);
163
0
      buffer.codeUint16(mBlobOffset);
164
0
      buffer.codeUint16(mBlobCount);
165
0
166
0
      MOZ_ASSERT(buffer.cursor() == startOffset + HeaderSize());
167
0
    }
Unexecuted instantiation: void mozilla::dom::ipc::SharedMap::Entry::Code<mozilla::loader::InputBuffer>(mozilla::loader::InputBuffer&)
Unexecuted instantiation: void mozilla::dom::ipc::SharedMap::Entry::Code<mozilla::loader::OutputBuffer>(mozilla::loader::OutputBuffer&)
168
169
    /**
170
     * Returns the size that this entry will take up in the map header. This
171
     * must be equal to the number of bytes encoded by Code().
172
     */
173
    size_t HeaderSize() const
174
0
    {
175
0
      return (sizeof(uint16_t) + mName.Length() +
176
0
              sizeof(DataOffset()) +
177
0
              sizeof(mSize) +
178
0
              sizeof(mBlobOffset) +
179
0
              sizeof(mBlobCount));
180
0
    }
181
182
    /**
183
     * Updates the value of this entry to the given structured clone data, of
184
     * which it takes ownership. The passed StructuredCloneData object must not
185
     * be used after this call.
186
     */
187
    void TakeData(StructuredCloneData&&);
188
189
    /**
190
     * This is called while building a new snapshot of the SharedMap. aDestPtr
191
     * must point to a buffer within the new snapshot with Size() bytes reserved
192
     * for it, and `aNewOffset` must be the offset of that buffer from the start
193
     * of the snapshot's memory region.
194
     *
195
     * This function copies the raw structured clone data for the entry's value
196
     * to the new buffer, and updates its internal state for use with the new
197
     * data. Its offset is updated to aNewOffset, and any StructuredCloneData
198
     * object it holds is destroyed.
199
     *
200
     * After this call, the entry is only valid in reference to the new
201
     * snapshot, and must not be accessed again until the SharedMap mMap has been
202
     * updated to point to it.
203
     */
204
    void ExtractData(char* aDestPtr, uint32_t aNewOffset, uint16_t aNewBlobOffset);
205
206
    // Returns the UTF-8-encoded name of the entry, which is used as its key in
207
    // the map.
208
0
    const nsCString& Name() const { return mName; }
209
210
    // Decodes the entry's value into the current Realm of the given JS context
211
    // and puts the result in aRetVal on success.
212
    void Read(JSContext* aCx, JS::MutableHandleValue aRetVal,
213
              ErrorResult& aRv);
214
215
    // Returns the byte size of the entry's raw structured clone data.
216
0
    uint32_t Size() const { return mSize; }
217
218
  private:
219
    // Returns a pointer to the entry value's structured clone data within the
220
    // SharedMap's mapped memory region. This is *only* valid shen mData
221
    // contains a uint32_t.
222
    const char* Data() const
223
0
    {
224
0
      return mMap.Data() + DataOffset();
225
0
    }
226
227
    // Returns the offset of the entry value's structured clone data within the
228
    // SharedMap's mapped memory region. This is *only* valid shen mData
229
    // contains a uint32_t.
230
    uint32_t& DataOffset()
231
0
    {
232
0
      return mData.as<uint32_t>();
233
0
    }
234
    const uint32_t& DataOffset() const
235
0
    {
236
0
      return mData.as<uint32_t>();
237
0
    }
238
239
  public:
240
    uint16_t BlobOffset() const { return mBlobOffset; }
241
0
    uint16_t BlobCount() const { return mBlobCount; }
242
243
    Span<const RefPtr<BlobImpl>> Blobs()
244
0
    {
245
0
      if (mData.is<StructuredCloneData>()) {
246
0
        return mData.as<StructuredCloneData>().BlobImpls();
247
0
      }
248
0
      return {&mMap.mBlobImpls[mBlobOffset], BlobCount()};
249
0
    }
250
251
  private:
252
    // Returns the temporary StructuredCloneData object containing the entry's
253
    // value. This is *only* value when mData contains a StructuredCloneDAta
254
    // object.
255
    const StructuredCloneData& Holder() const
256
0
    {
257
0
      return mData.as<StructuredCloneData>();
258
0
    }
259
260
    SharedMap& mMap;
261
262
    // The entry's (UTF-8 encoded) name, which serves as its key in the map.
263
    nsCString mName;
264
265
    /**
266
     * This member provides a reference to the entry's structured clone data.
267
     * Its type varies depending on the state of the entry:
268
     *
269
     * - For entries which have been snapshotted into a shared memory region,
270
     *   this is a uint32_t offset into the parent SharedMap's Data() buffer.
271
     *
272
     * - For entries which have been changed in a WritableSharedMap instance,
273
     *   but not serialized to a shared memory snapshot yet, this is a
274
     *   StructuredCloneData instance, containing a process-local copy of the
275
     *   data. This will be discarded the next time the map is serialized, and
276
     *   replaced with a buffer offset, as described above.
277
     */
278
    Variant<uint32_t, StructuredCloneData> mData;
279
280
    // The size, in bytes, of the entry's structured clone data.
281
    uint32_t mSize = 0;
282
283
    uint16_t mBlobOffset = 0;
284
    uint16_t mBlobCount = 0;
285
  };
286
287
  const nsTArray<Entry*>& EntryArray() const;
288
289
  nsTArray<RefPtr<BlobImpl>> mBlobImpls;
290
291
  // Rebuilds the entry hashtable mEntries from the values serialized in the
292
  // current snapshot, if necessary. The hashtable is rebuilt lazily after
293
  // construction and after every Update() call, so this function must be called
294
  // before any attempt to access mEntries.
295
  Result<Ok, nsresult> MaybeRebuild();
296
  void MaybeRebuild() const;
297
298
  // Note: This header is included by WebIDL binding headers, and therefore
299
  // can't include "windows.h". Since FileDescriptor.h does include "windows.h"
300
  // on Windows, we can only forward declare FileDescriptor, and can't include
301
  // it as an inline member.
302
  UniquePtr<FileDescriptor> mMapFile;
303
  // The size of the memory-mapped region backed by mMapFile, in bytes.
304
  size_t mMapSize = 0;
305
306
  mutable nsClassHashtable<nsCStringHashKey, Entry> mEntries;
307
  mutable Maybe<nsTArray<Entry*>> mEntryArray;
308
309
  // Manages the memory mapping of the current snapshot. This is initialized
310
  // lazily after each SharedMap construction or updated, based on the values in
311
  // mMapFile and mMapSize.
312
  loader::AutoMemMap mMap;
313
314
  bool mWritable = false;
315
316
  // Returns a pointer to the beginning of the memory mapped snapshot. Entry
317
  // offsets are relative to this pointer, and Entry objects access their
318
  // structured clone data by indexing this pointer.
319
0
  char* Data() { return mMap.get<char>().get(); }
320
};
321
322
class WritableSharedMap final : public SharedMap
323
{
324
public:
325
  NS_DECL_ISUPPORTS_INHERITED
326
  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(WritableSharedMap, SharedMap)
327
328
  WritableSharedMap();
329
330
  // Sets the value of the given (UTF-8 encoded) key to a structured clone
331
  // snapshot of the given value.
332
  void Set(JSContext* cx, const nsACString& name, JS::HandleValue value, ErrorResult& aRv);
333
334
  // Deletes the given (UTF-8 encoded) key from the map.
335
  void Delete(const nsACString& name);
336
337
338
  // Conversion helpers for WebIDL callers
339
  void Set(JSContext* aCx, const nsAString& aName, JS::HandleValue aValue, ErrorResult& aRv)
340
  {
341
    return Set(aCx, NS_ConvertUTF16toUTF8(aName), aValue, aRv);
342
  }
343
344
  void Delete(const nsAString& aName)
345
  {
346
    return Delete(NS_ConvertUTF16toUTF8(aName));
347
  }
348
349
350
  // Flushes any queued changes to a new snapshot, and broadcasts it to all
351
  // child SharedMap instances.
352
  void Flush();
353
354
355
  // Sends the current set of shared map data to the given content process.
356
  void SendTo(ContentParent* aContentParent) const;
357
358
359
  /**
360
   * Returns the read-only SharedMap instance corresponding to this
361
   * WritableSharedMap for use in the parent process.
362
   */
363
  SharedMap* GetReadOnly();
364
365
366
  JSObject* WrapObject(JSContext* aCx, JS::HandleObject aGivenProto) override;
367
368
protected:
369
0
  ~WritableSharedMap() override = default;
370
371
private:
372
  // The set of (UTF-8 encoded) keys which have changed, or been deleted, since
373
  // the last snapshot.
374
  nsTArray<nsCString> mChangedKeys;
375
376
  RefPtr<SharedMap> mReadOnly;
377
378
  bool mPendingFlush = false;
379
380
  // Creates a new snapshot of the map, and updates all Entry instance to
381
  // reference its data.
382
  Result<Ok, nsresult> Serialize();
383
384
  void IdleFlush();
385
386
  // If there have been any changes since the last snapshot, creates a new
387
  // serialization and broadcasts it to all child SharedMap instances.
388
  void BroadcastChanges();
389
390
  // Marks the given (UTF-8 encoded) key as having changed. This adds it to
391
  // mChangedKeys, if not already present, and schedules a flush for the next
392
  // time the event loop is idle.
393
  nsresult KeyChanged(const nsACString& aName);
394
};
395
396
} // ipc
397
} // dom
398
} // mozilla
399
400
#endif // dom_ipc_SharedMap_h