Bug 1750871 - run mochitest-remote on fission everywhere. r=releng-reviewers,aki
[gecko.git] / dom / base / StructuredCloneHolder.h
blobc7c7f7ef12ace1c7abe95c29b6d2878b1ab8f226
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 mozilla_dom_StructuredCloneHolder_h
8 #define mozilla_dom_StructuredCloneHolder_h
10 #include <cstddef>
11 #include <cstdint>
12 #include <utility>
13 #include "js/StructuredClone.h"
14 #include "js/TypeDecls.h"
15 #include "mozilla/Assertions.h"
16 #include "mozilla/Attributes.h"
17 #include "mozilla/MemoryReporting.h"
18 #include "mozilla/RefPtr.h"
19 #include "mozilla/UniquePtr.h"
20 #include "nsCOMPtr.h"
21 #include "nsString.h"
22 #include "nsTArray.h"
24 class nsIEventTarget;
25 class nsIGlobalObject;
26 class nsIInputStream;
27 struct JSStructuredCloneReader;
28 struct JSStructuredCloneWriter;
30 namespace JS {
31 class Value;
32 struct WasmModule;
33 } // namespace JS
35 namespace mozilla {
36 class ErrorResult;
37 template <class T>
38 class OwningNonNull;
40 namespace layers {
41 class Image;
44 namespace gfx {
45 class DataSourceSurface;
48 namespace dom {
50 class BlobImpl;
51 class MessagePort;
52 class MessagePortIdentifier;
53 template <typename T>
54 class Sequence;
56 class StructuredCloneHolderBase {
57 public:
58 typedef JS::StructuredCloneScope StructuredCloneScope;
60 StructuredCloneHolderBase(
61 StructuredCloneScope aScope = StructuredCloneScope::SameProcess);
62 virtual ~StructuredCloneHolderBase();
64 // Note, it is unsafe to std::move() a StructuredCloneHolderBase since a raw
65 // this pointer is passed to mBuffer as a callback closure. That must
66 // be fixed if you want to implement a move constructor here.
67 StructuredCloneHolderBase(StructuredCloneHolderBase&& aOther) = delete;
69 // These methods should be implemented in order to clone data.
70 // Read more documentation in js/public/StructuredClone.h.
72 virtual JSObject* CustomReadHandler(
73 JSContext* aCx, JSStructuredCloneReader* aReader,
74 const JS::CloneDataPolicy& aCloneDataPolicy, uint32_t aTag,
75 uint32_t aIndex) = 0;
77 virtual bool CustomWriteHandler(JSContext* aCx,
78 JSStructuredCloneWriter* aWriter,
79 JS::Handle<JSObject*> aObj,
80 bool* aSameProcessScopeRequired) = 0;
82 // This method has to be called when this object is not needed anymore.
83 // It will free memory and the buffer. This has to be called because
84 // otherwise the buffer will be freed in the DTOR of this class and at that
85 // point we cannot use the overridden methods.
86 void Clear();
88 // If these 3 methods are not implement, transfering objects will not be
89 // allowed. Otherwise only arrayBuffers will be transferred.
91 virtual bool CustomReadTransferHandler(JSContext* aCx,
92 JSStructuredCloneReader* aReader,
93 uint32_t aTag, void* aContent,
94 uint64_t aExtraData,
95 JS::MutableHandleObject aReturnObject);
97 virtual bool CustomWriteTransferHandler(JSContext* aCx,
98 JS::Handle<JSObject*> aObj,
99 // Output:
100 uint32_t* aTag,
101 JS::TransferableOwnership* aOwnership,
102 void** aContent,
103 uint64_t* aExtraData);
105 virtual void CustomFreeTransferHandler(uint32_t aTag,
106 JS::TransferableOwnership aOwnership,
107 void* aContent, uint64_t aExtraData);
109 virtual bool CustomCanTransferHandler(JSContext* aCx,
110 JS::Handle<JSObject*> aObj,
111 bool* aSameProcessScopeRequired);
113 // These methods are what you should use to read/write data.
115 // Execute the serialization of aValue using the Structured Clone Algorithm.
116 // The data can read back using Read().
117 bool Write(JSContext* aCx, JS::Handle<JS::Value> aValue);
119 // Like Write() but it supports the transferring of objects and handling
120 // of cloning policy.
121 bool Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
122 JS::Handle<JS::Value> aTransfer,
123 const JS::CloneDataPolicy& aCloneDataPolicy);
125 // If Write() has been called, this method retrieves data and stores it into
126 // aValue.
127 bool Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue);
129 // Like Read() but it supports handling of clone policy.
130 bool Read(JSContext* aCx, JS::MutableHandle<JS::Value> aValue,
131 const JS::CloneDataPolicy& aCloneDataPolicy);
133 bool HasData() const { return !!mBuffer; }
135 JSStructuredCloneData& BufferData() const {
136 MOZ_ASSERT(mBuffer, "Write() has never been called.");
137 return mBuffer->data();
140 size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) {
141 size_t size = 0;
142 if (HasData()) {
143 size += mBuffer->sizeOfIncludingThis(aMallocSizeOf);
145 return size;
148 void SetErrorMessage(const char* aErrorMessage) {
149 mErrorMessage.Assign(aErrorMessage);
152 protected:
153 UniquePtr<JSAutoStructuredCloneBuffer> mBuffer;
155 StructuredCloneScope mStructuredCloneScope;
157 // Error message when a data clone error is about to throw. It's held while
158 // the error callback is fired and it will be throw with a data clone error
159 // later.
160 nsCString mErrorMessage;
162 #ifdef DEBUG
163 bool mClearCalled;
164 #endif
167 class BlobImpl;
168 class MessagePort;
169 class MessagePortIdentifier;
171 class StructuredCloneHolder : public StructuredCloneHolderBase {
172 public:
173 enum CloningSupport { CloningSupported, CloningNotSupported };
175 enum TransferringSupport { TransferringSupported, TransferringNotSupported };
177 // If cloning is supported, this object will clone objects such as Blobs,
178 // FileList, ImageData, etc.
179 // If transferring is supported, we will transfer MessagePorts and in the
180 // future other transferrable objects.
181 // The StructuredCloneScope is useful to know where the cloned/transferred
182 // data can be read and written. Additional checks about the nature of the
183 // objects will be done based on this scope value because not all the
184 // objects can be sent between threads or processes.
185 explicit StructuredCloneHolder(CloningSupport aSupportsCloning,
186 TransferringSupport aSupportsTransferring,
187 StructuredCloneScope aStructuredCloneScope);
188 virtual ~StructuredCloneHolder();
190 StructuredCloneHolder(StructuredCloneHolder&& aOther) = delete;
192 // Normally you should just use Write() and Read().
194 virtual void Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
195 ErrorResult& aRv);
197 virtual void Write(JSContext* aCx, JS::Handle<JS::Value> aValue,
198 JS::Handle<JS::Value> aTransfer,
199 const JS::CloneDataPolicy& aCloneDataPolicy,
200 ErrorResult& aRv);
202 void Read(nsIGlobalObject* aGlobal, JSContext* aCx,
203 JS::MutableHandle<JS::Value> aValue, ErrorResult& aRv);
205 void Read(nsIGlobalObject* aGlobal, JSContext* aCx,
206 JS::MutableHandle<JS::Value> aValue,
207 const JS::CloneDataPolicy& aCloneDataPolicy, ErrorResult& aRv);
209 // Call this method to know if this object is keeping some DOM object alive.
210 bool HasClonedDOMObjects() const {
211 return !mBlobImplArray.IsEmpty() || !mWasmModuleArray.IsEmpty() ||
212 !mClonedSurfaces.IsEmpty() || !mInputStreamArray.IsEmpty();
215 nsTArray<RefPtr<BlobImpl>>& BlobImpls() {
216 MOZ_ASSERT(mSupportsCloning,
217 "Blobs cannot be taken/set if cloning is not supported.");
218 return mBlobImplArray;
221 nsTArray<RefPtr<JS::WasmModule>>& WasmModules() {
222 MOZ_ASSERT(mSupportsCloning,
223 "WasmModules cannot be taken/set if cloning is not supported.");
224 return mWasmModuleArray;
227 nsTArray<nsCOMPtr<nsIInputStream>>& InputStreams() {
228 MOZ_ASSERT(mSupportsCloning,
229 "InputStreams cannot be taken/set if cloning is not supported.");
230 return mInputStreamArray;
233 // This method returns the final scope. If the final scope is unknown,
234 // DifferentProcess is returned because it's the most restrictive one.
235 StructuredCloneScope CloneScope() const {
236 if (mStructuredCloneScope == StructuredCloneScope::UnknownDestination) {
237 return StructuredCloneScope::DifferentProcess;
239 return mStructuredCloneScope;
242 // The global object is set internally just during the Read(). This method
243 // can be used by read functions to retrieve it.
244 nsIGlobalObject* GlobalDuringRead() const { return mGlobal; }
246 // This must be called if the transferring has ports generated by Read().
247 // MessagePorts are not thread-safe and they must be retrieved in the thread
248 // where they are created.
249 nsTArray<RefPtr<MessagePort>>&& TakeTransferredPorts() {
250 MOZ_ASSERT(mSupportsTransferring);
251 return std::move(mTransferredPorts);
254 // This method uses TakeTransferredPorts() to populate a sequence of
255 // MessagePorts for WebIDL binding classes.
256 bool TakeTransferredPortsAsSequence(
257 Sequence<OwningNonNull<mozilla::dom::MessagePort>>& aPorts);
259 nsTArray<MessagePortIdentifier>& PortIdentifiers() const {
260 MOZ_ASSERT(mSupportsTransferring);
261 return mPortIdentifiers;
264 nsTArray<RefPtr<gfx::DataSourceSurface>>& GetSurfaces() {
265 return mClonedSurfaces;
268 // Implementations of the virtual methods to allow cloning of objects which
269 // JS engine itself doesn't clone.
271 virtual JSObject* CustomReadHandler(
272 JSContext* aCx, JSStructuredCloneReader* aReader,
273 const JS::CloneDataPolicy& aCloneDataPolicy, uint32_t aTag,
274 uint32_t aIndex) override;
276 virtual bool CustomWriteHandler(JSContext* aCx,
277 JSStructuredCloneWriter* aWriter,
278 JS::Handle<JSObject*> aObj,
279 bool* aSameProcessScopeRequired) override;
281 virtual bool CustomReadTransferHandler(
282 JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag,
283 void* aContent, uint64_t aExtraData,
284 JS::MutableHandleObject aReturnObject) override;
286 virtual bool CustomWriteTransferHandler(JSContext* aCx,
287 JS::Handle<JSObject*> aObj,
288 uint32_t* aTag,
289 JS::TransferableOwnership* aOwnership,
290 void** aContent,
291 uint64_t* aExtraData) override;
293 virtual void CustomFreeTransferHandler(uint32_t aTag,
294 JS::TransferableOwnership aOwnership,
295 void* aContent,
296 uint64_t aExtraData) override;
298 virtual bool CustomCanTransferHandler(
299 JSContext* aCx, JS::Handle<JSObject*> aObj,
300 bool* aSameProcessScopeRequired) override;
302 // These 2 static methods are useful to read/write fully serializable objects.
303 // They can be used by custom StructuredCloneHolderBase classes to
304 // serialize objects such as ImageData, CryptoKey, RTCCertificate, etc.
306 static JSObject* ReadFullySerializableObjects(
307 JSContext* aCx, JSStructuredCloneReader* aReader, uint32_t aTag);
309 static bool WriteFullySerializableObjects(JSContext* aCx,
310 JSStructuredCloneWriter* aWriter,
311 JS::Handle<JSObject*> aObj);
313 // Helper functions for reading and writing strings.
314 static bool ReadString(JSStructuredCloneReader* aReader, nsString& aString);
315 static bool WriteString(JSStructuredCloneWriter* aWriter,
316 const nsAString& aString);
318 static const JSStructuredCloneCallbacks sCallbacks;
320 protected:
321 // If you receive a buffer from IPC, you can use this method to retrieve a
322 // JS::Value. It can happen that you want to pre-populate the array of Blobs
323 // and/or the PortIdentifiers.
324 void ReadFromBuffer(nsIGlobalObject* aGlobal, JSContext* aCx,
325 JSStructuredCloneData& aBuffer,
326 JS::MutableHandle<JS::Value> aValue,
327 const JS::CloneDataPolicy& aCloneDataPolicy,
328 ErrorResult& aRv);
330 void ReadFromBuffer(nsIGlobalObject* aGlobal, JSContext* aCx,
331 JSStructuredCloneData& aBuffer,
332 uint32_t aAlgorithmVersion,
333 JS::MutableHandle<JS::Value> aValue,
334 const JS::CloneDataPolicy& aCloneDataPolicy,
335 ErrorResult& aRv);
337 void SameProcessScopeRequired(bool* aSameProcessScopeRequired);
339 bool mSupportsCloning;
340 bool mSupportsTransferring;
342 // SizeOfExcludingThis is inherited from StructuredCloneHolderBase. It doesn't
343 // account for objects in the following arrays because a) they're not expected
344 // to be stored in long-lived StructuredCloneHolder objects, and b) in the
345 // case of BlobImpl objects, MemoryBlobImpls have their own memory reporters,
346 // and the other types do not hold significant amounts of memory alive.
348 // Used for cloning blobs in the structured cloning algorithm.
349 nsTArray<RefPtr<BlobImpl>> mBlobImplArray;
351 // Used for cloning JS::WasmModules in the structured cloning algorithm.
352 nsTArray<RefPtr<JS::WasmModule>> mWasmModuleArray;
354 // Used for cloning InputStream in the structured cloning algorithm.
355 nsTArray<nsCOMPtr<nsIInputStream>> mInputStreamArray;
357 // This is used for sharing the backend of ImageBitmaps.
358 // The DataSourceSurface object must be thread-safely reference-counted.
359 // The DataSourceSurface object will not be written ever via any ImageBitmap
360 // instance, so no race condition will occur.
361 nsTArray<RefPtr<gfx::DataSourceSurface>> mClonedSurfaces;
363 // This raw pointer is only set within ::Read() and is unset by the end.
364 nsIGlobalObject* MOZ_NON_OWNING_REF mGlobal;
366 // This array contains the ports once we've finished the reading. It's
367 // generated from the mPortIdentifiers array.
368 nsTArray<RefPtr<MessagePort>> mTransferredPorts;
370 // This array contains the identifiers of the MessagePorts. Based on these we
371 // are able to reconnect the new transferred ports with the other
372 // MessageChannel ports.
373 mutable nsTArray<MessagePortIdentifier> mPortIdentifiers;
375 #ifdef DEBUG
376 nsCOMPtr<nsIEventTarget> mCreationEventTarget;
377 #endif
380 } // namespace dom
381 } // namespace mozilla
383 #endif // mozilla_dom_StructuredCloneHolder_h