forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathJSONObject.cpp
More file actions
2398 lines (2144 loc) · 95.7 KB
/
Copy pathJSONObject.cpp
File metadata and controls
2398 lines (2144 loc) · 95.7 KB
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
/*
* Copyright (C) 2009-2024 Apple Inc. All rights reserved.
* Copyright (C) 2020 Alexey Shvayka <shvaikalesh@gmail.com>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "JSONObject.h"
#include "ArrayConstructor.h"
#include "BigIntObject.h"
#include "BooleanObject.h"
#include "GetterSetter.h"
#include "JSArrayInlines.h"
#include "JSCInlines.h"
#include "JSRawJSONObject.h"
#include "LiteralParser.h"
#include "NumberObject.h"
#include "ObjectConstructorInlines.h"
#include "PropertyNameArray.h"
#include "VMInlines.h"
#include <charconv>
#include <wtf/MathExtras.h>
#include <wtf/UnalignedAccess.h>
#include <wtf/dragonbox/dragonbox_to_chars.h>
#include <wtf/text/EscapedFormsForJSON.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/ParsingUtilities.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringBuilderJSON.h>
#include <wtf/text/StringCommon.h>
// Turn this on to log information about fastStringify usage, with a focus on why it failed.
#define FAST_STRINGIFY_LOG_USAGE 0
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
namespace JSC {
STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSONObject);
static JSC_DECLARE_HOST_FUNCTION(jsonProtoFuncParse);
static JSC_DECLARE_HOST_FUNCTION(jsonProtoFuncStringify);
static JSC_DECLARE_HOST_FUNCTION(jsonProtoFuncIsRawJSON);
static JSC_DECLARE_HOST_FUNCTION(jsonProtoFuncRawJSON);
}
#include "JSONObject.lut.h"
namespace JSC {
JSONObject::JSONObject(VM& vm, Structure* structure)
: JSNonFinalObject(vm, structure)
{
}
void JSONObject::finishCreation(VM& vm, JSGlobalObject* globalObject)
{
Base::finishCreation(vm);
ASSERT(inherits(info()));
JSC_TO_STRING_TAG_WITHOUT_TRANSITION();
if (Options::useJSONSourceTextAccess()) {
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->isRawJSON, jsonProtoFuncIsRawJSON, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->rawJSON, jsonProtoFuncRawJSON, static_cast<unsigned>(PropertyAttribute::DontEnum), 1, ImplementationVisibility::Public);
}
}
// PropertyNameForFunctionCall objects must be on the stack, since the JSValue that they create is not marked.
class PropertyNameForFunctionCall {
public:
PropertyNameForFunctionCall(PropertyName);
PropertyNameForFunctionCall(unsigned);
JSValue value(VM&) const;
private:
PropertyName m_propertyName;
unsigned m_number;
mutable JSValue m_value;
};
class Stringifier {
WTF_MAKE_NONCOPYABLE(Stringifier);
WTF_FORBID_HEAP_ALLOCATION;
public:
static String stringify(JSGlobalObject&, JSValue, JSValue replacer, JSValue space);
private:
class Holder {
public:
enum RootHolderTag { RootHolder };
Holder(JSGlobalObject*, JSObject*, Structure*);
Holder(RootHolderTag, JSObject*);
JSObject* NODELETE object() const { return m_object; }
bool NODELETE isArray() const { return m_isArray; }
bool NODELETE hasFastObjectProperties() const { return m_hasFastObjectProperties; }
bool appendNextProperty(Stringifier&, StringBuilder&);
private:
JSObject* m_object { nullptr };
Structure* m_structure { nullptr };
const bool m_isJSArray { false };
const bool m_isArray { false };
bool m_hasFastObjectProperties { false };
unsigned m_index { 0 };
unsigned m_size { 0 };
RefPtr<PropertyNameArray> m_propertyNames;
Vector<std::tuple<PropertyName, unsigned>, 8> m_propertiesAndOffsets;
};
friend class Holder;
Stringifier(JSGlobalObject*, JSValue replacer, JSValue space);
JSValue toJSON(JSValue, const PropertyNameForFunctionCall&);
enum StringifyResult { StringifyFailed, StringifySucceeded, StringifyFailedDueToUndefinedOrSymbolValue };
StringifyResult appendStringifiedValue(StringBuilder&, JSValue, const Holder&, const PropertyNameForFunctionCall&);
bool willIndent() const;
void indent();
void unindent();
void startNewLine(StringBuilder&) const;
bool NODELETE isCallableReplacer() const { return m_replacerCallData.type != CallData::Type::None; }
JSGlobalObject* const m_globalObject;
JSValue m_replacer;
bool m_usingArrayReplacer { false };
PropertyNameArrayBuilder m_arrayReplacerPropertyNames;
CallData m_replacerCallData;
String m_gap;
MarkedArgumentBufferWithSize<16> m_objectStack;
Vector<Holder, 16, UnsafeVectorOverflow> m_holderStack;
String m_repeatedGap;
StringView m_indent;
};
// ------------------------------ helper functions --------------------------------
static inline JSValue unwrapBoxedPrimitive(JSGlobalObject* globalObject, JSObject* object)
{
if (object->inherits<NumberObject>())
return jsNumber(object->toNumber(globalObject));
if (object->inherits<StringObject>())
return object->toString(globalObject);
if (object->inherits<BooleanObject>() || object->inherits<BigIntObject>())
return uncheckedDowncast<JSWrapperObject>(object)->internalValue();
// Do not unwrap SymbolObject to Symbol. It is not performed in the spec.
// http://www.ecma-international.org/ecma-262/6.0/#sec-serializejsonproperty
return object;
}
static inline JSValue unwrapBoxedPrimitive(JSGlobalObject* globalObject, JSValue value)
{
return value.isObject() ? unwrapBoxedPrimitive(globalObject, asObject(value)) : value;
}
static constexpr unsigned maxGapLength = 10;
static inline String gap(JSGlobalObject* globalObject, JSValue space)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
space = unwrapBoxedPrimitive(globalObject, space);
RETURN_IF_EXCEPTION(scope, { });
// If the space value is a number, create a gap string with that number of spaces.
if (space.isNumber()) {
unsigned count = clampTo<unsigned>(space.asNumber(), 0, maxGapLength);
char spaces[maxGapLength];
for (unsigned i = 0; i < count; ++i)
spaces[i] = ' ';
return String(std::span { spaces }.first(count));
}
// If the space value is a string, use it as the gap string, otherwise use no gap string.
String spaces = space.getString(globalObject);
RETURN_IF_EXCEPTION(scope, { });
if (spaces.length() <= maxGapLength)
return spaces;
return spaces.substringSharingImpl(0, maxGapLength);
}
// ------------------------------ PropertyNameForFunctionCall --------------------------------
inline PropertyNameForFunctionCall::PropertyNameForFunctionCall(PropertyName propertyName)
: m_propertyName(propertyName)
{
}
inline PropertyNameForFunctionCall::PropertyNameForFunctionCall(unsigned number)
: m_number(number)
{
}
JSValue PropertyNameForFunctionCall::value(VM& vm) const
{
if (!m_value) {
if (!m_propertyName.isNull())
m_value = jsString(vm, String { m_propertyName.uid() });
else {
if (m_number <= 9)
return vm.smallStrings.singleCharacterString(m_number + '0');
m_value = jsNontrivialString(vm, vm.numericStrings.add(m_number));
}
}
return m_value;
}
// ------------------------------ Stringifier --------------------------------
Stringifier::Stringifier(JSGlobalObject* globalObject, JSValue replacer, JSValue space)
: m_globalObject(globalObject)
, m_replacer(replacer)
, m_arrayReplacerPropertyNames(globalObject->vm(), PropertyNameMode::Strings, PrivateSymbolMode::Exclude)
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (m_replacer.isObject()) {
JSObject* replacerObject = asObject(m_replacer);
m_replacerCallData = JSC::getCallData(replacerObject);
if (m_replacerCallData.type == CallData::Type::None) {
bool isArrayReplacer = JSC::isArray(globalObject, replacerObject);
RETURN_IF_EXCEPTION(scope, );
if (isArrayReplacer) {
m_usingArrayReplacer = true;
forEachInArrayLike(globalObject, replacerObject, [&] (JSValue name) -> bool {
if (name.isObject()) {
auto* nameObject = uncheckedDowncast<JSObject>(name);
if (!nameObject->inherits<NumberObject>() && !nameObject->inherits<StringObject>())
return true;
} else if (!name.isNumber() && !name.isString())
return true;
JSString* propertyNameString = name.toString(globalObject);
RETURN_IF_EXCEPTION(scope, false);
auto propertyName = propertyNameString->toIdentifier(globalObject);
RETURN_IF_EXCEPTION(scope, false);
m_arrayReplacerPropertyNames.add(WTF::move(propertyName));
return true;
});
RETURN_IF_EXCEPTION(scope, );
}
}
}
scope.release();
m_gap = gap(globalObject, space);
}
String Stringifier::stringify(JSGlobalObject& globalObject, JSValue value, JSValue replacer, JSValue space)
{
VM& vm = globalObject.vm();
auto scope = DECLARE_THROW_SCOPE(vm);
Stringifier stringifier(&globalObject, replacer, space);
RETURN_IF_EXCEPTION(scope, { });
PropertyNameForFunctionCall emptyPropertyName(vm.propertyNames->emptyIdentifier.impl());
// If the replacer is not callable, root object wrapper is non-user-observable.
// We can skip creating this wrapper object.
JSObject* object = nullptr;
if (stringifier.isCallableReplacer()) {
object = constructEmptyObject(&globalObject);
object->putDirect(vm, vm.propertyNames->emptyIdentifier, value);
}
StringBuilder result(OverflowPolicy::RecordOverflow);
Holder root(Holder::RootHolder, object);
auto stringifyResult = stringifier.appendStringifiedValue(result, value, root, emptyPropertyName);
RETURN_IF_EXCEPTION(scope, { });
if (result.hasOverflowed()) [[unlikely]] {
throwOutOfMemoryError(&globalObject, scope);
return { };
}
if (stringifyResult != StringifySucceeded) [[unlikely]]
RELEASE_AND_RETURN(scope, { });
RELEASE_AND_RETURN(scope, result.toString());
}
ALWAYS_INLINE JSValue Stringifier::toJSON(JSValue baseValue, const PropertyNameForFunctionCall& propertyName)
{
VM& vm = m_globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
scope.assertNoException();
JSValue toJSONFunction;
if (baseValue.isObject())
toJSONFunction = asObject(baseValue)->structure()->cachedSpecialProperty(CachedSpecialPropertyKey::ToJSON);
if (!toJSONFunction) {
PropertySlot slot(baseValue, PropertySlot::InternalMethodType::Get);
bool hasProperty = baseValue.getPropertySlot(m_globalObject, vm.propertyNames->toJSON, slot);
RETURN_IF_EXCEPTION(scope, { });
toJSONFunction = hasProperty ? slot.getValue(m_globalObject, vm.propertyNames->toJSON) : jsUndefined();
RETURN_IF_EXCEPTION(scope, { });
if (baseValue.isObject())
asObject(baseValue)->structure()->cacheSpecialProperty(m_globalObject, vm, toJSONFunction, CachedSpecialPropertyKey::ToJSON, slot);
}
auto callData = JSC::getCallData(toJSONFunction);
if (callData.type == CallData::Type::None)
return baseValue;
auto args = WTF::toArray<EncodedJSValue>({
JSValue::encode(propertyName.value(vm)),
});
RELEASE_AND_RETURN(scope, call(m_globalObject, asObject(toJSONFunction), callData, baseValue, ArgList { args.data(), args.size() }));
}
// We clamp recursion well beyond anything reasonable.
constexpr unsigned maximumSideStackRecursion = 40000;
Stringifier::StringifyResult Stringifier::appendStringifiedValue(StringBuilder& builder, JSValue value, const Holder& holder, const PropertyNameForFunctionCall& propertyName)
{
VM& vm = m_globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// Recursion is avoided by !holderStackWasEmpty check and do/while loop at the end of this method.
// We're having this recursion check here as a fail safe in case the code
// below get modified such that recursion is no longer avoided.
if (!vm.isSafeToRecurseSoft()) [[unlikely]] {
throwStackOverflowError(m_globalObject, scope);
return StringifyFailed;
}
// Call the toJSON function.
if (value.isObject() || value.isBigInt()) {
value = toJSON(value, propertyName);
RETURN_IF_EXCEPTION(scope, StringifyFailed);
}
// Call the replacer function.
if (isCallableReplacer()) {
auto args = WTF::toArray<EncodedJSValue>({
JSValue::encode(propertyName.value(vm)),
JSValue::encode(value),
});
ASSERT(holder.object());
value = call(m_globalObject, m_replacer, m_replacerCallData, holder.object(), ArgList { args.data(), args.size() });
RETURN_IF_EXCEPTION(scope, StringifyFailed);
}
if ((value.isUndefined() || value.isSymbol()) && !holder.isArray())
return StringifyFailedDueToUndefinedOrSymbolValue;
if (value.isObject()) {
JSObject* object = asObject(value);
if (object->inherits<JSRawJSONObject>()) {
String string = uncheckedDowncast<JSRawJSONObject>(object)->rawJSON(vm)->value(m_globalObject);
RETURN_IF_EXCEPTION(scope, StringifyFailed);
builder.append(WTF::move(string));
return StringifySucceeded;
}
value = unwrapBoxedPrimitive(m_globalObject, object);
RETURN_IF_EXCEPTION(scope, StringifyFailed);
}
if (value.isNull()) {
builder.append("null"_s);
return StringifySucceeded;
}
if (value.isBoolean()) {
if (value.isTrue())
builder.append("true"_s);
else
builder.append("false"_s);
return StringifySucceeded;
}
if (value.isString()) {
auto string = asString(value)->value(m_globalObject);
RETURN_IF_EXCEPTION(scope, StringifyFailed);
builder.appendQuotedJSONString(string);
return StringifySucceeded;
}
if (value.isNumber()) {
if (value.isInt32())
builder.append(value.asInt32());
else {
double number = value.asNumber();
if (!std::isfinite(number))
builder.append("null"_s);
else
builder.append(number);
}
return StringifySucceeded;
}
if (value.isBigInt()) {
throwTypeError(m_globalObject, scope, "JSON.stringify cannot serialize BigInt."_s);
return StringifyFailed;
}
if (!value.isObject())
return StringifyFailed;
JSObject* object = asObject(value);
if (object->isCallable()) {
if (holder.isArray()) {
builder.append("null"_s);
return StringifySucceeded;
}
return StringifyFailedDueToUndefinedOrSymbolValue;
}
if (builder.hasOverflowed()) [[unlikely]]
return StringifyFailed;
// Handle cycle detection, and put the holder on the stack.
for (unsigned i = 0; i < m_holderStack.size(); i++) {
if (m_holderStack[i].object() == object) {
throwTypeError(m_globalObject, scope, "JSON.stringify cannot serialize cyclic structures."_s);
return StringifyFailed;
}
}
if (m_holderStack.size() >= maximumSideStackRecursion) [[unlikely]] {
throwStackOverflowError(m_globalObject, scope);
return StringifyFailed;
}
bool holderStackWasEmpty = m_holderStack.isEmpty();
Structure* structure = object->structure();
m_holderStack.append(Holder(m_globalObject, object, structure));
m_objectStack.appendWithCrashOnOverflow(object);
m_objectStack.appendWithCrashOnOverflow(structure);
RETURN_IF_EXCEPTION(scope, StringifyFailed);
if (!holderStackWasEmpty)
return StringifySucceeded;
do {
while (m_holderStack.last().appendNextProperty(*this, builder))
RETURN_IF_EXCEPTION(scope, StringifyFailed);
RETURN_IF_EXCEPTION(scope, StringifyFailed);
if (builder.hasOverflowed()) [[unlikely]]
return StringifyFailed;
m_holderStack.removeLast();
m_objectStack.removeLast();
m_objectStack.removeLast();
} while (!m_holderStack.isEmpty());
return StringifySucceeded;
}
inline bool NODELETE Stringifier::willIndent() const
{
return !m_gap.isEmpty();
}
inline void Stringifier::indent()
{
// Use a single shared string, m_repeatedGap, so we don't keep allocating new ones as we indent and unindent.
unsigned newSize = m_indent.length() + m_gap.length();
if (newSize > m_repeatedGap.length())
m_repeatedGap = makeString(m_repeatedGap, m_gap);
ASSERT(newSize <= m_repeatedGap.length());
m_indent = StringView { m_repeatedGap }.left(newSize);
}
inline void NODELETE Stringifier::unindent()
{
ASSERT(m_indent.length() >= m_gap.length());
m_indent = StringView { m_repeatedGap }.left(m_indent.length() - m_gap.length());
}
inline void Stringifier::startNewLine(StringBuilder& builder) const
{
if (willIndent())
builder.append('\n', m_indent);
}
inline Stringifier::Holder::Holder(JSGlobalObject* globalObject, JSObject* object, Structure* structure)
: m_object(object)
, m_structure(structure)
, m_isJSArray(isJSArray(object))
, m_isArray(JSC::isArray(globalObject, object))
{
}
inline Stringifier::Holder::Holder(RootHolderTag, JSObject* object)
: m_object(object)
{
}
bool Stringifier::Holder::appendNextProperty(Stringifier& stringifier, StringBuilder& builder)
{
ASSERT(m_index <= m_size);
JSGlobalObject* globalObject = stringifier.m_globalObject;
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
// First time through, initialize.
if (!m_index) {
if (m_isArray) {
uint64_t length = toLength(globalObject, m_object);
RETURN_IF_EXCEPTION(scope, false);
if (length > std::numeric_limits<uint32_t>::max()) [[unlikely]] {
throwOutOfMemoryError(globalObject, scope);
return false;
}
m_size = static_cast<uint32_t>(length);
RETURN_IF_EXCEPTION(scope, false);
builder.append('[');
} else {
if (stringifier.m_usingArrayReplacer) {
m_propertyNames = stringifier.m_arrayReplacerPropertyNames.data();
m_size = m_propertyNames->propertyNameVector().size();
} else if (m_object->structure() == m_structure && canPerformFastPropertyNameEnumerationForJSONStringifyWithSideEffect(m_structure)) {
m_hasFastObjectProperties = m_structure->canPerformFastPropertyEnumeration();
m_structure->forEachProperty(vm, [&](const auto& entry) -> bool {
if (entry.attributes() & PropertyAttribute::DontEnum)
return true;
PropertyName propertyName(entry.key());
if (propertyName.isSymbol())
return true;
m_propertiesAndOffsets.constructAndAppend(propertyName, entry.offset());
return true;
});
m_size = m_propertiesAndOffsets.size();
} else {
PropertyNameArrayBuilder objectPropertyNames(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude);
m_object->methodTable()->getOwnPropertyNames(m_object, globalObject, objectPropertyNames, DontEnumPropertiesMode::Exclude);
RETURN_IF_EXCEPTION(scope, false);
m_propertyNames = objectPropertyNames.releaseData();
m_size = m_propertyNames->propertyNameVector().size();
}
builder.append('{');
}
stringifier.indent();
}
if (builder.hasOverflowed()) [[unlikely]]
return false;
// Last time through, finish up and return false.
if (m_index == m_size) {
stringifier.unindent();
if (m_size && builder[builder.length() - 1] != '{')
stringifier.startNewLine(builder);
builder.append(m_isArray ? ']' : '}');
return false;
}
// Handle a single element of the array or object.
unsigned index = m_index++;
unsigned rollBackPoint = 0;
StringifyResult stringifyResult;
if (m_isArray) {
// Get the value.
JSValue value;
if (m_isJSArray && m_object->canGetIndexQuickly(index))
value = m_object->getIndexQuickly(index);
else {
value = m_object->get(globalObject, index);
RETURN_IF_EXCEPTION(scope, false);
}
// Append the separator string.
if (index)
builder.append(',');
stringifier.startNewLine(builder);
// Append the stringified value.
stringifyResult = stringifier.appendStringifiedValue(builder, value, *this, index);
ASSERT(stringifyResult != StringifyFailedDueToUndefinedOrSymbolValue);
} else {
PropertyName propertyName;
JSValue value;
if (m_hasFastObjectProperties) {
propertyName = std::get<0>(m_propertiesAndOffsets[index]);
if (m_object->structureID() == m_structure->id()) {
unsigned offset = std::get<1>(m_propertiesAndOffsets[index]);
value = m_object->getDirect(offset);
} else {
value = m_object->get(globalObject, propertyName);
RETURN_IF_EXCEPTION(scope, false);
}
} else {
if (m_propertyNames) {
propertyName = m_propertyNames->propertyNameVector()[index];
value = m_object->get(globalObject, propertyName);
RETURN_IF_EXCEPTION(scope, false);
} else {
propertyName = std::get<0>(m_propertiesAndOffsets[index]);
if (m_object->structureID() == m_structure->id()) {
unsigned offset = std::get<1>(m_propertiesAndOffsets[index]);
value = m_object->getDirect(offset);
if (value.isGetterSetter()) {
value = uncheckedDowncast<GetterSetter>(value)->callGetter(globalObject, m_object);
RETURN_IF_EXCEPTION(scope, false);
} else if (value.isCustomGetterSetter()) {
value = m_object->get(globalObject, propertyName);
RETURN_IF_EXCEPTION(scope, false);
}
} else {
value = m_object->get(globalObject, propertyName);
RETURN_IF_EXCEPTION(scope, false);
}
}
}
rollBackPoint = builder.length();
// Append the separator string.
if (builder[rollBackPoint - 1] != '{')
builder.append(',');
stringifier.startNewLine(builder);
// Append the property name, colon, and space.
builder.appendQuotedJSONString(*propertyName.uid());
builder.append(':');
if (stringifier.willIndent())
builder.append(' ');
// Append the stringified value.
stringifyResult = stringifier.appendStringifiedValue(builder, value, *this, propertyName);
}
RETURN_IF_EXCEPTION(scope, false);
// From this point on, no access to the this pointer or to any members, because the
// Holder object may have moved if the call to stringify pushed a new Holder onto
// m_holderStack.
switch (stringifyResult) {
case StringifyFailed:
builder.append("null"_s);
break;
case StringifySucceeded:
break;
case StringifyFailedDueToUndefinedOrSymbolValue:
// This only occurs when we get an undefined value or a symbol value for
// an object property. In this case we don't want the separator and
// property name that we already appended, so roll back.
builder.shrink(rollBackPoint);
break;
}
return true;
}
// ------------------------------ FastStringifier --------------------------------
// FastStringifier does a no-side-effects stringify of the most common types of
// objects and arrays. It bails out if the serialization is any longer than a
// fixed buffer and handles only the simplest cases, including only 8-bit character
// strings. Instead of explicit checks to prevent excessive recursion and cycles,
// it counts on hitting the buffer size limit to catch those things. If it fails,
// since there is no side effect, the full general purpose Stringifier can be used
// and the only cost of the fast stringifying attempt is the time wasted.
//
// In DynamicBuffer mode the buffer limit is the 2GB string length limit, so the
// buffer limit alone is far too expensive as a cycle check: a cyclic value with a
// gap reaches it only after writing (and repeatedly reallocating) gigabytes. A
// depth limit bounds that wasted work. Values nested deeper than the limit take
// the general Stringifier, whose holder stack detects cycles immediately.
enum class BufferMode : uint8_t {
StaticBuffer,
DynamicBuffer,
};
enum class HasGap : bool { No, Yes };
enum class FailureReason : uint8_t {
BufferFull,
Found16BitEarly,
Found16BitLate,
StackOverflow,
DepthLimit,
Unknown,
};
template<typename CharType, BufferMode bufferMode>
class FastStringifier {
public:
// Returns null string if the fast case fails.
static String stringify(JSGlobalObject&, JSValue, JSValue replacer, JSValue space, std::optional<FailureReason>&);
static constexpr unsigned staticBufferSize = bufferMode == BufferMode::StaticBuffer ? 8192 : 8;
static constexpr unsigned dynamicBufferInlineCapacity = bufferMode == BufferMode::StaticBuffer ? 0 : 1024;
// DynamicBuffer mode only: values nested deeper than this bail to the general
// Stringifier. Keeps a cyclic value from filling the buffer up to the string
// length limit before the general Stringifier gets to throw for the cycle.
static constexpr unsigned maximumDepth = 512;
// m_depth drives the indentation when there is a gap, and the maximumDepth
// check in DynamicBuffer mode.
static constexpr bool trackDepthWithoutGap = bufferMode == BufferMode::DynamicBuffer;
static constexpr bool useShortCopyTier = bufferMode == BufferMode::DynamicBuffer;
private:
explicit FastStringifier(JSGlobalObject&);
template<HasGap hasGap> void append(JSValue);
void appendInt32(int32_t);
template<HasGap hasGap> void appendInt32Array(JSArray&);
String result();
static constexpr unsigned maxInt32StringLength = ("-2147483648"_s).length();
// FIXME These should probably just take an ASCIILiteral.
void append(char, char, char, char);
void append(char, char, char, char, char);
bool setGap(JSValue space);
unsigned newLineAndIndentSize() const;
void appendNewLineAndIndentUnchecked();
template<typename T> void recordFailure(FailureReason, T&& reason);
template<typename T> void NODELETE recordFailure(T&& reason)
{
recordFailure(FailureReason::Unknown, std::forward<T>(reason));
}
void recordBufferFull();
String firstGetterSetterPropertyName(JSObject&) const;
void recordFastPropertyEnumerationFailure(JSObject&);
bool haveFailure() const;
bool hasRemainingCapacity(unsigned size = 1);
bool hasRemainingCapacitySlow(unsigned size);
bool mayHaveToJSON(JSObject&) const;
static void logOutcome(ASCIILiteral);
static void logOutcome(String&&);
static unsigned usableBufferSize(unsigned availableBufferSize);
CharType* buffer();
const CharType* buffer() const;
std::span<CharType> bufferSpan();
JSGlobalObject& m_globalObject;
VM& m_vm;
unsigned m_length { 0 }; // length of content already filled into m_buffer.
unsigned m_capacity { 0 };
unsigned m_depth { 0 };
unsigned m_gapLength { 0 };
std::array<Latin1Character, maxGapLength> m_gap;
bool m_checkedObjectPrototype { false };
bool m_checkedArrayPrototype { false };
std::optional<FailureReason> m_failureReason;
Vector<CharType, dynamicBufferInlineCapacity, CrashOnOverflow, 16, WTF::StringImplMalloc> m_dynamicBuffer;
uint8_t* m_stackLimit { nullptr };
CharType m_buffer[staticBufferSize];
};
#if !FAST_STRINGIFY_LOG_USAGE
template<typename CharType, BufferMode bufferMode>
inline void FastStringifier<CharType, bufferMode>::logOutcome(ASCIILiteral)
{
}
#else
static void logOutcomeImpl(String&& outcome)
{
static NeverDestroyed<HashCountedSet<String>> set;
static std::atomic<unsigned> count;
set->add(outcome);
if (!(++count % 100)) {
Vector<KeyValuePair<String, unsigned>> vector;
for (auto& pair : set.get())
vector.append(pair);
std::ranges::sort(vector, [](auto& a, auto &b) {
return a.value != b.value ? a.value > b.value : codePointCompareLessThan(a.key, b.key);
});
dataLogLn("fastStringify outcomes");
for (auto& pair : vector) {
dataLogF("%5u", pair.value);
dataLogLn(": ", pair.key);
}
}
}
template<typename CharType, BufferMode bufferMode>
void FastStringifier<CharType, bufferMode>::logOutcome(ASCIILiteral outcome)
{
logOutcomeImpl(String { outcome });
}
template<typename CharType, BufferMode bufferMode>
void FastStringifier<CharType, bufferMode>::logOutcome(String&& outcome)
{
logOutcomeImpl(WTF::move(outcome));
}
#endif
template<typename CharType, BufferMode bufferMode>
ALWAYS_INLINE CharType* FastStringifier<CharType, bufferMode>::buffer()
{
if constexpr (bufferMode == BufferMode::StaticBuffer)
return m_buffer;
else
return m_dynamicBuffer.mutableSpan().data();
}
template<typename CharType, BufferMode bufferMode>
ALWAYS_INLINE const CharType* FastStringifier<CharType, bufferMode>::buffer() const
{
if constexpr (bufferMode == BufferMode::StaticBuffer)
return m_buffer;
else
return m_dynamicBuffer.span().data();
}
template<typename CharType, BufferMode bufferMode>
ALWAYS_INLINE std::span<CharType> FastStringifier<CharType, bufferMode>::bufferSpan()
{
if constexpr (bufferMode == BufferMode::StaticBuffer)
return std::span<CharType> { m_buffer };
else
return m_dynamicBuffer.mutableSpan();
}
template<typename CharType, BufferMode bufferMode>
inline unsigned FastStringifier<CharType, bufferMode>::usableBufferSize(unsigned availableBufferSize)
{
// FastStringifier relies on m_capacity (i.e. the remaining usable capacity) in m_buffer
// to limit recursion. Hence, we need to compute an appropriate m_capacity value.
//
// To do this, we empirically measured the worst case stack usage incurred by 1 recursion
// of any of the append methods. Assuming each call to append() only consumes 1 Latin1Character in
// m_buffer, the amount of buffer size that FastStringifier is allowed to run with can be
// estimated as:
//
// stackCapacityForRecursion = remainingStackCapacity - maxLeafFunctionStackUsage
// maxAllowedBufferSize = stackCapacityForRecursion / maxRecursionFrameSize
// usableBufferSize = min(maxAllowedBufferSize, sizeof(m_buffer))
//
// 1. A leaf function is any function that append() calls which does not recurse.
// At peak recursion, there needs to be enough room left on the stack to execute any
// of these leaf functions i.e. maxLeafFunctionStackUsage.
//
// We estimate maxLeafFunctionStackUsage to be StackBounds::DefaultReservedZone.
// stack.recursionLimit() already adds DefaultReservedZone to the bottom of the stack.
// Hence, using stack.recursionLimit() to compute stackCapacityForRecursion will leave
// us with the needed stack space for leaf functions to execute.
//
// 2. We can compute m_capacity as:
//
// m_capacity = m_length + usableBufferSize
//
// where m_length is the position of the next usable character for emission in m_buffer.
//
// 3. This calculation of m_capacity is a best effort estimate. If we're not
// conservative enough and get it wrong, the worst that can happen is that we'll
// crash when recursion causes us to step on the stack guard page at the bottom of
// the stack. The goal of trying to estimate a good m_capacity value is to avoid
// this stack overflow crash.
//
// Note that for a Release build, maxRecursionFrameSize is measured to be less than
// 384 bytes. This is well below stack guard page sizes which are between 4 and 16K
// depending on the OS. Hence, recursing too deeply with FastStringifier::append()
// is guaranteed to crash in the stack guard page.
//
// 4. If we're too conservative, we might fail out of FastStringifier too eagerly.
// In this case, we'll just fall back to the slow path Stringifier. The only down
// side here is potential loss of some performance opportunity when we encounter
// a workload that recurses deeply. We expect such workloads to be rare.
auto& stack = Thread::currentSingleton().stack();
uint8_t* stackPointer = std::bit_cast<uint8_t*>(currentStackPointer());
uint8_t* stackLimit = std::bit_cast<uint8_t*>(stack.recursionLimit());
size_t stackCapacityForRecursion = stackPointer - stackLimit;
#if ASAN_ENABLED
// Measured to be ~4608 for a Debug ASAN build on arm64E, rounding up to 5K for margin.
constexpr size_t maxRecursionFrameSize = 5 * KB;
#elif !defined(NDEBUG)
// Measured to be ~912 for a Debug build on arm64E, rounding up to 1280 for margin.
constexpr size_t maxRecursionFrameSize = 1280;
#else
// Measured to be ~224 for a Release build on arm64E, rounding up to 384 for margin.
constexpr size_t maxRecursionFrameSize = 384;
#endif
ASSERT(static_cast<unsigned>(stackCapacityForRecursion) == stackCapacityForRecursion);
unsigned allowedBufferSize = stackCapacityForRecursion / maxRecursionFrameSize;
unsigned usableBufferSize = std::min(allowedBufferSize, availableBufferSize);
return usableBufferSize;
}
template<typename CharType, BufferMode bufferMode>
inline FastStringifier<CharType, bufferMode>::FastStringifier(JSGlobalObject& globalObject)
: m_globalObject(globalObject)
, m_vm(globalObject.vm())
{
if constexpr (bufferMode == BufferMode::StaticBuffer)
m_capacity = m_length + usableBufferSize(staticBufferSize);
else {
m_dynamicBuffer.grow(dynamicBufferInlineCapacity);
m_capacity = dynamicBufferInlineCapacity;
m_stackLimit = std::bit_cast<uint8_t*>(m_vm.softStackLimit());
}
}
template<typename CharType, BufferMode bufferMode>
inline bool FastStringifier<CharType, bufferMode>::haveFailure() const
{
return !!m_failureReason;
}
template<typename CharType, BufferMode bufferMode>
inline String FastStringifier<CharType, bufferMode>::result()
{
if (haveFailure())
return { };
#if FAST_STRINGIFY_LOG_USAGE
static std::atomic<unsigned> maxSizeSeen;
if (m_length > maxSizeSeen) {
maxSizeSeen = m_length;
dataLogLn("max fastStringify buffer size used: ", m_length);
}
logOutcome("success"_s);
#endif
if constexpr (bufferMode == BufferMode::DynamicBuffer) {
m_dynamicBuffer.shrink(m_length);
return StringImpl::adopt(WTF::move(m_dynamicBuffer));
}
return std::span { static_cast<const FastStringifier*>(this)->buffer(), m_length };
}
template<typename CharType, BufferMode bufferMode>
template<typename T> inline void FastStringifier<CharType, bufferMode>::recordFailure(FailureReason failureReason, T&& reason)
{
if (!haveFailure())
logOutcome(std::forward<T>(reason));
m_failureReason = failureReason;
}
template<typename CharType, BufferMode bufferMode>
inline void FastStringifier<CharType, bufferMode>::recordBufferFull()
{
recordFailure(FailureReason::BufferFull, "buffer full"_s);
}
template<typename CharType, BufferMode bufferMode>
ALWAYS_INLINE bool FastStringifier<CharType, bufferMode>::hasRemainingCapacity(unsigned size)
{
ASSERT(!haveFailure());
ASSERT(size > 0);
unsigned remainingCapacity = m_capacity - m_length;
if (size <= remainingCapacity)
return true;
return hasRemainingCapacitySlow(size);
}
template<typename CharType, BufferMode bufferMode>
bool FastStringifier<CharType, bufferMode>::hasRemainingCapacitySlow(unsigned size)
{
ASSERT(!haveFailure());
if constexpr (bufferMode == BufferMode::StaticBuffer) {
unsigned unusedBufferSize = staticBufferSize - m_length;
unsigned usableSize = usableBufferSize(unusedBufferSize);
if (usableSize < size)
return false;
m_capacity = m_length + usableSize;
ASSERT(m_capacity - m_length >= size);
return true;
} else {
size_t newSize = std::max<size_t>(m_dynamicBuffer.size() * 2, m_dynamicBuffer.size() + size);
if (!StringImpl::isValidLength<CharType>(newSize)) [[unlikely]]
return false;