-
Notifications
You must be signed in to change notification settings - Fork 54
/
StructuredClone.cpp
3380 lines (2865 loc) · 100 KB
/
StructuredClone.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* This file implements the structured data algorithms of
* https://html.spec.whatwg.org/multipage/structured-data.html
*
* The spec is in two parts:
*
* - StructuredSerialize examines a JS value and produces a graph of Records.
* - StructuredDeserialize walks the Records and produces a new JS value.
*
* The differences between our implementation and the spec are minor:
*
* - We call the two phases "write" and "read".
* - Our algorithms use an explicit work stack, rather than recursion.
* - Serialized data is a flat array of bytes, not a (possibly cyclic) graph
* of "Records".
* - As a consequence, we handle non-treelike object graphs differently.
* We serialize objects that appear in multiple places in the input as
* backreferences, using sequential integer indexes.
* See `JSStructuredCloneReader::allObjs`, our take on the "memory" map
* in the spec's StructuredDeserialize.
*/
#include "js/StructuredClone.h"
#include "mozilla/Casting.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/RangedPtr.h"
#include "mozilla/Unused.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "jsapi.h"
#include "jsdate.h"
#include "builtin/DataViewObject.h"
#include "builtin/MapObject.h"
#include "js/Array.h" // JS::GetArrayLength, JS::IsArrayObject
#include "js/ArrayBuffer.h" // JS::{ArrayBufferHasData,DetachArrayBuffer,IsArrayBufferObject,New{,Mapped}ArrayBufferWithContents,ReleaseMappedArrayBufferContents}
#include "js/Date.h"
#include "js/GCHashTable.h"
#include "js/RegExpFlags.h" // JS::RegExpFlag, JS::RegExpFlags
#include "js/SharedArrayBuffer.h" // JS::IsSharedArrayBufferObject
#include "js/Wrapper.h"
#include "vm/BigIntType.h"
#include "vm/JSContext.h"
#include "vm/RegExpObject.h"
#include "vm/SavedFrame.h"
#include "vm/SharedArrayObject.h"
#include "vm/TypedArrayObject.h"
#include "vm/WrapperObject.h"
#include "wasm/WasmJS.h"
#include "vm/InlineCharBuffer-inl.h"
#include "vm/JSContext-inl.h"
#include "vm/JSObject-inl.h"
using namespace js;
using JS::CanonicalizeNaN;
using JS::RegExpFlag;
using JS::RegExpFlags;
using JS::RootedValueVector;
using mozilla::AssertedCast;
using mozilla::BitwiseCast;
using mozilla::NativeEndian;
using mozilla::NumbersAreIdentical;
using mozilla::RangedPtr;
// When you make updates here, make sure you consider whether you need to bump
// the value of JS_STRUCTURED_CLONE_VERSION in js/public/StructuredClone.h. You
// will likely need to increment the version if anything at all changes in the
// serialization format.
//
// Note that SCTAG_END_OF_KEYS is written into the serialized form and should
// have a stable ID, it need not be at the end of the list and should not be
// used for sizing data structures.
enum StructuredDataType : uint32_t {
// Structured data types provided by the engine
SCTAG_FLOAT_MAX = 0xFFF00000,
SCTAG_HEADER = 0xFFF10000,
SCTAG_NULL = 0xFFFF0000,
SCTAG_UNDEFINED,
SCTAG_BOOLEAN,
SCTAG_INT32,
SCTAG_STRING,
SCTAG_DATE_OBJECT,
SCTAG_REGEXP_OBJECT,
SCTAG_ARRAY_OBJECT,
SCTAG_OBJECT_OBJECT,
SCTAG_ARRAY_BUFFER_OBJECT,
SCTAG_BOOLEAN_OBJECT,
SCTAG_STRING_OBJECT,
SCTAG_NUMBER_OBJECT,
SCTAG_BACK_REFERENCE_OBJECT,
SCTAG_DO_NOT_USE_1, // Required for backwards compatibility
SCTAG_DO_NOT_USE_2, // Required for backwards compatibility
SCTAG_TYPED_ARRAY_OBJECT,
SCTAG_MAP_OBJECT,
SCTAG_SET_OBJECT,
SCTAG_END_OF_KEYS,
SCTAG_DO_NOT_USE_3, // Required for backwards compatibility
SCTAG_DATA_VIEW_OBJECT,
SCTAG_SAVED_FRAME_OBJECT,
// No new tags before principals.
SCTAG_JSPRINCIPALS,
SCTAG_NULL_JSPRINCIPALS,
SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_SYSTEM,
SCTAG_RECONSTRUCTED_SAVED_FRAME_PRINCIPALS_IS_NOT_SYSTEM,
SCTAG_SHARED_ARRAY_BUFFER_OBJECT,
SCTAG_SHARED_WASM_MEMORY_OBJECT,
SCTAG_BIGINT,
SCTAG_BIGINT_OBJECT,
SCTAG_TYPED_ARRAY_V1_MIN = 0xFFFF0100,
SCTAG_TYPED_ARRAY_V1_INT8 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Int8,
SCTAG_TYPED_ARRAY_V1_UINT8 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint8,
SCTAG_TYPED_ARRAY_V1_INT16 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Int16,
SCTAG_TYPED_ARRAY_V1_UINT16 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint16,
SCTAG_TYPED_ARRAY_V1_INT32 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Int32,
SCTAG_TYPED_ARRAY_V1_UINT32 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint32,
SCTAG_TYPED_ARRAY_V1_FLOAT32 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Float32,
SCTAG_TYPED_ARRAY_V1_FLOAT64 = SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Float64,
SCTAG_TYPED_ARRAY_V1_UINT8_CLAMPED =
SCTAG_TYPED_ARRAY_V1_MIN + Scalar::Uint8Clamped,
// BigInt64 and BigUint64 are not supported in the v1 format.
SCTAG_TYPED_ARRAY_V1_MAX = SCTAG_TYPED_ARRAY_V1_UINT8_CLAMPED,
// Define a separate range of numbers for Transferable-only tags, since
// they are not used for persistent clone buffers and therefore do not
// require bumping JS_STRUCTURED_CLONE_VERSION.
SCTAG_TRANSFER_MAP_HEADER = 0xFFFF0200,
SCTAG_TRANSFER_MAP_PENDING_ENTRY,
SCTAG_TRANSFER_MAP_ARRAY_BUFFER,
SCTAG_TRANSFER_MAP_STORED_ARRAY_BUFFER,
SCTAG_TRANSFER_MAP_END_OF_BUILTIN_TYPES,
SCTAG_END_OF_BUILTIN_TYPES
};
/*
* Format of transfer map:
* <SCTAG_TRANSFER_MAP_HEADER, TransferableMapHeader(UNREAD|TRANSFERRED)>
* numTransferables (64 bits)
* array of:
* <SCTAG_TRANSFER_MAP_*, TransferableOwnership>
* pointer (64 bits)
* extraData (64 bits), eg byte length for ArrayBuffers
*/
// Data associated with an SCTAG_TRANSFER_MAP_HEADER that tells whether the
// contents have been read out yet or not.
enum TransferableMapHeader { SCTAG_TM_UNREAD = 0, SCTAG_TM_TRANSFERRED };
static inline uint64_t PairToUInt64(uint32_t tag, uint32_t data) {
return uint64_t(data) | (uint64_t(tag) << 32);
}
namespace js {
template <typename T, typename AllocPolicy>
struct BufferIterator {
using BufferList = mozilla::BufferList<AllocPolicy>;
explicit BufferIterator(const BufferList& buffer)
: mBuffer(buffer), mIter(buffer.Iter()) {
static_assert(8 % sizeof(T) == 0);
}
explicit BufferIterator(const JSStructuredCloneData& data)
: mBuffer(data.bufList_), mIter(data.Start()) {}
BufferIterator& operator=(const BufferIterator& other) {
MOZ_ASSERT(&mBuffer == &other.mBuffer);
mIter = other.mIter;
return *this;
}
BufferIterator operator++(int) {
BufferIterator ret = *this;
if (!mIter.AdvanceAcrossSegments(mBuffer, sizeof(T))) {
MOZ_ASSERT(false, "Failed to read StructuredCloneData. Data incomplete");
}
return ret;
}
BufferIterator& operator+=(size_t size) {
if (!mIter.AdvanceAcrossSegments(mBuffer, size)) {
MOZ_ASSERT(false, "Failed to read StructuredCloneData. Data incomplete");
}
return *this;
}
size_t operator-(const BufferIterator& other) {
MOZ_ASSERT(&mBuffer == &other.mBuffer);
return mBuffer.RangeLength(other.mIter, mIter);
}
void next() {
if (!mIter.AdvanceAcrossSegments(mBuffer, sizeof(T))) {
MOZ_ASSERT(false, "Failed to read StructuredCloneData. Data incomplete");
}
}
bool done() const { return mIter.Done(); }
MOZ_MUST_USE bool readBytes(char* outData, size_t size) {
return mBuffer.ReadBytes(mIter, outData, size);
}
void write(const T& data) {
MOZ_ASSERT(mIter.HasRoomFor(sizeof(T)));
*reinterpret_cast<T*>(mIter.Data()) = data;
}
T peek() const {
MOZ_ASSERT(mIter.HasRoomFor(sizeof(T)));
return *reinterpret_cast<T*>(mIter.Data());
}
bool canPeek() const { return mIter.HasRoomFor(sizeof(T)); }
const BufferList& mBuffer;
typename BufferList::IterImpl mIter;
};
SharedArrayRawBufferRefs& SharedArrayRawBufferRefs::operator=(
SharedArrayRawBufferRefs&& other) {
takeOwnership(std::move(other));
return *this;
}
SharedArrayRawBufferRefs::~SharedArrayRawBufferRefs() { releaseAll(); }
bool SharedArrayRawBufferRefs::acquire(JSContext* cx,
SharedArrayRawBuffer* rawbuf) {
if (!refs_.append(rawbuf)) {
ReportOutOfMemory(cx);
return false;
}
if (!rawbuf->addReference()) {
refs_.popBack();
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_SC_SAB_REFCNT_OFLO);
return false;
}
return true;
}
bool SharedArrayRawBufferRefs::acquireAll(
JSContext* cx, const SharedArrayRawBufferRefs& that) {
if (!refs_.reserve(refs_.length() + that.refs_.length())) {
ReportOutOfMemory(cx);
return false;
}
for (auto ref : that.refs_) {
if (!ref->addReference()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_SC_SAB_REFCNT_OFLO);
return false;
}
MOZ_ALWAYS_TRUE(refs_.append(ref));
}
return true;
}
void SharedArrayRawBufferRefs::takeOwnership(SharedArrayRawBufferRefs&& other) {
MOZ_ASSERT(refs_.empty());
refs_ = std::move(other.refs_);
}
void SharedArrayRawBufferRefs::releaseAll() {
for (auto ref : refs_) {
ref->dropReference();
}
refs_.clear();
}
// SCOutput provides an interface to write raw data -- eg uint64_ts, doubles,
// arrays of bytes -- into a structured clone data output stream. It also knows
// how to free any transferable data within that stream.
//
// Note that it contains a full JSStructuredCloneData object, which holds the
// callbacks necessary to read/write/transfer/free the data. For the purpose of
// this class, only the freeTransfer callback is relevant; the rest of the
// callbacks are used by the higher-level JSStructuredCloneWriter interface.
struct SCOutput {
public:
using Iter = BufferIterator<uint64_t, SystemAllocPolicy>;
SCOutput(JSContext* cx, JS::StructuredCloneScope scope);
JSContext* context() const { return cx; }
JS::StructuredCloneScope scope() const { return buf.scope(); }
void sameProcessScopeRequired() { buf.sameProcessScopeRequired(); }
MOZ_MUST_USE bool write(uint64_t u);
MOZ_MUST_USE bool writePair(uint32_t tag, uint32_t data);
MOZ_MUST_USE bool writeDouble(double d);
MOZ_MUST_USE bool writeBytes(const void* p, size_t nbytes);
MOZ_MUST_USE bool writeChars(const Latin1Char* p, size_t nchars);
MOZ_MUST_USE bool writeChars(const char16_t* p, size_t nchars);
template <class T>
MOZ_MUST_USE bool writeArray(const T* p, size_t nelems);
void setCallbacks(const JSStructuredCloneCallbacks* callbacks, void* closure,
OwnTransferablePolicy policy) {
buf.setCallbacks(callbacks, closure, policy);
}
void extractBuffer(JSStructuredCloneData* data) { *data = std::move(buf); }
void discardTransferables();
uint64_t tell() const { return buf.Size(); }
uint64_t count() const { return buf.Size() / sizeof(uint64_t); }
Iter iter() { return Iter(buf); }
size_t offset(Iter dest) { return dest - iter(); }
JSContext* cx;
JSStructuredCloneData buf;
};
class SCInput {
typedef js::BufferIterator<uint64_t, SystemAllocPolicy> BufferIterator;
public:
SCInput(JSContext* cx, const JSStructuredCloneData& data);
JSContext* context() const { return cx; }
static void getPtr(uint64_t data, void** ptr);
static void getPair(uint64_t data, uint32_t* tagp, uint32_t* datap);
MOZ_MUST_USE bool read(uint64_t* p);
MOZ_MUST_USE bool readPair(uint32_t* tagp, uint32_t* datap);
MOZ_MUST_USE bool readDouble(double* p);
MOZ_MUST_USE bool readBytes(void* p, size_t nbytes);
MOZ_MUST_USE bool readChars(Latin1Char* p, size_t nchars);
MOZ_MUST_USE bool readChars(char16_t* p, size_t nchars);
MOZ_MUST_USE bool readPtr(void**);
MOZ_MUST_USE bool get(uint64_t* p);
MOZ_MUST_USE bool getPair(uint32_t* tagp, uint32_t* datap);
const BufferIterator& tell() const { return point; }
void seekTo(const BufferIterator& pos) { point = pos; }
void seekBy(size_t pos) { point += pos; }
template <class T>
MOZ_MUST_USE bool readArray(T* p, size_t nelems);
bool reportTruncated() {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_SC_BAD_SERIALIZED_DATA, "truncated");
return false;
}
private:
void staticAssertions() {
static_assert(sizeof(char16_t) == 2);
static_assert(sizeof(uint32_t) == 4);
}
JSContext* cx;
BufferIterator point;
};
} // namespace js
struct JSStructuredCloneReader {
public:
explicit JSStructuredCloneReader(SCInput& in, JS::StructuredCloneScope scope,
const JS::CloneDataPolicy& cloneDataPolicy,
const JSStructuredCloneCallbacks* cb,
void* cbClosure)
: in(in),
allowedScope(scope),
cloneDataPolicy(cloneDataPolicy),
objs(in.context()),
allObjs(in.context()),
callbacks(cb),
closure(cbClosure) {}
SCInput& input() { return in; }
bool read(MutableHandleValue vp);
private:
JSContext* context() { return in.context(); }
bool readHeader();
bool readTransferMap();
template <typename CharT>
JSString* readStringImpl(uint32_t nchars);
JSString* readString(uint32_t data);
BigInt* readBigInt(uint32_t data);
MOZ_MUST_USE bool readTypedArray(uint32_t arrayType, uint32_t nelems,
MutableHandleValue vp, bool v1Read = false);
MOZ_MUST_USE bool readDataView(uint32_t byteLength, MutableHandleValue vp);
MOZ_MUST_USE bool readArrayBuffer(uint32_t nbytes, MutableHandleValue vp);
MOZ_MUST_USE bool readSharedArrayBuffer(MutableHandleValue vp);
MOZ_MUST_USE bool readSharedWasmMemory(uint32_t nbytes,
MutableHandleValue vp);
MOZ_MUST_USE bool readV1ArrayBuffer(uint32_t arrayType, uint32_t nelems,
MutableHandleValue vp);
JSObject* readSavedFrame(uint32_t principalsTag);
MOZ_MUST_USE bool startRead(MutableHandleValue vp);
SCInput& in;
// The widest scope that the caller will accept, where
// SameProcess is the widest (it can store anything it wants)
// and DifferentProcess is the narrowest (it cannot contain pointers and must
// be valid cross-process.)
JS::StructuredCloneScope allowedScope;
const JS::CloneDataPolicy cloneDataPolicy;
// Stack of objects with properties remaining to be read.
RootedValueVector objs;
// Array of all objects read during this deserialization, for resolving
// backreferences.
//
// For backreferences to work correctly, objects must be added to this
// array in exactly the order expected by the version of the Writer that
// created the serialized data, even across years and format versions. This
// is usually no problem, since both algorithms do a single linear pass
// over the serialized data. There is one hitch; see readTypedArray.
//
// The values in this vector are objects, except it can temporarily have
// one `undefined` placeholder value (the readTypedArray hack).
RootedValueVector allObjs;
// The user defined callbacks that will be used for cloning.
const JSStructuredCloneCallbacks* callbacks;
// Any value passed to JS_ReadStructuredClone.
void* closure;
friend bool JS_ReadTypedArray(JSStructuredCloneReader* r,
MutableHandleValue vp);
};
struct JSStructuredCloneWriter {
public:
explicit JSStructuredCloneWriter(JSContext* cx,
JS::StructuredCloneScope scope,
const JS::CloneDataPolicy& cloneDataPolicy,
const JSStructuredCloneCallbacks* cb,
void* cbClosure, const Value& tVal)
: out(cx, scope),
callbacks(cb),
closure(cbClosure),
objs(out.context()),
counts(out.context()),
objectEntries(out.context()),
otherEntries(out.context()),
memory(out.context()),
transferable(out.context(), tVal),
transferableObjects(out.context(), TransferableObjectsSet(cx)),
cloneDataPolicy(cloneDataPolicy) {
out.setCallbacks(cb, cbClosure, OwnTransferablePolicy::NoTransferables);
}
~JSStructuredCloneWriter();
bool init() {
return parseTransferable() && writeHeader() && writeTransferMap();
}
bool write(HandleValue v);
SCOutput& output() { return out; }
void extractBuffer(JSStructuredCloneData* newData) {
out.extractBuffer(newData);
}
private:
JSStructuredCloneWriter() = delete;
JSStructuredCloneWriter(const JSStructuredCloneWriter&) = delete;
JSContext* context() { return out.context(); }
bool writeHeader();
bool writeTransferMap();
bool writeString(uint32_t tag, JSString* str);
bool writeBigInt(uint32_t tag, BigInt* bi);
bool writeArrayBuffer(HandleObject obj);
bool writeTypedArray(HandleObject obj);
bool writeDataView(HandleObject obj);
bool writeSharedArrayBuffer(HandleObject obj);
bool writeSharedWasmMemory(HandleObject obj);
bool startObject(HandleObject obj, bool* backref);
bool startWrite(HandleValue v);
bool traverseObject(HandleObject obj, ESClass cls);
bool traverseMap(HandleObject obj);
bool traverseSet(HandleObject obj);
bool traverseSavedFrame(HandleObject obj);
template <typename... Args>
bool reportDataCloneError(uint32_t errorId, Args&&... aArgs);
bool parseTransferable();
bool transferOwnership();
inline void checkStack();
SCOutput out;
// The user defined callbacks that will be used to signal cloning, in some
// cases.
const JSStructuredCloneCallbacks* callbacks;
// Any value passed to the callbacks.
void* closure;
// Vector of objects with properties remaining to be written.
//
// NB: These can span multiple compartments, so the compartment must be
// entered before any manipulation is performed.
RootedValueVector objs;
// counts[i] is the number of entries of objs[i] remaining to be written.
// counts.length() == objs.length() and sum(counts) == entries.length().
Vector<size_t> counts;
// For JSObject: Property IDs as value
RootedIdVector objectEntries;
// For Map: Key followed by value
// For Set: Key
// For SavedFrame: parent SavedFrame
RootedValueVector otherEntries;
// The "memory" list described in the HTML5 internal structured cloning
// algorithm. memory is a superset of objs; items are never removed from
// Memory until a serialization operation is finished
using CloneMemory =
GCHashMap<JSObject*, uint32_t, MovableCellHasher<JSObject*>,
SystemAllocPolicy>;
Rooted<CloneMemory> memory;
struct TransferableObjectsHasher : public DefaultHasher<JSObject*> {
static inline HashNumber hash(const Lookup& l) {
return DefaultHasher<JSObject*>::hash(l);
}
};
// Set of transferable objects
RootedValue transferable;
typedef GCHashSet<JSObject*, TransferableObjectsHasher>
TransferableObjectsSet;
Rooted<TransferableObjectsSet> transferableObjects;
const JS::CloneDataPolicy cloneDataPolicy;
friend bool JS_WriteString(JSStructuredCloneWriter* w, HandleString str);
friend bool JS_WriteTypedArray(JSStructuredCloneWriter* w, HandleValue v);
friend bool JS_ObjectNotWritten(JSStructuredCloneWriter* w, HandleObject obj);
};
JS_FRIEND_API uint64_t js::GetSCOffset(JSStructuredCloneWriter* writer) {
MOZ_ASSERT(writer);
return writer->output().count() * sizeof(uint64_t);
}
static_assert(SCTAG_END_OF_BUILTIN_TYPES <= JS_SCTAG_USER_MIN);
static_assert(JS_SCTAG_USER_MIN <= JS_SCTAG_USER_MAX);
static_assert(Scalar::Int8 == 0);
template <typename... Args>
static void ReportDataCloneError(JSContext* cx,
const JSStructuredCloneCallbacks* callbacks,
uint32_t errorId, void* closure,
Args&&... aArgs) {
unsigned errorNumber;
switch (errorId) {
case JS_SCERR_DUP_TRANSFERABLE:
errorNumber = JSMSG_SC_DUP_TRANSFERABLE;
break;
case JS_SCERR_TRANSFERABLE:
errorNumber = JSMSG_SC_NOT_TRANSFERABLE;
break;
case JS_SCERR_UNSUPPORTED_TYPE:
errorNumber = JSMSG_SC_UNSUPPORTED_TYPE;
break;
case JS_SCERR_SHMEM_TRANSFERABLE:
errorNumber = JSMSG_SC_SHMEM_TRANSFERABLE;
break;
case JS_SCERR_TYPED_ARRAY_DETACHED:
errorNumber = JSMSG_TYPED_ARRAY_DETACHED;
break;
case JS_SCERR_WASM_NO_TRANSFER:
errorNumber = JSMSG_WASM_NO_TRANSFER;
break;
case JS_SCERR_NOT_CLONABLE:
errorNumber = JSMSG_SC_NOT_CLONABLE;
break;
case JS_SCERR_NOT_CLONABLE_WITH_COOP_COEP:
errorNumber = JSMSG_SC_NOT_CLONABLE_WITH_COOP_COEP;
break;
default:
MOZ_CRASH("Unkown errorId");
break;
}
if (callbacks && callbacks->reportError) {
MOZ_RELEASE_ASSERT(!cx->isExceptionPending());
JSErrorReport report;
report.errorNumber = errorNumber;
// Get js error message if it's possible and propagate it through callback.
if (JS_ExpandErrorArgumentsASCII(cx, GetErrorMessage, errorNumber, &report,
std::forward<Args>(aArgs)...) &&
report.message()) {
callbacks->reportError(cx, errorId, closure, report.message().c_str());
} else {
ReportOutOfMemory(cx);
callbacks->reportError(cx, errorId, closure, "");
}
return;
}
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNumber,
std::forward<Args>(aArgs)...);
}
bool WriteStructuredClone(JSContext* cx, HandleValue v,
JSStructuredCloneData* bufp,
JS::StructuredCloneScope scope,
const JS::CloneDataPolicy& cloneDataPolicy,
const JSStructuredCloneCallbacks* cb, void* cbClosure,
const Value& transferable) {
JSStructuredCloneWriter w(cx, scope, cloneDataPolicy, cb, cbClosure,
transferable);
if (!w.init()) {
return false;
}
if (!w.write(v)) {
return false;
}
w.extractBuffer(bufp);
return true;
}
bool ReadStructuredClone(JSContext* cx, const JSStructuredCloneData& data,
JS::StructuredCloneScope scope, MutableHandleValue vp,
const JS::CloneDataPolicy& cloneDataPolicy,
const JSStructuredCloneCallbacks* cb,
void* cbClosure) {
SCInput in(cx, data);
JSStructuredCloneReader r(in, scope, cloneDataPolicy, cb, cbClosure);
return r.read(vp);
}
static bool StructuredCloneHasTransferObjects(
const JSStructuredCloneData& data) {
if (data.Size() < sizeof(uint64_t)) {
return false;
}
uint64_t u;
BufferIterator<uint64_t, SystemAllocPolicy> iter(data);
MOZ_ALWAYS_TRUE(iter.readBytes(reinterpret_cast<char*>(&u), sizeof(u)));
uint32_t tag = uint32_t(u >> 32);
return (tag == SCTAG_TRANSFER_MAP_HEADER);
}
namespace js {
SCInput::SCInput(JSContext* cx, const JSStructuredCloneData& data)
: cx(cx), point(data) {
static_assert(JSStructuredCloneData::BufferList::kSegmentAlignment % 8 == 0,
"structured clone buffer reads should be aligned");
MOZ_ASSERT(data.Size() % 8 == 0);
}
bool SCInput::read(uint64_t* p) {
if (!point.canPeek()) {
*p = 0; // initialize to shut GCC up
return reportTruncated();
}
*p = NativeEndian::swapFromLittleEndian(point.peek());
point.next();
return true;
}
bool SCInput::readPair(uint32_t* tagp, uint32_t* datap) {
uint64_t u;
bool ok = read(&u);
if (ok) {
*tagp = uint32_t(u >> 32);
*datap = uint32_t(u);
}
return ok;
}
bool SCInput::get(uint64_t* p) {
if (!point.canPeek()) {
return reportTruncated();
}
*p = NativeEndian::swapFromLittleEndian(point.peek());
return true;
}
bool SCInput::getPair(uint32_t* tagp, uint32_t* datap) {
uint64_t u = 0;
if (!get(&u)) {
return false;
}
*tagp = uint32_t(u >> 32);
*datap = uint32_t(u);
return true;
}
void SCInput::getPair(uint64_t data, uint32_t* tagp, uint32_t* datap) {
uint64_t u = NativeEndian::swapFromLittleEndian(data);
*tagp = uint32_t(u >> 32);
*datap = uint32_t(u);
}
bool SCInput::readDouble(double* p) {
uint64_t u;
if (!read(&u)) {
return false;
}
*p = CanonicalizeNaN(mozilla::BitwiseCast<double>(u));
return true;
}
template <typename T>
static void swapFromLittleEndianInPlace(T* ptr, size_t nelems) {
if (nelems > 0) {
NativeEndian::swapFromLittleEndianInPlace(ptr, nelems);
}
}
template <>
void swapFromLittleEndianInPlace(uint8_t* ptr, size_t nelems) {}
// Data is packed into an integral number of uint64_t words. Compute the
// padding required to finish off the final word.
static size_t ComputePadding(size_t nelems, size_t elemSize) {
// We want total length mod 8, where total length is nelems * sizeof(T),
// but that might overflow. So reduce nelems to nelems mod 8, since we are
// going to be doing a mod 8 later anyway.
size_t leftoverLength = (nelems % sizeof(uint64_t)) * elemSize;
return (-leftoverLength) & (sizeof(uint64_t) - 1);
}
template <class T>
bool SCInput::readArray(T* p, size_t nelems) {
if (!nelems) {
return true;
}
static_assert(sizeof(uint64_t) % sizeof(T) == 0);
// Fail if nelems is so huge that computing the full size will overflow.
mozilla::CheckedInt<size_t> size =
mozilla::CheckedInt<size_t>(nelems) * sizeof(T);
if (!size.isValid()) {
return reportTruncated();
}
if (!point.readBytes(reinterpret_cast<char*>(p), size.value())) {
// To avoid any way in which uninitialized data could escape, zero the array
// if filling it failed.
std::uninitialized_fill_n(p, nelems, 0);
return false;
}
swapFromLittleEndianInPlace(p, nelems);
point += ComputePadding(nelems, sizeof(T));
return true;
}
bool SCInput::readBytes(void* p, size_t nbytes) {
return readArray((uint8_t*)p, nbytes);
}
bool SCInput::readChars(Latin1Char* p, size_t nchars) {
static_assert(sizeof(Latin1Char) == sizeof(uint8_t),
"Latin1Char must fit in 1 byte");
return readBytes(p, nchars);
}
bool SCInput::readChars(char16_t* p, size_t nchars) {
MOZ_ASSERT(sizeof(char16_t) == sizeof(uint16_t));
return readArray((uint16_t*)p, nchars);
}
void SCInput::getPtr(uint64_t data, void** ptr) {
*ptr = reinterpret_cast<void*>(NativeEndian::swapFromLittleEndian(data));
}
bool SCInput::readPtr(void** p) {
uint64_t u;
if (!read(&u)) {
return false;
}
*p = reinterpret_cast<void*>(u);
return true;
}
SCOutput::SCOutput(JSContext* cx, JS::StructuredCloneScope scope)
: cx(cx), buf(scope) {}
bool SCOutput::write(uint64_t u) {
uint64_t v = NativeEndian::swapToLittleEndian(u);
if (!buf.AppendBytes(reinterpret_cast<char*>(&v), sizeof(u))) {
ReportOutOfMemory(context());
return false;
}
return true;
}
bool SCOutput::writePair(uint32_t tag, uint32_t data) {
// As it happens, the tag word appears after the data word in the output.
// This is because exponents occupy the last 2 bytes of doubles on the
// little-endian platforms we care most about.
//
// For example, TrueValue() is written using writePair(SCTAG_BOOLEAN, 1).
// PairToUInt64 produces the number 0xFFFF000200000001.
// That is written out as the bytes 01 00 00 00 02 00 FF FF.
return write(PairToUInt64(tag, data));
}
static inline double ReinterpretPairAsDouble(uint32_t tag, uint32_t data) {
return BitwiseCast<double>(PairToUInt64(tag, data));
}
bool SCOutput::writeDouble(double d) {
return write(BitwiseCast<uint64_t>(CanonicalizeNaN(d)));
}
template <class T>
bool SCOutput::writeArray(const T* p, size_t nelems) {
static_assert(8 % sizeof(T) == 0);
static_assert(sizeof(uint64_t) % sizeof(T) == 0);
if (nelems == 0) {
return true;
}
for (size_t i = 0; i < nelems; i++) {
T value = NativeEndian::swapToLittleEndian(p[i]);
if (!buf.AppendBytes(reinterpret_cast<char*>(&value), sizeof(value))) {
return false;
}
}
// Zero-pad to 8 bytes boundary.
size_t padbytes = ComputePadding(nelems, sizeof(T));
char zeroes[sizeof(uint64_t)] = {0};
if (!buf.AppendBytes(zeroes, padbytes)) {
return false;
}
return true;
}
template <>
bool SCOutput::writeArray<uint8_t>(const uint8_t* p, size_t nelems) {
if (nelems == 0) {
return true;
}
if (!buf.AppendBytes(reinterpret_cast<const char*>(p), nelems)) {
return false;
}
// zero-pad to 8 bytes boundary
size_t padbytes = ComputePadding(nelems, 1);
char zeroes[sizeof(uint64_t)] = {0};
if (!buf.AppendBytes(zeroes, padbytes)) {
return false;
}
return true;
}
bool SCOutput::writeBytes(const void* p, size_t nbytes) {
return writeArray((const uint8_t*)p, nbytes);
}
bool SCOutput::writeChars(const char16_t* p, size_t nchars) {
static_assert(sizeof(char16_t) == sizeof(uint16_t),
"required so that treating char16_t[] memory as uint16_t[] "
"memory is permissible");
return writeArray((const uint16_t*)p, nchars);
}
bool SCOutput::writeChars(const Latin1Char* p, size_t nchars) {
static_assert(sizeof(Latin1Char) == sizeof(uint8_t),
"Latin1Char must fit in 1 byte");
return writeBytes(p, nchars);
}
void SCOutput::discardTransferables() { buf.discardTransferables(); }
} // namespace js
// If the buffer contains Transferables, free them. Note that custom
// Transferables will use the JSStructuredCloneCallbacks::freeTransfer() to
// delete their transferables.
void JSStructuredCloneData::discardTransferables() {
if (!Size()) {
return;
}
if (ownTransferables_ != OwnTransferablePolicy::OwnsTransferablesIfAny) {
return;
}
// DifferentProcess clones cannot contain pointers, so nothing needs to be
// released.
if (scope() == JS::StructuredCloneScope::DifferentProcess) {
return;
}
FreeTransferStructuredCloneOp freeTransfer = nullptr;
if (callbacks_) {
freeTransfer = callbacks_->freeTransfer;
}
auto point = BufferIterator<uint64_t, SystemAllocPolicy>(*this);
if (point.done()) {
return; // Empty buffer
}
uint32_t tag, data;
MOZ_RELEASE_ASSERT(point.canPeek());
SCInput::getPair(point.peek(), &tag, &data);
point.next();
if (tag == SCTAG_HEADER) {
if (point.done()) {
return;
}
MOZ_RELEASE_ASSERT(point.canPeek());
SCInput::getPair(point.peek(), &tag, &data);
point.next();
}
if (tag != SCTAG_TRANSFER_MAP_HEADER) {
return;
}
if (TransferableMapHeader(data) == SCTAG_TM_TRANSFERRED) {
return;
}
// freeTransfer should not GC
JS::AutoSuppressGCAnalysis nogc;
if (point.done()) {
return;
}
uint64_t numTransferables = NativeEndian::swapFromLittleEndian(point.peek());
point.next();
while (numTransferables--) {