summaryrefslogtreecommitdiffstats
path: root/dom/base/StructuredCloneHolder.h
blob: c7c7f7ef12ace1c7abe95c29b6d2878b1ab8f226 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_StructuredCloneHolder_h
#define mozilla_dom_StructuredCloneHolder_h

#include <cstddef>
#include <cstdint>
#include <utility>
#include "js/StructuredClone.h"
#include "js/TypeDecls.h"
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/RefPtr.h"
#include "mozilla/UniquePtr.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsTArray.h"

class nsIEventTarget;
class nsIGlobalObject;
class nsIInputStream;
struct JSStructuredCloneReader;
struct JSStructuredCloneWriter;

namespace JS {
class Value;
struct WasmModule;
}  // namespace JS

namespace mozilla {
class ErrorResult;
template <class T>
class OwningNonNull;

namespace layers {
class Image;
}

namespace gfx {
class DataSourceSurface;
}

namespace dom {

class BlobImpl;
class MessagePort;
class MessagePortIdentifier;
template <typename T>
class Sequence;

class StructuredCloneHolderBase {
 public:
  typedef JS::StructuredCloneScope StructuredCloneScope;

  StructuredCloneHolderBase(
      StructuredCloneScope aScope = StructuredCloneScope::SameProcess);
  virtual ~StructuredCloneHolderBase();

  // Note, it is unsafe to std::move() a StructuredCloneHolderBase since a raw
  // this pointer is passed to mBuffer as a callback closure.  That must
  // be fixed if you want to implement a move constructor here.
  StructuredCloneHolderBase(StructuredCloneHolderBase&& aOther) = delete;

  // These methods should be implemented in order to clone data.
  // Read more documentation in js/public/StructuredClone.h.

  virtual JSObject* CustomReadHandler(
      JSContext* aCx, JSStructuredCloneReader* aReader,
      const JS::CloneDataPolicy& aCloneDataPolicy, uint32_t aTag,
      uint32_t aIndex) = 0;

  virtual bool CustomWriteHandler(JSContext* aCx,
                                  JSStructuredCloneWriter* aWriter,
                                  JS::Handle<JSObject*> aObj,
                                  bool* aSameProcessScopeRequired) = 0;

  // This method has to be called when this object is not needed anymore.
  // It will free memory and the buffer. This has to be called because
  // otherwise the buffer will be freed in the DTOR of this class and at that
  // point we cannot use the overridden methods.
  void Clear();

  // If these 3 methods are not implement, transfering objects will not be
  // allowed. Otherwise only arrayBuffers will be transferred.

  virtual bool CustomReadTransferHandler(JSContext* aCx,
                                         JSStructuredCloneReader* aReader,
                                         uint32_t aTag, void* aContent,
                                         uint64_t aExtraData,
                                         JS::MutableHandleObject aReturnObject);

  virtual bool CustomWriteTransferHandler(JSContext* aCx,
                                          JS::Handle<JSObject*> aObj,
                                          // Output:
                                          uint32_t* aTag,
                                          JS::TransferableOwnership* aOwnership,
                                          void** aContent,
                                          uint64_t* aExtraData);

  virtual void CustomFreeTransferHandler(uint32_t aTag,
                                         JS::TransferableOwnership aOwnership,
                                         void* aContent, uint64_t aExtraData);

  virtual bool CustomCanTransferHandler(JSContext* aCx,
                                        JS::Handle<JSObject*> aObj,
                                        bool* aSameProcessScopeRequired);

  // These methods are what you should use to read/write data.

  // Execute the serialization of aValue using the Structured Clone Algorithm.
  // The data can read back using Read().
  bool Write(JSContext* aCx, JS::Handle<JS::Value> aValue);

  // Like Write() but it supports the transferring of objects and handling
  // of cloning policy.
  bool Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
             JS::Handle<JS::Value> aTransfer,
             const JS::CloneDataPolicy& aCloneDataPolicy);

  // If Write() has been called, this method retrieves data and stores it into
  // aValue.
  bool Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue);

  // Like Read() but it supports handling of clone policy.
  bool Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue,
            const JS::CloneDataPolicy& aCloneDataPolicy);

  bool HasData() const { return !!mBuffer; }

  JSStructuredCloneData& BufferData() const {
    MOZ_ASSERT(mBuffer, "Write() has never been called.");
    return mBuffer->data();
  }

  size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) {
    size_t size = 0;
    if (HasData()) {
      size += mBuffer->sizeOfIncludingThis(aMallocSizeOf);
    }
    return size;
  }

  void SetErrorMessage(const char* aErrorMessage) {
    mErrorMessage.Assign(aErrorMessage);
  }

 protected:
  UniquePtr<JSAutoStructuredCloneBuffer> mBuffer;

  StructuredCloneScope mStructuredCloneScope;

  // Error message when a data clone error is about to throw. It's held while
  // the error callback is fired and it will be throw with a data clone error
  // later.
  nsCString mErrorMessage;

