Debian Codegraph @

js/src/vm/StructuredClone.cpp

raw
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/. */
6
7 /*
8 * This file implements the structured data algorithms of
9 * https://html.spec.whatwg.org/multipage/structured-data.html
10 *
11 * The spec is in two parts:
12 *
13 * - StructuredSerialize examines a JS value and produces a graph of Records.
14 * - StructuredDeserialize walks the Records and produces a new JS value.
15 *
16 * The differences between our implementation and the spec are minor:
17 *
18 * - We call the two phases "write" and "read".
19 * - Our algorithms use an explicit work stack, rather than recursion.
20 * - Serialized data is a flat array of bytes, not a (possibly cyclic) graph
21 * of "Records".
22 * - As a consequence, we handle non-treelike object graphs differently.
23 * We serialize objects that appear in multiple places in the input as
24 * backreferences, using sequential integer indexes.
25 * See `JSStructuredCloneReader::allObjs`, our take on the "memory" map
26 * in the spec's StructuredDeserialize.
27 */
28
29 #include "js/StructuredClone.h"
30
31 #include "mozilla/Casting.h"
32 #include "mozilla/CheckedInt.h"
33 #include "mozilla/EndianUtils.h"
34 #include "mozilla/FloatingPoint.h"
35 #include "mozilla/Maybe.h"
36 #include "mozilla/ScopeExit.h"
37
38 #include <algorithm>
39 #include <memory>
40 #include <utility>
41
42 #include "jsdate.h"
43
44 #include "builtin/DataViewObject.h"
45 #include "builtin/MapObject.h"
46 #include "gc/GC.h" // AutoSelectGCHeap
47 #include "js/Array.h" // JS::GetArrayLength, JS::IsArrayObject
48 #include "js/ArrayBuffer.h" // JS::{ArrayBufferHasData,DetachArrayBuffer,IsArrayBufferObject,New{,Mapped}ArrayBufferWithContents,ReleaseMappedArrayBufferContents}
49 #include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin
50 #include "js/Date.h"
51 #include "js/experimental/TypedData.h" // JS_NewDataView, JS_New{{Ui,I}nt{8,16,32},Float{32,64},Uint8Clamped,Big{Ui,I}nt64}ArrayWithBuffer
52 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
53 #include "js/GCAPI.h"
54 #include "js/GCHashTable.h"
55 #include "js/Object.h" // JS::GetBuiltinClass
56 #include "js/PropertyAndElement.h" // JS_GetElement
57 #include "js/RegExpFlags.h" // JS::RegExpFlag, JS::RegExpFlags
58 #include "js/ScalarType.h" // js::Scalar::Type
59 #include "js/SharedArrayBuffer.h" // JS::IsSharedArrayBufferObject
60 #include "js/Wrapper.h"
61 #include "util/DifferentialTesting.h"
62 #include "vm/BigIntType.h"
63 #include "vm/ErrorObject.h"
64 #include "vm/JSContext.h"
65 #include "vm/PlainObject.h" // js::PlainObject
66 #include "vm/RegExpObject.h"
67 #include "vm/SavedFrame.h"
68 #include "vm/SharedArrayObject.h"
69 #include "vm/TypedArrayObject.h"
70 #include "wasm/WasmJS.h"
71
72 #include "vm/ArrayObject-inl.h"
73 #include "vm/Compartment-inl.h"
74 #include "vm/ErrorObject-inl.h"
75 #include "vm/JSContext-inl.h"
76 #include "vm/JSObject-inl.h"
77 #include "vm/NativeObject-inl.h"
78 #include "vm/ObjectOperations-inl.h"
79 #include "vm/Realm-inl.h"
80 #include "vm/StringType-inl.h"
81
82 using namespace js;
83
84 using JS::CanonicalizeNaN;
85 using JS::GetBuiltinClass;
86 using JS::RegExpFlag;
87 using JS::RegExpFlags;
88 using JS::RootedValueVector;
89 using mozilla::AssertedCast;
90 using mozilla::BitwiseCast;
91 using mozilla::Maybe;
92 using mozilla::NativeEndian;
93 using mozilla::NumbersAreIdentical;
94
95 // When you make updates here, make sure you consider whether you need to bump
96 // the value of JS_STRUCTURED_CLONE_VERSION in js/public/StructuredClone.h. You
97 // will likely need to increment the version if anything at all changes in the
98 // serialization format.
99 //
100 // Note that SCTAG_END_OF_KEYS is written into the serialized form and should
101 // have a stable ID, it need not be at the end of the list and should not be
102 // used for sizing data structures.
103
104 enum StructuredDataType : uint32_t {
105 // Structured data types provided by the engine
106 SCTAG_FLOAT_MAX = 0xFFF00000,
107 SCTAG_HEADER = 0xFFF10000,
108 SCTAG_NULL = 0xFFFF0000,
109 SCTAG_UNDEFINED,
110 SCTAG_BOOLEAN,
111 SCTAG_INT32,
112 SCTAG_STRING,
113 SCTAG_DATE_OBJECT,
114 SCTAG_REGEXP_OBJECT,
115 SCTAG_ARRAY_OBJECT,
116 SCTAG_OBJECT_OBJECT,
117 SCTAG_ARRAY_BUFFER_OBJECT_V2, // Old version, for backwards compatibility.
118 SCTAG_BOOLEAN_OBJECT,
119 SCTAG_STRING_OBJECT,
120 SCTAG_NUMBER_OBJECT,
121 SCTAG_BACK_REFERENCE_OBJECT,
122 SCTAG_DO_NOT_USE_1, // Required for backwards compatibility
123 SCTAG_DO_NOT_USE_2, // Required for backwards compatibility
124 SCTAG_TYPED_ARRAY_OBJECT_V2, // Old version, for backwards compatibility.
125 SCTAG_MAP_OBJECT,
126 SCTAG_SET_OBJECT,
127 SCTAG_END_OF_KEYS,
128 SCTAG_DO_NOT_USE_3, // Required for backwards compatibility
129 SCTAG_DATA_VIEW_OBJECT_V2, // Old version, for backwards compatibility.
130 SCTAG_SAVED_FRAME_OBJECT,
131
132 // No new tags before principals.
133 SCTAG_JSPRINCIPALS,
134 SCTAG_NULL_JSPRINCIPALS,
135 SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_SYSTEM,
136 SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_NOT_SYSTEM,
137
138 SCTAG_SHARED_ARRAY_BUFFER_OBJECT,
139 SCTAG_SHARED_WASM_MEMORY_OBJECT,
140
141 SCTAG_BIGINT,
142 SCTAG_BIGINT_OBJECT,
143
144 SCTAG_ARRAY_BUFFER_OBJECT,
145 SCTAG_TYPED_ARRAY_OBJECT,
146 SCTAG_DATA_VIEW_OBJECT,
147
148 SCTAG_ERROR_OBJECT,
149
150 SCTAG_RESIZABLE_ARRAY_BUFFER_OBJECT,
151 SCTAG_GROWABLE_SHARED_ARRAY_BUFFER_OBJECT,
152
153 SCTAG_TYPED_ARRAY_V1_MIN = 0xFFFF0100,
154 SCTAG_TYPED_ARRAY_V1_INT8 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Int8,
155 SCTAG_TYPED_ARRAY_V1_UINT8 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint8,
156 SCTAG_TYPED_ARRAY_V1_INT16 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Int16,
157 SCTAG_TYPED_ARRAY_V1_UINT16 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint16,
158 SCTAG_TYPED_ARRAY_V1_INT32 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Int32,
159 SCTAG_TYPED_ARRAY_V1_UINT32 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint32,
160 SCTAG_TYPED_ARRAY_V1_FLOAT32 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Float32,
161 SCTAG_TYPED_ARRAY_V1_FLOAT64 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Float64,
162 SCTAG_TYPED_ARRAY_V1_UINT8_CLAMPED =
163 SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint8Clamped,
164 // BigInt64 and BigUint64 are not supported in the v1 format.
165 SCTAG_TYPED_ARRAY_V1_MAX = SCTAG_TYPED_ARRAY_V1_UINT8_CLAMPED,
166
167 // Define a separate range of numbers for Transferable-only tags, since
168 // they are not used for persistent clone buffers and therefore do not
169 // require bumping JS_STRUCTURED_CLONE_VERSION.
170 SCTAG_TRANSFER_MAP_HEADER = 0xFFFF0200,
171 SCTAG_TRANSFER_MAP_PENDING_ENTRY,
172 SCTAG_TRANSFER_MAP_ARRAY_BUFFER,
173 SCTAG_TRANSFER_MAP_STORED_ARRAY_BUFFER,
174 SCTAG_TRANSFER_MAP_END_OF_BUILTIN_TYPES,
175
176 SCTAG_END_OF_BUILTIN_TYPES
177 };
178
179 /*
180 * Format of transfer map:
181 * - <SCTAG_TRANSFER_MAP_HEADER, UNREAD|TRANSFERRING|TRANSFERRED>
182 * - numTransferables (64 bits)
183 * - array of:
184 * - <SCTAG_TRANSFER_MAP_*, TransferableOwnership> pointer (64
185 * bits)
186 * - extraData (64 bits), eg byte length for ArrayBuffers
187 * - any data written for custom transferables
188 */
189
190 // Data associated with an SCTAG_TRANSFER_MAP_HEADER that tells whether the
191 // contents have been read out yet or not. TRANSFERRING is for the case where we
192 // have started but not completed reading, which due to errors could mean that
193 // there are things still owned by the clone buffer that need to be released, so
194 // discarding should not just be skipped.
195 enum TransferableMapHeader {
196 SCTAG_TM_UNREAD = 0,
197 SCTAG_TM_TRANSFERRING,
198 SCTAG_TM_TRANSFERRED,
199
200 SCTAG_TM_END
201 };
202
203 static inline uint64_t PairToUInt64(uint32_t tag, uint32_t data) {
204 return uint64_t(data) | (uint64_t(tag) << 32);
205 }
206
207 namespace js {
208
209 template <typename T, typename AllocPolicy>
210 struct BufferIterator {
211 using BufferList = mozilla::BufferList<AllocPolicy>;
212
213 explicit BufferIterator(const BufferList& buffer)
214 : mBuffer(buffer), mIter(buffer.Iter()) {
215 static_assert(8 % sizeof(T) == 0);
216 }
217
218 explicit BufferIterator(const JSStructuredCloneData& data)
219 : mBuffer(data.bufList_), mIter(data.Start()) {}
220
221 BufferIterator& operator=(const BufferIterator& other) {
222 MOZ_ASSERT(&mBuffer == &other.mBuffer);
223 mIter = other.mIter;
224 return *this;
225 }
226
227 [[nodiscard]] bool advance(size_t size = sizeof(T)) {
228 return mIter.AdvanceAcrossSegments(mBuffer, size);
229 }
230
231 BufferIterator operator++(int) {
232 BufferIterator ret = *this;
233 if (!advance(sizeof(T))) {
234 MOZ_ASSERT(false, "Failed to read StructuredCloneData. Data incomplete");
235 }
236 return ret;
237 }
238
239 BufferIterator& operator+=(size_t size) {
240 if (!advance(size)) {
241 MOZ_ASSERT(false, "Failed to read StructuredCloneData. Data incomplete");
242 }
243 return *this;
244 }
245
246 size_t operator-(const BufferIterator& other) const {
247 MOZ_ASSERT(&mBuffer == &other.mBuffer);
248 return mBuffer.RangeLength(other.mIter, mIter);
249 }
250
251 bool operator==(const BufferIterator& other) const {
252 return mBuffer.Start() == other.mBuffer.Start() && mIter == other.mIter;
253 }
254 bool operator!=(const BufferIterator& other) const {
255 return !(*this == other);
256 }
257
258 bool done() const { return mIter.Done(); }
259
260 [[nodiscard]] bool readBytes(char* outData, size_t size) {
261 return mBuffer.ReadBytes(mIter, outData, size);
262 }
263
264 void write(const T& data) {
265 MOZ_ASSERT(mIter.HasRoomFor(sizeof(T)));
266 *reinterpret_cast<T*>(mIter.Data()) = data;
267 }
268
269 T peek() const {
270 MOZ_ASSERT(mIter.HasRoomFor(sizeof(T)));
271 return *reinterpret_cast<T*>(mIter.Data());
272 }
273
274 bool canPeek() const { return mIter.HasRoomFor(sizeof(T)); }
275
276 const BufferList& mBuffer;
277 typename BufferList::IterImpl mIter;
278 };
279
280 SharedArrayRawBufferRefs& SharedArrayRawBufferRefs::operator=(
281 SharedArrayRawBufferRefs&& other) {
282 takeOwnership(std::move(other));
283 return *this;
284 }
285
286 SharedArrayRawBufferRefs::~SharedArrayRawBufferRefs() { releaseAll(); }
287
288 bool SharedArrayRawBufferRefs::acquire(JSContext* cx,
289 SharedArrayRawBuffer* rawbuf) {
290 if (!refs_.append(rawbuf)) {
291 ReportOutOfMemory(cx);
292 return false;
293 }
294
295 if (!rawbuf->addReference()) {
296 refs_.popBack();
297 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
298 JSMSG_SC_SAB_REFCNT_OFLO);
299 return false;
300 }
301
302 return true;
303 }
304
305 bool SharedArrayRawBufferRefs::acquireAll(
306 JSContext* cx, const SharedArrayRawBufferRefs& that) {
307 if (!refs_.reserve(refs_.length() + that.refs_.length())) {
308 ReportOutOfMemory(cx);
309 return false;
310 }
311
312 for (auto ref : that.refs_) {
313 if (!ref->addReference()) {
314 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
315 JSMSG_SC_SAB_REFCNT_OFLO);
316 return false;
317 }
318 MOZ_ALWAYS_TRUE(refs_.append(ref));
319 }
320
321 return true;
322 }
323
324 void SharedArrayRawBufferRefs::takeOwnership(SharedArrayRawBufferRefs&& other) {
325 MOZ_ASSERT(refs_.empty());
326 refs_ = std::move(other.refs_);
327 }
328
329 void SharedArrayRawBufferRefs::releaseAll() {
330 for (auto ref : refs_) {
331 ref->dropReference();
332 }
333 refs_.clear();
334 }
335
336 // SCOutput provides an interface to write raw data -- eg uint64_ts, doubles,
337 // arrays of bytes -- into a structured clone data output stream. It also knows
338 // how to free any transferable data within that stream.
339 //
340 // Note that it contains a full JSStructuredCloneData object, which holds the
341 // callbacks necessary to read/write/transfer/free the data. For the purpose of
342 // this class, only the freeTransfer callback is relevant; the rest of the
343 // callbacks are used by the higher-level JSStructuredCloneWriter interface.
344 struct SCOutput {
345 public:
346 using Iter = BufferIterator<uint64_t, SystemAllocPolicy>;
347
348 SCOutput(JSContext* cx, JS::StructuredCloneScope scope);
349
350 JSContext* context() const { return cx; }
351 JS::StructuredCloneScope scope() const { return buf.scope(); }
352 void sameProcessScopeRequired() { buf.sameProcessScopeRequired(); }
353
354 [[nodiscard]] bool write(uint64_t u);
355 [[nodiscard]] bool writePair(uint32_t tag, uint32_t data);
356 [[nodiscard]] bool writeDouble(double d);
357 [[nodiscard]] bool writeBytes(const void* p, size_t nbytes);
358 [[nodiscard]] bool writeChars(const Latin1Char* p, size_t nchars);
359 [[nodiscard]] bool writeChars(const char16_t* p, size_t nchars);
360
361 template <class T>
362 [[nodiscard]] bool writeArray(const T* p, size_t nelems);
363
364 void setCallbacks(const JSStructuredCloneCallbacks* callbacks, void* closure,
365 OwnTransferablePolicy policy) {
366 buf.setCallbacks(callbacks, closure, policy);
367 }
368 void extractBuffer(JSStructuredCloneData* data) { *data = std::move(buf); }
369
370 uint64_t tell() const { return buf.Size(); }
371 uint64_t count() const { return buf.Size() / sizeof(uint64_t); }
372 Iter iter() { return Iter(buf); }
373
374 size_t offset(Iter dest) { return dest - iter(); }
375
376 JSContext* cx;
377 JSStructuredCloneData buf;
378 };
379
380 class SCInput {
381 public:
382 using BufferIterator = js::BufferIterator<uint64_t, SystemAllocPolicy>;
383
384 SCInput(JSContext* cx, const JSStructuredCloneData& data);
385
386 JSContext* context() const { return cx; }
387
388 static void getPtr(uint64_t data, void** ptr);
389 static void getPair(uint64_t data, uint32_t* tagp, uint32_t* datap);
390
391 [[nodiscard]] bool read(uint64_t* p);
392 [[nodiscard]] bool readPair(uint32_t* tagp, uint32_t* datap);
393 [[nodiscard]] bool readDouble(double* p);
394 [[nodiscard]] bool readBytes(void* p, size_t nbytes);
395 [[nodiscard]] bool readChars(Latin1Char* p, size_t nchars);
396 [[nodiscard]] bool readChars(char16_t* p, size_t nchars);
397 [[nodiscard]] bool readPtr(void**);
398
399 [[nodiscard]] bool get(uint64_t* p);
400 [[nodiscard]] bool getPair(uint32_t* tagp, uint32_t* datap);
401
402 const BufferIterator& tell() const { return point; }
403 void seekTo(const BufferIterator& pos) { point = pos; }
404 [[nodiscard]] bool seekBy(size_t pos) {
405 if (!point.advance(pos)) {
406 reportTruncated();
407 return false;
408 }
409 return true;
410 }
411
412 template <class T>
413 [[nodiscard]] bool readArray(T* p, size_t nelems);
414
415 bool reportTruncated() {
416 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
417 JSMSG_SC_BAD_SERIALIZED_DATA, "truncated");
418 return false;
419 }
420
421 private:
422 void staticAssertions() {
423 static_assert(sizeof(char16_t) == 2);
424 static_assert(sizeof(uint32_t) == 4);
425 }
426
427 JSContext* cx;
428 BufferIterator point;
429 };
430
431 } // namespace js
432
433 struct JSStructuredCloneReader {
434 public:
435 explicit JSStructuredCloneReader(SCInput& in, JS::StructuredCloneScope scope,
436 const JS::CloneDataPolicy& cloneDataPolicy,
437 const JSStructuredCloneCallbacks* cb,
438 void* cbClosure);
439
440 SCInput& input() { return in; }
441 bool read(MutableHandleValue vp, size_t nbytes);
442
443 private:
444 JSContext* context() { return in.context(); }
445
446 bool readHeader();
447 bool readTransferMap();
448
449 [[nodiscard]] bool readUint32(uint32_t* num);
450
451 enum ShouldAtomizeStrings : bool {
452 DontAtomizeStrings = false,
453 AtomizeStrings = true
454 };
455
456 template <typename CharT>
457 JSString* readStringImpl(uint32_t nchars, ShouldAtomizeStrings atomize);
458 JSString* readString(uint32_t data, ShouldAtomizeStrings atomize);
459
460 BigInt* readBigInt(uint32_t data);
461
462 [[nodiscard]] bool readTypedArray(uint32_t arrayType, uint64_t nelems,
463 MutableHandleValue vp, bool v1Read = false);
464
465 [[nodiscard]] bool readDataView(uint64_t byteLength, MutableHandleValue vp);
466
467 [[nodiscard]] bool readArrayBuffer(StructuredDataType type, uint32_t data,
468 MutableHandleValue vp);
469 [[nodiscard]] bool readV1ArrayBuffer(uint32_t arrayType, uint32_t nelems,
470 MutableHandleValue vp);
471
472 [[nodiscard]] bool readSharedArrayBuffer(StructuredDataType type,
473 MutableHandleValue vp);
474
475 [[nodiscard]] bool readSharedWasmMemory(uint32_t nbytes,
476 MutableHandleValue vp);
477
478 // A serialized SavedFrame contains primitive values in a header followed by
479 // an optional parent frame that is read recursively.
480 [[nodiscard]] JSObject* readSavedFrameHeader(uint32_t principalsTag);
481 [[nodiscard]] bool readSavedFrameFields(Handle<SavedFrame*> frameObj,
482 HandleValue parent, bool* state);
483
484 // A serialized Error contains primitive values in a header followed by
485 // 'cause', 'errors', and 'stack' fields that are read recursively.
486 [[nodiscard]] JSObject* readErrorHeader(uint32_t type);
487 [[nodiscard]] bool readErrorFields(Handle<ErrorObject*> errorObj,
488 HandleValue cause, bool* state);
489
490 [[nodiscard]] bool readMapField(Handle<MapObject*> mapObj, HandleValue key);
491
492 [[nodiscard]] bool readObjectField(HandleObject obj, HandleValue key);
493
494 [[nodiscard]] bool startRead(
495 MutableHandleValue vp,
496 ShouldAtomizeStrings atomizeStrings = DontAtomizeStrings);
497
498 SCInput& in;
499
500 // The widest scope that the caller will accept, where
501 // SameProcess is the widest (it can store anything it wants)
502 // and DifferentProcess is the narrowest (it cannot contain pointers and must
503 // be valid cross-process.)
504 //
505 // Although this can be initially set to other "unresolved" values (eg
506 // Unassigned), by the end of a successful readHeader() this will be resolved
507 // to SameProcess or DifferentProcess.
508 JS::StructuredCloneScope allowedScope;
509
510 const JS::CloneDataPolicy cloneDataPolicy;
511
512 // Stack of objects with properties remaining to be read.
513 RootedValueVector objs;
514
515 // Maintain a stack of state values for the `objs` stack. Since this is only
516 // needed for a very small subset of objects (those with a known set of
517 // object children), the state information is stored as a stack of
518 // <object, state> pairs where the object determines which element of the
519 // `objs` stack that it corresponds to. So when reading from the `objs` stack,
520 // the state will be retrieved only if the top object on `objState` matches
521 // the top object of `objs`.
522 //
523 // Currently, the only state needed is a boolean indicating whether the fields
524 // have been read yet.
525 Rooted<GCVector<std::pair<HeapPtr<JSObject*>, bool>, 8>> objState;
526
527 // Array of all objects read during this deserialization, for resolving
528 // backreferences.
529 //
530 // For backreferences to work correctly, objects must be added to this
531 // array in exactly the order expected by the version of the Writer that
532 // created the serialized data, even across years and format versions. This
533 // is usually no problem, since both algorithms do a single linear pass
534 // over the serialized data. There is one hitch; see readTypedArray.
535 //
536 // The values in this vector are objects, except it can temporarily have
537 // one `undefined` placeholder value (the readTypedArray hack).
538 RootedValueVector allObjs;
539
540 size_t numItemsRead;
541
542 // The user defined callbacks that will be used for cloning.
543 const JSStructuredCloneCallbacks* callbacks;
544
545 // Any value passed to JS_ReadStructuredClone.
546 void* closure;
547
548 // The heap to use for allocating common GC things. This starts out as the
549 // nursery (the default) but may switch to the tenured heap if nursery
550 // collection occurs, as nursery allocation is pointless after the
551 // deserialized root object is tenured.
552 //
553 // This is only used for the most common kind, e.g. plain objects, strings
554 // and a couple of others.
555 AutoSelectGCHeap gcHeap;
556
557 friend bool JS_ReadString(JSStructuredCloneReader* r,
558 JS::MutableHandleString str);
559 friend bool JS_ReadTypedArray(JSStructuredCloneReader* r,
560 MutableHandleValue vp);
561
562 // Provide a way to detect whether any of the clone data is never used. When
563 // "tail" data (currently, this is only stored data for Transferred
564 // ArrayBuffers in the DifferentProcess scope) is read, record the first and
565 // last positions. At the end of deserialization, make sure there's nothing
566 // between the end of the main data and the beginning of the tail, nor after
567 // the end of the tail.
568 mozilla::Maybe<SCInput::BufferIterator> tailStartPos;
569 mozilla::Maybe<SCInput::BufferIterator> tailEndPos;
570 };
571
572 struct JSStructuredCloneWriter {
573 public:
574 explicit JSStructuredCloneWriter(JSContext* cx,
575 JS::StructuredCloneScope scope,
576 const JS::CloneDataPolicy& cloneDataPolicy,
577 const JSStructuredCloneCallbacks* cb,
578 void* cbClosure, const Value& tVal)
579 : out(cx, scope),
580 callbacks(cb),
581 closure(cbClosure),
582 objs(cx),
583 counts(cx),
584 objectEntries(cx),
585 otherEntries(cx),
586 memory(cx),
587 transferable(cx, tVal),
588 transferableObjects(cx, TransferableObjectsList(cx)),
589 cloneDataPolicy(cloneDataPolicy) {
590 out.setCallbacks(cb, cbClosure,
591 OwnTransferablePolicy::OwnsTransferablesIfAny);
592 }
593
594 bool init() {
595 return parseTransferable() && writeHeader() && writeTransferMap();
596 }
597
598 bool write(HandleValue v);
599
600 SCOutput& output() { return out; }
601
602 void extractBuffer(JSStructuredCloneData* newData) {
603 out.extractBuffer(newData);
604 }
605
606 private:
607 JSStructuredCloneWriter() = delete;
608 JSStructuredCloneWriter(const JSStructuredCloneWriter&) = delete;
609
610 JSContext* context() { return out.context(); }
611
612 bool writeHeader();
613 bool writeTransferMap();
614
615 bool writeString(uint32_t tag, JSString* str);
616 bool writeBigInt(uint32_t tag, BigInt* bi);
617 bool writeArrayBuffer(HandleObject obj);
618 bool writeTypedArray(HandleObject obj);
619 bool writeDataView(HandleObject obj);
620 bool writeSharedArrayBuffer(HandleObject obj);
621 bool writeSharedWasmMemory(HandleObject obj);
622 bool startObject(HandleObject obj, bool* backref);
623 bool writePrimitive(HandleValue v);
624 bool startWrite(HandleValue v);
625 bool traverseObject(HandleObject obj, ESClass cls);
626 bool traverseMap(HandleObject obj);
627 bool traverseSet(HandleObject obj);
628 bool traverseSavedFrame(HandleObject obj);
629 bool traverseError(HandleObject obj);
630
631 template <typename... Args>
632 bool reportDataCloneError(uint32_t errorId, Args&&... aArgs);
633
634 bool parseTransferable();
635 bool transferOwnership();
636
637 inline void checkStack();
638
639 SCOutput out;
640
641 // The user defined callbacks that will be used to signal cloning, in some
642 // cases.
643 const JSStructuredCloneCallbacks* callbacks;
644
645 // Any value passed to the callbacks.
646 void* closure;
647
648 // Vector of objects with properties remaining to be written.
649 //
650 // NB: These can span multiple compartments, so the compartment must be
651 // entered before any manipulation is performed.
652 RootedValueVector objs;
653
654 // counts[i] is the number of entries of objs[i] remaining to be written.
655 // counts.length() == objs.length() and sum(counts) == entries.length().
656 Vector<size_t> counts;
657
658 // For JSObject: Property IDs as value
659 RootedIdVector objectEntries;
660
661 // For Map: Key followed by value
662 // For Set: Key
663 // For SavedFrame: parent SavedFrame
664 // For Error: cause, errors, stack
665 RootedValueVector otherEntries;
666
667 // The "memory" list described in the HTML5 internal structured cloning
668 // algorithm. memory is a superset of objs; items are never removed from
669 // Memory until a serialization operation is finished
670 using CloneMemory = GCHashMap<JSObject*, uint32_t,
671 StableCellHasher<JSObject*>, SystemAllocPolicy>;
672 Rooted<CloneMemory> memory;
673
674 // Set of transferable objects
675 RootedValue transferable;
676 using TransferableObjectsList = GCVector<JSObject*>;
677 Rooted<TransferableObjectsList> transferableObjects;
678
679 const JS::CloneDataPolicy cloneDataPolicy;
680
681 friend bool JS_WriteString(JSStructuredCloneWriter* w, HandleString str);
682 friend bool JS_WriteTypedArray(JSStructuredCloneWriter* w, HandleValue v);
683 friend bool JS_ObjectNotWritten(JSStructuredCloneWriter* w, HandleObject obj);
684 };
685
686 JS_PUBLIC_API uint64_t js::GetSCOffset(JSStructuredCloneWriter* writer) {
687 MOZ_ASSERT(writer);
688 return writer->output().count() * sizeof(uint64_t);
689 }
690
691 static_assert(SCTAG_END_OF_BUILTIN_TYPES <= JS_SCTAG_USER_MIN);
692 static_assert(JS_SCTAG_USER_MIN <= JS_SCTAG_USER_MAX);
693 static_assert(Scalar::Int8 == 0);
694
695 template <typename... Args>
696 static void ReportDataCloneError(JSContext* cx,
697 const JSStructuredCloneCallbacks* callbacks,
698 uint32_t errorId, void* closure,
699 Args&&... aArgs) {
700 unsigned errorNumber;
701 switch (errorId) {
702 case JS_SCERR_DUP_TRANSFERABLE:
703 errorNumber = JSMSG_SC_DUP_TRANSFERABLE;
704 break;
705
706 case JS_SCERR_TRANSFERABLE:
707 errorNumber = JSMSG_SC_NOT_TRANSFERABLE;
708 break;
709
710 case JS_SCERR_UNSUPPORTED_TYPE:
711 errorNumber = JSMSG_SC_UNSUPPORTED_TYPE;
712 break;
713
714 case JS_SCERR_SHMEM_TRANSFERABLE:
715 errorNumber = JSMSG_SC_SHMEM_TRANSFERABLE;
716 break;
717
718 case JS_SCERR_TRANSFERABLE_TWICE:
719 errorNumber = JSMSG_SC_TRANSFERABLE_TWICE;
720 break;
721
722 case JS_SCERR_TYPED_ARRAY_DETACHED:
723 errorNumber = JSMSG_TYPED_ARRAY_DETACHED;
724 break;
725
726 case JS_SCERR_WASM_NO_TRANSFER:
727 errorNumber = JSMSG_WASM_NO_TRANSFER;
728 break;
729
730 case JS_SCERR_NOT_CLONABLE:
731 errorNumber = JSMSG_SC_NOT_CLONABLE;
732 break;
733
734 case JS_SCERR_NOT_CLONABLE_WITH_COOP_COEP:
735 errorNumber = JSMSG_SC_NOT_CLONABLE_WITH_COOP_COEP;
736 break;
737
738 default:
739 MOZ_CRASH("Unkown errorId");
740 break;
741 }
742
743 if (callbacks && callbacks->reportError) {
744 MOZ_RELEASE_ASSERT(!cx->isExceptionPending());
745
746 JSErrorReport report;
747 report.errorNumber = errorNumber;
748 // Get js error message if it's possible and propagate it through callback.
749 if (JS_ExpandErrorArgumentsASCII(cx, GetErrorMessage, errorNumber, &report,
750 std::forward<Args>(aArgs)...) &&
751 report.message()) {
752 callbacks->reportError(cx, errorId, closure, report.message().c_str());
753 } else {
754 ReportOutOfMemory(cx);
755
756 callbacks->reportError(cx, errorId, closure, "");
757 }
758
759 return;
760 }
761
762 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNumber,
763 std::forward<Args>(aArgs)...);
764 }
765
766 bool WriteStructuredClone(JSContext* cx, HandleValue v,
767 JSStructuredCloneData* bufp,
768 JS::StructuredCloneScope scope,
769 const JS::CloneDataPolicy& cloneDataPolicy,
770 const JSStructuredCloneCallbacks* cb, void* cbClosure,
771 const Value& transferable) {
772 JSStructuredCloneWriter w(cx, scope, cloneDataPolicy, cb, cbClosure,
773 transferable);
774 if (!w.init()) {
775 return false;
776 }
777 if (!w.write(v)) {
778 return false;
779 }
780 w.extractBuffer(bufp);
781 return true;
782 }
783
784 bool ReadStructuredClone(JSContext* cx, const JSStructuredCloneData& data,
785 JS::StructuredCloneScope scope, MutableHandleValue vp,
786 const JS::CloneDataPolicy& cloneDataPolicy,
787 const JSStructuredCloneCallbacks* cb,
788 void* cbClosure) {
789 if (data.Size() % 8) {
790 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
791 JSMSG_SC_BAD_SERIALIZED_DATA, "misaligned");
792 return false;
793 }
794 SCInput in(cx, data);
795 JSStructuredCloneReader r(in, scope, cloneDataPolicy, cb, cbClosure);
796 return r.read(vp, data.Size());
797 }
798
799 static bool StructuredCloneHasTransferObjects(
800 const JSStructuredCloneData& data) {
801 if (data.Size() < sizeof(uint64_t)) {
802 return false;
803 }
804
805 uint64_t u;
806 BufferIterator<uint64_t, SystemAllocPolicy> iter(data);
807 MOZ_ALWAYS_TRUE(iter.readBytes(reinterpret_cast<char*>(&u), sizeof(u)));
808 uint32_t tag = uint32_t(u >> 32);
809 return (tag == SCTAG_TRANSFER_MAP_HEADER);
810 }
811
812 namespace js {
813
814 SCInput::SCInput(JSContext* cx, const JSStructuredCloneData& data)
815 : cx(cx), point(data) {
816 static_assert(JSStructuredCloneData::BufferList::kSegmentAlignment % 8 == 0,
817 "structured clone buffer reads should be aligned");
818 MOZ_ASSERT(data.Size() % 8 == 0);
819 }
820
821 bool SCInput::read(uint64_t* p) {
822 if (!point.canPeek()) {
823 *p = 0; // initialize to shut GCC up
824 return reportTruncated();
825 }
826 *p = NativeEndian::swapFromLittleEndian(point.peek());
827 MOZ_ALWAYS_TRUE(point.advance());
828 return true;
829 }
830
831 bool SCInput::readPair(uint32_t* tagp, uint32_t* datap) {
832 uint64_t u;
833 bool ok = read(&u);
834 if (ok) {
835 *tagp = uint32_t(u >> 32);
836 *datap = uint32_t(u);
837 }
838 return ok;
839 }
840
841 bool SCInput::get(uint64_t* p) {
842 if (!point.canPeek()) {
843 return reportTruncated();
844 }
845 *p = NativeEndian::swapFromLittleEndian(point.peek());
846 return true;
847 }
848
849 bool SCInput::getPair(uint32_t* tagp, uint32_t* datap) {
850 uint64_t u = 0;
851 if (!get(&u)) {
852 return false;
853 }
854
855 *tagp = uint32_t(u >> 32);
856 *datap = uint32_t(u);
857 return true;
858 }
859
860 void SCInput::getPair(uint64_t data, uint32_t* tagp, uint32_t* datap) {
861 uint64_t u = NativeEndian::swapFromLittleEndian(data);
862 *tagp = uint32_t(u >> 32);
863 *datap = uint32_t(u);
864 }
865
866 bool SCInput::readDouble(double* p) {
867 uint64_t u;
868 if (!read(&u)) {
869 return false;
870 }
871 *p = CanonicalizeNaN(mozilla::BitwiseCast<double>(u));
872 return true;
873 }
874
875 template <typename T>
876 static void swapFromLittleEndianInPlace(T* ptr, size_t nelems) {
877 if (nelems > 0) {
878 NativeEndian::swapFromLittleEndianInPlace(ptr, nelems);
879 }
880 }
881
882 template <>
883 void swapFromLittleEndianInPlace(uint8_t* ptr, size_t nelems) {}
884
885 // Data is packed into an integral number of uint64_t words. Compute the
886 // padding required to finish off the final word.
887 static size_t ComputePadding(size_t nelems, size_t elemSize) {
888 // We want total length mod 8, where total length is nelems * sizeof(T),
889 // but that might overflow. So reduce nelems to nelems mod 8, since we are
890 // going to be doing a mod 8 later anyway.
891 size_t leftoverLength = (nelems % sizeof(uint64_t)) * elemSize;
892 return (-leftoverLength) & (sizeof(uint64_t) - 1);
893 }
894
895 template <class T>
896 bool SCInput::readArray(T* p, size_t nelems) {
897 if (!nelems) {
898 return true;
899 }
900
901 static_assert(sizeof(uint64_t) % sizeof(T) == 0);
902
903 // Fail if nelems is so huge that computing the full size will overflow.
904 mozilla::CheckedInt<size_t> size =
905 mozilla::CheckedInt<size_t>(nelems) * sizeof(T);
906 if (!size.isValid()) {
907 return reportTruncated();
908 }
909
910 if (!point.readBytes(reinterpret_cast<char*>(p), size.value())) {
911 // To avoid any way in which uninitialized data could escape, zero the array
912 // if filling it failed.
913 std::uninitialized_fill_n(p, nelems, 0);
914 return reportTruncated();
915 }
916
917 swapFromLittleEndianInPlace(p, nelems);
918
919 point += ComputePadding(nelems, sizeof(T));
920
921 return true;
922 }
923
924 bool SCInput::readBytes(void* p, size_t nbytes) {
925 return readArray((uint8_t*)p, nbytes);
926 }
927
928 bool SCInput::readChars(Latin1Char* p, size_t nchars) {
929 static_assert(sizeof(Latin1Char) == sizeof(uint8_t),
930 "Latin1Char must fit in 1 byte");
931 return readBytes(p, nchars);
932 }
933
934 bool SCInput::readChars(char16_t* p, size_t nchars) {
935 MOZ_ASSERT(sizeof(char16_t) == sizeof(uint16_t));
936 return readArray((uint16_t*)p, nchars);
937 }
938
939 void SCInput::getPtr(uint64_t data, void** ptr) {
940 *ptr = reinterpret_cast<void*>(NativeEndian::swapFromLittleEndian(data));
941 }
942
943 bool SCInput::readPtr(void** p) {
944 uint64_t u;
945 if (!read(&u)) {
946 return false;
947 }
948 *p = reinterpret_cast<void*>(u);
949 return true;
950 }
951
952 SCOutput::SCOutput(JSContext* cx, JS::StructuredCloneScope scope)
953 : cx(cx), buf(scope) {}
954
955 bool SCOutput::write(uint64_t u) {
956 uint64_t v = NativeEndian::swapToLittleEndian(u);
957 if (!buf.AppendBytes(reinterpret_cast<char*>(&v), sizeof(u))) {
958 ReportOutOfMemory(context());
959 return false;
960 }
961 return true;
962 }
963
964 bool SCOutput::writePair(uint32_t tag, uint32_t data) {
965 // As it happens, the tag word appears after the data word in the output.
966 // This is because exponents occupy the last 2 bytes of doubles on the
967 // little-endian platforms we care most about.
968 //
969 // For example, TrueValue() is written using writePair(SCTAG_BOOLEAN, 1).
970 // PairToUInt64 produces the number 0xFFFF000200000001.
971 // That is written out as the bytes 01 00 00 00 02 00 FF FF.
972 return write(PairToUInt64(tag, data));
973 }
974
975 static inline double ReinterpretPairAsDouble(uint32_t tag, uint32_t data) {
976 return BitwiseCast<double>(PairToUInt64(tag, data));
977 }
978
979 bool SCOutput::writeDouble(double d) {
980 return write(BitwiseCast<uint64_t>(CanonicalizeNaN(d)));
981 }
982
983 template <class T>
984 bool SCOutput::writeArray(const T* p, size_t nelems) {
985 static_assert(8 % sizeof(T) == 0);
986 static_assert(sizeof(uint64_t) % sizeof(T) == 0);
987
988 if (nelems == 0) {
989 return true;
990 }
991
992 for (size_t i = 0; i < nelems; i++) {
993 T value = NativeEndian::swapToLittleEndian(p[i]);
994 if (!buf.AppendBytes(reinterpret_cast<char*>(&value), sizeof(value))) {
995 ReportOutOfMemory(context());
996 return false;
997 }
998 }
999
1000 // Zero-pad to 8 bytes boundary.
1001 size_t padbytes = ComputePadding(nelems, sizeof(T));
1002 char zeroes[sizeof(uint64_t)] = {0};
1003 if (!buf.AppendBytes(zeroes, padbytes)) {
1004 ReportOutOfMemory(context());
1005 return false;
1006 }
1007
1008 return true;
1009 }
1010
1011 template <>
1012 bool SCOutput::writeArray<uint8_t>(const uint8_t* p, size_t nelems) {
1013 if (nelems == 0) {
1014 return true;
1015 }
1016
1017 if (!buf.AppendBytes(reinterpret_cast<const char*>(p), nelems)) {
1018 ReportOutOfMemory(context());
1019 return false;
1020 }
1021
1022 // zero-pad to 8 bytes boundary
1023 size_t padbytes = ComputePadding(nelems, 1);
1024 char zeroes[sizeof(uint64_t)] = {0};
1025 if (!buf.AppendBytes(zeroes, padbytes)) {
1026 ReportOutOfMemory(context());
1027 return false;
1028 }
1029
1030 return true;
1031 }
1032
1033 bool SCOutput::writeBytes(const void* p, size_t nbytes) {
1034 return writeArray((const uint8_t*)p, nbytes);
1035 }
1036
1037 bool SCOutput::writeChars(const char16_t* p, size_t nchars) {
1038 static_assert(sizeof(char16_t) == sizeof(uint16_t),
1039 "required so that treating char16_t[] memory as uint16_t[] "
1040 "memory is permissible");
1041 return writeArray((const uint16_t*)p, nchars);
1042 }
1043
1044 bool SCOutput::writeChars(const Latin1Char* p, size_t nchars) {
1045 static_assert(sizeof(Latin1Char) == sizeof(uint8_t),
1046 "Latin1Char must fit in 1 byte");
1047 return writeBytes(p, nchars);
1048 }
1049
1050 } // namespace js
1051
1052 JSStructuredCloneData::~JSStructuredCloneData() { discardTransferables(); }
1053
1054 // If the buffer contains Transferables, free them. Note that custom
1055 // Transferables will use the JSStructuredCloneCallbacks::freeTransfer() to
1056 // delete their transferables.
1057 void JSStructuredCloneData::discardTransferables() {
1058 if (!Size()) {
1059 return;
1060 }
1061
1062 if (ownTransferables_ != OwnTransferablePolicy::OwnsTransferablesIfAny) {
1063 return;
1064 }
1065
1066 // DifferentProcess clones cannot contain pointers, so nothing needs to be
1067 // released.
1068 if (scope() == JS::StructuredCloneScope::DifferentProcess) {
1069 return;
1070 }
1071
1072 FreeTransferStructuredCloneOp freeTransfer = nullptr;
1073 if (callbacks_) {
1074 freeTransfer = callbacks_->freeTransfer;
1075 }
1076
1077 auto point = BufferIterator<uint64_t, SystemAllocPolicy>(*this);
1078 if (point.done()) {
1079 return; // Empty buffer
1080 }
1081
1082 uint32_t tag, data;
1083 MOZ_RELEASE_ASSERT(point.canPeek());
1084 SCInput::getPair(point.peek(), &tag, &data);
1085 MOZ_ALWAYS_TRUE(point.advance());
1086
1087 if (tag == SCTAG_HEADER) {
1088 if (point.done()) {
1089 return;
1090 }
1091
1092 MOZ_RELEASE_ASSERT(point.canPeek());
1093 SCInput::getPair(point.peek(), &tag, &data);
1094 MOZ_ALWAYS_TRUE(point.advance());
1095 }
1096
1097 if (tag != SCTAG_TRANSFER_MAP_HEADER) {
1098 return;
1099 }
1100
1101 if (TransferableMapHeader(data) == SCTAG_TM_TRANSFERRED) {
1102 return;
1103 }
1104
1105 // freeTransfer should not GC
1106 JS::AutoSuppressGCAnalysis nogc;
1107
1108 if (point.done()) {
1109 return;
1110 }
1111
1112 MOZ_RELEASE_ASSERT(point.canPeek());
1113 uint64_t numTransferables = NativeEndian::swapFromLittleEndian(point.peek());
1114 MOZ_ALWAYS_TRUE(point.advance());
1115 while (numTransferables--) {
1116 if (!point.canPeek()) {
1117 return;
1118 }
1119
1120 uint32_t ownership;
1121 SCInput::getPair(point.peek(), &tag, &ownership);
1122 MOZ_ALWAYS_TRUE(point.advance());
1123 MOZ_ASSERT(tag >= SCTAG_TRANSFER_MAP_PENDING_ENTRY);
1124 if (!point.canPeek()) {
1125 return;
1126 }
1127
1128 void* content;
1129 SCInput::getPtr(point.peek(), &content);
1130 MOZ_ALWAYS_TRUE(point.advance());
1131 if (!point.canPeek()) {
1132 return;
1133 }
1134
1135 uint64_t extraData = NativeEndian::swapFromLittleEndian(point.peek());
1136 MOZ_ALWAYS_TRUE(point.advance());
1137
1138 if (ownership < JS::SCTAG_TMO_FIRST_OWNED) {
1139 continue;
1140 }
1141
1142 if (ownership == JS::SCTAG_TMO_ALLOC_DATA) {
1143 js_free(content);
1144 } else if (ownership == JS::SCTAG_TMO_MAPPED_DATA) {
1145 JS::ReleaseMappedArrayBufferContents(content, extraData);
1146 } else if (freeTransfer) {
1147 freeTransfer(tag, JS::TransferableOwnership(ownership), content,
1148 extraData, closure_);
1149 } else {
1150 MOZ_ASSERT(false, "unknown ownership");
1151 }
1152 }
1153 }
1154
1155 static_assert(JSString::MAX_LENGTH < UINT32_MAX);
1156
1157 bool JSStructuredCloneWriter::parseTransferable() {
1158 // NOTE: The transferables set is tested for non-emptiness at various
1159 // junctures in structured cloning, so this set must be initialized
1160 // by this method in all non-error cases.
1161 MOZ_ASSERT(transferableObjects.empty(),
1162 "parseTransferable called with stale data");
1163
1164 if (transferable.isNull() || transferable.isUndefined()) {
1165 return true;
1166 }
1167
1168 if (!transferable.isObject()) {
1169 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
1170 }
1171
1172 JSContext* cx = context();
1173 RootedObject array(cx, &transferable.toObject());
1174 bool isArray;
1175 if (!JS::IsArrayObject(cx, array, &isArray)) {
1176 return false;
1177 }
1178 if (!isArray) {
1179 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
1180 }
1181
1182 uint32_t length;
1183 if (!JS::GetArrayLength(cx, array, &length)) {
1184 return false;
1185 }
1186
1187 // Initialize the set for the provided array's length.
1188 if (!transferableObjects.reserve(length)) {
1189 return false;
1190 }
1191
1192 if (length == 0) {
1193 return true;
1194 }
1195
1196 RootedValue v(context());
1197 RootedObject tObj(context());
1198
1199 Rooted<GCHashSet<js::HeapPtr<JSObject*>,
1200 js::StableCellHasher<js::HeapPtr<JSObject*>>,
1201 SystemAllocPolicy>>
1202 seen(context());
1203
1204 for (uint32_t i = 0; i < length; ++i) {
1205 if (!CheckForInterrupt(cx)) {
1206 return false;
1207 }
1208
1209 if (!JS_GetElement(cx, array, i, &v)) {
1210 return false;
1211 }
1212
1213 if (!v.isObject()) {
1214 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
1215 }
1216 tObj = &v.toObject();
1217
1218 RootedObject unwrappedObj(cx, CheckedUnwrapStatic(tObj));
1219 if (!unwrappedObj) {
1220 ReportAccessDenied(cx);
1221 return false;
1222 }
1223
1224 // Shared memory cannot be transferred because it is not possible (nor
1225 // desirable) to detach the memory in agents that already hold a
1226 // reference to it.
1227
1228 if (unwrappedObj->is<SharedArrayBufferObject>()) {
1229 return reportDataCloneError(JS_SCERR_SHMEM_TRANSFERABLE);
1230 }
1231
1232 else if (unwrappedObj->is<WasmMemoryObject>()) {
1233 if (unwrappedObj->as<WasmMemoryObject>().isShared()) {
1234 return reportDataCloneError(JS_SCERR_SHMEM_TRANSFERABLE);
1235 }
1236 }
1237
1238 // External array buffers may be able to be transferred in the future,
1239 // but that is not currently implemented.
1240
1241 else if (unwrappedObj->is<ArrayBufferObject>()) {
1242 if (unwrappedObj->as<ArrayBufferObject>().isExternal()) {
1243 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
1244 }
1245 }
1246
1247 else {
1248 if (!out.buf.callbacks_ || !out.buf.callbacks_->canTransfer) {
1249 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
1250 }
1251
1252 JSAutoRealm ar(cx, unwrappedObj);
1253 bool sameProcessScopeRequired = false;
1254 if (!out.buf.callbacks_->canTransfer(
1255 cx, unwrappedObj, &sameProcessScopeRequired, out.buf.closure_)) {
1256 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
1257 }
1258
1259 if (sameProcessScopeRequired) {
1260 output().sameProcessScopeRequired();
1261 }
1262 }
1263
1264 // No duplicates allowed. Normally the transferable list is very short, but
1265 // some users are passing >10k. Switch to a hash-based lookup when the
1266 // linear list starts getting long.
1267 constexpr uint32_t MAX_LINEAR = 10;
1268
1269 // Switch from a linear scan to a set lookup, initializing the set with all
1270 // objects seen so far.
1271 if (i == MAX_LINEAR) {
1272 for (JSObject* obj : transferableObjects) {
1273 if (!seen.putNew(obj)) {
1274 seen.clear(); // Fall back to linear scan on OOM.
1275 break;
1276 }
1277 }
1278 }
1279
1280 if (seen.empty()) {
1281 if (std::find(transferableObjects.begin(), transferableObjects.end(),
1282 tObj) != transferableObjects.end()) {
1283 return reportDataCloneError(JS_SCERR_DUP_TRANSFERABLE);
1284 }
1285 } else {
1286 MOZ_ASSERT(seen.count() == i); // All objs are distinct up to this point.
1287 auto p = seen.lookupForAdd(tObj);
1288 if (p) {
1289 return reportDataCloneError(JS_SCERR_DUP_TRANSFERABLE);
1290 }
1291 if (!seen.add(p, tObj)) {
1292 seen.clear(); // Fall back to linear scan on OOM.
1293 }
1294 }
1295
1296 if (!transferableObjects.append(tObj)) {
1297 return false;
1298 }
1299 }
1300
1301 return true;
1302 }
1303
1304 template <typename... Args>
1305 bool JSStructuredCloneWriter::reportDataCloneError(uint32_t errorId,
1306 Args&&... aArgs) {
1307 ReportDataCloneError(context(), out.buf.callbacks_, errorId, out.buf.closure_,
1308 std::forward<Args>(aArgs)...);
1309 return false;
1310 }
1311
1312 bool JSStructuredCloneWriter::writeString(uint32_t tag, JSString* str) {
1313 JSLinearString* linear = str->ensureLinear(context());
1314 if (!linear) {
1315 return false;
1316 }
1317
1318 #if FUZZING_JS_FUZZILLI
1319 if (js::SupportDifferentialTesting()) {
1320 // TODO we could always output a twoByteChar string
1321 return true;
1322 }
1323 #endif
1324
1325 static_assert(JSString::MAX_LENGTH < (1 << 30),
1326 "String length must fit in 30 bits");
1327
1328 // Try to share the underlying StringBuffer without copying the contents.
1329 bool useBuffer = linear->hasStringBuffer() &&
1330 output().scope() == JS::StructuredCloneScope::SameProcess;
1331
1332 uint32_t length = linear->length();
1333 bool isLatin1 = linear->hasLatin1Chars();
1334 uint32_t lengthAndBits =
1335 length | (uint32_t(isLatin1) << 31) | (uint32_t(useBuffer) << 30);
1336 if (!out.writePair(tag, lengthAndBits)) {
1337 return false;
1338 }
1339
1340 if (useBuffer) {
1341 mozilla::StringBuffer* buffer = linear->stringBuffer();
1342 if (!out.buf.stringBufferRefsHeld_.emplaceBack(buffer)) {
1343 ReportOutOfMemory(context());
1344 return false;
1345 }
1346 uintptr_t p = reinterpret_cast<uintptr_t>(buffer);
1347 return out.writeBytes(&p, sizeof(p));
1348 }
1349
1350 JS::AutoCheckCannotGC nogc;
1351 return linear->hasLatin1Chars()
1352 ? out.writeChars(linear->latin1Chars(nogc), length)
1353 : out.writeChars(linear->twoByteChars(nogc), length);
1354 }
1355
1356 bool JSStructuredCloneWriter::writeBigInt(uint32_t tag, BigInt* bi) {
1357 bool signBit = bi->isNegative();
1358 size_t length = bi->digitLength();
1359 // The length must fit in 31 bits to leave room for a sign bit.
1360 if (length > size_t(INT32_MAX)) {
1361 return false;
1362 }
1363 uint32_t lengthAndSign = length | (static_cast<uint32_t>(signBit) << 31);
1364
1365 if (!out.writePair(tag, lengthAndSign)) {
1366 return false;
1367 }
1368 return out.writeArray(bi->digits().data(), length);
1369 }
1370
1371 inline void JSStructuredCloneWriter::checkStack() {
1372 #ifdef DEBUG
1373 // To avoid making serialization O(n^2), limit stack-checking at 10.
1374 const size_t MAX = 10;
1375
1376 size_t limit = std::min(counts.length(), MAX);
1377 MOZ_ASSERT(objs.length() == counts.length());
1378 size_t total = 0;
1379 for (size_t i = 0; i < limit; i++) {
1380 MOZ_ASSERT(total + counts[i] >= total);
1381 total += counts[i];
1382 }
1383 if (counts.length() <= MAX) {
1384 MOZ_ASSERT(total == objectEntries.length() + otherEntries.length());
1385 } else {
1386 MOZ_ASSERT(total <= objectEntries.length() + otherEntries.length());
1387 }
1388
1389 size_t j = objs.length();
1390 for (size_t i = 0; i < limit; i++) {
1391 --j;
1392 MOZ_ASSERT(memory.has(&objs[j].toObject()));
1393 }
1394 #endif
1395 }
1396
1397 /*
1398 * Write out a typed array. Note that post-v1 structured clone buffers do not
1399 * perform endianness conversion on stored data, so multibyte typed arrays
1400 * cannot be deserialized into a different endianness machine. Endianness
1401 * conversion would prevent sharing ArrayBuffers: if you have Int8Array and
1402 * Int16Array views of the same ArrayBuffer, should the data bytes be
1403 * byte-swapped when writing or not? The Int8Array requires them to not be
1404 * swapped; the Int16Array requires that they are.
1405 */
1406 bool JSStructuredCloneWriter::writeTypedArray(HandleObject obj) {
1407 Rooted<TypedArrayObject*> tarr(context(),
1408 obj->maybeUnwrapAs<TypedArrayObject>());
1409 JSAutoRealm ar(context(), tarr);
1410
1411 #ifdef FUZZING_JS_FUZZILLI
1412 if (js::SupportDifferentialTesting() && !tarr->hasBuffer()) {
1413 // fake oom because differential testing will fail
1414 fprintf(stderr, "[unhandlable oom]");
1415 _exit(-1);
1416 return false;
1417 }
1418 #endif
1419
1420 if (!TypedArrayObject::ensureHasBuffer(context(), tarr)) {
1421 return false;
1422 }
1423
1424 if (!out.writePair(SCTAG_TYPED_ARRAY_OBJECT, uint32_t(tarr->type()))) {
1425 return false;
1426 }
1427
1428 mozilla::Maybe<size_t> nelems = tarr->length();
1429 if (!nelems) {
1430 return reportDataCloneError(JS_SCERR_TYPED_ARRAY_DETACHED);
1431 }
1432
1433 // Auto-length TypedArrays are tagged by storing `-1` for the length. We still
1434 // need to query the length to check for detached or out-of-bounds lengths.
1435 bool isAutoLength = tarr->is<ResizableTypedArrayObject>() &&
1436 tarr->as<ResizableTypedArrayObject>().isAutoLength();
1437 uint64_t length = isAutoLength ? uint64_t(-1) : uint64_t(*nelems);
1438 if (!out.write(length)) {
1439 return false;
1440 }
1441
1442 // Write out the ArrayBuffer tag and contents
1443 RootedValue val(context(), tarr->bufferValue());
1444 if (!startWrite(val)) {
1445 return false;
1446 }
1447
1448 uint64_t byteOffset = tarr->byteOffset().valueOr(0);
1449 return out.write(byteOffset);
1450 }
1451
1452 bool JSStructuredCloneWriter::writeDataView(HandleObject obj) {
1453 Rooted<DataViewObject*> view(context(), obj->maybeUnwrapAs<DataViewObject>());
1454 JSAutoRealm ar(context(), view);
1455
1456 if (!out.writePair(SCTAG_DATA_VIEW_OBJECT, 0)) {
1457 return false;
1458 }
1459
1460 mozilla::Maybe<size_t> byteLength = view->byteLength();
1461 if (!byteLength) {
1462 return reportDataCloneError(JS_SCERR_TYPED_ARRAY_DETACHED);
1463 }
1464
1465 // Auto-length DataViews are tagged by storing `-1` for the length. We still
1466 // need to query the length to check for detached or out-of-bounds lengths.
1467 bool isAutoLength = view->is<ResizableDataViewObject>() &&
1468 view->as<ResizableDataViewObject>().isAutoLength();
1469 uint64_t length = isAutoLength ? uint64_t(-1) : uint64_t(*byteLength);
1470 if (!out.write(length)) {
1471 return false;
1472 }
1473
1474 // Write out the ArrayBuffer tag and contents
1475 RootedValue val(context(), view->bufferValue());
1476 if (!startWrite(val)) {
1477 return false;
1478 }
1479
1480 uint64_t byteOffset = view->byteOffset().valueOr(0);
1481 return out.write(byteOffset);
1482 }
1483
1484 bool JSStructuredCloneWriter::writeArrayBuffer(HandleObject obj) {
1485 Rooted<ArrayBufferObject*> buffer(context(),
1486 obj->maybeUnwrapAs<ArrayBufferObject>());
1487 JSAutoRealm ar(context(), buffer);
1488
1489 StructuredDataType type = !buffer->isResizable()
1490 ? SCTAG_ARRAY_BUFFER_OBJECT
1491 : SCTAG_RESIZABLE_ARRAY_BUFFER_OBJECT;
1492
1493 if (!out.writePair(type, 0)) {
1494 return false;
1495 }
1496
1497 uint64_t byteLength = buffer->byteLength();
1498 if (!out.write(byteLength)) {
1499 return false;
1500 }
1501
1502 if (buffer->isResizable()) {
1503 uint64_t maxByteLength =
1504 buffer->as<ResizableArrayBufferObject>().maxByteLength();
1505 if (!out.write(maxByteLength)) {
1506 return false;
1507 }
1508 }
1509
1510 return out.writeBytes(buffer->dataPointer(), byteLength);
1511 }
1512
1513 bool JSStructuredCloneWriter::writeSharedArrayBuffer(HandleObject obj) {
1514 MOZ_ASSERT(obj->canUnwrapAs<SharedArrayBufferObject>());
1515
1516 if (!cloneDataPolicy.areSharedMemoryObjectsAllowed()) {
1517 auto error = context()->realm()->creationOptions().getCoopAndCoepEnabled()
1518 ? JS_SCERR_NOT_CLONABLE_WITH_COOP_COEP
1519 : JS_SCERR_NOT_CLONABLE;
1520 reportDataCloneError(error, "SharedArrayBuffer");
1521 return false;
1522 }
1523
1524 output().sameProcessScopeRequired();
1525
1526 // We must not transmit SAB pointers (including for WebAssembly.Memory)
1527 // cross-process. The cloneDataPolicy should have guarded against this;
1528 // since it did not then throw, with a very explicit message.
1529
1530 if (output().scope() > JS::StructuredCloneScope::SameProcess) {
1531 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
1532 JSMSG_SC_SHMEM_POLICY);
1533 return false;
1534 }
1535
1536 Rooted<SharedArrayBufferObject*> sharedArrayBuffer(
1537 context(), obj->maybeUnwrapAs<SharedArrayBufferObject>());
1538 SharedArrayRawBuffer* rawbuf = sharedArrayBuffer->rawBufferObject();
1539
1540 if (!out.buf.refsHeld_.acquire(context(), rawbuf)) {
1541 return false;
1542 }
1543
1544 // We must serialize the length so that the buffer object arrives in the
1545 // receiver with the same length, and not with the length read from the
1546 // rawbuf - that length can be different, and it can change at any time.
1547
1548 StructuredDataType type = !sharedArrayBuffer->isGrowable()
1549 ? SCTAG_SHARED_ARRAY_BUFFER_OBJECT
1550 : SCTAG_GROWABLE_SHARED_ARRAY_BUFFER_OBJECT;
1551
1552 intptr_t p = reinterpret_cast<intptr_t>(rawbuf);
1553 uint64_t byteLength = sharedArrayBuffer->byteLengthOrMaxByteLength();
1554 if (!(out.writePair(type, /* unused data word */ 0) &&
1555 out.writeBytes(&byteLength, sizeof(byteLength)) &&
1556 out.writeBytes(&p, sizeof(p)))) {
1557 return false;
1558 }
1559
1560 if (callbacks && callbacks->sabCloned &&
1561 !callbacks->sabCloned(context(), /*receiving=*/false, closure)) {
1562 return false;
1563 }
1564
1565 return true;
1566 }
1567
1568 bool JSStructuredCloneWriter::writeSharedWasmMemory(HandleObject obj) {
1569 MOZ_ASSERT(obj->canUnwrapAs<WasmMemoryObject>());
1570
1571 // Check the policy here so that we can report a sane error.
1572 if (!cloneDataPolicy.areSharedMemoryObjectsAllowed()) {
1573 auto error = context()->realm()->creationOptions().getCoopAndCoepEnabled()
1574 ? JS_SCERR_NOT_CLONABLE_WITH_COOP_COEP
1575 : JS_SCERR_NOT_CLONABLE;
1576 reportDataCloneError(error, "WebAssembly.Memory");
1577 return false;
1578 }
1579
1580 // If this changes, might need to change what we write.
1581 MOZ_ASSERT(WasmMemoryObject::RESERVED_SLOTS == 3);
1582
1583 Rooted<WasmMemoryObject*> memoryObj(context(),
1584 &obj->unwrapAs<WasmMemoryObject>());
1585 JSAutoRealm ar(context(), memoryObj);
1586 Rooted<SharedArrayBufferObject*> sab(
1587 context(), &memoryObj->buffer().as<SharedArrayBufferObject>());
1588
1589 return out.writePair(SCTAG_SHARED_WASM_MEMORY_OBJECT, 0) &&
1590 out.writePair(SCTAG_BOOLEAN, memoryObj->isHuge()) &&
1591 writeSharedArrayBuffer(sab);
1592 }
1593
1594 bool JSStructuredCloneWriter::startObject(HandleObject obj, bool* backref) {
1595 // Handle cycles in the object graph.
1596 CloneMemory::AddPtr p = memory.lookupForAdd(obj);
1597 if ((*backref = p.found())) {
1598 return out.writePair(SCTAG_BACK_REFERENCE_OBJECT, p->value());
1599 }
1600 if (!memory.add(p, obj, memory.count())) {
1601 ReportOutOfMemory(context());
1602 return false;
1603 }
1604
1605 if (memory.count() == UINT32_MAX) {
1606 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
1607 JSMSG_NEED_DIET, "object graph to serialize");
1608 return false;
1609 }
1610
1611 return true;
1612 }
1613
1614 static bool TryAppendNativeProperties(JSContext* cx, HandleObject obj,
1615 MutableHandleIdVector entries,
1616 size_t* properties, bool* optimized) {
1617 *optimized = false;
1618
1619 if (!obj->is<NativeObject>()) {
1620 return true;
1621 }
1622
1623 Handle<NativeObject*> nobj = obj.as<NativeObject>();
1624 if (nobj->isIndexed() || nobj->is<TypedArrayObject>() ||
1625 nobj->getClass()->getNewEnumerate() || nobj->getClass()->getEnumerate()) {
1626 return true;
1627 }
1628
1629 *optimized = true;
1630
1631 size_t count = 0;
1632 // We iterate from the last to the first property, so the property names
1633 // are already in reverse order.
1634 for (ShapePropertyIter<NoGC> iter(nobj->shape()); !iter.done(); iter++) {
1635 jsid id = iter->key();
1636
1637 // Ignore symbols and non-enumerable properties.
1638 if (!iter->enumerable() || id.isSymbol()) {
1639 continue;
1640 }
1641
1642 MOZ_ASSERT(id.isString());
1643 if (!entries.append(id)) {
1644 return false;
1645 }
1646
1647 count++;
1648 }
1649
1650 // Add dense element ids in reverse order.
1651 for (uint32_t i = nobj->getDenseInitializedLength(); i > 0; --i) {
1652 if (nobj->getDenseElement(i - 1).isMagic(JS_ELEMENTS_HOLE)) {
1653 continue;
1654 }
1655
1656 if (!entries.append(PropertyKey::Int(i - 1))) {
1657 return false;
1658 }
1659
1660 count++;
1661 }
1662
1663 *properties = count;
1664 return true;
1665 }
1666
1667 // Objects are written as a "preorder" traversal of the object graph: object
1668 // "headers" (the class tag and any data needed for initial construction) are
1669 // visited first, then the children are recursed through (where children are
1670 // properties, Set or Map entries, etc.). So for example
1671 //
1672 // obj1 = { key1: { key1.1: val1.1, key1.2: val1.2 }, key2: {} }
1673 //
1674 // would be stored as:
1675 //
1676 // <Object tag for obj1>
1677 // <key1 data>
1678 // <Object tag for key1's value>
1679 // <key1.1 data>
1680 // <val1.1 data>
1681 // <key1.2 data>
1682 // <val1.2 data>
1683 // <end-of-children marker for key1's value>
1684 // <key2 data>
1685 // <Object tag for key2's value>
1686 // <end-of-children marker for key2's value>
1687 // <end-of-children marker for obj1>
1688 //
1689 // This nests nicely (ie, an entire recursive value starts with its tag and
1690 // ends with its end-of-children marker) and so it can be presented indented.
1691 // But see traverseMap below for how this looks different for Maps.
1692 bool JSStructuredCloneWriter::traverseObject(HandleObject obj, ESClass cls) {
1693 size_t count;
1694 bool optimized = false;
1695 if (!js::SupportDifferentialTesting()) {
1696 if (!TryAppendNativeProperties(context(), obj, &objectEntries, &count,
1697 &optimized)) {
1698 return false;
1699 }
1700 }
1701
1702 if (!optimized) {
1703 // Get enumerable property ids and put them in reverse order so that they
1704 // will come off the stack in forward order.
1705 RootedIdVector properties(context());
1706 if (!GetPropertyKeys(context(), obj, JSITER_OWNONLY, &properties)) {
1707 return false;
1708 }
1709
1710 for (size_t i = properties.length(); i > 0; --i) {
1711 jsid id = properties[i - 1];
1712
1713 MOZ_ASSERT(id.isString() || id.isInt());
1714 if (!objectEntries.append(id)) {
1715 return false;
1716 }
1717 }
1718
1719 count = properties.length();
1720 }
1721
1722 // Push obj and count to the stack.
1723 if (!objs.append(ObjectValue(*obj)) || !counts.append(count)) {
1724 return false;
1725 }
1726
1727 checkStack();
1728
1729 #if DEBUG
1730 ESClass cls2;
1731 if (!GetBuiltinClass(context(), obj, &cls2)) {
1732 return false;
1733 }
1734 MOZ_ASSERT(cls2 == cls);
1735 #endif
1736
1737 // Write the header for obj.
1738 if (cls == ESClass::Array) {
1739 uint32_t length = 0;
1740 if (!JS::GetArrayLength(context(), obj, &length)) {
1741 return false;
1742 }
1743
1744 return out.writePair(SCTAG_ARRAY_OBJECT,
1745 NativeEndian::swapToLittleEndian(length));
1746 }
1747
1748 return out.writePair(SCTAG_OBJECT_OBJECT, 0);
1749 }
1750
1751 // Use the same basic setup as for traverseObject, but now keys can themselves
1752 // be complex objects. Keys and values are visited first via startWrite(), then
1753 // the key's children (if any) are handled, then the value's children.
1754 //
1755 // m = new Map();
1756 // m.set(key1 = ..., value1 = ...)
1757 //
1758 // where key1 and value2 are both objects would be stored as
1759 //
1760 // <Map tag>
1761 // <key1 class tag>
1762 // <value1 class tag>
1763 // ...key1 fields...
1764 // <end-of-children marker for key1>
1765 // ...value1 fields...
1766 // <end-of-children marker for value1>
1767 // <end-of-children marker for Map>
1768 //
1769 // Notice how the end-of-children marker for key1 is sandwiched between the
1770 // value1 beginning and end.
1771 bool JSStructuredCloneWriter::traverseMap(HandleObject obj) {
1772 Rooted<GCVector<Value>> newEntries(context(), GCVector<Value>(context()));
1773 {
1774 // If there is no wrapper, the compartment munging is a no-op.
1775 Rooted<MapObject*> unwrapped(context(), obj->maybeUnwrapAs<MapObject>());
1776 MOZ_ASSERT(unwrapped);
1777 JSAutoRealm ar(context(), unwrapped);
1778 if (!unwrapped->getKeysAndValuesInterleaved(&newEntries)) {
1779 return false;
1780 }
1781 }
1782 if (!context()->compartment()->wrap(context(), &newEntries)) {
1783 return false;
1784 }
1785
1786 for (size_t i = newEntries.length(); i > 0; --i) {
1787 if (!otherEntries.append(newEntries[i - 1])) {
1788 return false;
1789 }
1790 }
1791
1792 // Push obj and count to the stack.
1793 if (!objs.append(ObjectValue(*obj)) || !counts.append(newEntries.length())) {
1794 return false;
1795 }
1796
1797 checkStack();
1798
1799 // Write the header for obj.
1800 return out.writePair(SCTAG_MAP_OBJECT, 0);
1801 }
1802
1803 // Similar to traverseMap, only there is a single value instead of a key and
1804 // value, and thus no interleaving is possible: a value will be fully emitted
1805 // before the next value is begun.
1806 bool JSStructuredCloneWriter::traverseSet(HandleObject obj) {
1807 Rooted<GCVector<Value>> keys(context(), GCVector<Value>(context()));
1808 {
1809 // If there is no wrapper, the compartment munging is a no-op.
1810 Rooted<SetObject*> unwrapped(context(), obj->maybeUnwrapAs<SetObject>());
1811 MOZ_ASSERT(unwrapped);
1812 JSAutoRealm ar(context(), unwrapped);
1813 if (!unwrapped->keys(&keys)) {
1814 return false;
1815 }
1816 }
1817 if (!context()->compartment()->wrap(context(), &keys)) {
1818 return false;
1819 }
1820
1821 for (size_t i = keys.length(); i > 0; --i) {
1822 if (!otherEntries.append(keys[i - 1])) {
1823 return false;
1824 }
1825 }
1826
1827 // Push obj and count to the stack.
1828 if (!objs.append(ObjectValue(*obj)) || !counts.append(keys.length())) {
1829 return false;
1830 }
1831
1832 checkStack();
1833
1834 // Write the header for obj.
1835 return out.writePair(SCTAG_SET_OBJECT, 0);
1836 }
1837
1838 bool JSStructuredCloneWriter::traverseSavedFrame(HandleObject obj) {
1839 Rooted<SavedFrame*> savedFrame(context(), obj->maybeUnwrapAs<SavedFrame>());
1840 MOZ_ASSERT(savedFrame);
1841
1842 RootedObject parent(context(), savedFrame->getParent());
1843 if (!context()->compartment()->wrap(context(), &parent)) {
1844 return false;
1845 }
1846
1847 if (!objs.append(ObjectValue(*obj)) ||
1848 !otherEntries.append(parent ? ObjectValue(*parent) : NullValue()) ||
1849 !counts.append(1)) {
1850 return false;
1851 }
1852
1853 checkStack();
1854
1855 // Write the SavedFrame tag and the SavedFrame's principals.
1856
1857 if (savedFrame->getPrincipals() ==
1858 &ReconstructedSavedFramePrincipals::IsSystem) {
1859 if (!out.writePair(SCTAG_SAVED_FRAME_OBJECT,
1860 SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_SYSTEM)) {
1861 return false;
1862 };
1863 } else if (savedFrame->getPrincipals() ==
1864 &ReconstructedSavedFramePrincipals::IsNotSystem) {
1865 if (!out.writePair(
1866 SCTAG_SAVED_FRAME_OBJECT,
1867 SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_NOT_SYSTEM)) {
1868 return false;
1869 }
1870 } else {
1871 if (auto principals = savedFrame->getPrincipals()) {
1872 if (!out.writePair(SCTAG_SAVED_FRAME_OBJECT, SCTAG_JSPRINCIPALS) ||
1873 !principals->write(context(), this)) {
1874 return false;
1875 }
1876 } else {
1877 if (!out.writePair(SCTAG_SAVED_FRAME_OBJECT, SCTAG_NULL_JSPRINCIPALS)) {
1878 return false;
1879 }
1880 }
1881 }
1882
1883 // Write the SavedFrame's reserved slots, except for the parent, which is
1884 // queued on objs for further traversal.
1885
1886 RootedValue val(context());
1887
1888 val = BooleanValue(savedFrame->getMutedErrors());
1889 if (!writePrimitive(val)) {
1890 return false;
1891 }
1892
1893 context()->markAtom(savedFrame->getSource());
1894 val = StringValue(savedFrame->getSource());
1895 if (!writePrimitive(val)) {
1896 return false;
1897 }
1898
1899 val = NumberValue(savedFrame->getLine());
1900 if (!writePrimitive(val)) {
1901 return false;
1902 }
1903
1904 val = NumberValue(*savedFrame->getColumn().addressOfValueForTranscode());
1905 if (!writePrimitive(val)) {
1906 return false;
1907 }
1908
1909 auto name = savedFrame->getFunctionDisplayName();
1910 if (name) {
1911 context()->markAtom(name);
1912 }
1913 val = name ? StringValue(name) : NullValue();
1914 if (!writePrimitive(val)) {
1915 return false;
1916 }
1917
1918 auto cause = savedFrame->getAsyncCause();
1919 if (cause) {
1920 context()->markAtom(cause);
1921 }
1922 val = cause ? StringValue(cause) : NullValue();
1923 if (!writePrimitive(val)) {
1924 return false;
1925 }
1926
1927 return true;
1928 }
1929
1930 // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
1931 // 2.7.3 StructuredSerializeInternal ( value, forStorage [ , memory ] )
1932 //
1933 // Step 17. Otherwise, if value has an [[ErrorData]] internal slot and
1934 // value is not a platform object, then:
1935 //
1936 // Note: This contains custom extensions for handling non-standard properties.
1937 bool JSStructuredCloneWriter::traverseError(HandleObject obj) {
1938 JSContext* cx = context();
1939
1940 // 1. Let name be ? Get(value, "name").
1941 RootedValue name(cx);
1942 if (!GetProperty(cx, obj, obj, cx->names().name, &name)) {
1943 return false;
1944 }
1945
1946 // 2. If name is not one of "Error", "EvalError", "RangeError",
1947 // "ReferenceError", "SyntaxError", "TypeError", or "URIError",
1948 // (not yet specified: or "AggregateError")
1949 // then set name to "Error".
1950 JSExnType type = JSEXN_ERR;
1951 if (name.isString()) {
1952 JSLinearString* linear = name.toString()->ensureLinear(cx);
1953 if (!linear) {
1954 return false;
1955 }
1956
1957 if (EqualStrings(linear, cx->names().Error)) {
1958 type = JSEXN_ERR;
1959 } else if (EqualStrings(linear, cx->names().EvalError)) {
1960 type = JSEXN_EVALERR;
1961 } else if (EqualStrings(linear, cx->names().RangeError)) {
1962 type = JSEXN_RANGEERR;
1963 } else if (EqualStrings(linear, cx->names().ReferenceError)) {
1964 type = JSEXN_REFERENCEERR;
1965 } else if (EqualStrings(linear, cx->names().SyntaxError)) {
1966 type = JSEXN_SYNTAXERR;
1967 } else if (EqualStrings(linear, cx->names().TypeError)) {
1968 type = JSEXN_TYPEERR;
1969 } else if (EqualStrings(linear, cx->names().URIError)) {
1970 type = JSEXN_URIERR;
1971 } else if (EqualStrings(linear, cx->names().AggregateError)) {
1972 type = JSEXN_AGGREGATEERR;
1973 }
1974 }
1975
1976 // 3. Let valueMessageDesc be ? value.[[GetOwnProperty]]("message").
1977 RootedId messageId(cx, NameToId(cx->names().message));
1978 Rooted<Maybe<PropertyDescriptor>> messageDesc(cx);
1979 if (!GetOwnPropertyDescriptor(cx, obj, messageId, &messageDesc)) {
1980 return false;
1981 }
1982
1983 // 4. Let message be undefined if IsDataDescriptor(valueMessageDesc) is false,
1984 // and ? ToString(valueMessageDesc.[[Value]]) otherwise.
1985 RootedString message(cx);
1986 if (messageDesc.isSome() && messageDesc->isDataDescriptor()) {
1987 RootedValue messageVal(cx, messageDesc->value());
1988 message = ToString<CanGC>(cx, messageVal);
1989 if (!message) {
1990 return false;
1991 }
1992 }
1993
1994 // 5. Set serialized to { [[Type]]: "Error", [[Name]]: name, [[Message]]:
1995 // message }.
1996
1997 if (!objs.append(ObjectValue(*obj))) {
1998 return false;
1999 }
2000
2001 Rooted<ErrorObject*> unwrapped(cx, obj->maybeUnwrapAs<ErrorObject>());
2002 MOZ_ASSERT(unwrapped);
2003
2004 // Non-standard: Serialize |stack|.
2005 // The Error stack property is saved as SavedFrames.
2006 RootedValue stack(cx, NullValue());
2007 RootedObject stackObj(cx, unwrapped->stack());
2008 if (stackObj) {
2009 MOZ_ASSERT(stackObj->canUnwrapAs<SavedFrame>());
2010 stack.setObject(*stackObj);
2011 if (!cx->compartment()->wrap(cx, &stack)) {
2012 return false;
2013 }
2014 }
2015 if (!otherEntries.append(stack)) {
2016 return false;
2017 }
2018
2019 // Serialize |errors|
2020 if (type == JSEXN_AGGREGATEERR) {
2021 RootedValue errors(cx);
2022 if (!GetProperty(cx, obj, obj, cx->names().errors, &errors)) {
2023 return false;
2024 }
2025 if (!otherEntries.append(errors)) {
2026 return false;
2027 }
2028 } else {
2029 if (!otherEntries.append(NullValue())) {
2030 return false;
2031 }
2032 }
2033
2034 // Non-standard: Serialize |cause|. Because this property
2035 // might be missing we also write "hasCause" later.
2036 RootedId causeId(cx, NameToId(cx->names().cause));
2037 Rooted<Maybe<PropertyDescriptor>> causeDesc(cx);
2038 if (!GetOwnPropertyDescriptor(cx, obj, causeId, &causeDesc)) {
2039 return false;
2040 }
2041
2042 Rooted<Maybe<Value>> cause(cx);
2043 if (causeDesc.isSome() && causeDesc->isDataDescriptor()) {
2044 cause = mozilla::Some(causeDesc->value());
2045 }
2046 if (!cx->compartment()->wrap(cx, &cause)) {
2047 return false;
2048 }
2049 if (!otherEntries.append(cause.get().valueOr(NullValue()))) {
2050 return false;
2051 }
2052
2053 // |cause| + |errors| + |stack|, pushed in reverse order
2054 if (!counts.append(3)) {
2055 return false;
2056 }
2057
2058 checkStack();
2059
2060 if (!out.writePair(SCTAG_ERROR_OBJECT, type)) {
2061 return false;
2062 }
2063
2064 RootedValue val(cx, message ? StringValue(message) : NullValue());
2065 if (!writePrimitive(val)) {
2066 return false;
2067 }
2068
2069 // hasCause
2070 val = BooleanValue(cause.isSome());
2071 if (!writePrimitive(val)) {
2072 return false;
2073 }
2074
2075 // Non-standard: Also serialize fileName, lineNumber and columnNumber.
2076 {
2077 JSAutoRealm ar(cx, unwrapped);
2078 val = StringValue(unwrapped->fileName(cx));
2079 }
2080 if (!cx->compartment()->wrap(cx, &val) || !writePrimitive(val)) {
2081 return false;
2082 }
2083
2084 val = Int32Value(unwrapped->lineNumber());
2085 if (!writePrimitive(val)) {
2086 return false;
2087 }
2088
2089 val = Int32Value(*unwrapped->columnNumber().addressOfValueForTranscode());
2090 return writePrimitive(val);
2091 }
2092
2093 bool JSStructuredCloneWriter::writePrimitive(HandleValue v) {
2094 MOZ_ASSERT(v.isPrimitive());
2095 context()->check(v);
2096
2097 if (v.isString()) {
2098 return writeString(SCTAG_STRING, v.toString());
2099 } else if (v.isInt32()) {
2100 if (js::SupportDifferentialTesting()) {
2101 return out.writeDouble(v.toInt32());
2102 }
2103 return out.writePair(SCTAG_INT32, v.toInt32());
2104 } else if (v.isDouble()) {
2105 return out.writeDouble(v.toDouble());
2106 } else if (v.isBoolean()) {
2107 return out.writePair(SCTAG_BOOLEAN, v.toBoolean());
2108 } else if (v.isNull()) {
2109 return out.writePair(SCTAG_NULL, 0);
2110 } else if (v.isUndefined()) {
2111 return out.writePair(SCTAG_UNDEFINED, 0);
2112 } else if (v.isBigInt()) {
2113 return writeBigInt(SCTAG_BIGINT, v.toBigInt());
2114 }
2115
2116 return reportDataCloneError(JS_SCERR_UNSUPPORTED_TYPE);
2117 }
2118
2119 bool JSStructuredCloneWriter::startWrite(HandleValue v) {
2120 context()->check(v);
2121
2122 if (v.isPrimitive()) {
2123 return writePrimitive(v);
2124 }
2125
2126 if (!v.isObject()) {
2127 return reportDataCloneError(JS_SCERR_UNSUPPORTED_TYPE);
2128 }
2129
2130 RootedObject obj(context(), &v.toObject());
2131
2132 bool backref;
2133 if (!startObject(obj, &backref)) {
2134 return false;
2135 }
2136 if (backref) {
2137 return true;
2138 }
2139
2140 ESClass cls;
2141 if (!GetBuiltinClass(context(), obj, &cls)) {
2142 return false;
2143 }
2144
2145 switch (cls) {
2146 case ESClass::Object:
2147 case ESClass::Array:
2148 return traverseObject(obj, cls);
2149 case ESClass::Number: {
2150 RootedValue unboxed(context());
2151 if (!Unbox(context(), obj, &unboxed)) {
2152 return false;
2153 }
2154 return out.writePair(SCTAG_NUMBER_OBJECT, 0) &&
2155 out.writeDouble(unboxed.toNumber());
2156 }
2157 case ESClass::String: {
2158 RootedValue unboxed(context());
2159 if (!Unbox(context(), obj, &unboxed)) {
2160 return false;
2161 }
2162 return writeString(SCTAG_STRING_OBJECT, unboxed.toString());
2163 }
2164 case ESClass::Boolean: {
2165 RootedValue unboxed(context());
2166 if (!Unbox(context(), obj, &unboxed)) {
2167 return false;
2168 }
2169 return out.writePair(SCTAG_BOOLEAN_OBJECT, unboxed.toBoolean());
2170 }
2171 case ESClass::RegExp: {
2172 RegExpShared* re = RegExpToShared(context(), obj);
2173 if (!re) {
2174 return false;
2175 }
2176 return out.writePair(SCTAG_REGEXP_OBJECT, re->getFlags().value()) &&
2177 writeString(SCTAG_STRING, re->getSource());
2178 }
2179 case ESClass::ArrayBuffer: {
2180 if (JS::IsArrayBufferObject(obj) && JS::ArrayBufferHasData(obj)) {
2181 return writeArrayBuffer(obj);
2182 }
2183 break;
2184 }
2185 case ESClass::SharedArrayBuffer:
2186 if (JS::IsSharedArrayBufferObject(obj)) {
2187 return writeSharedArrayBuffer(obj);
2188 }
2189 break;
2190 case ESClass::Date: {
2191 RootedValue unboxed(context());
2192 if (!Unbox(context(), obj, &unboxed)) {
2193 return false;
2194 }
2195 return out.writePair(SCTAG_DATE_OBJECT, 0) &&
2196 out.writeDouble(unboxed.toNumber());
2197 }
2198 case ESClass::Set:
2199 return traverseSet(obj);
2200 case ESClass::Map:
2201 return traverseMap(obj);
2202 case ESClass::Error:
2203 return traverseError(obj);
2204 case ESClass::BigInt: {
2205 RootedValue unboxed(context());
2206 if (!Unbox(context(), obj, &unboxed)) {
2207 return false;
2208 }
2209 return writeBigInt(SCTAG_BIGINT_OBJECT, unboxed.toBigInt());
2210 }
2211 case ESClass::Promise:
2212 case ESClass::MapIterator:
2213 case ESClass::SetIterator:
2214 case ESClass::Arguments:
2215 case ESClass::Function:
2216 break;
2217 case ESClass::Other: {
2218 if (obj->canUnwrapAs<TypedArrayObject>()) {
2219 return writeTypedArray(obj);
2220 }
2221 if (obj->canUnwrapAs<DataViewObject>()) {
2222 return writeDataView(obj);
2223 }
2224 if (wasm::IsSharedWasmMemoryObject(obj)) {
2225 return writeSharedWasmMemory(obj);
2226 }
2227 if (obj->canUnwrapAs<SavedFrame>()) {
2228 return traverseSavedFrame(obj);
2229 }
2230 break;
2231 }
2232 }
2233
2234 if (out.buf.callbacks_ && out.buf.callbacks_->write) {
2235 bool sameProcessScopeRequired = false;
2236 if (!out.buf.callbacks_->write(context(), this, obj,
2237 &sameProcessScopeRequired,
2238 out.buf.closure_)) {
2239 return false;
2240 }
2241
2242 if (sameProcessScopeRequired) {
2243 output().sameProcessScopeRequired();
2244 }
2245
2246 return true;
2247 }
2248
2249 return reportDataCloneError(JS_SCERR_UNSUPPORTED_TYPE);
2250 }
2251
2252 bool JSStructuredCloneWriter::writeHeader() {
2253 return out.writePair(SCTAG_HEADER, (uint32_t)output().scope());
2254 }
2255
2256 bool JSStructuredCloneWriter::writeTransferMap() {
2257 if (transferableObjects.empty()) {
2258 return true;
2259 }
2260
2261 if (!out.writePair(SCTAG_TRANSFER_MAP_HEADER, (uint32_t)SCTAG_TM_UNREAD)) {
2262 return false;
2263 }
2264
2265 if (!out.write(transferableObjects.length())) {
2266 return false;
2267 }
2268
2269 RootedObject obj(context());
2270 for (auto* o : transferableObjects) {
2271 obj = o;
2272 if (!memory.put(obj, memory.count())) {
2273 ReportOutOfMemory(context());
2274 return false;
2275 }
2276
2277 // Emit a placeholder pointer. We defer stealing the data until later
2278 // (and, if necessary, detaching this object if it's an ArrayBuffer).
2279 if (!out.writePair(SCTAG_TRANSFER_MAP_PENDING_ENTRY,
2280 JS::SCTAG_TMO_UNFILLED)) {
2281 return false;
2282 }
2283 if (!out.write(0)) { // Pointer to ArrayBuffer contents.
2284 return false;
2285 }
2286 if (!out.write(0)) { // extraData
2287 return false;
2288 }
2289 }
2290
2291 return true;
2292 }
2293
2294 bool JSStructuredCloneWriter::transferOwnership() {
2295 if (transferableObjects.empty()) {
2296 return true;
2297 }
2298
2299 // Walk along the transferables and the transfer map at the same time,
2300 // grabbing out pointers from the transferables and stuffing them into the
2301 // transfer map.
2302 auto point = out.iter();
2303 MOZ_RELEASE_ASSERT(point.canPeek());
2304 MOZ_ASSERT(uint32_t(NativeEndian::swapFromLittleEndian(point.peek()) >> 32) ==
2305 SCTAG_HEADER);
2306 point++;
2307 MOZ_RELEASE_ASSERT(point.canPeek());
2308 MOZ_ASSERT(uint32_t(NativeEndian::swapFromLittleEndian(point.peek()) >> 32) ==
2309 SCTAG_TRANSFER_MAP_HEADER);
2310 point++;
2311 MOZ_RELEASE_ASSERT(point.canPeek());
2312 MOZ_ASSERT(NativeEndian::swapFromLittleEndian(point.peek()) ==
2313 transferableObjects.length());
2314 point++;
2315
2316 JSContext* cx = context();
2317 RootedObject obj(cx);
2318 JS::StructuredCloneScope scope = output().scope();
2319 for (auto* o : transferableObjects) {
2320 obj = o;
2321
2322 uint32_t tag;
2323 JS::TransferableOwnership ownership;
2324 void* content;
2325 uint64_t extraData;
2326
2327 #if DEBUG
2328 SCInput::getPair(point.peek(), &tag, (uint32_t*)&ownership);
2329 MOZ_ASSERT(tag == SCTAG_TRANSFER_MAP_PENDING_ENTRY);
2330 MOZ_ASSERT(ownership == JS::SCTAG_TMO_UNFILLED);
2331 #endif
2332
2333 ESClass cls;
2334 if (!GetBuiltinClass(cx, obj, &cls)) {
2335 return false;
2336 }
2337
2338 if (cls == ESClass::ArrayBuffer) {
2339 tag = SCTAG_TRANSFER_MAP_ARRAY_BUFFER;
2340
2341 // The current setup of the array buffer inheritance hierarchy doesn't
2342 // lend itself well to generic manipulation via proxies.
2343 Rooted<ArrayBufferObject*> arrayBuffer(
2344 cx, obj->maybeUnwrapAs<ArrayBufferObject>());
2345 JSAutoRealm ar(cx, arrayBuffer);
2346
2347 if (arrayBuffer->isDetached()) {
2348 reportDataCloneError(JS_SCERR_TYPED_ARRAY_DETACHED);
2349 return false;
2350 }
2351
2352 if (arrayBuffer->isPreparedForAsmJS()) {
2353 reportDataCloneError(JS_SCERR_WASM_NO_TRANSFER);
2354 return false;
2355 }
2356
2357 if (scope == JS::StructuredCloneScope::DifferentProcess ||
2358 scope == JS::StructuredCloneScope::DifferentProcessForIndexedDB ||
2359 arrayBuffer->isResizable()) {
2360 // Write Transferred ArrayBuffers in DifferentProcess scope at
2361 // the end of the clone buffer, and store the offset within the
2362 // buffer to where the ArrayBuffer was written. Note that this
2363 // will invalidate the current position iterator.
2364 //
2365 // Resizable ArrayBuffers need to store two extra data, the byte length
2366 // and the maximum byte length, but the current transferables format
2367 // supports only a single additional datum. Therefore resizable buffers
2368 // currently go through this slower code path.
2369
2370 size_t pointOffset = out.offset(point);
2371 tag = SCTAG_TRANSFER_MAP_STORED_ARRAY_BUFFER;
2372 ownership = JS::SCTAG_TMO_UNOWNED;
2373 content = nullptr;
2374 extraData = out.tell() -
2375 pointOffset; // Offset from tag to current end of buffer
2376 if (!writeArrayBuffer(arrayBuffer)) {
2377 ReportOutOfMemory(cx);
2378 return false;
2379 }
2380
2381 // Must refresh the point iterator after its collection has
2382 // been modified.
2383 point = out.iter();
2384 point += pointOffset;
2385
2386 if (!JS::DetachArrayBuffer(cx, arrayBuffer)) {
2387 return false;
2388 }
2389 } else {
2390 size_t nbytes = arrayBuffer->byteLength();
2391
2392 using BufferContents = ArrayBufferObject::BufferContents;
2393
2394 BufferContents bufContents =
2395 ArrayBufferObject::extractStructuredCloneContents(cx, arrayBuffer);
2396 if (!bufContents) {
2397 return false; // out of memory
2398 }
2399
2400 content = bufContents.data();
2401 if (bufContents.kind() == ArrayBufferObject::MAPPED) {
2402 ownership = JS::SCTAG_TMO_MAPPED_DATA;
2403 } else {
2404 MOZ_ASSERT(
2405 bufContents.kind() ==
2406 ArrayBufferObject::MALLOCED_ARRAYBUFFER_CONTENTS_ARENA ||
2407 bufContents.kind() ==
2408 ArrayBufferObject::MALLOCED_UNKNOWN_ARENA,
2409 "failing to handle new ArrayBuffer kind?");
2410 ownership = JS::SCTAG_TMO_ALLOC_DATA;
2411 }
2412 extraData = nbytes;
2413 }
2414 } else {
2415 if (!out.buf.callbacks_ || !out.buf.callbacks_->writeTransfer) {
2416 return reportDataCloneError(JS_SCERR_TRANSFERABLE);
2417 }
2418 if (!out.buf.callbacks_->writeTransfer(cx, obj, out.buf.closure_, &tag,
2419 &ownership, &content,
2420 &extraData)) {
2421 return false;
2422 }
2423 MOZ_ASSERT(tag > SCTAG_TRANSFER_MAP_PENDING_ENTRY);
2424 }
2425
2426 point.write(NativeEndian::swapToLittleEndian(PairToUInt64(tag, ownership)));
2427 MOZ_ALWAYS_TRUE(point.advance());
2428 point.write(
2429 NativeEndian::swapToLittleEndian(reinterpret_cast<uint64_t>(content)));
2430 MOZ_ALWAYS_TRUE(point.advance());
2431 point.write(NativeEndian::swapToLittleEndian(extraData));
2432 MOZ_ALWAYS_TRUE(point.advance());
2433 }
2434
2435 #if DEBUG
2436 // Make sure there aren't any more transfer map entries after the expected
2437 // number we read out.
2438 if (!point.done()) {
2439 uint32_t tag, data;
2440 SCInput::getPair(point.peek(), &tag, &data);
2441 MOZ_ASSERT(tag < SCTAG_TRANSFER_MAP_HEADER ||
2442 tag >= SCTAG_TRANSFER_MAP_END_OF_BUILTIN_TYPES);
2443 }
2444 #endif
2445 return true;
2446 }
2447
2448 bool JSStructuredCloneWriter::write(HandleValue v) {
2449 if (!startWrite(v)) {
2450 return false;
2451 }
2452
2453 RootedObject obj(context());
2454 RootedValue key(context());
2455 RootedValue val(context());
2456 RootedId id(context());
2457
2458 RootedValue cause(context());
2459 RootedValue errors(context());
2460 RootedValue stack(context());
2461
2462 while (!counts.empty()) {
2463 obj = &objs.back().toObject();
2464 context()->check(obj);
2465 if (counts.back()) {
2466 counts.back()--;
2467
2468 ESClass cls;
2469 if (!GetBuiltinClass(context(), obj, &cls)) {
2470 return false;
2471 }
2472
2473 if (cls == ESClass::Map) {
2474 key = otherEntries.popCopy();
2475 checkStack();
2476
2477 counts.back()--;
2478 val = otherEntries.popCopy();
2479 checkStack();
2480
2481 if (!startWrite(key) || !startWrite(val)) {
2482 return false;
2483 }
2484 } else if (cls == ESClass::Set || obj->canUnwrapAs<SavedFrame>()) {
2485 key = otherEntries.popCopy();
2486 checkStack();
2487
2488 if (!startWrite(key)) {
2489 return false;
2490 }
2491 } else if (cls == ESClass::Error) {
2492 cause = otherEntries.popCopy();
2493 checkStack();
2494
2495 counts.back()--;
2496 errors = otherEntries.popCopy();
2497 checkStack();
2498
2499 counts.back()--;
2500 stack = otherEntries.popCopy();
2501 checkStack();
2502
2503 if (!startWrite(cause) || !startWrite(errors) || !startWrite(stack)) {
2504 return false;
2505 }
2506 } else {
2507 id = objectEntries.popCopy();
2508 key = IdToValue(id);
2509 checkStack();
2510
2511 // If obj still has an own property named id, write it out.
2512 bool found;
2513 if (GetOwnPropertyPure(context(), obj, id, val.address(), &found)) {
2514 if (found) {
2515 if (!writePrimitive(key) || !startWrite(val)) {
2516 return false;
2517 }
2518 }
2519 continue;
2520 }
2521
2522 if (!HasOwnProperty(context(), obj, id, &found)) {
2523 return false;
2524 }
2525
2526 if (found) {
2527 #if FUZZING_JS_FUZZILLI
2528 // supress calls into user code
2529 if (js::SupportDifferentialTesting()) {
2530 fprintf(stderr, "Differential testing: cannot call GetProperty\n");
2531 return false;
2532 }
2533 #endif
2534
2535 if (!writePrimitive(key) ||
2536 !GetProperty(context(), obj, obj, id, &val) || !startWrite(val)) {
2537 return false;
2538 }
2539 }
2540 }
2541 } else {
2542 if (!out.writePair(SCTAG_END_OF_KEYS, 0)) {
2543 return false;
2544 }
2545 objs.popBack();
2546 counts.popBack();
2547 }
2548 }
2549
2550 memory.clear();
2551 return transferOwnership();
2552 }
2553
2554 JSStructuredCloneReader::JSStructuredCloneReader(
2555 SCInput& in, JS::StructuredCloneScope scope,
2556 const JS::CloneDataPolicy& cloneDataPolicy,
2557 const JSStructuredCloneCallbacks* cb, void* cbClosure)
2558 : in(in),
2559 allowedScope(scope),
2560 cloneDataPolicy(cloneDataPolicy),
2561 objs(in.context()),
2562 objState(in.context(), in.context()),
2563 allObjs(in.context()),
2564 numItemsRead(0),
2565 callbacks(cb),
2566 closure(cbClosure),
2567 gcHeap(in.context()) {
2568 // Readers should never enable SAB for a DifferentProcess scope.
2569 MOZ_RELEASE_ASSERT(!(scope == JS::StructuredCloneScope::DifferentProcess &&
2570 cloneDataPolicy.areSharedMemoryObjectsAllowed()));
2571
2572 // Avoid the need to bounds check by keeping a never-matching element at the
2573 // base of the `objState` stack. This append() will always succeed because
2574 // the objState vector has a nonzero MinInlineCapacity.
2575 MOZ_ALWAYS_TRUE(objState.append(std::make_pair(nullptr, true)));
2576 }
2577
2578 template <typename CharT>
2579 JSString* JSStructuredCloneReader::readStringImpl(
2580 uint32_t nchars, ShouldAtomizeStrings atomize) {
2581 if (atomize) {
2582 AtomStringChars<CharT> chars;
2583 if (!chars.maybeAlloc(context(), nchars) ||
2584 !in.readChars(chars.data(), nchars)) {
2585 return nullptr;
2586 }
2587 return chars.toAtom(context(), nchars);
2588 }
2589
2590 // Uses `StringChars::unsafeData()` because `readChars` can report an error,
2591 // which can trigger a GC.
2592 StringChars<CharT> chars(context());
2593 if (!chars.maybeAlloc(context(), nchars, gcHeap) ||
2594 !in.readChars(chars.unsafeData(), nchars)) {
2595 return nullptr;
2596 }
2597 return chars.template toStringDontDeflate<CanGC>(context(), nchars, gcHeap);
2598 }
2599
2600 JSString* JSStructuredCloneReader::readString(uint32_t data,
2601 ShouldAtomizeStrings atomize) {
2602 uint32_t nchars = data & BitMask(30);
2603 bool latin1 = data & (1 << 31);
2604 bool hasBuffer = data & (1 << 30);
2605
2606 if (nchars > JSString::MAX_LENGTH) {
2607 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2608 JSMSG_SC_BAD_SERIALIZED_DATA, "string length");
2609 return nullptr;
2610 }
2611
2612 if (hasBuffer) {
2613 if (allowedScope > JS::StructuredCloneScope::SameProcess) {
2614 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2615 JSMSG_SC_BAD_SERIALIZED_DATA,
2616 "invalid scope for string buffer");
2617 return nullptr;
2618 }
2619
2620 uintptr_t p;
2621 if (!in.readBytes(&p, sizeof(p))) {
2622 in.reportTruncated();
2623 return nullptr;
2624 }
2625 RefPtr<mozilla::StringBuffer> buffer(
2626 reinterpret_cast<mozilla::StringBuffer*>(p));
2627 JSContext* cx = context();
2628 if (atomize) {
2629 if (latin1) {
2630 return AtomizeChars(cx, static_cast<Latin1Char*>(buffer->Data()),
2631 nchars);
2632 }
2633 return AtomizeChars(cx, static_cast<char16_t*>(buffer->Data()), nchars);
2634 }
2635 if (latin1) {
2636 Rooted<JSString::OwnedChars<Latin1Char>> owned(cx, std::move(buffer),
2637 nchars);
2638 return JSLinearString::newValidLength<CanGC, Latin1Char>(cx, &owned,
2639 gcHeap);
2640 }
2641 Rooted<JSString::OwnedChars<char16_t>> owned(cx, std::move(buffer), nchars);
2642 return JSLinearString::newValidLength<CanGC, char16_t>(cx, &owned, gcHeap);
2643 }
2644
2645 return latin1 ? readStringImpl<Latin1Char>(nchars, atomize)
2646 : readStringImpl<char16_t>(nchars, atomize);
2647 }
2648
2649 [[nodiscard]] bool JSStructuredCloneReader::readUint32(uint32_t* num) {
2650 Rooted<Value> lineVal(context());
2651 if (!startRead(&lineVal)) {
2652 return false;
2653 }
2654 if (!lineVal.isInt32()) {
2655 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2656 JSMSG_SC_BAD_SERIALIZED_DATA, "integer required");
2657 return false;
2658 }
2659 *num = uint32_t(lineVal.toInt32());
2660 return true;
2661 }
2662
2663 BigInt* JSStructuredCloneReader::readBigInt(uint32_t data) {
2664 size_t length = data & BitMask(31);
2665 bool isNegative = data & (1 << 31);
2666 if (length == 0) {
2667 return BigInt::zero(context());
2668 }
2669 RootedBigInt result(context(), BigInt::createUninitialized(
2670 context(), length, isNegative, gcHeap));
2671 if (!result) {
2672 return nullptr;
2673 }
2674 if (!in.readArray(result->digits().data(), length)) {
2675 return nullptr;
2676 }
2677 return JS::BigInt::destructivelyTrimHighZeroDigits(context(), result);
2678 }
2679
2680 static uint32_t TagToV1ArrayType(uint32_t tag) {
2681 MOZ_ASSERT(tag >= SCTAG_TYPED_ARRAY_V1_MIN &&
2682 tag <= SCTAG_TYPED_ARRAY_V1_MAX);
2683 return tag - SCTAG_TYPED_ARRAY_V1_MIN;
2684 }
2685
2686 bool JSStructuredCloneReader::readTypedArray(uint32_t arrayType,
2687 uint64_t nelems,
2688 MutableHandleValue vp,
2689 bool v1Read) {
2690 if (arrayType > (v1Read ? Scalar::Uint8Clamped : Scalar::Float16)) {
2691 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2692 JSMSG_SC_BAD_SERIALIZED_DATA,
2693 "unhandled typed array element type");
2694 return false;
2695 }
2696
2697 // Push a placeholder onto the allObjs list to stand in for the typed array.
2698 uint32_t placeholderIndex = allObjs.length();
2699 Value dummy = UndefinedValue();
2700 if (!allObjs.append(dummy)) {
2701 return false;
2702 }
2703
2704 // Auto-length TypedArrays are tagged by using `-1` for their length.
2705 bool isAutoLength = nelems == uint64_t(-1);
2706
2707 // Zero |nelems| if it was only used as a tag.
2708 if (isAutoLength) {
2709 nelems = 0;
2710 }
2711
2712 // Read the ArrayBuffer object and its contents (but no properties)
2713 RootedValue v(context());
2714 uint64_t byteOffset;
2715 if (v1Read) {
2716 MOZ_ASSERT(!isAutoLength, "v1Read can't produce auto-length TypedArrays");
2717 if (!readV1ArrayBuffer(arrayType, nelems, &v)) {
2718 return false;
2719 }
2720 byteOffset = 0;
2721 } else {
2722 if (!startRead(&v)) {
2723 return false;
2724 }
2725 if (!in.read(&byteOffset)) {
2726 return false;
2727 }
2728 }
2729
2730 // Ensure invalid 64-bit values won't be truncated below.
2731 if (nelems > ArrayBufferObject::ByteLengthLimit ||
2732 byteOffset > ArrayBufferObject::ByteLengthLimit) {
2733 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2734 JSMSG_SC_BAD_SERIALIZED_DATA,
2735 "invalid typed array length or offset");
2736 return false;
2737 }
2738
2739 if (!v.isObject() || !v.toObject().is<ArrayBufferObjectMaybeShared>()) {
2740 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2741 JSMSG_SC_BAD_SERIALIZED_DATA,
2742 "typed array must be backed by an ArrayBuffer");
2743 return false;
2744 }
2745
2746 RootedObject buffer(context(), &v.toObject());
2747 RootedObject obj(context(), nullptr);
2748
2749 // Negative values represent an absent length parameter.
2750 int64_t length = isAutoLength ? -1 : int64_t(nelems);
2751
2752 switch (arrayType) {
2753 #define CREATE_FROM_BUFFER(ExternalType, NativeType, Name) \
2754 case Scalar::Name: \
2755 obj = JS::TypedArray<Scalar::Name>::fromBuffer(context(), buffer, \
2756 byteOffset, length) \
2757 .asObject(); \
2758 break;
2759
2760 JS_FOR_EACH_TYPED_ARRAY(CREATE_FROM_BUFFER)
2761 #undef CREATE_FROM_BUFFER
2762
2763 default:
2764 MOZ_CRASH("Can't happen: arrayType range checked above");
2765 }
2766
2767 if (!obj) {
2768 return false;
2769 }
2770 vp.setObject(*obj);
2771
2772 allObjs[placeholderIndex].set(vp);
2773
2774 return true;
2775 }
2776
2777 bool JSStructuredCloneReader::readDataView(uint64_t byteLength,
2778 MutableHandleValue vp) {
2779 // Push a placeholder onto the allObjs list to stand in for the DataView.
2780 uint32_t placeholderIndex = allObjs.length();
2781 Value dummy = UndefinedValue();
2782 if (!allObjs.append(dummy)) {
2783 return false;
2784 }
2785
2786 // Read the ArrayBuffer object and its contents (but no properties).
2787 RootedValue v(context());
2788 if (!startRead(&v)) {
2789 return false;
2790 }
2791 if (!v.isObject() || !v.toObject().is<ArrayBufferObjectMaybeShared>()) {
2792 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2793 JSMSG_SC_BAD_SERIALIZED_DATA,
2794 "DataView must be backed by an ArrayBuffer");
2795 return false;
2796 }
2797
2798 // Read byteOffset.
2799 uint64_t byteOffset;
2800 if (!in.read(&byteOffset)) {
2801 return false;
2802 }
2803
2804 // Auto-length DataViews are tagged by using `-1` for their byte length.
2805 bool isAutoLength = byteLength == uint64_t(-1);
2806
2807 // Zero |byteLength| if it was only used as a tag.
2808 if (isAutoLength) {
2809 byteLength = 0;
2810 }
2811
2812 // Ensure invalid 64-bit values won't be truncated below.
2813 if (byteLength > ArrayBufferObject::ByteLengthLimit ||
2814 byteOffset > ArrayBufferObject::ByteLengthLimit) {
2815 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2816 JSMSG_SC_BAD_SERIALIZED_DATA,
2817 "invalid DataView length or offset");
2818 return false;
2819 }
2820
2821 RootedObject buffer(context(), &v.toObject());
2822 RootedObject obj(context());
2823 if (!isAutoLength) {
2824 obj = JS_NewDataView(context(), buffer, byteOffset, byteLength);
2825 } else {
2826 obj = js::NewDataView(context(), buffer, byteOffset);
2827 }
2828 if (!obj) {
2829 return false;
2830 }
2831 vp.setObject(*obj);
2832
2833 allObjs[placeholderIndex].set(vp);
2834
2835 return true;
2836 }
2837
2838 bool JSStructuredCloneReader::readArrayBuffer(StructuredDataType type,
2839 uint32_t data,
2840 MutableHandleValue vp) {
2841 // V2 stores the length in |data|. The current version stores the
2842 // length separately to allow larger length values.
2843 uint64_t nbytes = 0;
2844 uint64_t maxbytes = 0;
2845 if (type == SCTAG_ARRAY_BUFFER_OBJECT) {
2846 if (!in.read(&nbytes)) {
2847 return false;
2848 }
2849 } else if (type == SCTAG_RESIZABLE_ARRAY_BUFFER_OBJECT) {
2850 if (!in.read(&nbytes)) {
2851 return false;
2852 }
2853 if (!in.read(&maxbytes)) {
2854 return false;
2855 }
2856 } else {
2857 MOZ_ASSERT(type == SCTAG_ARRAY_BUFFER_OBJECT_V2);
2858 nbytes = data;
2859 }
2860
2861 // The maximum ArrayBuffer size depends on the platform, and we cast to size_t
2862 // below, so we have to check this here.
2863 if (nbytes > ArrayBufferObject::ByteLengthLimit ||
2864 maxbytes > ArrayBufferObject::ByteLengthLimit) {
2865 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2866 JSMSG_BAD_ARRAY_LENGTH);
2867 return false;
2868 }
2869
2870 JSObject* obj;
2871 if (type != SCTAG_RESIZABLE_ARRAY_BUFFER_OBJECT) {
2872 MOZ_ASSERT(maxbytes == 0);
2873 obj = ArrayBufferObject::createZeroed(context(), size_t(nbytes));
2874 } else {
2875 obj = ResizableArrayBufferObject::createZeroed(context(), size_t(nbytes),
2876 size_t(maxbytes));
2877 }
2878 if (!obj) {
2879 return false;
2880 }
2881 vp.setObject(*obj);
2882 ArrayBufferObject& buffer = obj->as<ArrayBufferObject>();
2883 MOZ_ASSERT(buffer.byteLength() == nbytes);
2884 return in.readArray(buffer.dataPointer(), nbytes);
2885 }
2886
2887 bool JSStructuredCloneReader::readSharedArrayBuffer(StructuredDataType type,
2888 MutableHandleValue vp) {
2889 MOZ_ASSERT(type == SCTAG_SHARED_ARRAY_BUFFER_OBJECT ||
2890 type == SCTAG_GROWABLE_SHARED_ARRAY_BUFFER_OBJECT);
2891
2892 if (!cloneDataPolicy.areIntraClusterClonableSharedObjectsAllowed() ||
2893 !cloneDataPolicy.areSharedMemoryObjectsAllowed()) {
2894 auto error = context()->realm()->creationOptions().getCoopAndCoepEnabled()
2895 ? JS_SCERR_NOT_CLONABLE_WITH_COOP_COEP
2896 : JS_SCERR_NOT_CLONABLE;
2897 ReportDataCloneError(context(), callbacks, error, closure,
2898 "SharedArrayBuffer");
2899 return false;
2900 }
2901
2902 uint64_t byteLength;
2903 if (!in.readBytes(&byteLength, sizeof(byteLength))) {
2904 return in.reportTruncated();
2905 }
2906
2907 // The maximum ArrayBuffer size depends on the platform, and we cast to size_t
2908 // below, so we have to check this here.
2909 if (byteLength > ArrayBufferObject::ByteLengthLimit) {
2910 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2911 JSMSG_BAD_ARRAY_LENGTH);
2912 return false;
2913 }
2914
2915 intptr_t p;
2916 if (!in.readBytes(&p, sizeof(p))) {
2917 return in.reportTruncated();
2918 }
2919
2920 bool isGrowable = type == SCTAG_GROWABLE_SHARED_ARRAY_BUFFER_OBJECT;
2921
2922 SharedArrayRawBuffer* rawbuf = reinterpret_cast<SharedArrayRawBuffer*>(p);
2923 MOZ_RELEASE_ASSERT(rawbuf->isWasm() || isGrowable == rawbuf->isGrowableJS());
2924
2925 // There's no guarantee that the receiving agent has enabled shared memory
2926 // even if the transmitting agent has done so. Ideally we'd check at the
2927 // transmission point, but that's tricky, and it will be a very rare problem
2928 // in any case. Just fail at the receiving end if we can't handle it.
2929
2930 if (!context()
2931 ->realm()
2932 ->creationOptions()
2933 .getSharedMemoryAndAtomicsEnabled()) {
2934 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2935 JSMSG_SC_SAB_DISABLED);
2936 return false;
2937 }
2938
2939 // The new object will have a new reference to the rawbuf.
2940
2941 if (!rawbuf->addReference()) {
2942 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2943 JSMSG_SC_SAB_REFCNT_OFLO);
2944 return false;
2945 }
2946
2947 RootedObject obj(context());
2948 if (!isGrowable) {
2949 obj = SharedArrayBufferObject::New(context(), rawbuf, byteLength);
2950 } else {
2951 obj = SharedArrayBufferObject::NewGrowable(context(), rawbuf, byteLength);
2952 }
2953 if (!obj) {
2954 rawbuf->dropReference();
2955 return false;
2956 }
2957
2958 // `rawbuf` is now owned by `obj`.
2959
2960 if (callbacks && callbacks->sabCloned &&
2961 !callbacks->sabCloned(context(), /*receiving=*/true, closure)) {
2962 return false;
2963 }
2964
2965 vp.setObject(*obj);
2966 return true;
2967 }
2968
2969 bool JSStructuredCloneReader::readSharedWasmMemory(uint32_t nbytes,
2970 MutableHandleValue vp) {
2971 JSContext* cx = context();
2972 if (nbytes != 0) {
2973 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2974 JSMSG_SC_BAD_SERIALIZED_DATA,
2975 "invalid shared wasm memory tag");
2976 return false;
2977 }
2978
2979 if (!cloneDataPolicy.areIntraClusterClonableSharedObjectsAllowed() ||
2980 !cloneDataPolicy.areSharedMemoryObjectsAllowed()) {
2981 auto error = context()->realm()->creationOptions().getCoopAndCoepEnabled()
2982 ? JS_SCERR_NOT_CLONABLE_WITH_COOP_COEP
2983 : JS_SCERR_NOT_CLONABLE;
2984 ReportDataCloneError(cx, callbacks, error, closure, "WebAssembly.Memory");
2985 return false;
2986 }
2987
2988 // Read the isHuge flag
2989 RootedValue isHuge(cx);
2990 if (!startRead(&isHuge)) {
2991 return false;
2992 }
2993 if (!isHuge.isBoolean()) {
2994 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
2995 JSMSG_SC_BAD_SERIALIZED_DATA,
2996 "isHuge must be a boolean");
2997 return false;
2998 }
2999
3000 // Read the SharedArrayBuffer object.
3001 RootedValue payload(cx);
3002 if (!startRead(&payload)) {
3003 return false;
3004 }
3005 if (!payload.isObject() ||
3006 !payload.toObject().is<SharedArrayBufferObject>() ||
3007 payload.toObject().as<SharedArrayBufferObject>().isGrowable()) {
3008 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3009 JSMSG_SC_BAD_SERIALIZED_DATA,
3010 "shared wasm memory must be backed by a "
3011 "non-growable SharedArrayBuffer");
3012 return false;
3013 }
3014
3015 Rooted<ArrayBufferObjectMaybeShared*> sab(
3016 cx, &payload.toObject().as<SharedArrayBufferObject>());
3017
3018 // Construct the memory.
3019 RootedObject proto(
3020 cx, GlobalObject::getOrCreatePrototype(cx, JSProto_WasmMemory));
3021 if (!proto) {
3022 return false;
3023 }
3024 RootedObject memory(
3025 cx, WasmMemoryObject::create(cx, sab, isHuge.toBoolean(), proto));
3026 if (!memory) {
3027 return false;
3028 }
3029
3030 vp.setObject(*memory);
3031 return true;
3032 }
3033
3034 /*
3035 * Read in the data for a structured clone version 1 ArrayBuffer, performing
3036 * endianness-conversion while reading.
3037 */
3038 bool JSStructuredCloneReader::readV1ArrayBuffer(uint32_t arrayType,
3039 uint32_t nelems,
3040 MutableHandleValue vp) {
3041 if (arrayType > Scalar::Uint8Clamped) {
3042 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3043 JSMSG_SC_BAD_SERIALIZED_DATA,
3044 "invalid TypedArray type");
3045 return false;
3046 }
3047
3048 mozilla::CheckedInt<size_t> nbytes =
3049 mozilla::CheckedInt<size_t>(nelems) *
3050 TypedArrayElemSize(static_cast<Scalar::Type>(arrayType));
3051 if (!nbytes.isValid() || nbytes.value() > UINT32_MAX) {
3052 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3053 JSMSG_SC_BAD_SERIALIZED_DATA,
3054 "invalid typed array size");
3055 return false;
3056 }
3057
3058 JSObject* obj = ArrayBufferObject::createZeroed(context(), nbytes.value());
3059 if (!obj) {
3060 return false;
3061 }
3062 vp.setObject(*obj);
3063 ArrayBufferObject& buffer = obj->as<ArrayBufferObject>();
3064 MOZ_ASSERT(buffer.byteLength() == nbytes);
3065
3066 switch (arrayType) {
3067 case Scalar::Int8:
3068 case Scalar::Uint8:
3069 case Scalar::Uint8Clamped:
3070 return in.readArray((uint8_t*)buffer.dataPointer(), nelems);
3071 case Scalar::Int16:
3072 case Scalar::Uint16:
3073 return in.readArray((uint16_t*)buffer.dataPointer(), nelems);
3074 case Scalar::Int32:
3075 case Scalar::Uint32:
3076 case Scalar::Float32:
3077 return in.readArray((uint32_t*)buffer.dataPointer(), nelems);
3078 case Scalar::Float64:
3079 case Scalar::BigInt64:
3080 case Scalar::BigUint64:
3081 return in.readArray((uint64_t*)buffer.dataPointer(), nelems);
3082 default:
3083 MOZ_CRASH("Can't happen: arrayType range checked by caller");
3084 }
3085 }
3086
3087 static bool PrimitiveToObject(JSContext* cx, MutableHandleValue vp) {
3088 JSObject* obj = js::PrimitiveToObject(cx, vp);
3089 if (!obj) {
3090 return false;
3091 }
3092
3093 vp.setObject(*obj);
3094 return true;
3095 }
3096
3097 bool JSStructuredCloneReader::startRead(MutableHandleValue vp,
3098 ShouldAtomizeStrings atomizeStrings) {
3099 uint32_t tag, data;
3100 bool alreadAppended = false;
3101
3102 AutoCheckRecursionLimit recursion(in.context());
3103 if (!recursion.check(in.context())) {
3104 return false;
3105 }
3106
3107 if (!in.readPair(&tag, &data)) {
3108 return false;
3109 }
3110
3111 numItemsRead++;
3112
3113 switch (tag) {
3114 case SCTAG_NULL:
3115 vp.setNull();
3116 break;
3117
3118 case SCTAG_UNDEFINED:
3119 vp.setUndefined();
3120 break;
3121
3122 case SCTAG_INT32:
3123 vp.setInt32(data);
3124 break;
3125
3126 case SCTAG_BOOLEAN:
3127 case SCTAG_BOOLEAN_OBJECT:
3128 vp.setBoolean(!!data);
3129 if (tag == SCTAG_BOOLEAN_OBJECT && !PrimitiveToObject(context(), vp)) {
3130 return false;
3131 }
3132 break;
3133
3134 case SCTAG_STRING:
3135 case SCTAG_STRING_OBJECT: {
3136 JSString* str = readString(data, atomizeStrings);
3137 if (!str) {
3138 return false;
3139 }
3140 vp.setString(str);
3141 if (tag == SCTAG_STRING_OBJECT && !PrimitiveToObject(context(), vp)) {
3142 return false;
3143 }
3144 break;
3145 }
3146
3147 case SCTAG_NUMBER_OBJECT: {
3148 double d;
3149 if (!in.readDouble(&d)) {
3150 return false;
3151 }
3152 vp.setDouble(CanonicalizeNaN(d));
3153 if (!PrimitiveToObject(context(), vp)) {
3154 return false;
3155 }
3156 break;
3157 }
3158
3159 case SCTAG_BIGINT:
3160 case SCTAG_BIGINT_OBJECT: {
3161 RootedBigInt bi(context(), readBigInt(data));
3162 if (!bi) {
3163 return false;
3164 }
3165 vp.setBigInt(bi);
3166 if (tag == SCTAG_BIGINT_OBJECT && !PrimitiveToObject(context(), vp)) {
3167 return false;
3168 }
3169 break;
3170 }
3171
3172 case SCTAG_DATE_OBJECT: {
3173 double d;
3174 if (!in.readDouble(&d)) {
3175 return false;
3176 }
3177 JS::ClippedTime t = JS::TimeClip(d);
3178 if (!NumbersAreIdentical(d, t.toDouble())) {
3179 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3180 JSMSG_SC_BAD_SERIALIZED_DATA, "date");
3181 return false;
3182 }
3183 JSObject* obj = NewDateObjectMsec(context(), t);
3184 if (!obj) {
3185 return false;
3186 }
3187 vp.setObject(*obj);
3188 break;
3189 }
3190
3191 case SCTAG_REGEXP_OBJECT: {
3192 if ((data & RegExpFlag::AllFlags) != data) {
3193 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3194 JSMSG_SC_BAD_SERIALIZED_DATA, "regexp");
3195 return false;
3196 }
3197
3198 RegExpFlags flags(AssertedCast<uint8_t>(data));
3199
3200 uint32_t tag2, stringData;
3201 if (!in.readPair(&tag2, &stringData)) {
3202 return false;
3203 }
3204 if (tag2 != SCTAG_STRING) {
3205 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3206 JSMSG_SC_BAD_SERIALIZED_DATA, "regexp");
3207 return false;
3208 }
3209
3210 JSString* str = readString(stringData, AtomizeStrings);
3211 if (!str) {
3212 return false;
3213 }
3214
3215 Rooted<JSAtom*> atom(context(), &str->asAtom());
3216
3217 NewObjectKind kind =
3218 gcHeap == gc::Heap::Tenured ? TenuredObject : GenericObject;
3219 RegExpObject* reobj = RegExpObject::create(context(), atom, flags, kind);
3220 if (!reobj) {
3221 return false;
3222 }
3223 vp.setObject(*reobj);
3224 break;
3225 }
3226
3227 case SCTAG_ARRAY_OBJECT:
3228 case SCTAG_OBJECT_OBJECT: {
3229 NewObjectKind kind =
3230 gcHeap == gc::Heap::Tenured ? TenuredObject : GenericObject;
3231 JSObject* obj;
3232 if (tag == SCTAG_ARRAY_OBJECT) {
3233 obj = NewDenseUnallocatedArray(
3234 context(), NativeEndian::swapFromLittleEndian(data), kind);
3235 } else {
3236 obj = NewPlainObject(context(), kind);
3237 }
3238 if (!obj || !objs.append(ObjectValue(*obj))) {
3239 return false;
3240 }
3241
3242 vp.setObject(*obj);
3243 break;
3244 }
3245
3246 case SCTAG_BACK_REFERENCE_OBJECT: {
3247 if (data >= allObjs.length() || !allObjs[data].isObject()) {
3248 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3249 JSMSG_SC_BAD_SERIALIZED_DATA,
3250 "invalid back reference in input");
3251 return false;
3252 }
3253 vp.set(allObjs[data]);
3254 return true;
3255 }
3256
3257 case SCTAG_TRANSFER_MAP_HEADER:
3258 case SCTAG_TRANSFER_MAP_PENDING_ENTRY:
3259 // We should be past all the transfer map tags.
3260 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3261 JSMSG_SC_BAD_SERIALIZED_DATA, "invalid input");
3262 return false;
3263
3264 case SCTAG_ARRAY_BUFFER_OBJECT_V2:
3265 case SCTAG_ARRAY_BUFFER_OBJECT:
3266 case SCTAG_RESIZABLE_ARRAY_BUFFER_OBJECT:
3267 if (!readArrayBuffer(StructuredDataType(tag), data, vp)) {
3268 return false;
3269 }
3270 break;
3271
3272 case SCTAG_SHARED_ARRAY_BUFFER_OBJECT:
3273 case SCTAG_GROWABLE_SHARED_ARRAY_BUFFER_OBJECT:
3274 if (!readSharedArrayBuffer(StructuredDataType(tag), vp)) {
3275 return false;
3276 }
3277 break;
3278
3279 case SCTAG_SHARED_WASM_MEMORY_OBJECT:
3280 if (!readSharedWasmMemory(data, vp)) {
3281 return false;
3282 }
3283 break;
3284
3285 case SCTAG_TYPED_ARRAY_OBJECT_V2: {
3286 // readTypedArray adds the array to allObjs.
3287 // V2 stores the length (nelems) in |data| and the arrayType separately.
3288 uint64_t arrayType;
3289 if (!in.read(&arrayType)) {
3290 return false;
3291 }
3292 uint64_t nelems = data;
3293 return readTypedArray(arrayType, nelems, vp);
3294 }
3295
3296 case SCTAG_TYPED_ARRAY_OBJECT: {
3297 // readTypedArray adds the array to allObjs.
3298 // The current version stores the array type in |data| and the length
3299 // (nelems) separately to support large TypedArrays.
3300 uint32_t arrayType = data;
3301 uint64_t nelems;
3302 if (!in.read(&nelems)) {
3303 return false;
3304 }
3305 return readTypedArray(arrayType, nelems, vp);
3306 }
3307
3308 case SCTAG_DATA_VIEW_OBJECT_V2: {
3309 // readDataView adds the array to allObjs.
3310 uint64_t byteLength = data;
3311 return readDataView(byteLength, vp);
3312 }
3313
3314 case SCTAG_DATA_VIEW_OBJECT: {
3315 // readDataView adds the array to allObjs.
3316 uint64_t byteLength;
3317 if (!in.read(&byteLength)) {
3318 return false;
3319 }
3320 return readDataView(byteLength, vp);
3321 }
3322
3323 case SCTAG_MAP_OBJECT: {
3324 JSObject* obj = MapObject::create(context());
3325 if (!obj || !objs.append(ObjectValue(*obj))) {
3326 return false;
3327 }
3328 vp.setObject(*obj);
3329 break;
3330 }
3331
3332 case SCTAG_SET_OBJECT: {
3333 JSObject* obj = SetObject::create(context());
3334 if (!obj || !objs.append(ObjectValue(*obj))) {
3335 return false;
3336 }
3337 vp.setObject(*obj);
3338 break;
3339 }
3340
3341 case SCTAG_SAVED_FRAME_OBJECT: {
3342 auto* obj = readSavedFrameHeader(data);
3343 if (!obj || !objs.append(ObjectValue(*obj)) ||
3344 !objState.append(std::make_pair(obj, false))) {
3345 return false;
3346 }
3347 vp.setObject(*obj);
3348 break;
3349 }
3350
3351 case SCTAG_ERROR_OBJECT: {
3352 auto* obj = readErrorHeader(data);
3353 if (!obj || !objs.append(ObjectValue(*obj)) ||
3354 !objState.append(std::make_pair(obj, false))) {
3355 return false;
3356 }
3357 vp.setObject(*obj);
3358 break;
3359 }
3360
3361 case SCTAG_END_OF_KEYS:
3362 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3363 JSMSG_SC_BAD_SERIALIZED_DATA,
3364 "truncated input");
3365 return false;
3366 break;
3367
3368 default: {
3369 if (tag <= SCTAG_FLOAT_MAX) {
3370 double d = ReinterpretPairAsDouble(tag, data);
3371 vp.setNumber(CanonicalizeNaN(d));
3372 break;
3373 }
3374
3375 if (SCTAG_TYPED_ARRAY_V1_MIN <= tag && tag <= SCTAG_TYPED_ARRAY_V1_MAX) {
3376 // A v1-format typed array
3377 // readTypedArray adds the array to allObjs
3378 return readTypedArray(TagToV1ArrayType(tag), data, vp, true);
3379 }
3380
3381 if (!callbacks || !callbacks->read) {
3382 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3383 JSMSG_SC_BAD_SERIALIZED_DATA,
3384 "unsupported type");
3385 return false;
3386 }
3387
3388 // callbacks->read() might read other objects from the buffer.
3389 // In startWrite we always write the object itself before calling
3390 // the custom function. We should do the same here to keep
3391 // indexing consistent.
3392 uint32_t placeholderIndex = allObjs.length();
3393 Value dummy = UndefinedValue();
3394 if (!allObjs.append(dummy)) {
3395 return false;
3396 }
3397 JSObject* obj =
3398 callbacks->read(context(), this, cloneDataPolicy, tag, data, closure);
3399 if (!obj) {
3400 return false;
3401 }
3402 vp.setObject(*obj);
3403 allObjs[placeholderIndex].set(vp);
3404 alreadAppended = true;
3405 }
3406 }
3407
3408 if (!alreadAppended && vp.isObject() && !allObjs.append(vp)) {
3409 return false;
3410 }
3411
3412 return true;
3413 }
3414
3415 bool JSStructuredCloneReader::readHeader() {
3416 uint32_t tag, data;
3417 if (!in.getPair(&tag, &data)) {
3418 return in.reportTruncated();
3419 }
3420
3421 JS::StructuredCloneScope storedScope;
3422 if (tag == SCTAG_HEADER) {
3423 MOZ_ALWAYS_TRUE(in.readPair(&tag, &data));
3424 storedScope = JS::StructuredCloneScope(data);
3425 } else {
3426 // Old structured clone buffer. We must have read it from disk.
3427 storedScope = JS::StructuredCloneScope::DifferentProcessForIndexedDB;
3428 }
3429
3430 // Backward compatibility with old structured clone buffers. Value '0' was
3431 // used for SameProcessSameThread scope.
3432 if ((int)storedScope == 0) {
3433 storedScope = JS::StructuredCloneScope::SameProcess;
3434 }
3435
3436 if (storedScope < JS::StructuredCloneScope::SameProcess ||
3437 storedScope > JS::StructuredCloneScope::DifferentProcessForIndexedDB) {
3438 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3439 JSMSG_SC_BAD_SERIALIZED_DATA,
3440 "invalid structured clone scope");
3441 return false;
3442 }
3443
3444 if (allowedScope == JS::StructuredCloneScope::DifferentProcessForIndexedDB) {
3445 // Bug 1434308 and bug 1458320 - the scopes stored in old IndexedDB
3446 // clones are incorrect. Treat them as if they were DifferentProcess.
3447 allowedScope = JS::StructuredCloneScope::DifferentProcess;
3448 return true;
3449 }
3450
3451 if (storedScope < allowedScope) {
3452 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3453 JSMSG_SC_BAD_SERIALIZED_DATA,
3454 "incompatible structured clone scope");
3455 return false;
3456 }
3457
3458 if (allowedScope == JS::StructuredCloneScope::DifferentProcess) {
3459 MOZ_RELEASE_ASSERT(
3460 !cloneDataPolicy.areIntraClusterClonableSharedObjectsAllowed());
3461 MOZ_RELEASE_ASSERT(!cloneDataPolicy.areSharedMemoryObjectsAllowed());
3462 }
3463
3464 return true;
3465 }
3466
3467 bool JSStructuredCloneReader::readTransferMap() {
3468 JSContext* cx = context();
3469 auto headerPos = in.tell();
3470
3471 uint32_t tag, data;
3472 if (!in.getPair(&tag, &data)) {
3473 return in.reportTruncated();
3474 }
3475
3476 if (tag != SCTAG_TRANSFER_MAP_HEADER) {
3477 // No transfer map header found.
3478 return true;
3479 }
3480
3481 if (data >= SCTAG_TM_END) {
3482 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3483 JSMSG_SC_BAD_SERIALIZED_DATA,
3484 "invalid transfer map header");
3485 return false;
3486 }
3487 auto transferState = static_cast<TransferableMapHeader>(data);
3488
3489 if (transferState == SCTAG_TM_TRANSFERRED) {
3490 return true;
3491 }
3492
3493 if (transferState == SCTAG_TM_TRANSFERRING) {
3494 ReportDataCloneError(cx, callbacks, JS_SCERR_TRANSFERABLE_TWICE, closure);
3495 return false;
3496 }
3497
3498 headerPos.write(
3499 PairToUInt64(SCTAG_TRANSFER_MAP_HEADER, SCTAG_TM_TRANSFERRING));
3500
3501 uint64_t numTransferables;
3502 MOZ_ALWAYS_TRUE(in.readPair(&tag, &data));
3503 if (!in.read(&numTransferables)) {
3504 return false;
3505 }
3506
3507 for (uint64_t i = 0; i < numTransferables; i++) {
3508 auto pos = in.tell();
3509
3510 if (!in.readPair(&tag, &data)) {
3511 return false;
3512 }
3513
3514 if (tag == SCTAG_TRANSFER_MAP_PENDING_ENTRY) {
3515 ReportDataCloneError(cx, callbacks, JS_SCERR_TRANSFERABLE, closure);
3516 return false;
3517 }
3518
3519 RootedObject obj(cx);
3520
3521 void* content;
3522 if (!in.readPtr(&content)) {
3523 return false;
3524 }
3525
3526 uint64_t extraData;
3527 if (!in.read(&extraData)) {
3528 return false;
3529 }
3530
3531 if (tag == SCTAG_TRANSFER_MAP_ARRAY_BUFFER) {
3532 MOZ_ASSERT(allowedScope <= JS::StructuredCloneScope::LastResolvedScope);
3533 if (allowedScope == JS::StructuredCloneScope::DifferentProcess) {
3534 // Transferred ArrayBuffers in a DifferentProcess clone buffer
3535 // are treated as if they weren't Transferred at all. We should
3536 // only see SCTAG_TRANSFER_MAP_STORED_ARRAY_BUFFER.
3537 ReportDataCloneError(cx, callbacks, JS_SCERR_TRANSFERABLE, closure);
3538 return false;
3539 }
3540
3541 MOZ_RELEASE_ASSERT(extraData <= ArrayBufferObject::ByteLengthLimit);
3542 size_t nbytes = extraData;
3543
3544 MOZ_ASSERT(data == JS::SCTAG_TMO_ALLOC_DATA ||
3545 data == JS::SCTAG_TMO_MAPPED_DATA);
3546 if (data == JS::SCTAG_TMO_ALLOC_DATA) {
3547 // When the ArrayBuffer can't be allocated, |content| will be free'ed
3548 // in `JSStructuredCloneData::discardTransferables()`.
3549 obj = JS::NewArrayBufferWithContents(
3550 cx, nbytes, content,
3551 JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory);
3552 } else if (data == JS::SCTAG_TMO_MAPPED_DATA) {
3553 obj = JS::NewMappedArrayBufferWithContents(cx, nbytes, content);
3554 }
3555 } else if (tag == SCTAG_TRANSFER_MAP_STORED_ARRAY_BUFFER) {
3556 auto savedPos = in.tell();
3557 auto guard = mozilla::MakeScopeExit([&] { in.seekTo(savedPos); });
3558 in.seekTo(pos);
3559 if (!in.seekBy(static_cast<size_t>(extraData))) {
3560 return false;
3561 }
3562
3563 if (tailStartPos.isNothing()) {
3564 tailStartPos = mozilla::Some(in.tell());
3565 }
3566
3567 uint32_t tag, data;
3568 if (!in.readPair(&tag, &data)) {
3569 return false;
3570 }
3571 if (tag != SCTAG_ARRAY_BUFFER_OBJECT_V2 &&
3572 tag != SCTAG_ARRAY_BUFFER_OBJECT &&
3573 tag != SCTAG_RESIZABLE_ARRAY_BUFFER_OBJECT) {
3574 ReportDataCloneError(cx, callbacks, JS_SCERR_TRANSFERABLE, closure);
3575 return false;
3576 }
3577 RootedValue val(cx);
3578 if (!readArrayBuffer(StructuredDataType(tag), data, &val)) {
3579 return false;
3580 }
3581 obj = &val.toObject();
3582 tailEndPos = mozilla::Some(in.tell());
3583 } else {
3584 if (!callbacks || !callbacks->readTransfer) {
3585 ReportDataCloneError(cx, callbacks, JS_SCERR_TRANSFERABLE, closure);
3586 return false;
3587 }
3588 if (!callbacks->readTransfer(cx, this, cloneDataPolicy, tag, content,
3589 extraData, closure, &obj)) {
3590 if (!cx->isExceptionPending()) {
3591 ReportDataCloneError(cx, callbacks, JS_SCERR_TRANSFERABLE, closure);
3592 }
3593 return false;
3594 }
3595 MOZ_ASSERT(obj);
3596 MOZ_ASSERT(!cx->isExceptionPending());
3597 }
3598
3599 // On failure, the buffer will still own the data (since its ownership
3600 // will not get set to SCTAG_TMO_UNOWNED), so the data will be freed by
3601 // DiscardTransferables.
3602 if (!obj) {
3603 return false;
3604 }
3605
3606 // Mark the SCTAG_TRANSFER_MAP_* entry as no longer owned by the input
3607 // buffer.
3608 pos.write(PairToUInt64(tag, JS::SCTAG_TMO_UNOWNED));
3609 MOZ_ASSERT(!pos.done());
3610
3611 if (!allObjs.append(ObjectValue(*obj))) {
3612 return false;
3613 }
3614 }
3615
3616 // Mark the whole transfer map as consumed.
3617 #ifdef DEBUG
3618 SCInput::getPair(headerPos.peek(), &tag, &data);
3619 MOZ_ASSERT(tag == SCTAG_TRANSFER_MAP_HEADER);
3620 MOZ_ASSERT(TransferableMapHeader(data) == SCTAG_TM_TRANSFERRING);
3621 #endif
3622 headerPos.write(
3623 PairToUInt64(SCTAG_TRANSFER_MAP_HEADER, SCTAG_TM_TRANSFERRED));
3624
3625 return true;
3626 }
3627
3628 JSObject* JSStructuredCloneReader::readSavedFrameHeader(
3629 uint32_t principalsTag) {
3630 Rooted<SavedFrame*> savedFrame(context(), SavedFrame::create(context()));
3631 if (!savedFrame) {
3632 return nullptr;
3633 }
3634
3635 JSPrincipals* principals;
3636 if (principalsTag == SCTAG_JSPRINCIPALS) {
3637 if (!context()->runtime()->readPrincipals) {
3638 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3639 JSMSG_SC_UNSUPPORTED_TYPE);
3640 return nullptr;
3641 }
3642
3643 if (!context()->runtime()->readPrincipals(context(), this, &principals)) {
3644 return nullptr;
3645 }
3646 } else if (principalsTag ==
3647 SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_SYSTEM) {
3648 principals = &ReconstructedSavedFramePrincipals::IsSystem;
3649 principals->refcount++;
3650 } else if (principalsTag ==
3651 SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_NOT_SYSTEM) {
3652 principals = &ReconstructedSavedFramePrincipals::IsNotSystem;
3653 principals->refcount++;
3654 } else if (principalsTag == SCTAG_NULL_JSPRINCIPALS) {
3655 principals = nullptr;
3656 } else {
3657 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3658 JSMSG_SC_BAD_SERIALIZED_DATA,
3659 "bad SavedFrame principals");
3660 return nullptr;
3661 }
3662
3663 RootedValue mutedErrors(context());
3664 RootedValue source(context());
3665 {
3666 // Read a |mutedErrors| boolean followed by a |source| string.
3667 // The |mutedErrors| boolean is present in all new structured-clone data,
3668 // but in older data it will be absent and only the |source| string will be
3669 // found.
3670 if (!startRead(&mutedErrors, AtomizeStrings)) {
3671 return nullptr;
3672 }
3673
3674 if (mutedErrors.isBoolean()) {
3675 if (!startRead(&source, AtomizeStrings) || !source.isString()) {
3676 return nullptr;
3677 }
3678 } else if (mutedErrors.isString()) {
3679 // Backwards compatibility: Handle missing |mutedErrors| boolean,
3680 // this is actually just a |source| string.
3681 source = mutedErrors;
3682 mutedErrors.setBoolean(true); // Safe default value.
3683 } else {
3684 // Invalid type.
3685 return nullptr;
3686 }
3687 }
3688
3689 savedFrame->initPrincipalsAlreadyHeldAndMutedErrors(principals,
3690 mutedErrors.toBoolean());
3691
3692 savedFrame->initSource(&source.toString()->asAtom());
3693
3694 uint32_t line;
3695 if (!readUint32(&line)) {
3696 return nullptr;
3697 }
3698 savedFrame->initLine(line);
3699
3700 JS::TaggedColumnNumberOneOrigin column;
3701 if (!readUint32(column.addressOfValueForTranscode())) {
3702 return nullptr;
3703 }
3704 savedFrame->initColumn(column);
3705
3706 // Don't specify a source ID when reading a cloned saved frame, as these IDs
3707 // are only valid within a specific process.
3708 savedFrame->initSourceId(0);
3709
3710 RootedValue name(context());
3711 if (!startRead(&name, AtomizeStrings)) {
3712 return nullptr;
3713 }
3714 if (!(name.isString() || name.isNull())) {
3715 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3716 JSMSG_SC_BAD_SERIALIZED_DATA,
3717 "invalid saved frame cause");
3718 return nullptr;
3719 }
3720 JSAtom* atomName = nullptr;
3721 if (name.isString()) {
3722 atomName = &name.toString()->asAtom();
3723 }
3724
3725 savedFrame->initFunctionDisplayName(atomName);
3726
3727 RootedValue cause(context());
3728 if (!startRead(&cause, AtomizeStrings)) {
3729 return nullptr;
3730 }
3731 if (!(cause.isString() || cause.isNull())) {
3732 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3733 JSMSG_SC_BAD_SERIALIZED_DATA,
3734 "invalid saved frame cause");
3735 return nullptr;
3736 }
3737 JSAtom* atomCause = nullptr;
3738 if (cause.isString()) {
3739 atomCause = &cause.toString()->asAtom();
3740 }
3741 savedFrame->initAsyncCause(atomCause);
3742
3743 return savedFrame;
3744 }
3745
3746 // SavedFrame object: there is one child value, the parent SavedFrame,
3747 // which is either null or another SavedFrame object.
3748 bool JSStructuredCloneReader::readSavedFrameFields(Handle<SavedFrame*> frameObj,
3749 HandleValue parent,
3750 bool* state) {
3751 if (*state) {
3752 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3753 JSMSG_SC_BAD_SERIALIZED_DATA,
3754 "multiple SavedFrame parents");
3755 return false;
3756 }
3757
3758 SavedFrame* parentFrame;
3759 if (parent.isNull()) {
3760 parentFrame = nullptr;
3761 } else if (parent.isObject() && parent.toObject().is<SavedFrame>()) {
3762 parentFrame = &parent.toObject().as<SavedFrame>();
3763 } else {
3764 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3765 JSMSG_SC_BAD_SERIALIZED_DATA,
3766 "invalid SavedFrame parent");
3767 return false;
3768 }
3769
3770 frameObj->initParent(parentFrame);
3771 *state = true;
3772 return true;
3773 }
3774
3775 JSObject* JSStructuredCloneReader::readErrorHeader(uint32_t type) {
3776 JSContext* cx = context();
3777
3778 switch (type) {
3779 case JSEXN_ERR:
3780 case JSEXN_EVALERR:
3781 case JSEXN_RANGEERR:
3782 case JSEXN_REFERENCEERR:
3783 case JSEXN_SYNTAXERR:
3784 case JSEXN_TYPEERR:
3785 case JSEXN_URIERR:
3786 case JSEXN_AGGREGATEERR:
3787 break;
3788 default:
3789 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3790 JSMSG_SC_BAD_SERIALIZED_DATA,
3791 "invalid error type");
3792 return nullptr;
3793 }
3794
3795 RootedString message(cx);
3796 {
3797 RootedValue messageVal(cx);
3798 if (!startRead(&messageVal)) {
3799 return nullptr;
3800 }
3801 if (messageVal.isString()) {
3802 message = messageVal.toString();
3803 } else if (!messageVal.isNull()) {
3804 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3805 JSMSG_SC_BAD_SERIALIZED_DATA,
3806 "invalid 'message' field for Error object");
3807 return nullptr;
3808 }
3809 }
3810
3811 // We have to set |cause| to something if it exists, otherwise the shape
3812 // would be wrong. The actual value will be overwritten later.
3813 RootedValue val(cx);
3814 if (!startRead(&val)) {
3815 return nullptr;
3816 }
3817 if (!val.isBoolean()) {
3818 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3819 JSMSG_SC_BAD_SERIALIZED_DATA,
3820 "hasCause must be a boolean");
3821 return nullptr;
3822 }
3823 bool hasCause = val.toBoolean();
3824 Rooted<Maybe<Value>> cause(cx, mozilla::Nothing());
3825 if (hasCause) {
3826 cause = mozilla::Some(BooleanValue(true));
3827 }
3828
3829 if (!startRead(&val)) {
3830 return nullptr;
3831 }
3832 if (!val.isString()) {
3833 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3834 JSMSG_SC_BAD_SERIALIZED_DATA,
3835 "invalid 'fileName' field for Error object");
3836 return nullptr;
3837 }
3838 RootedString fileName(cx, val.toString());
3839
3840 uint32_t lineNumber;
3841 JS::ColumnNumberOneOrigin columnNumber;
3842 if (!readUint32(&lineNumber) ||
3843 !readUint32(columnNumber.addressOfValueForTranscode())) {
3844 return nullptr;
3845 }
3846
3847 // The |cause| and |stack| slots of the objects might be overwritten later.
3848 // For AggregateErrors the |errors| property will be added.
3849 RootedObject errorObj(
3850 cx, ErrorObject::create(cx, static_cast<JSExnType>(type), nullptr,
3851 fileName, 0, lineNumber, columnNumber, nullptr,
3852 message, cause));
3853 if (!errorObj) {
3854 return nullptr;
3855 }
3856
3857 return errorObj;
3858 }
3859
3860 // Error objects have 3 fields, some or all of them null: cause,
3861 // errors, and stack.
3862 bool JSStructuredCloneReader::readErrorFields(Handle<ErrorObject*> errorObj,
3863 HandleValue cause, bool* state) {
3864 JSContext* cx = context();
3865 if (*state) {
3866 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3867 JSMSG_SC_BAD_SERIALIZED_DATA,
3868 "unexpected child value seen for Error object");
3869 return false;
3870 }
3871
3872 RootedValue errors(cx);
3873 RootedValue stack(cx);
3874 if (!startRead(&errors) || !startRead(&stack)) {
3875 return false;
3876 }
3877
3878 bool hasCause = errorObj->getCause().isSome();
3879 if (hasCause) {
3880 errorObj->setCauseSlot(cause);
3881 } else if (!cause.isNull()) {
3882 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3883 JSMSG_SC_BAD_SERIALIZED_DATA,
3884 "invalid 'cause' field for Error object");
3885 return false;
3886 }
3887
3888 if (errorObj->type() == JSEXN_AGGREGATEERR) {
3889 if (!errors.isObject() || !errors.toObject().is<ArrayObject>()) {
3890 JS_ReportErrorNumberASCII(
3891 cx, GetErrorMessage, nullptr, JSMSG_SC_BAD_SERIALIZED_DATA,
3892 "AggregateError 'errors' field must be an Array");
3893 return false;
3894 }
3895 if (!DefineDataProperty(context(), errorObj, cx->names().errors, errors,
3896 0)) {
3897 return false;
3898 }
3899 } else if (!errors.isNull()) {
3900 JS_ReportErrorNumberASCII(
3901 cx, GetErrorMessage, nullptr, JSMSG_SC_BAD_SERIALIZED_DATA,
3902 "unexpected 'errors' field seen for non-AggregateError");
3903 return false;
3904 }
3905
3906 if (stack.isObject()) {
3907 RootedObject stackObj(cx, &stack.toObject());
3908 if (!stackObj->is<SavedFrame>()) {
3909 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3910 JSMSG_SC_BAD_SERIALIZED_DATA,
3911 "invalid 'stack' field for Error object");
3912 return false;
3913 }
3914 errorObj->setStackSlot(stack);
3915 } else if (!stack.isNull()) {
3916 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3917 JSMSG_SC_BAD_SERIALIZED_DATA,
3918 "invalid 'stack' field for Error object");
3919 return false;
3920 }
3921
3922 *state = true;
3923 return true;
3924 }
3925
3926 // Read a value and treat as a key,value pair.
3927 bool JSStructuredCloneReader::readMapField(Handle<MapObject*> mapObj,
3928 HandleValue key) {
3929 RootedValue val(context());
3930 if (!startRead(&val)) {
3931 return false;
3932 }
3933 return mapObj->set(context(), key, val);
3934 }
3935
3936 // Read a value and treat as a key,value pair. Interpret as a plain property
3937 // value.
3938 bool JSStructuredCloneReader::readObjectField(HandleObject obj,
3939 HandleValue key) {
3940 if (!key.isString() && !key.isInt32()) {
3941 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
3942 JSMSG_SC_BAD_SERIALIZED_DATA,
3943 "property key expected");
3944 return false;
3945 }
3946
3947 RootedValue val(context());
3948 if (!startRead(&val)) {
3949 return false;
3950 }
3951
3952 RootedId id(context());
3953 if (!PrimitiveValueToId<CanGC>(context(), key, &id)) {
3954 return false;
3955 }
3956
3957 // Fast path for adding a new property to a plain object. The property names
3958 // we see here should be unique, but we check for duplicates to guard against
3959 // corrupt or malicious data.
3960 if (id.isString() && obj->is<PlainObject>() &&
3961 MOZ_LIKELY(!obj->as<PlainObject>().contains(context(), id))) {
3962 return AddDataPropertyToPlainObject(context(), obj.as<PlainObject>(), id,
3963 val);
3964 }
3965
3966 // Fast path for adding an array element. The index shouldn't exceed the
3967 // array's length, but we check for this in `addDenseElementNoLengthChange` to
3968 // guard against corrupt or malicious data.
3969 if (id.isInt() && obj->is<ArrayObject>()) {
3970 ArrayObject* arr = &obj->as<ArrayObject>();
3971 switch (arr->addDenseElementNoLengthChange(context(), id.toInt(), val)) {
3972 case DenseElementResult::Failure:
3973 return false;
3974 case DenseElementResult::Success:
3975 return true;
3976 case DenseElementResult::Incomplete:
3977 // Fall-through to slow path.
3978 break;
3979 }
3980 }
3981
3982 return DefineDataProperty(context(), obj, id, val);
3983 }
3984
3985 // Perform the whole recursive reading procedure.
3986 bool JSStructuredCloneReader::read(MutableHandleValue vp, size_t nbytes) {
3987 if (!readHeader()) {
3988 return false;
3989 }
3990 MOZ_ASSERT(allowedScope <= JS::StructuredCloneScope::LastResolvedScope,
3991 "allowedScope should have been resolved by now");
3992
3993 if (!readTransferMap()) {
3994 return false;
3995 }
3996
3997 MOZ_ASSERT(objs.length() == 0);
3998 MOZ_ASSERT(objState.length() == 1);
3999
4000 // Start out by reading in the main object and pushing it onto the 'objs'
4001 // stack. The data related to this object and its descendants extends from
4002 // here to the SCTAG_END_OF_KEYS at the end of the stream.
4003 if (!startRead(vp)) {
4004 return false;
4005 }
4006
4007 // Stop when the stack shows that all objects have been read.
4008 while (objs.length() != 0) {
4009 // What happens depends on the top obj on the objs stack.
4010 RootedObject obj(context(), &objs.back().toObject());
4011
4012 uint32_t tag, data;
4013 if (!in.getPair(&tag, &data)) {
4014 return false;
4015 }
4016
4017 if (tag == SCTAG_END_OF_KEYS) {
4018 // Pop the current obj off the stack, since we are done with it and
4019 // its children.
4020 MOZ_ALWAYS_TRUE(in.readPair(&tag, &data));
4021 objs.popBack();
4022 if (objState.back().first == obj) {
4023 objState.popBack();
4024 }
4025 continue;
4026 }
4027
4028 // Remember the index of the current top of the state stack, which will
4029 // correspond to the state for `obj` iff `obj` is a type that uses state.
4030 // startRead() may push additional entries before the state is accessed and
4031 // updated while filling in the object's data.
4032 size_t objStateIdx = objState.length() - 1;
4033
4034 // The input stream contains a sequence of "child" values, whose
4035 // interpretation depends on the type of obj. These values can be
4036 // anything, and startRead() will push onto 'objs' for any non-leaf
4037 // value (i.e., anything that may contain children).
4038 //
4039 // startRead() will allocate the (empty) object, but note that when
4040 // startRead() returns, 'key' is not yet initialized with any of its
4041 // properties. Those will be filled in by returning to the head of this
4042 // loop, processing the first child obj, and continuing until all
4043 // children have been fully created.
4044 //
4045 // Note that this means the ordering in the stream is a little funky for
4046 // things like Map. See the comment above traverseMap() for an example.
4047
4048 bool expectKeyValuePairs =
4049 !(obj->is<MapObject>() || obj->is<SetObject>() ||
4050 obj->is<SavedFrame>() || obj->is<ErrorObject>());
4051
4052 RootedValue key(context());
4053 ShouldAtomizeStrings atomize =
4054 expectKeyValuePairs ? AtomizeStrings : DontAtomizeStrings;
4055 if (!startRead(&key, atomize)) {
4056 return false;
4057 }
4058
4059 if (key.isNull() && expectKeyValuePairs) {
4060 // Backwards compatibility: Null formerly indicated the end of
4061 // object properties.
4062
4063 // No legacy objects used the state stack.
4064 MOZ_ASSERT(objState[objStateIdx].first() != obj);
4065
4066 objs.popBack();
4067 continue;
4068 }
4069
4070 context()->check(key);
4071
4072 if (obj->is<SetObject>()) {
4073 // Set object: the values between obj header (from startRead()) and
4074 // SCTAG_END_OF_KEYS are all interpreted as values to add to the set.
4075 if (!obj->as<SetObject>().add(context(), key)) {
4076 return false;
4077 }
4078 } else if (obj->is<MapObject>()) {
4079 Rooted<MapObject*> mapObj(context(), &obj->as<MapObject>());
4080 if (!readMapField(mapObj, key)) {
4081 return false;
4082 }
4083 } else if (obj->is<SavedFrame>()) {
4084 Rooted<SavedFrame*> frameObj(context(), &obj->as<SavedFrame>());
4085 MOZ_ASSERT(objState[objStateIdx].first() == obj);
4086 bool state = objState[objStateIdx].second();
4087 if (!readSavedFrameFields(frameObj, key, &state)) {
4088 return false;
4089 }
4090 objState[objStateIdx].second() = state;
4091 } else if (obj->is<ErrorObject>()) {
4092 Rooted<ErrorObject*> errorObj(context(), &obj->as<ErrorObject>());
4093 MOZ_ASSERT(objState[objStateIdx].first() == obj);
4094 bool state = objState[objStateIdx].second();
4095 if (!readErrorFields(errorObj, key, &state)) {
4096 return false;
4097 }
4098 objState[objStateIdx].second() = state;
4099 } else {
4100 MOZ_ASSERT(expectKeyValuePairs);
4101 // Everything else uses a series of key,value,key,value,... Value
4102 // objects.
4103 if (!readObjectField(obj, key)) {
4104 return false;
4105 }
4106 }
4107 }
4108
4109 allObjs.clear();
4110
4111 // For fuzzing, it is convenient to allow extra data at the end
4112 // of the input buffer so that more possible inputs are considered
4113 // valid.
4114 #ifndef FUZZING
4115 bool extraData;
4116 if (tailStartPos.isSome()) {
4117 // in.tell() is the end of the main data. If "tail" data was consumed,
4118 // then check whether there's any data between the main data and the
4119 // beginning of the tail, or after the last read point in the tail.
4120 extraData = (in.tell() != *tailStartPos || !tailEndPos->done());
4121 } else {
4122 extraData = !in.tell().done();
4123 }
4124 if (extraData) {
4125 JS_ReportErrorNumberASCII(context(), GetErrorMessage, nullptr,
4126 JSMSG_SC_BAD_SERIALIZED_DATA,
4127 "extra data after end");
4128 return false;
4129 }
4130 #endif
4131 return true;
4132 }
4133
4134 JS_PUBLIC_API bool JS_ReadStructuredClone(
4135 JSContext* cx, const JSStructuredCloneData& buf, uint32_t version,
4136 JS::StructuredCloneScope scope, MutableHandleValue vp,
4137 const JS::CloneDataPolicy& cloneDataPolicy,
4138 const JSStructuredCloneCallbacks* optionalCallbacks, void* closure) {
4139 AssertHeapIsIdle();
4140 CHECK_THREAD(cx);
4141
4142 if (version > JS_STRUCTURED_CLONE_VERSION) {
4143 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4144 JSMSG_SC_BAD_CLONE_VERSION);
4145 return false;
4146 }
4147 const JSStructuredCloneCallbacks* callbacks = optionalCallbacks;
4148 return ReadStructuredClone(cx, buf, scope, vp, cloneDataPolicy, callbacks,
4149 closure);
4150 }
4151
4152 JS_PUBLIC_API bool JS_WriteStructuredClone(
4153 JSContext* cx, HandleValue value, JSStructuredCloneData* bufp,
4154 JS::StructuredCloneScope scope, const JS::CloneDataPolicy& cloneDataPolicy,
4155 const JSStructuredCloneCallbacks* optionalCallbacks, void* closure,
4156 HandleValue transferable) {
4157 AssertHeapIsIdle();
4158 CHECK_THREAD(cx);
4159 cx->check(value);
4160
4161 const JSStructuredCloneCallbacks* callbacks = optionalCallbacks;
4162 return WriteStructuredClone(cx, value, bufp, scope, cloneDataPolicy,
4163 callbacks, closure, transferable);
4164 }
4165
4166 JS_PUBLIC_API bool JS_StructuredCloneHasTransferables(
4167 JSStructuredCloneData& data, bool* hasTransferable) {
4168 *hasTransferable = StructuredCloneHasTransferObjects(data);
4169 return true;
4170 }
4171
4172 JS_PUBLIC_API bool JS_StructuredClone(
4173 JSContext* cx, HandleValue value, MutableHandleValue vp,
4174 const JSStructuredCloneCallbacks* optionalCallbacks, void* closure) {
4175 AssertHeapIsIdle();
4176 CHECK_THREAD(cx);
4177
4178 // Strings are associated with zones, not compartments,
4179 // so we copy the string by wrapping it.
4180 if (value.isString()) {
4181 RootedString strValue(cx, value.toString());
4182 if (!cx->compartment()->wrap(cx, &strValue)) {
4183 return false;
4184 }
4185 vp.setString(strValue);
4186 return true;
4187 }
4188
4189 const JSStructuredCloneCallbacks* callbacks = optionalCallbacks;
4190
4191 JSAutoStructuredCloneBuffer buf(JS::StructuredCloneScope::SameProcess,
4192 callbacks, closure);
4193 {
4194 if (value.isObject()) {
4195 RootedObject obj(cx, &value.toObject());
4196 obj = CheckedUnwrapStatic(obj);
4197 if (!obj) {
4198 ReportAccessDenied(cx);
4199 return false;
4200 }
4201 AutoRealm ar(cx, obj);
4202 RootedValue unwrappedVal(cx, ObjectValue(*obj));
4203 if (!buf.write(cx, unwrappedVal, callbacks, closure)) {
4204 return false;
4205 }
4206 } else {
4207 if (!buf.write(cx, value, callbacks, closure)) {
4208 return false;
4209 }
4210 }
4211 }
4212
4213 return buf.read(cx, vp, JS::CloneDataPolicy(), callbacks, closure);
4214 }
4215
4216 JSAutoStructuredCloneBuffer::JSAutoStructuredCloneBuffer(
4217 JSAutoStructuredCloneBuffer&& other)
4218 : data_(other.scope()) {
4219 version_ = other.version_;
4220 other.giveTo(&data_);
4221 }
4222
4223 JSAutoStructuredCloneBuffer& JSAutoStructuredCloneBuffer::operator=(
4224 JSAutoStructuredCloneBuffer&& other) {
4225 MOZ_ASSERT(&other != this);
4226 MOZ_ASSERT(scope() == other.scope());
4227 clear();
4228 version_ = other.version_;
4229 other.giveTo(&data_);
4230 return *this;
4231 }
4232
4233 void JSAutoStructuredCloneBuffer::clear() {
4234 data_.discardTransferables();
4235 data_.ownTransferables_ = OwnTransferablePolicy::NoTransferables;
4236 data_.refsHeld_.releaseAll();
4237 data_.stringBufferRefsHeld_.clear();
4238 data_.Clear();
4239 version_ = 0;
4240 }
4241
4242 void JSAutoStructuredCloneBuffer::adopt(
4243 JSStructuredCloneData&& data, uint32_t version,
4244 const JSStructuredCloneCallbacks* callbacks, void* closure) {
4245 clear();
4246 data_ = std::move(data);
4247 version_ = version;
4248 data_.setCallbacks(callbacks, closure,
4249 OwnTransferablePolicy::OwnsTransferablesIfAny);
4250 }
4251
4252 void JSAutoStructuredCloneBuffer::giveTo(JSStructuredCloneData* data) {
4253 *data = std::move(data_);
4254 version_ = 0;
4255 data_.setCallbacks(nullptr, nullptr, OwnTransferablePolicy::NoTransferables);
4256 data_.Clear();
4257 }
4258
4259 bool JSAutoStructuredCloneBuffer::read(
4260 JSContext* cx, MutableHandleValue vp,
4261 const JS::CloneDataPolicy& cloneDataPolicy,
4262 const JSStructuredCloneCallbacks* optionalCallbacks, void* closure) {
4263 MOZ_ASSERT(cx);
4264 return !!JS_ReadStructuredClone(
4265 cx, data_, version_, data_.scope(), vp, cloneDataPolicy,
4266 optionalCallbacks ? optionalCallbacks : data_.callbacks_,
4267 optionalCallbacks ? closure : data_.closure_);
4268 }
4269
4270 bool JSAutoStructuredCloneBuffer::write(
4271 JSContext* cx, HandleValue value,
4272 const JSStructuredCloneCallbacks* optionalCallbacks, void* closure) {
4273 HandleValue transferable = UndefinedHandleValue;
4274 return write(cx, value, transferable, JS::CloneDataPolicy(),
4275 optionalCallbacks ? optionalCallbacks : data_.callbacks_,
4276 optionalCallbacks ? closure : data_.closure_);
4277 }
4278
4279 bool JSAutoStructuredCloneBuffer::write(
4280 JSContext* cx, HandleValue value, HandleValue transferable,
4281 const JS::CloneDataPolicy& cloneDataPolicy,
4282 const JSStructuredCloneCallbacks* optionalCallbacks, void* closure) {
4283 clear();
4284 bool ok = JS_WriteStructuredClone(
4285 cx, value, &data_, data_.scopeForInternalWriting(), cloneDataPolicy,
4286 optionalCallbacks ? optionalCallbacks : data_.callbacks_,
4287 optionalCallbacks ? closure : data_.closure_, transferable);
4288 if (!ok) {
4289 version_ = JS_STRUCTURED_CLONE_VERSION;
4290 }
4291 return ok;
4292 }
4293
4294 JS_PUBLIC_API bool JS_ReadUint32Pair(JSStructuredCloneReader* r, uint32_t* p1,
4295 uint32_t* p2) {
4296 return r->input().readPair((uint32_t*)p1, (uint32_t*)p2);
4297 }
4298
4299 JS_PUBLIC_API bool JS_ReadBytes(JSStructuredCloneReader* r, void* p,
4300 size_t len) {
4301 return r->input().readBytes(p, len);
4302 }
4303
4304 JS_PUBLIC_API bool JS_ReadString(JSStructuredCloneReader* r,
4305 MutableHandleString str) {
4306 uint32_t tag, data;
4307 if (!r->input().readPair(&tag, &data)) {
4308 return false;
4309 }
4310
4311 if (tag == SCTAG_STRING) {
4312 if (JSString* s =
4313 r->readString(data, JSStructuredCloneReader::DontAtomizeStrings)) {
4314 str.set(s);
4315 return true;
4316 }
4317 return false;
4318 }
4319
4320 JS_ReportErrorNumberASCII(r->context(), GetErrorMessage, nullptr,
4321 JSMSG_SC_BAD_SERIALIZED_DATA, "expected string");
4322 return false;
4323 }
4324
4325 JS_PUBLIC_API bool JS_ReadDouble(JSStructuredCloneReader* r, double* v) {
4326 return r->input().readDouble(v);
4327 }
4328
4329 JS_PUBLIC_API bool JS_ReadTypedArray(JSStructuredCloneReader* r,
4330 MutableHandleValue vp) {
4331 uint32_t tag, data;
4332 if (!r->input().readPair(&tag, &data)) {
4333 return false;
4334 }
4335
4336 if (tag >= SCTAG_TYPED_ARRAY_V1_MIN && tag <= SCTAG_TYPED_ARRAY_V1_MAX) {
4337 return r->readTypedArray(TagToV1ArrayType(tag), data, vp, true);
4338 }
4339
4340 if (tag == SCTAG_TYPED_ARRAY_OBJECT_V2) {
4341 // V2 stores the length (nelems) in |data| and the arrayType separately.
4342 uint64_t arrayType;
4343 if (!r->input().read(&arrayType)) {
4344 return false;
4345 }
4346 uint64_t nelems = data;
4347 return r->readTypedArray(arrayType, nelems, vp);
4348 }
4349
4350 if (tag == SCTAG_TYPED_ARRAY_OBJECT) {
4351 // The current version stores the array type in |data| and the length
4352 // (nelems) separately to support large TypedArrays.
4353 uint32_t arrayType = data;
4354 uint64_t nelems;
4355 if (!r->input().read(&nelems)) {
4356 return false;
4357 }
4358 return r->readTypedArray(arrayType, nelems, vp);
4359 }
4360
4361 JS_ReportErrorNumberASCII(r->context(), GetErrorMessage, nullptr,
4362 JSMSG_SC_BAD_SERIALIZED_DATA,
4363 "expected type array");
4364 return false;
4365 }
4366
4367 JS_PUBLIC_API bool JS_WriteUint32Pair(JSStructuredCloneWriter* w, uint32_t tag,
4368 uint32_t data) {
4369 return w->output().writePair(tag, data);
4370 }
4371
4372 JS_PUBLIC_API bool JS_WriteBytes(JSStructuredCloneWriter* w, const void* p,
4373 size_t len) {
4374 return w->output().writeBytes(p, len);
4375 }
4376
4377 JS_PUBLIC_API bool JS_WriteString(JSStructuredCloneWriter* w,
4378 HandleString str) {
4379 return w->writeString(SCTAG_STRING, str);
4380 }
4381
4382 JS_PUBLIC_API bool JS_WriteDouble(JSStructuredCloneWriter* w, double v) {
4383 return w->output().writeDouble(v);
4384 }
4385
4386 JS_PUBLIC_API bool JS_WriteTypedArray(JSStructuredCloneWriter* w,
4387 HandleValue v) {
4388 MOZ_ASSERT(v.isObject());
4389 w->context()->check(v);
4390 RootedObject obj(w->context(), &v.toObject());
4391
4392 // startWrite can write everything, thus we should check here
4393 // and report error if the user passes a wrong type.
4394 if (!obj->canUnwrapAs<TypedArrayObject>()) {
4395 ReportAccessDenied(w->context());
4396 return false;
4397 }
4398
4399 // We should use startWrite instead of writeTypedArray, because
4400 // typed array is an object, we should add it to the |memory|
4401 // (allObjs) list. Directly calling writeTypedArray won't add it.
4402 return w->startWrite(v);
4403 }
4404
4405 JS_PUBLIC_API bool JS_ObjectNotWritten(JSStructuredCloneWriter* w,
4406 HandleObject obj) {
4407 w->memory.remove(w->memory.lookup(obj));
4408
4409 return true;
4410 }
4411
4412 JS_PUBLIC_API JS::StructuredCloneScope JS_GetStructuredCloneScope(
4413 JSStructuredCloneWriter* w) {
4414 return w->output().scope();
4415 }