#ifdef DEBUG
  bool mClearCalled;
#endif
};

class BlobImpl;
class MessagePort;
class MessagePortIdentifier;

class StructuredCloneHolder : public StructuredCloneHolderBase {
 public:
  enum CloningSupport { CloningSupported, CloningNotSupported };

  enum TransferringSupport { TransferringSupported, TransferringNotSupported };

  // If cloning is supported, this object will clone objects such as Blobs,
  // FileList, ImageData, etc.
  // If transferring is supported, we will transfer MessagePorts and in the
  // future other transferrable objects.
  // The StructuredCloneScope is useful to know where the cloned/transferred
  // data can be read and written. Additional checks about the nature of the
  // objects will be done based on this scope value because not all the
  // objects can be sent between threads or processes.
  explicit StructuredCloneHolder(CloningSupport aSupportsCloning,
                                 TransferringSupport aSupportsTransferring,
                                 StructuredCloneScope aStructuredCloneScope);
  virtual ~StructuredCloneHolder();

  StructuredCloneHolder(StructuredCloneHolder&& aOther) = delete;

  // Normally you should just use Write() and Read().

  virtual void Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
                     ErrorResult& aRv);

  virtual void Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
                     JS::Handle<JS::Value> aTransfer,
                     const JS::CloneDataPolicy& aCloneDataPolicy,
                     ErrorResult& aRv);

  void Read(nsIGlobalObject* aGlobal, JSContext* aCx,
            JS::MutableHandle<JS::Value> aValue, ErrorResult& aRv);

  void Read(nsIGlobalObject* aGlobal, JSContext* aCx,
            JS::MutableHandle<JS::Value> aValue,
            const JS::CloneDataPolicy& aCloneDataPolicy, ErrorResult& aRv);

  // Call this method to know if this object is keeping some DOM object alive.
  bool HasClonedDOMObjects() const {
    return !mBlobImplArray.IsEmpty() || !mWasmModuleArray.IsEmpty() ||
           !mClonedSurfaces.IsEmpty() || !mInputStreamArray.IsEmpty();
  }

  nsTArray<RefPtr<BlobImpl>>& BlobImpls() {
    MOZ_ASSERT(mSupportsCloning,
               "Blobs cannot be taken/set if cloning is not supported.");
    return mBlobImplArray;
  }

  nsTArray<RefPtr<JS::WasmModule>>& WasmModules() {
    MOZ_ASSERT(mSupportsCloning,
               "WasmModules cannot be taken/set if cloning is not supported.");
    return mWasmModuleArray;
  }

  nsTArray<nsCOMPtr<nsIInputStream>>& InputStreams() {
    MOZ_ASSERT(mSupportsCloning,
               "InputStreams cannot be taken/set if cloning is not supported.");
    return mInputStreamArray;
  }

  // This method returns the final scope. If the final scope is unknown,
  // DifferentProcess is returned because it's the most restrictive one.
  StructuredCloneScope CloneScope() const {
    if (mStructuredCloneScope == StructuredCloneScope::UnknownDestination) {
      return StructuredCloneScope::DifferentProcess;
    }
    return mStructuredCloneScope;
  }

  // The global object is set internally just during the Read(). This method
  // can be used by read functions to retrieve it.
  nsIGlobalObject* GlobalDuringRead() const { return mGlobal; }

  // This must be called if the transferring has ports generated by Read().
  // MessagePorts are not thread-safe and they must be retrieved in the thread
  // where they are created.
  nsTArray<RefPtr<MessagePort>>&& TakeTransferredPorts() {
    MOZ_ASSERT(mSupportsTransferring);
    return std::move(mTransferredPorts);
  }

  // This method uses TakeTransferredPorts() to populate a sequence of
  // MessagePorts for WebIDL binding classes.
  bool TakeTransferredPortsAsSequence(
      Sequence<OwningNonNull<mozilla::dom::MessagePort>>& aPorts);

  nsTArray<MessagePortIdentifier>& PortIdentifiers() const {
    MOZ_ASSERT(mSupportsTransferring);
    return mPortIdentifiers;
  }

  nsTArray<RefPtr<gfx::DataSourceSurface>>& GetSurfaces() {
    return mClonedSurfaces;
  }

  // Implementations of the virtual methods to allow cloning of objects which
  // JS engine itself doesn't clone.

  virtual JSObject* CustomReadHandler(
      JSContext* aCx, JSStructuredCloneReader* aReader,
      const JS::CloneDataPolicy& aCloneDataPolicy, uint32_t aTag,
      uint32_t aIndex) override;

  virtual bool CustomWriteHandler(JSContext* aCx,
                                  JSStructuredCloneWriter* aWriter,
                                  JS::Handle<JSObject*> aObj,
                                  bool* aSameProcessScopeRequired) override;

  virtual bool CustomReadTransferHandler(
      JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag,
      void* aContent, uint64_t aExtraData,
      JS::MutableHandleObject aReturnObject) override;

  virtual bool CustomWriteTransferHandler(JSContext* aCx,
                                          JS::Handle<JSObject*> aObj,
                                          uint32_t* aTag,
                                          JS::TransferableOwnership* aOwnership,
                                          void** aContent,
                                          uint64_t* aExtraData) override;

  virtual void CustomFreeTransferHandler(uint32_t aTag,
                                         JS::TransferableOwnership aOwnership,
                                         void* aContent,
                                         uint64_t aExtraData) override;

  virtual bool CustomCanTransferHandler(
      JSContext* aCx, JS::Handle<JSObject*> aObj,
      bool* aSameProcessScopeRequired) override;

  // These 2 static methods are useful to read/write fully serializable objects.
  // They can be used by custom StructuredCloneHolderBase classes to
  // serialize objects such as ImageData, CryptoKey, RTCCertificate, etc.

  static JSObject* ReadFullySerializableObjects(
      JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag);

  static bool WriteFullySerializableObjects(JSContext* aCx,
                                            JSStructuredCloneWriter* aWriter,
                                            JS::Handle<JSObject*> aObj);

  // Helper functions for reading and writing strings.
  static bool ReadString(JSStructuredCloneReader* aReader, nsString& aString);
  static bool WriteString(JSStructuredCloneWriter* aWriter,
                          const nsAString& aString);

  static const JSStructuredCloneCallbacks sCallbacks;

 protected:
  // If you receive a buffer from IPC, you can use this method to retrieve a
  // JS::Value. It can happen that you want to pre-populate the array of Blobs
  // and/or the PortIdentifiers.
  void ReadFromBuffer(nsIGlobalObject* aGlobal, JSContext* aCx,
                      JSStructuredCloneData& aBuffer,
                      JS::MutableHandle<JS::Value> aValue,
                      const JS::CloneDataPolicy& aCloneDataPolicy,
                      ErrorResult& aRv);

  void ReadFromBuffer(nsIGlobalObject* aGlobal, JSContext* aCx,
                      JSStructuredCloneData& aBuffer,
                      uint32_t aAlgorithmVersion,
                      JS::MutableHandle<JS::Value> aValue,
                      const JS::CloneDataPolicy& aCloneDataPolicy,
                      ErrorResult& aRv);

  void SameProcessScopeRequired(bool* aSameProcessScopeRequired);

  bool mSupportsCloning;
  bool mSupportsTransferring;

  // SizeOfExcludingThis is inherited from StructuredCloneHolderBase. It doesn't
  // account for objects in the following arrays because a) they're not expected
  // to be stored in long-lived StructuredCloneHolder objects, and b) in the
  // case of BlobImpl objects, MemoryBlobImpls have their own memory reporters,
  // and the other types do not hold significant amounts of memory alive.

  // Used for cloning blobs in the structured cloning algorithm.
  nsTArray<RefPtr<BlobImpl>> mBlobImplArray;

  // Used for cloning JS::WasmModules in the structured cloning algorithm.
  nsTArray<RefPtr<JS::WasmModule>> mWasmModuleArray;

  // Used for cloning InputStream in the structured cloning algorithm.
  nsTArray<nsCOMPtr<nsIInputStream>> mInputStreamArray;

  // This is used for sharing the backend of ImageBitmaps.
  // The DataSourceSurface object must be thread-safely reference-counted.
  // The DataSourceSurface object will not be written ever via any ImageBitmap
  // instance, so no race condition will occur.
  nsTArray<RefPtr<gfx::DataSourceSurface>> mClonedSurfaces;

  // This raw pointer is only set within ::Read() and is unset by the end.
  nsIGlobalObject* MOZ_NON_OWNING_REF mGlobal;

  // This array contains the ports once we've finished the reading. It's
  // generated from the mPortIdentifiers array.
  nsTArray<RefPtr<MessagePort>> mTransferredPorts;

  // This array contains the identifiers of the MessagePorts. Based on these we
  // are able to reconnect the new transferred ports with the other
  // MessageChannel ports.
  mutable nsTArray<MessagePortIdentifier> mPortIdentifiers;

#ifdef DEBUG
  nsCOMPtr<nsIEventTarget> mCreationEventTarget;
#endif
};

}  // namespace dom
}  // namespace mozilla

#endif  // mozilla_dom_StructuredCloneHolder_h