| 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 |
#include "builtin/JSON.h" |
| 8 |
|
| 9 |
#include "mozilla/CheckedInt.h" |
| 10 |
#include "mozilla/FloatingPoint.h" |
| 11 |
#include "mozilla/Range.h" |
| 12 |
#include "mozilla/ScopeExit.h" |
| 13 |
#include "mozilla/Variant.h" |
| 14 |
|
| 15 |
#include <algorithm> |
| 16 |
|
| 17 |
#include "jsnum.h" |
| 18 |
#include "jstypes.h" |
| 19 |
|
| 20 |
#include "builtin/Array.h" |
| 21 |
#include "builtin/BigInt.h" |
| 22 |
#include "builtin/ParseRecordObject.h" |
| 23 |
#include "builtin/RawJSONObject.h" |
| 24 |
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_* |
| 25 |
#include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit |
| 26 |
#include "js/Object.h" // JS::GetBuiltinClass |
| 27 |
#include "js/Prefs.h" // JS::Prefs |
| 28 |
#include "js/ProfilingCategory.h" |
| 29 |
#include "js/PropertySpec.h" |
| 30 |
#include "js/StableStringChars.h" |
| 31 |
#include "js/TypeDecls.h" |
| 32 |
#include "js/Value.h" |
| 33 |
#include "util/StringBuilder.h" |
| 34 |
#include "vm/BooleanObject.h" // js::BooleanObject |
| 35 |
#include "vm/EqualityOperations.h" // js::SameValue |
| 36 |
#include "vm/Interpreter.h" |
| 37 |
#include "vm/Iteration.h" |
| 38 |
#include "vm/JSAtomUtils.h" // ToAtom |
| 39 |
#include "vm/JSContext.h" |
| 40 |
#include "vm/JSObject.h" |
| 41 |
#include "vm/JSONParser.h" |
| 42 |
#include "vm/NativeObject.h" |
| 43 |
#include "vm/NumberObject.h" // js::NumberObject |
| 44 |
#include "vm/PlainObject.h" // js::PlainObject |
| 45 |
#include "vm/StringObject.h" // js::StringObject |
| 46 |
#include "builtin/Array-inl.h" |
| 47 |
#include "vm/GeckoProfiler-inl.h" |
| 48 |
#include "vm/JSAtomUtils-inl.h" // AtomToId, PrimitiveValueToId, IndexToId, IdToString, |
| 49 |
#include "vm/NativeObject-inl.h" |
| 50 |
|
| 51 |
using namespace js; |
| 52 |
|
| 53 |
using mozilla::AsVariant; |
| 54 |
using mozilla::CheckedInt; |
| 55 |
using mozilla::Maybe; |
| 56 |
using mozilla::RangedPtr; |
| 57 |
using mozilla::Variant; |
| 58 |
|
| 59 |
using JS::AutoStableStringChars; |
| 60 |
|
| 61 |
/* https://262.ecma-international.org/14.0/#sec-quotejsonstring |
| 62 |
* Requires that the destination has enough space allocated for src after |
| 63 |
* escaping (that is, `2 + 6 * (srcEnd - srcBegin)` characters). |
| 64 |
*/ |
| 65 |
template <typename SrcCharT, typename DstCharT> |
| 66 |
static MOZ_ALWAYS_INLINE RangedPtr<DstCharT> InfallibleQuoteJSONString( |
| 67 |
RangedPtr<const SrcCharT> srcBegin, RangedPtr<const SrcCharT> srcEnd, |
| 68 |
RangedPtr<DstCharT> dstPtr) { |
| 69 |
// Maps characters < 256 to the value that must follow the '\\' in the quoted |
| 70 |
// string. Entries with 'u' are handled as \\u00xy, and entries with 0 are not |
| 71 |
// escaped in any way. Characters >= 256 are all assumed to be unescaped. |
| 72 |
static const Latin1Char escapeLookup[256] = { |
| 73 |
// clang-format off |
| 74 |
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', |
| 75 |
'n', 'u', 'f', 'r', 'u', 'u', 'u', 'u', 'u', 'u', |
| 76 |
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', |
| 77 |
'u', 'u', 0, 0, '\"', 0, 0, 0, 0, 0, |
| 78 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 79 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 80 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 81 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 82 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 83 |
0, 0, '\\', // rest are all zeros |
| 84 |
// clang-format on |
| 85 |
}; |
| 86 |
|
| 87 |
/* Step 1. */ |
| 88 |
*dstPtr++ = '"'; |
| 89 |
|
| 90 |
auto ToLowerHex = [](uint8_t u) { |
| 91 |
MOZ_ASSERT(u <= 0xF); |
| 92 |
return "0123456789abcdef"[u]; |
| 93 |
}; |
| 94 |
|
| 95 |
/* Step 2. */ |
| 96 |
while (srcBegin != srcEnd) { |
| 97 |
const SrcCharT c = *srcBegin++; |
| 98 |
|
| 99 |
// Handle the Latin-1 cases. |
| 100 |
if (MOZ_LIKELY(c < sizeof(escapeLookup))) { |
| 101 |
Latin1Char escaped = escapeLookup[c]; |
| 102 |
|
| 103 |
// Directly copy non-escaped code points. |
| 104 |
if (escaped == 0) { |
| 105 |
*dstPtr++ = c; |
| 106 |
continue; |
| 107 |
} |
| 108 |
|
| 109 |
// Escape the rest, elaborating Unicode escapes when needed. |
| 110 |
*dstPtr++ = '\\'; |
| 111 |
*dstPtr++ = escaped; |
| 112 |
if (escaped == 'u') { |
| 113 |
*dstPtr++ = '0'; |
| 114 |
*dstPtr++ = '0'; |
| 115 |
|
| 116 |
uint8_t x = c >> 4; |
| 117 |
MOZ_ASSERT(x < 10); |
| 118 |
*dstPtr++ = '0' + x; |
| 119 |
|
| 120 |
*dstPtr++ = ToLowerHex(c & 0xF); |
| 121 |
} |
| 122 |
|
| 123 |
continue; |
| 124 |
} |
| 125 |
|
| 126 |
// Non-ASCII non-surrogates are directly copied. |
| 127 |
if (!unicode::IsSurrogate(c)) { |
| 128 |
*dstPtr++ = c; |
| 129 |
continue; |
| 130 |
} |
| 131 |
|
| 132 |
// So too for complete surrogate pairs. |
| 133 |
if (MOZ_LIKELY(unicode::IsLeadSurrogate(c) && srcBegin < srcEnd && |
| 134 |
unicode::IsTrailSurrogate(*srcBegin))) { |
| 135 |
*dstPtr++ = c; |
| 136 |
*dstPtr++ = *srcBegin++; |
| 137 |
continue; |
| 138 |
} |
| 139 |
|
| 140 |
// But lone surrogates are Unicode-escaped. |
| 141 |
char32_t as32 = char32_t(c); |
| 142 |
*dstPtr++ = '\\'; |
| 143 |
*dstPtr++ = 'u'; |
| 144 |
*dstPtr++ = ToLowerHex(as32 >> 12); |
| 145 |
*dstPtr++ = ToLowerHex((as32 >> 8) & 0xF); |
| 146 |
*dstPtr++ = ToLowerHex((as32 >> 4) & 0xF); |
| 147 |
*dstPtr++ = ToLowerHex(as32 & 0xF); |
| 148 |
} |
| 149 |
|
| 150 |
/* Steps 3-4. */ |
| 151 |
*dstPtr++ = '"'; |
| 152 |
return dstPtr; |
| 153 |
} |
| 154 |
|
| 155 |
template <typename SrcCharT, typename DstCharT> |
| 156 |
static size_t QuoteJSONStringHelper(const JSLinearString& linear, |
| 157 |
StringBuilder& sb, size_t sbOffset) { |
| 158 |
size_t len = linear.length(); |
| 159 |
|
| 160 |
JS::AutoCheckCannotGC nogc; |
| 161 |
RangedPtr<const SrcCharT> srcBegin{linear.chars<SrcCharT>(nogc), len}; |
| 162 |
RangedPtr<DstCharT> dstBegin{sb.begin<DstCharT>(), sb.begin<DstCharT>(), |
| 163 |
sb.end<DstCharT>()}; |
| 164 |
RangedPtr<DstCharT> dstEnd = |
| 165 |
InfallibleQuoteJSONString(srcBegin, srcBegin + len, dstBegin + sbOffset); |
| 166 |
|
| 167 |
return dstEnd - dstBegin; |
| 168 |
} |
| 169 |
|
| 170 |
static bool QuoteJSONString(JSContext* cx, StringBuilder& sb, JSString* str) { |
| 171 |
JSLinearString* linear = str->ensureLinear(cx); |
| 172 |
if (!linear) { |
| 173 |
return false; |
| 174 |
} |
| 175 |
|
| 176 |
if (linear->hasTwoByteChars() && !sb.ensureTwoByteChars()) { |
| 177 |
return false; |
| 178 |
} |
| 179 |
|
| 180 |
// We resize the backing buffer to the maximum size we could possibly need, |
| 181 |
// write the escaped string into it, and shrink it back to the size we ended |
| 182 |
// up needing. |
| 183 |
|
| 184 |
size_t len = linear->length(); |
| 185 |
size_t sbInitialLen = sb.length(); |
| 186 |
|
| 187 |
CheckedInt<size_t> reservedLen = CheckedInt<size_t>(len) * 6 + 2; |
| 188 |
if (MOZ_UNLIKELY(!reservedLen.isValid())) { |
| 189 |
ReportAllocationOverflow(cx); |
| 190 |
return false; |
| 191 |
} |
| 192 |
|
| 193 |
if (!sb.growByUninitialized(reservedLen.value())) { |
| 194 |
return false; |
| 195 |
} |
| 196 |
|
| 197 |
size_t newSize; |
| 198 |
|
| 199 |
if (linear->hasTwoByteChars()) { |
| 200 |
newSize = |
| 201 |
QuoteJSONStringHelper<char16_t, char16_t>(*linear, sb, sbInitialLen); |
| 202 |
} else if (sb.isUnderlyingBufferLatin1()) { |
| 203 |
newSize = QuoteJSONStringHelper<Latin1Char, Latin1Char>(*linear, sb, |
| 204 |
sbInitialLen); |
| 205 |
} else { |
| 206 |
newSize = |
| 207 |
QuoteJSONStringHelper<Latin1Char, char16_t>(*linear, sb, sbInitialLen); |
| 208 |
} |
| 209 |
|
| 210 |
sb.shrinkTo(newSize); |
| 211 |
|
| 212 |
return true; |
| 213 |
} |
| 214 |
|
| 215 |
namespace { |
| 216 |
|
| 217 |
using ObjectVector = GCVector<JSObject*, 8>; |
| 218 |
|
| 219 |
class StringifyContext { |
| 220 |
public: |
| 221 |
StringifyContext(JSContext* cx, StringBuilder& sb, const StringBuilder& gap, |
| 222 |
HandleObject replacer, const RootedIdVector& propertyList, |
| 223 |
bool maybeSafely) |
| 224 |
: sb(sb), |
| 225 |
gap(gap), |
| 226 |
replacer(cx, replacer), |
| 227 |
stack(cx, ObjectVector(cx)), |
| 228 |
propertyList(propertyList), |
| 229 |
depth(0), |
| 230 |
maybeSafely(maybeSafely) { |
| 231 |
MOZ_ASSERT_IF(maybeSafely, !replacer); |
| 232 |
MOZ_ASSERT_IF(maybeSafely, gap.empty()); |
| 233 |
} |
| 234 |
|
| 235 |
StringBuilder& sb; |
| 236 |
const StringBuilder& gap; |
| 237 |
RootedObject replacer; |
| 238 |
Rooted<ObjectVector> stack; |
| 239 |
const RootedIdVector& propertyList; |
| 240 |
uint32_t depth; |
| 241 |
bool maybeSafely; |
| 242 |
}; |
| 243 |
|
| 244 |
} /* anonymous namespace */ |
| 245 |
|
| 246 |
static bool SerializeJSONProperty(JSContext* cx, const Value& v, |
| 247 |
StringifyContext* scx); |
| 248 |
|
| 249 |
static bool WriteIndent(StringifyContext* scx, uint32_t limit) { |
| 250 |
if (!scx->gap.empty()) { |
| 251 |
if (!scx->sb.append('\n')) { |
| 252 |
return false; |
| 253 |
} |
| 254 |
|
| 255 |
if (scx->gap.isUnderlyingBufferLatin1()) { |
| 256 |
for (uint32_t i = 0; i < limit; i++) { |
| 257 |
if (!scx->sb.append(scx->gap.rawLatin1Begin(), |
| 258 |
scx->gap.rawLatin1End())) { |
| 259 |
return false; |
| 260 |
} |
| 261 |
} |
| 262 |
} else { |
| 263 |
for (uint32_t i = 0; i < limit; i++) { |
| 264 |
if (!scx->sb.append(scx->gap.rawTwoByteBegin(), |
| 265 |
scx->gap.rawTwoByteEnd())) { |
| 266 |
return false; |
| 267 |
} |
| 268 |
} |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
return true; |
| 273 |
} |
| 274 |
|
| 275 |
namespace { |
| 276 |
|
| 277 |
template <typename KeyType> |
| 278 |
class KeyStringifier {}; |
| 279 |
|
| 280 |
template <> |
| 281 |
class KeyStringifier<uint32_t> { |
| 282 |
public: |
| 283 |
static JSString* toString(JSContext* cx, uint32_t index) { |
| 284 |
return IndexToString(cx, index); |
| 285 |
} |
| 286 |
}; |
| 287 |
|
| 288 |
template <> |
| 289 |
class KeyStringifier<HandleId> { |
| 290 |
public: |
| 291 |
static JSString* toString(JSContext* cx, HandleId id) { |
| 292 |
return IdToString(cx, id); |
| 293 |
} |
| 294 |
}; |
| 295 |
|
| 296 |
} /* anonymous namespace */ |
| 297 |
|
| 298 |
/* |
| 299 |
* https://262.ecma-international.org/14.0/#sec-serializejsonproperty, steps |
| 300 |
* 2-4, extracted to enable preprocessing of property values when stringifying |
| 301 |
* objects in SerializeJSONObject. |
| 302 |
*/ |
| 303 |
template <typename KeyType> |
| 304 |
static bool PreprocessValue(JSContext* cx, HandleObject holder, KeyType key, |
| 305 |
MutableHandleValue vp, StringifyContext* scx) { |
| 306 |
// We don't want to do any preprocessing here if scx->maybeSafely, |
| 307 |
// since the stuff we do here can have side-effects. |
| 308 |
if (scx->maybeSafely) { |
| 309 |
return true; |
| 310 |
} |
| 311 |
|
| 312 |
RootedString keyStr(cx); |
| 313 |
|
| 314 |
// Step 2. Modified by BigInt spec 6.1 to check for a toJSON method on the |
| 315 |
// BigInt prototype when the value is a BigInt, and to pass the BigInt |
| 316 |
// primitive value as receiver. |
| 317 |
if (vp.isObject() || vp.isBigInt()) { |
| 318 |
RootedValue toJSON(cx); |
| 319 |
RootedObject obj(cx, JS::ToObject(cx, vp)); |
| 320 |
if (!obj) { |
| 321 |
return false; |
| 322 |
} |
| 323 |
|
| 324 |
if (!GetProperty(cx, obj, vp, cx->names().toJSON, &toJSON)) { |
| 325 |
return false; |
| 326 |
} |
| 327 |
|
| 328 |
if (IsCallable(toJSON)) { |
| 329 |
keyStr = KeyStringifier<KeyType>::toString(cx, key); |
| 330 |
if (!keyStr) { |
| 331 |
return false; |
| 332 |
} |
| 333 |
|
| 334 |
RootedValue arg0(cx, StringValue(keyStr)); |
| 335 |
if (!js::Call(cx, toJSON, vp, arg0, vp)) { |
| 336 |
return false; |
| 337 |
} |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
/* Step 3. */ |
| 342 |
if (scx->replacer && scx->replacer->isCallable()) { |
| 343 |
MOZ_ASSERT(holder != nullptr, |
| 344 |
"holder object must be present when replacer is callable"); |
| 345 |
|
| 346 |
if (!keyStr) { |
| 347 |
keyStr = KeyStringifier<KeyType>::toString(cx, key); |
| 348 |
if (!keyStr) { |
| 349 |
return false; |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
RootedValue arg0(cx, StringValue(keyStr)); |
| 354 |
RootedValue replacerVal(cx, ObjectValue(*scx->replacer)); |
| 355 |
if (!js::Call(cx, replacerVal, holder, arg0, vp, vp)) { |
| 356 |
return false; |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
/* Step 4. */ |
| 361 |
if (vp.get().isObject()) { |
| 362 |
RootedObject obj(cx, &vp.get().toObject()); |
| 363 |
|
| 364 |
ESClass cls; |
| 365 |
if (!JS::GetBuiltinClass(cx, obj, &cls)) { |
| 366 |
return false; |
| 367 |
} |
| 368 |
|
| 369 |
if (cls == ESClass::Number) { |
| 370 |
double d; |
| 371 |
if (!ToNumber(cx, vp, &d)) { |
| 372 |
return false; |
| 373 |
} |
| 374 |
vp.setNumber(d); |
| 375 |
} else if (cls == ESClass::String) { |
| 376 |
JSString* str = ToStringSlow<CanGC>(cx, vp); |
| 377 |
if (!str) { |
| 378 |
return false; |
| 379 |
} |
| 380 |
vp.setString(str); |
| 381 |
} else if (cls == ESClass::Boolean || cls == ESClass::BigInt) { |
| 382 |
if (!Unbox(cx, obj, vp)) { |
| 383 |
return false; |
| 384 |
} |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
return true; |
| 389 |
} |
| 390 |
|
| 391 |
/* |
| 392 |
* Determines whether a value which has passed by |
| 393 |
* https://262.ecma-international.org/14.0/#sec-serializejsonproperty steps |
| 394 |
* 1-4's gauntlet will result in SerializeJSONProperty returning |undefined|. |
| 395 |
* This function is used to properly omit properties resulting in such values |
| 396 |
* when stringifying objects, while properly stringifying such properties as |
| 397 |
* null when they're encountered in arrays. |
| 398 |
*/ |
| 399 |
static inline bool IsFilteredValue(const Value& v) { |
| 400 |
MOZ_ASSERT_IF(v.isMagic(), v.isMagic(JS_ELEMENTS_HOLE)); |
| 401 |
return v.isUndefined() || v.isSymbol() || v.isMagic() || IsCallable(v); |
| 402 |
} |
| 403 |
|
| 404 |
class CycleDetector { |
| 405 |
public: |
| 406 |
CycleDetector(StringifyContext* scx, HandleObject obj) |
| 407 |
: stack_(&scx->stack), obj_(obj), appended_(false) {} |
| 408 |
|
| 409 |
MOZ_ALWAYS_INLINE bool foundCycle(JSContext* cx) { |
| 410 |
JSObject* obj = obj_; |
| 411 |
for (JSObject* obj2 : stack_) { |
| 412 |
if (MOZ_UNLIKELY(obj == obj2)) { |
| 413 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 414 |
JSMSG_JSON_CYCLIC_VALUE); |
| 415 |
return false; |
| 416 |
} |
| 417 |
} |
| 418 |
appended_ = stack_.append(obj); |
| 419 |
return appended_; |
| 420 |
} |
| 421 |
|
| 422 |
~CycleDetector() { |
| 423 |
if (MOZ_LIKELY(appended_)) { |
| 424 |
MOZ_ASSERT(stack_.back() == obj_); |
| 425 |
stack_.popBack(); |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
private: |
| 430 |
MutableHandle<ObjectVector> stack_; |
| 431 |
HandleObject obj_; |
| 432 |
bool appended_; |
| 433 |
}; |
| 434 |
|
| 435 |
static inline JSString* MaybeGetRawJSON(JSContext* cx, JSObject* obj) { |
| 436 |
auto* unwrappedObj = obj->maybeUnwrapIf<js::RawJSONObject>(); |
| 437 |
if (!unwrappedObj) { |
| 438 |
return nullptr; |
| 439 |
} |
| 440 |
JSAutoRealm ar(cx, unwrappedObj); |
| 441 |
|
| 442 |
JSString* rawJSON = unwrappedObj->rawJSON(cx); |
| 443 |
MOZ_ASSERT(rawJSON); |
| 444 |
return rawJSON; |
| 445 |
} |
| 446 |
|
| 447 |
/* https://262.ecma-international.org/14.0/#sec-serializejsonobject */ |
| 448 |
static bool SerializeJSONObject(JSContext* cx, HandleObject obj, |
| 449 |
StringifyContext* scx) { |
| 450 |
/* |
| 451 |
* This method implements the SerializeJSONObject algorithm, but: |
| 452 |
* |
| 453 |
* * The algorithm is somewhat reformulated to allow the final string to |
| 454 |
* be streamed into a single buffer, rather than be created and copied |
| 455 |
* into place incrementally as the algorithm specifies it. This |
| 456 |
* requires moving portions of the SerializeJSONProperty call in 8a into |
| 457 |
* this algorithm (and in SerializeJSONArray as well). |
| 458 |
*/ |
| 459 |
|
| 460 |
MOZ_ASSERT_IF(scx->maybeSafely, obj->is<PlainObject>()); |
| 461 |
|
| 462 |
/* Steps 1-2, 11. */ |
| 463 |
CycleDetector detect(scx, obj); |
| 464 |
if (!detect.foundCycle(cx)) { |
| 465 |
return false; |
| 466 |
} |
| 467 |
|
| 468 |
if (!scx->sb.append('{')) { |
| 469 |
return false; |
| 470 |
} |
| 471 |
|
| 472 |
/* Steps 5-7. */ |
| 473 |
Maybe<RootedIdVector> ids; |
| 474 |
const RootedIdVector* props; |
| 475 |
if (scx->replacer && !scx->replacer->isCallable()) { |
| 476 |
// NOTE: We can't assert |IsArray(scx->replacer)| because the replacer |
| 477 |
// might have been a revocable proxy to an array. Such a proxy |
| 478 |
// satisfies |IsArray|, but any side effect of JSON.stringify |
| 479 |
// could revoke the proxy so that |!IsArray(scx->replacer)|. See |
| 480 |
// bug 1196497. |
| 481 |
props = &scx->propertyList; |
| 482 |
} else { |
| 483 |
MOZ_ASSERT_IF(scx->replacer, scx->propertyList.length() == 0); |
| 484 |
ids.emplace(cx); |
| 485 |
if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, ids.ptr())) { |
| 486 |
return false; |
| 487 |
} |
| 488 |
props = ids.ptr(); |
| 489 |
} |
| 490 |
|
| 491 |
/* My kingdom for not-quite-initialized-from-the-start references. */ |
| 492 |
const RootedIdVector& propertyList = *props; |
| 493 |
|
| 494 |
/* Steps 8-10, 13. */ |
| 495 |
bool wroteMember = false; |
| 496 |
RootedId id(cx); |
| 497 |
for (size_t i = 0, len = propertyList.length(); i < len; i++) { |
| 498 |
if (!CheckForInterrupt(cx)) { |
| 499 |
return false; |
| 500 |
} |
| 501 |
|
| 502 |
/* |
| 503 |
* Steps 8a-8b. Note that the call to SerializeJSONProperty is broken up |
| 504 |
* into 1) getting the property; 2) processing for toJSON, calling the |
| 505 |
* replacer, and handling boxed Number/String/Boolean objects; 3) filtering |
| 506 |
* out values which process to |undefined|, and 4) stringifying all values |
| 507 |
* which pass the filter. |
| 508 |
*/ |
| 509 |
id = propertyList[i]; |
| 510 |
RootedValue outputValue(cx); |
| 511 |
#ifdef DEBUG |
| 512 |
if (scx->maybeSafely) { |
| 513 |
PropertyResult prop; |
| 514 |
if (!NativeLookupOwnPropertyNoResolve(cx, &obj->as<NativeObject>(), id, |
| 515 |
&prop)) { |
| 516 |
return false; |
| 517 |
} |
| 518 |
MOZ_ASSERT(prop.isNativeProperty() && |
| 519 |
prop.propertyInfo().isDataDescriptor()); |
| 520 |
} |
| 521 |
#endif // DEBUG |
| 522 |
{ |
| 523 |
RootedValue objValue(cx, ObjectValue(*obj)); |
| 524 |
if (!GetProperty(cx, obj, objValue, id, &outputValue)) { |
| 525 |
return false; |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
if (!PreprocessValue(cx, obj, HandleId(id), &outputValue, scx)) { |
| 530 |
return false; |
| 531 |
} |
| 532 |
if (IsFilteredValue(outputValue)) { |
| 533 |
continue; |
| 534 |
} |
| 535 |
|
| 536 |
/* Output a comma unless this is the first member to write. */ |
| 537 |
if (wroteMember && !scx->sb.append(',')) { |
| 538 |
return false; |
| 539 |
} |
| 540 |
wroteMember = true; |
| 541 |
|
| 542 |
if (!WriteIndent(scx, scx->depth)) { |
| 543 |
return false; |
| 544 |
} |
| 545 |
|
| 546 |
JSString* s = IdToString(cx, id); |
| 547 |
if (!s) { |
| 548 |
return false; |
| 549 |
} |
| 550 |
|
| 551 |
if (!QuoteJSONString(cx, scx->sb, s) || !scx->sb.append(':') || |
| 552 |
!(scx->gap.empty() || scx->sb.append(' ')) || |
| 553 |
!SerializeJSONProperty(cx, outputValue, scx)) { |
| 554 |
return false; |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
if (wroteMember && !WriteIndent(scx, scx->depth - 1)) { |
| 559 |
return false; |
| 560 |
} |
| 561 |
|
| 562 |
return scx->sb.append('}'); |
| 563 |
} |
| 564 |
|
| 565 |
// For JSON.stringify and JSON.parse with a reviver function, we need to know |
| 566 |
// the length of an object for which JS::IsArray returned true. This must be |
| 567 |
// either an ArrayObject or a proxy wrapping one. |
| 568 |
static MOZ_ALWAYS_INLINE bool GetLengthPropertyForArrayLike(JSContext* cx, |
| 569 |
HandleObject obj, |
| 570 |
uint32_t* lengthp) { |
| 571 |
if (MOZ_LIKELY(obj->is<ArrayObject>())) { |
| 572 |
*lengthp = obj->as<ArrayObject>().length(); |
| 573 |
return true; |
| 574 |
} |
| 575 |
|
| 576 |
MOZ_ASSERT(obj->is<ProxyObject>()); |
| 577 |
|
| 578 |
uint64_t len = 0; |
| 579 |
if (!GetLengthProperty(cx, obj, &len)) { |
| 580 |
return false; |
| 581 |
} |
| 582 |
|
| 583 |
// A scripted proxy wrapping an array can return a length value larger than |
| 584 |
// UINT32_MAX. Stringification will likely report an OOM in this case. Match |
| 585 |
// other JS engines and report an early error in this case, although |
| 586 |
// technically this is observable, for example when stringifying with a |
| 587 |
// replacer function. |
| 588 |
if (len > UINT32_MAX) { |
| 589 |
ReportAllocationOverflow(cx); |
| 590 |
return false; |
| 591 |
} |
| 592 |
|
| 593 |
*lengthp = uint32_t(len); |
| 594 |
return true; |
| 595 |
} |
| 596 |
|
| 597 |
/* https://262.ecma-international.org/14.0/#sec-serializejsonarray */ |
| 598 |
static bool SerializeJSONArray(JSContext* cx, HandleObject obj, |
| 599 |
StringifyContext* scx) { |
| 600 |
/* |
| 601 |
* This method implements the SerializeJSONArray algorithm, but: |
| 602 |
* |
| 603 |
* * The algorithm is somewhat reformulated to allow the final string to |
| 604 |
* be streamed into a single buffer, rather than be created and copied |
| 605 |
* into place incrementally as the algorithm specifies it. This |
| 606 |
* requires moving portions of the SerializeJSONProperty call in 8a into |
| 607 |
* this algorithm (and in SerializeJSONObject as well). |
| 608 |
*/ |
| 609 |
|
| 610 |
/* Steps 1-2, 11. */ |
| 611 |
CycleDetector detect(scx, obj); |
| 612 |
if (!detect.foundCycle(cx)) { |
| 613 |
return false; |
| 614 |
} |
| 615 |
|
| 616 |
if (!scx->sb.append('[')) { |
| 617 |
return false; |
| 618 |
} |
| 619 |
|
| 620 |
/* Step 6. */ |
| 621 |
uint32_t length; |
| 622 |
if (!GetLengthPropertyForArrayLike(cx, obj, &length)) { |
| 623 |
return false; |
| 624 |
} |
| 625 |
|
| 626 |
/* Steps 7-10. */ |
| 627 |
if (length != 0) { |
| 628 |
/* Steps 4, 10b(i). */ |
| 629 |
if (!WriteIndent(scx, scx->depth)) { |
| 630 |
return false; |
| 631 |
} |
| 632 |
|
| 633 |
/* Steps 7-10. */ |
| 634 |
RootedValue outputValue(cx); |
| 635 |
for (uint32_t i = 0; i < length; i++) { |
| 636 |
if (!CheckForInterrupt(cx)) { |
| 637 |
return false; |
| 638 |
} |
| 639 |
|
| 640 |
/* |
| 641 |
* Steps 8a-8c. Again note how the call to the spec's |
| 642 |
* SerializeJSONProperty method is broken up into getting the property, |
| 643 |
* running it past toJSON and the replacer and maybe unboxing, and |
| 644 |
* interpreting some values as |null| in separate steps. |
| 645 |
*/ |
| 646 |
#ifdef DEBUG |
| 647 |
if (scx->maybeSafely) { |
| 648 |
/* |
| 649 |
* Trying to do a JS_AlreadyHasOwnElement runs the risk of |
| 650 |
* hitting OOM on jsid creation. Let's just assert sanity for |
| 651 |
* small enough indices. |
| 652 |
*/ |
| 653 |
MOZ_ASSERT(obj->is<ArrayObject>()); |
| 654 |
MOZ_ASSERT(obj->is<NativeObject>()); |
| 655 |
Rooted<NativeObject*> nativeObj(cx, &obj->as<NativeObject>()); |
| 656 |
if (i <= PropertyKey::IntMax) { |
| 657 |
MOZ_ASSERT( |
| 658 |
nativeObj->containsDenseElement(i) != nativeObj->isIndexed(), |
| 659 |
"the array must either be small enough to remain " |
| 660 |
"fully dense (and otherwise un-indexed), *or* " |
| 661 |
"all its initially-dense elements were sparsified " |
| 662 |
"and the object is indexed"); |
| 663 |
} else { |
| 664 |
MOZ_ASSERT(nativeObj->isIndexed()); |
| 665 |
} |
| 666 |
} |
| 667 |
#endif |
| 668 |
if (!GetElement(cx, obj, i, &outputValue)) { |
| 669 |
return false; |
| 670 |
} |
| 671 |
if (!PreprocessValue(cx, obj, i, &outputValue, scx)) { |
| 672 |
return false; |
| 673 |
} |
| 674 |
if (IsFilteredValue(outputValue)) { |
| 675 |
if (!scx->sb.append("null")) { |
| 676 |
return false; |
| 677 |
} |
| 678 |
} else { |
| 679 |
if (!SerializeJSONProperty(cx, outputValue, scx)) { |
| 680 |
return false; |
| 681 |
} |
| 682 |
} |
| 683 |
|
| 684 |
/* Steps 3, 4, 10b(i). */ |
| 685 |
if (i < length - 1) { |
| 686 |
if (!scx->sb.append(',')) { |
| 687 |
return false; |
| 688 |
} |
| 689 |
if (!WriteIndent(scx, scx->depth)) { |
| 690 |
return false; |
| 691 |
} |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
/* Step 10(b)(iii). */ |
| 696 |
if (!WriteIndent(scx, scx->depth - 1)) { |
| 697 |
return false; |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
return scx->sb.append(']'); |
| 702 |
} |
| 703 |
|
| 704 |
/* https://262.ecma-international.org/14.0/#sec-serializejsonproperty */ |
| 705 |
static bool SerializeJSONProperty(JSContext* cx, const Value& v, |
| 706 |
StringifyContext* scx) { |
| 707 |
/* Step 12 must be handled by the caller. */ |
| 708 |
MOZ_ASSERT(!IsFilteredValue(v)); |
| 709 |
|
| 710 |
/* |
| 711 |
* This method implements the SerializeJSONProperty algorithm, but: |
| 712 |
* |
| 713 |
* * We move property retrieval (step 1) into callers to stream the |
| 714 |
* stringification process and avoid constantly copying strings. |
| 715 |
* * We move the preprocessing in steps 2-4 into a helper function to |
| 716 |
* allow both SerializeJSONObject and SerializeJSONArray to use this |
| 717 |
* method. While SerializeJSONArray could use it without this move, |
| 718 |
* SerializeJSONObject must omit any |undefined|-valued property per so it |
| 719 |
* can't stream out a value using the SerializeJSONProperty method exactly as |
| 720 |
* defined by the spec. |
| 721 |
* * We move step 12 into callers, again to ease streaming. |
| 722 |
*/ |
| 723 |
|
| 724 |
/* Step 8. */ |
| 725 |
if (v.isString()) { |
| 726 |
return QuoteJSONString(cx, scx->sb, v.toString()); |
| 727 |
} |
| 728 |
|
| 729 |
/* Step 5. */ |
| 730 |
if (v.isNull()) { |
| 731 |
return scx->sb.append("null"); |
| 732 |
} |
| 733 |
|
| 734 |
/* Steps 6-7. */ |
| 735 |
if (v.isBoolean()) { |
| 736 |
return v.toBoolean() ? scx->sb.append("true") : scx->sb.append("false"); |
| 737 |
} |
| 738 |
|
| 739 |
/* Step 9. */ |
| 740 |
if (v.isNumber()) { |
| 741 |
if (v.isDouble()) { |
| 742 |
if (!std::isfinite(v.toDouble())) { |
| 743 |
MOZ_ASSERT(!scx->maybeSafely, |
| 744 |
"input JS::ToJSONMaybeSafely must not include " |
| 745 |
"reachable non-finite numbers"); |
| 746 |
return scx->sb.append("null"); |
| 747 |
} |
| 748 |
} |
| 749 |
|
| 750 |
return NumberValueToStringBuilder(v, scx->sb); |
| 751 |
} |
| 752 |
|
| 753 |
/* Step 10. */ |
| 754 |
if (v.isBigInt()) { |
| 755 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 756 |
JSMSG_BIGINT_NOT_SERIALIZABLE); |
| 757 |
return false; |
| 758 |
} |
| 759 |
|
| 760 |
AutoCheckRecursionLimit recursion(cx); |
| 761 |
if (!recursion.check(cx)) { |
| 762 |
return false; |
| 763 |
} |
| 764 |
|
| 765 |
/* Step 11. */ |
| 766 |
MOZ_ASSERT(v.isObject()); |
| 767 |
RootedObject obj(cx, &v.toObject()); |
| 768 |
|
| 769 |
/* https://tc39.es/proposal-json-parse-with-source/#sec-serializejsonproperty |
| 770 |
* Step 4a.*/ |
| 771 |
if (JSString* rawJSON = MaybeGetRawJSON(cx, obj)) { |
| 772 |
return scx->sb.append(rawJSON); |
| 773 |
} |
| 774 |
|
| 775 |
MOZ_ASSERT( |
| 776 |
!scx->maybeSafely || obj->is<PlainObject>() || obj->is<ArrayObject>(), |
| 777 |
"input to JS::ToJSONMaybeSafely must not include reachable " |
| 778 |
"objects that are neither arrays nor plain objects"); |
| 779 |
|
| 780 |
scx->depth++; |
| 781 |
auto dec = mozilla::MakeScopeExit([&] { scx->depth--; }); |
| 782 |
|
| 783 |
bool isArray; |
| 784 |
if (!IsArray(cx, obj, &isArray)) { |
| 785 |
return false; |
| 786 |
} |
| 787 |
|
| 788 |
return isArray ? SerializeJSONArray(cx, obj, scx) |
| 789 |
: SerializeJSONObject(cx, obj, scx); |
| 790 |
} |
| 791 |
|
| 792 |
static bool CanFastStringifyObject(NativeObject* obj) { |
| 793 |
if (ClassCanHaveExtraEnumeratedProperties(obj->getClass())) { |
| 794 |
return false; |
| 795 |
} |
| 796 |
|
| 797 |
if (obj->is<ArrayObject>()) { |
| 798 |
// Arrays will look up all keys [0..length) so disallow anything that could |
| 799 |
// find those keys anywhere but in the dense elements. |
| 800 |
if (!IsPackedArray(obj) && ObjectMayHaveExtraIndexedProperties(obj)) { |
| 801 |
return false; |
| 802 |
} |
| 803 |
} else { |
| 804 |
// Non-Arrays will only look at own properties, but still disallow any |
| 805 |
// indexed properties other than in the dense elements because they would |
| 806 |
// require sorting. |
| 807 |
if (ObjectMayHaveExtraIndexedOwnProperties(obj)) { |
| 808 |
return false; |
| 809 |
} |
| 810 |
} |
| 811 |
|
| 812 |
// Only used for internal environment objects that should never be passed to |
| 813 |
// JSON.stringify. |
| 814 |
MOZ_ASSERT(!obj->getOpsLookupProperty()); |
| 815 |
|
| 816 |
return true; |
| 817 |
} |
| 818 |
|
| 819 |
#define FOR_EACH_STRINGIFY_BAIL_REASON(MACRO) \ |
| 820 |
MACRO(NO_REASON) \ |
| 821 |
MACRO(INELIGIBLE_OBJECT) \ |
| 822 |
MACRO(DEEP_RECURSION) \ |
| 823 |
MACRO(NON_DATA_PROPERTY) \ |
| 824 |
MACRO(TOO_MANY_PROPERTIES) \ |
| 825 |
MACRO(BIGINT) \ |
| 826 |
MACRO(API) \ |
| 827 |
MACRO(HAVE_REPLACER) \ |
| 828 |
MACRO(HAVE_SPACE) \ |
| 829 |
MACRO(PRIMITIVE) \ |
| 830 |
MACRO(HAVE_TOJSON) \ |
| 831 |
MACRO(IMPURE_LOOKUP) \ |
| 832 |
MACRO(INTERRUPT) |
| 833 |
|
| 834 |
enum class BailReason : uint8_t { |
| 835 |
#define DECLARE_ENUM(name) name, |
| 836 |
FOR_EACH_STRINGIFY_BAIL_REASON(DECLARE_ENUM) |
| 837 |
#undef DECLARE_ENUM |
| 838 |
}; |
| 839 |
|
| 840 |
static const char* DescribeStringifyBailReason(BailReason whySlow) { |
| 841 |
switch (whySlow) { |
| 842 |
#define ENUM_NAME(name) \ |
| 843 |
case BailReason::name: \ |
| 844 |
return #name; |
| 845 |
FOR_EACH_STRINGIFY_BAIL_REASON(ENUM_NAME) |
| 846 |
#undef ENUM_NAME |
| 847 |
default: |
| 848 |
return "Unknown"; |
| 849 |
} |
| 850 |
} |
| 851 |
|
| 852 |
// Iterator over all the dense elements of an object. Used |
| 853 |
// for both Arrays and non-Arrays. |
| 854 |
class DenseElementsIteratorForJSON { |
| 855 |
HeapSlotArray elements; |
| 856 |
uint32_t element; |
| 857 |
|
| 858 |
// Arrays can have a length less than getDenseInitializedLength(), in which |
| 859 |
// case the remaining Array elements are treated as UndefinedValue. |
| 860 |
uint32_t numElements; |
| 861 |
uint32_t length; |
| 862 |
|
| 863 |
public: |
| 864 |
explicit DenseElementsIteratorForJSON(NativeObject* nobj) |
| 865 |
: elements(nobj->getDenseElements()), |
| 866 |
element(0), |
| 867 |
numElements(nobj->getDenseInitializedLength()) { |
| 868 |
length = nobj->is<ArrayObject>() ? nobj->as<ArrayObject>().length() |
| 869 |
: numElements; |
| 870 |
} |
| 871 |
|
| 872 |
bool done() const { return element == length; } |
| 873 |
|
| 874 |
Value next() { |
| 875 |
// For Arrays, steps 6-8 of |
| 876 |
// https://262.ecma-international.org/14.0/#sec-serializejsonarray. For |
| 877 |
// non-Arrays, step 6a of |
| 878 |
// https://262.ecma-international.org/14.0/#sec-serializejsonobject |
| 879 |
// following the order from |
| 880 |
// https://262.ecma-international.org/14.0/#sec-ordinaryownpropertykeys |
| 881 |
|
| 882 |
MOZ_ASSERT(!done()); |
| 883 |
auto i = element++; |
| 884 |
// Consider specializing the iterator for Arrays vs non-Arrays to avoid this |
| 885 |
// branch. |
| 886 |
return i < numElements ? elements.begin()[i] : UndefinedValue(); |
| 887 |
} |
| 888 |
|
| 889 |
uint32_t getIndex() const { return element; } |
| 890 |
}; |
| 891 |
|
| 892 |
// An iterator over the non-element properties of a Shape, returned in forward |
| 893 |
// (creation) order. Note that it is fallible, so after iteration is complete |
| 894 |
// isOverflowed() should be called to verify that the results are actually |
| 895 |
// complete. |
| 896 |
|
| 897 |
class ShapePropertyForwardIterNoGC { |
| 898 |
// Pointer to the current PropMap with length and an index within it. |
| 899 |
PropMap* map_; |
| 900 |
uint32_t mapLength_; |
| 901 |
uint32_t i_ = 0; |
| 902 |
|
| 903 |
// Stack of PropMaps to iterate through, oldest properties on top. The current |
| 904 |
// map (map_, above) is never on this stack. |
| 905 |
mozilla::Vector<PropMap*> stack_; |
| 906 |
|
| 907 |
const NativeShape* shape_; |
| 908 |
|
| 909 |
MOZ_ALWAYS_INLINE void settle() { |
| 910 |
while (true) { |
| 911 |
if (MOZ_UNLIKELY(i_ == mapLength_)) { |
| 912 |
i_ = 0; |
| 913 |
if (stack_.empty()) { |
| 914 |
mapLength_ = 0; // Done |
| 915 |
return; |
| 916 |
} |
| 917 |
map_ = stack_.back(); |
| 918 |
stack_.popBack(); |
| 919 |
mapLength_ = |
| 920 |
stack_.empty() ? shape_->propMapLength() : PropMap::Capacity; |
| 921 |
} else if (MOZ_UNLIKELY(shape_->isDictionary() && !map_->hasKey(i_))) { |
| 922 |
// Dictionary maps can have "holes" for removed properties, so keep |
| 923 |
// going until we find a non-hole slot. |
| 924 |
i_++; |
| 925 |
} else { |
| 926 |
return; |
| 927 |
} |
| 928 |
} |
| 929 |
} |
| 930 |
|
| 931 |
public: |
| 932 |
explicit ShapePropertyForwardIterNoGC(NativeShape* shape) : shape_(shape) { |
| 933 |
// Set map_ to the PropMap containing the first property (the deepest map in |
| 934 |
// the previous() chain). Push pointers to all other PropMaps onto stack_. |
| 935 |
map_ = shape->propMap(); |
| 936 |
if (!map_) { |
| 937 |
// No properties. |
| 938 |
i_ = mapLength_ = 0; |
| 939 |
return; |
| 940 |
} |
| 941 |
while (map_->hasPrevious()) { |
| 942 |
if (!stack_.append(map_)) { |
| 943 |
// Overflowed. |
| 944 |
i_ = mapLength_ = UINT32_MAX; |
| 945 |
return; |
| 946 |
} |
| 947 |
map_ = map_->asLinked()->previous(); |
| 948 |
} |
| 949 |
|
| 950 |
// Set mapLength_ to the number of properties in map_ (including dictionary |
| 951 |
// holes, if any.) |
| 952 |
mapLength_ = stack_.empty() ? shape_->propMapLength() : PropMap::Capacity; |
| 953 |
|
| 954 |
settle(); |
| 955 |
} |
| 956 |
|
| 957 |
bool done() const { return i_ == mapLength_; } |
| 958 |
bool isOverflowed() const { return i_ == UINT32_MAX; } |
| 959 |
|
| 960 |
void operator++(int) { |
| 961 |
MOZ_ASSERT(!done()); |
| 962 |
i_++; |
| 963 |
settle(); |
| 964 |
} |
| 965 |
|
| 966 |
PropertyInfoWithKey get() const { |
| 967 |
MOZ_ASSERT(!done()); |
| 968 |
return map_->getPropertyInfoWithKey(i_); |
| 969 |
} |
| 970 |
|
| 971 |
PropertyInfoWithKey operator*() const { return get(); } |
| 972 |
|
| 973 |
// Fake pointer struct to make operator-> work. |
| 974 |
// See https://stackoverflow.com/a/52856349. |
| 975 |
struct FakePtr { |
| 976 |
PropertyInfoWithKey val_; |
| 977 |
const PropertyInfoWithKey* operator->() const { return &val_; } |
| 978 |
}; |
| 979 |
FakePtr operator->() const { return {get()}; } |
| 980 |
}; |
| 981 |
|
| 982 |
// Iterator over EnumerableOwnProperties |
| 983 |
// https://262.ecma-international.org/14.0/#sec-enumerableownproperties |
| 984 |
// that fails if it encounters any accessor properties, as they are not handled |
| 985 |
// by JSON FastSerializeJSONProperty, or if it sees too many properties on one |
| 986 |
// object. |
| 987 |
class OwnNonIndexKeysIterForJSON { |
| 988 |
ShapePropertyForwardIterNoGC shapeIter; |
| 989 |
bool done_ = false; |
| 990 |
BailReason fastFailed_ = BailReason::NO_REASON; |
| 991 |
|
| 992 |
void settle() { |
| 993 |
// Skip over any non-enumerable or Symbol properties, and permanently fail |
| 994 |
// if any enumerable non-data properties are encountered. |
| 995 |
for (; !shapeIter.done(); shapeIter++) { |
| 996 |
if (!shapeIter->enumerable()) { |
| 997 |
continue; |
| 998 |
} |
| 999 |
if (!shapeIter->isDataProperty()) { |
| 1000 |
fastFailed_ = BailReason::NON_DATA_PROPERTY; |
| 1001 |
done_ = true; |
| 1002 |
return; |
| 1003 |
} |
| 1004 |
PropertyKey id = shapeIter->key(); |
| 1005 |
if (!id.isSymbol()) { |
| 1006 |
return; |
| 1007 |
} |
| 1008 |
} |
| 1009 |
done_ = true; |
| 1010 |
} |
| 1011 |
|
| 1012 |
public: |
| 1013 |
explicit OwnNonIndexKeysIterForJSON(const NativeObject* nobj) |
| 1014 |
: shapeIter(nobj->shape()) { |
| 1015 |
if (MOZ_UNLIKELY(shapeIter.isOverflowed())) { |
| 1016 |
fastFailed_ = BailReason::TOO_MANY_PROPERTIES; |
| 1017 |
done_ = true; |
| 1018 |
return; |
| 1019 |
} |
| 1020 |
if (!nobj->hasEnumerableProperty()) { |
| 1021 |
// Non-Arrays with no enumerable properties can just be skipped. |
| 1022 |
MOZ_ASSERT(!nobj->is<ArrayObject>()); |
| 1023 |
done_ = true; |
| 1024 |
return; |
| 1025 |
} |
| 1026 |
settle(); |
| 1027 |
} |
| 1028 |
|
| 1029 |
bool done() const { return done_ || shapeIter.done(); } |
| 1030 |
BailReason cannotFastStringify() const { return fastFailed_; } |
| 1031 |
|
| 1032 |
PropertyInfoWithKey next() { |
| 1033 |
MOZ_ASSERT(!done()); |
| 1034 |
PropertyInfoWithKey prop = shapeIter.get(); |
| 1035 |
shapeIter++; |
| 1036 |
settle(); |
| 1037 |
return prop; |
| 1038 |
} |
| 1039 |
}; |
| 1040 |
|
| 1041 |
// Steps from https://262.ecma-international.org/14.0/#sec-serializejsonproperty |
| 1042 |
static bool EmitSimpleValue(JSContext* cx, StringBuilder& sb, const Value& v) { |
| 1043 |
/* Step 8. */ |
| 1044 |
if (v.isString()) { |
| 1045 |
return QuoteJSONString(cx, sb, v.toString()); |
| 1046 |
} |
| 1047 |
|
| 1048 |
/* Step 5. */ |
| 1049 |
if (v.isNull()) { |
| 1050 |
return sb.append("null"); |
| 1051 |
} |
| 1052 |
|
| 1053 |
/* Steps 6-7. */ |
| 1054 |
if (v.isBoolean()) { |
| 1055 |
return v.toBoolean() ? sb.append("true") : sb.append("false"); |
| 1056 |
} |
| 1057 |
|
| 1058 |
/* Step 9. */ |
| 1059 |
if (v.isNumber()) { |
| 1060 |
if (v.isDouble()) { |
| 1061 |
if (!std::isfinite(v.toDouble())) { |
| 1062 |
return sb.append("null"); |
| 1063 |
} |
| 1064 |
} |
| 1065 |
|
| 1066 |
return NumberValueToStringBuilder(v, sb); |
| 1067 |
} |
| 1068 |
|
| 1069 |
// Unrepresentable values. |
| 1070 |
if (v.isUndefined() || v.isMagic()) { |
| 1071 |
MOZ_ASSERT_IF(v.isMagic(), v.isMagic(JS_ELEMENTS_HOLE)); |
| 1072 |
return sb.append("null"); |
| 1073 |
} |
| 1074 |
|
| 1075 |
/* Step 10. */ |
| 1076 |
MOZ_CRASH("should have validated printable simple value already"); |
| 1077 |
} |
| 1078 |
|
| 1079 |
// https://262.ecma-international.org/14.0/#sec-serializejsonproperty step 8b |
| 1080 |
// where K is an integer index. |
| 1081 |
static bool EmitQuotedIndexColon(StringBuilder& sb, uint32_t index) { |
| 1082 |
Int32ToCStringBuf cbuf; |
| 1083 |
size_t cstrlen; |
| 1084 |
const char* cstr = ::Int32ToCString(&cbuf, index, &cstrlen); |
| 1085 |
if (!sb.reserve(sb.length() + 1 + cstrlen + 1 + 1)) { |
| 1086 |
return false; |
| 1087 |
} |
| 1088 |
sb.infallibleAppend('"'); |
| 1089 |
sb.infallibleAppend(cstr, cstrlen); |
| 1090 |
sb.infallibleAppend('"'); |
| 1091 |
sb.infallibleAppend(':'); |
| 1092 |
return true; |
| 1093 |
} |
| 1094 |
|
| 1095 |
// Similar to PreprocessValue: replace the value with a simpler one to |
| 1096 |
// stringify, but also detect whether the value is compatible with the fast |
| 1097 |
// path. If not, bail out by setting *whySlow and returning true. |
| 1098 |
static bool PreprocessFastValue(JSContext* cx, Value* vp, StringifyContext* scx, |
| 1099 |
BailReason* whySlow) { |
| 1100 |
MOZ_ASSERT(!scx->maybeSafely); |
| 1101 |
|
| 1102 |
// Steps are from |
| 1103 |
// https://262.ecma-international.org/14.0/#sec-serializejsonproperty |
| 1104 |
|
| 1105 |
// Disallow BigInts to avoid caring about BigInt.prototype.toJSON. |
| 1106 |
if (vp->isBigInt()) { |
| 1107 |
*whySlow = BailReason::BIGINT; |
| 1108 |
return true; |
| 1109 |
} |
| 1110 |
|
| 1111 |
if (!vp->isObject()) { |
| 1112 |
return true; |
| 1113 |
} |
| 1114 |
|
| 1115 |
if (!vp->toObject().is<NativeObject>()) { |
| 1116 |
*whySlow = BailReason::INELIGIBLE_OBJECT; |
| 1117 |
return true; |
| 1118 |
} |
| 1119 |
|
| 1120 |
// Step 2: lookup a .toJSON property (and bail if found). |
| 1121 |
NativeObject* obj = &vp->toObject().as<NativeObject>(); |
| 1122 |
PropertyResult toJSON; |
| 1123 |
NativeObject* holder; |
| 1124 |
PropertyKey id = NameToId(cx->names().toJSON); |
| 1125 |
if (!NativeLookupPropertyInline<NoGC, LookupResolveMode::CheckMayResolve>( |
| 1126 |
cx, obj, id, &holder, &toJSON)) { |
| 1127 |
// Looking up this property would require a side effect. |
| 1128 |
*whySlow = BailReason::IMPURE_LOOKUP; |
| 1129 |
return true; |
| 1130 |
} |
| 1131 |
if (toJSON.isFound()) { |
| 1132 |
*whySlow = BailReason::HAVE_TOJSON; |
| 1133 |
return true; |
| 1134 |
} |
| 1135 |
|
| 1136 |
// Step 4: convert primitive wrapper objects to primitives. Disallowed for |
| 1137 |
// fast path. |
| 1138 |
if (obj->is<NumberObject>() || obj->is<StringObject>() || |
| 1139 |
obj->is<BooleanObject>() || obj->is<BigIntObject>()) { |
| 1140 |
// Primitive wrapper objects can invoke arbitrary code when being coerced to |
| 1141 |
// their primitive values (eg via @@toStringTag). |
| 1142 |
*whySlow = BailReason::INELIGIBLE_OBJECT; |
| 1143 |
return true; |
| 1144 |
} |
| 1145 |
|
| 1146 |
if (obj->isCallable()) { |
| 1147 |
// Steps 11,12: Callable objects are treated as undefined. |
| 1148 |
vp->setUndefined(); |
| 1149 |
return true; |
| 1150 |
} |
| 1151 |
|
| 1152 |
if (!CanFastStringifyObject(obj)) { |
| 1153 |
*whySlow = BailReason::INELIGIBLE_OBJECT; |
| 1154 |
return true; |
| 1155 |
} |
| 1156 |
|
| 1157 |
return true; |
| 1158 |
} |
| 1159 |
|
| 1160 |
// FastSerializeJSONProperty maintains an explicit stack to handle nested |
| 1161 |
// objects. For each object, first the dense elements are iterated, then the |
| 1162 |
// named properties (included sparse indexes, which will cause |
| 1163 |
// FastSerializeJSONProperty to bail out.) |
| 1164 |
// |
| 1165 |
// The iterators for each of those parts are not merged into a single common |
| 1166 |
// iterator because the interface is different for the two parts, and they are |
| 1167 |
// handled separately in the FastSerializeJSONProperty code. |
| 1168 |
struct FastStackEntry { |
| 1169 |
NativeObject* nobj; |
| 1170 |
Variant<DenseElementsIteratorForJSON, OwnNonIndexKeysIterForJSON> iter; |
| 1171 |
bool isArray; // Cached nobj->is<ArrayObject>() |
| 1172 |
|
| 1173 |
// Given an object, a FastStackEntry starts with the dense elements. The |
| 1174 |
// caller is expected to inspect the variant to use it differently based on |
| 1175 |
// which iterator is active. |
| 1176 |
explicit FastStackEntry(NativeObject* obj) |
| 1177 |
: nobj(obj), |
| 1178 |
iter(AsVariant(DenseElementsIteratorForJSON(obj))), |
| 1179 |
isArray(obj->is<ArrayObject>()) {} |
| 1180 |
|
| 1181 |
// Called by Vector when moving data around. |
| 1182 |
FastStackEntry(FastStackEntry&& other) noexcept |
| 1183 |
: nobj(other.nobj), iter(std::move(other.iter)), isArray(other.isArray) {} |
| 1184 |
|
| 1185 |
// Move assignment, called when updating the `top` entry. |
| 1186 |
void operator=(FastStackEntry&& other) noexcept { |
| 1187 |
nobj = other.nobj; |
| 1188 |
iter = std::move(other.iter); |
| 1189 |
isArray = other.isArray; |
| 1190 |
} |
| 1191 |
|
| 1192 |
// Advance from dense elements to the named properties. |
| 1193 |
void advanceToProperties() { |
| 1194 |
iter = AsVariant(OwnNonIndexKeysIterForJSON(nobj)); |
| 1195 |
} |
| 1196 |
}; |
| 1197 |
|
| 1198 |
/* https://262.ecma-international.org/14.0/#sec-serializejsonproperty */ |
| 1199 |
static bool FastSerializeJSONProperty(JSContext* cx, Handle<Value> v, |
| 1200 |
StringifyContext* scx, |
| 1201 |
BailReason* whySlow) { |
| 1202 |
MOZ_ASSERT(*whySlow == BailReason::NO_REASON); |
| 1203 |
MOZ_ASSERT(v.isObject()); |
| 1204 |
|
| 1205 |
if (JSString* rawJSON = MaybeGetRawJSON(cx, &v.toObject())) { |
| 1206 |
return scx->sb.append(rawJSON); |
| 1207 |
} |
| 1208 |
|
| 1209 |
/* |
| 1210 |
* FastSerializeJSONProperty is an optimistic fast path for the |
| 1211 |
* SerializeJSONProperty algorithm that applies in limited situations. It |
| 1212 |
* falls back to SerializeJSONProperty() if: |
| 1213 |
* |
| 1214 |
* * Any externally visible code attempts to run: getter, enumerate |
| 1215 |
* hook, toJSON property. |
| 1216 |
* * Sparse index found (this would require accumulating props and sorting.) |
| 1217 |
* * Max stack depth is reached. (This will also detect self-referential |
| 1218 |
* input.) |
| 1219 |
* |
| 1220 |
* Algorithm: |
| 1221 |
* |
| 1222 |
* stack = [] |
| 1223 |
* top = iter(obj) |
| 1224 |
* wroteMember = false |
| 1225 |
* OUTER: while true: |
| 1226 |
* if !wroteMember: |
| 1227 |
* emit("[" or "{") |
| 1228 |
* while !top.done(): |
| 1229 |
* key, value = top.next() |
| 1230 |
* if top is a non-Array and value is skippable: |
| 1231 |
* continue |
| 1232 |
* if wroteMember: |
| 1233 |
* emit(",") |
| 1234 |
* wroteMember = true |
| 1235 |
* if value is object: |
| 1236 |
* emit(key + ":") if top is iterating a non-Array |
| 1237 |
* stack.push(top) |
| 1238 |
* top <- value |
| 1239 |
* wroteMember = false |
| 1240 |
* continue OUTER |
| 1241 |
* else: |
| 1242 |
* emit(value) or emit(key + ":" + value) |
| 1243 |
* emit("]" or "}") |
| 1244 |
* if stack is empty: done! |
| 1245 |
* top <- stack.pop() |
| 1246 |
* wroteMember = true |
| 1247 |
* |
| 1248 |
* except: |
| 1249 |
* |
| 1250 |
* * The `while !top.done()` loop is split into the dense element portion |
| 1251 |
* and the slot portion. Each is iterated to completion before advancing |
| 1252 |
* or finishing. |
| 1253 |
* |
| 1254 |
* * For Arrays, the named properties are not output, but they are still |
| 1255 |
* scanned to bail if any numeric keys are found that could be indexes. |
| 1256 |
*/ |
| 1257 |
|
| 1258 |
// FastSerializeJSONProperty will bail if an interrupt is requested in the |
| 1259 |
// middle of an operation, so handle any interrupts now before starting. Note: |
| 1260 |
// this can GC, but after this point nothing should be able to GC unless |
| 1261 |
// something fails, so rooting is unnecessary. |
| 1262 |
if (!CheckForInterrupt(cx)) { |
| 1263 |
return false; |
| 1264 |
} |
| 1265 |
|
| 1266 |
constexpr size_t MAX_STACK_DEPTH = 20; |
| 1267 |
Vector<FastStackEntry> stack(cx); |
| 1268 |
if (!stack.reserve(MAX_STACK_DEPTH - 1)) { |
| 1269 |
return false; |
| 1270 |
} |
| 1271 |
// Construct an iterator for the object, |
| 1272 |
// https://262.ecma-international.org/14.0/#sec-serializejsonobject step 6: |
| 1273 |
// EnumerableOwnPropertyNames or |
| 1274 |
// https://262.ecma-international.org/14.0/#sec-serializejsonarray step 7-8. |
| 1275 |
FastStackEntry top(&v.toObject().as<NativeObject>()); |
| 1276 |
bool wroteMember = false; |
| 1277 |
|
| 1278 |
if (!CanFastStringifyObject(top.nobj)) { |
| 1279 |
*whySlow = BailReason::INELIGIBLE_OBJECT; |
| 1280 |
return true; |
| 1281 |
} |
| 1282 |
|
| 1283 |
while (true) { |
| 1284 |
if (!wroteMember) { |
| 1285 |
if (!scx->sb.append(top.isArray ? '[' : '{')) { |
| 1286 |
return false; |
| 1287 |
} |
| 1288 |
} |
| 1289 |
|
| 1290 |
if (top.iter.is<DenseElementsIteratorForJSON>()) { |
| 1291 |
auto& iter = top.iter.as<DenseElementsIteratorForJSON>(); |
| 1292 |
bool nestedObject = false; |
| 1293 |
while (!iter.done()) { |
| 1294 |
// Interrupts can GC and we are working with unrooted pointers. |
| 1295 |
if (cx->hasPendingInterrupt(InterruptReason::CallbackUrgent) || |
| 1296 |
cx->hasPendingInterrupt(InterruptReason::CallbackCanWait)) { |
| 1297 |
*whySlow = BailReason::INTERRUPT; |
| 1298 |
return true; |
| 1299 |
} |
| 1300 |
|
| 1301 |
uint32_t index = iter.getIndex(); |
| 1302 |
Value val = iter.next(); |
| 1303 |
|
| 1304 |
if (!PreprocessFastValue(cx, &val, scx, whySlow)) { |
| 1305 |
return false; |
| 1306 |
} |
| 1307 |
if (*whySlow != BailReason::NO_REASON) { |
| 1308 |
return true; |
| 1309 |
} |
| 1310 |
if (IsFilteredValue(val)) { |
| 1311 |
if (top.isArray) { |
| 1312 |
// Arrays convert unrepresentable values to "null". |
| 1313 |
val = UndefinedValue(); |
| 1314 |
} else { |
| 1315 |
// Objects skip unrepresentable values. |
| 1316 |
continue; |
| 1317 |
} |
| 1318 |
} |
| 1319 |
|
| 1320 |
if (wroteMember && !scx->sb.append(',')) { |
| 1321 |
return false; |
| 1322 |
} |
| 1323 |
wroteMember = true; |
| 1324 |
|
| 1325 |
if (!top.isArray) { |
| 1326 |
if (!EmitQuotedIndexColon(scx->sb, index)) { |
| 1327 |
return false; |
| 1328 |
} |
| 1329 |
} |
| 1330 |
|
| 1331 |
if (val.isObject()) { |
| 1332 |
if (JSString* rawJSON = MaybeGetRawJSON(cx, &val.toObject())) { |
| 1333 |
if (!scx->sb.append(rawJSON)) { |
| 1334 |
return false; |
| 1335 |
} |
| 1336 |
} else { |
| 1337 |
if (stack.length() >= MAX_STACK_DEPTH - 1) { |
| 1338 |
*whySlow = BailReason::DEEP_RECURSION; |
| 1339 |
return true; |
| 1340 |
} |
| 1341 |
// Save the current iterator position on the stack and |
| 1342 |
// switch to processing the nested value. |
| 1343 |
stack.infallibleAppend(std::move(top)); |
| 1344 |
top = FastStackEntry(&val.toObject().as<NativeObject>()); |
| 1345 |
wroteMember = false; |
| 1346 |
nestedObject = true; // Break out to the outer loop. |
| 1347 |
break; |
| 1348 |
} |
| 1349 |
} else if (!EmitSimpleValue(cx, scx->sb, val)) { |
| 1350 |
return false; |
| 1351 |
} |
| 1352 |
} |
| 1353 |
|
| 1354 |
if (nestedObject) { |
| 1355 |
continue; // Break out to outer loop. |
| 1356 |
} |
| 1357 |
|
| 1358 |
MOZ_ASSERT(iter.done()); |
| 1359 |
if (top.isArray) { |
| 1360 |
MOZ_ASSERT(!top.nobj->isIndexed() || IsPackedArray(top.nobj)); |
| 1361 |
} else { |
| 1362 |
top.advanceToProperties(); |
| 1363 |
} |
| 1364 |
} |
| 1365 |
|
| 1366 |
if (top.iter.is<OwnNonIndexKeysIterForJSON>()) { |
| 1367 |
auto& iter = top.iter.as<OwnNonIndexKeysIterForJSON>(); |
| 1368 |
bool nesting = false; |
| 1369 |
while (!iter.done()) { |
| 1370 |
// Interrupts can GC and we are working with unrooted pointers. |
| 1371 |
if (cx->hasPendingInterrupt(InterruptReason::CallbackUrgent) || |
| 1372 |
cx->hasPendingInterrupt(InterruptReason::CallbackCanWait)) { |
| 1373 |
*whySlow = BailReason::INTERRUPT; |
| 1374 |
return true; |
| 1375 |
} |
| 1376 |
|
| 1377 |
PropertyInfoWithKey prop = iter.next(); |
| 1378 |
|
| 1379 |
// A non-Array with indexed elements would need to sort the indexes |
| 1380 |
// numerically, which this code does not support. These objects are |
| 1381 |
// skipped when obj->isIndexed(), so no index properties should be found |
| 1382 |
// here. |
| 1383 |
mozilla::DebugOnly<uint32_t> index = -1; |
| 1384 |
MOZ_ASSERT(!IdIsIndex(prop.key(), &index)); |
| 1385 |
|
| 1386 |
Value val = top.nobj->getSlot(prop.slot()); |
| 1387 |
if (!PreprocessFastValue(cx, &val, scx, whySlow)) { |
| 1388 |
return false; |
| 1389 |
} |
| 1390 |
if (*whySlow != BailReason::NO_REASON) { |
| 1391 |
return true; |
| 1392 |
} |
| 1393 |
if (IsFilteredValue(val)) { |
| 1394 |
// Undefined check in |
| 1395 |
// https://262.ecma-international.org/14.0/#sec-serializejsonobject |
| 1396 |
// step 8b, covering undefined, symbol |
| 1397 |
continue; |
| 1398 |
} |
| 1399 |
|
| 1400 |
if (wroteMember && !scx->sb.append(",")) { |
| 1401 |
return false; |
| 1402 |
} |
| 1403 |
wroteMember = true; |
| 1404 |
|
| 1405 |
MOZ_ASSERT(prop.key().isString()); |
| 1406 |
if (!QuoteJSONString(cx, scx->sb, prop.key().toString())) { |
| 1407 |
return false; |
| 1408 |
} |
| 1409 |
|
| 1410 |
if (!scx->sb.append(':')) { |
| 1411 |
return false; |
| 1412 |
} |
| 1413 |
if (val.isObject()) { |
| 1414 |
if (JSString* rawJSON = MaybeGetRawJSON(cx, &val.toObject())) { |
| 1415 |
if (!scx->sb.append(rawJSON)) { |
| 1416 |
return false; |
| 1417 |
} |
| 1418 |
} else { |
| 1419 |
if (stack.length() >= MAX_STACK_DEPTH - 1) { |
| 1420 |
*whySlow = BailReason::DEEP_RECURSION; |
| 1421 |
return true; |
| 1422 |
} |
| 1423 |
// Save the current iterator position on the stack and |
| 1424 |
// switch to processing the nested value. |
| 1425 |
stack.infallibleAppend(std::move(top)); |
| 1426 |
top = FastStackEntry(&val.toObject().as<NativeObject>()); |
| 1427 |
wroteMember = false; |
| 1428 |
nesting = true; // Break out to the outer loop. |
| 1429 |
break; |
| 1430 |
} |
| 1431 |
} else if (!EmitSimpleValue(cx, scx->sb, val)) { |
| 1432 |
return false; |
| 1433 |
} |
| 1434 |
} |
| 1435 |
*whySlow = iter.cannotFastStringify(); |
| 1436 |
if (*whySlow != BailReason::NO_REASON) { |
| 1437 |
return true; |
| 1438 |
} |
| 1439 |
if (nesting) { |
| 1440 |
continue; // Break out to outer loop. |
| 1441 |
} |
| 1442 |
MOZ_ASSERT(iter.done()); |
| 1443 |
} |
| 1444 |
|
| 1445 |
if (!scx->sb.append(top.isArray ? ']' : '}')) { |
| 1446 |
return false; |
| 1447 |
} |
| 1448 |
if (stack.empty()) { |
| 1449 |
return true; // Success! |
| 1450 |
} |
| 1451 |
top = std::move(stack.back()); |
| 1452 |
|
| 1453 |
stack.popBack(); |
| 1454 |
wroteMember = true; |
| 1455 |
} |
| 1456 |
} |
| 1457 |
|
| 1458 |
/* https://262.ecma-international.org/14.0/#sec-json.stringify */ |
| 1459 |
bool js::Stringify(JSContext* cx, MutableHandleValue vp, JSObject* replacer_, |
| 1460 |
const Value& space_, StringBuilder& sb, |
| 1461 |
StringifyBehavior stringifyBehavior) { |
| 1462 |
RootedObject replacer(cx, replacer_); |
| 1463 |
RootedValue space(cx, space_); |
| 1464 |
|
| 1465 |
MOZ_ASSERT_IF(stringifyBehavior == StringifyBehavior::RestrictedSafe, |
| 1466 |
space.isNull()); |
| 1467 |
MOZ_ASSERT_IF(stringifyBehavior == StringifyBehavior::RestrictedSafe, |
| 1468 |
vp.isObject()); |
| 1469 |
/** |
| 1470 |
* This uses MOZ_ASSERT, since it's actually asserting something jsapi |
| 1471 |
* consumers could get wrong, so needs a better error message. |
| 1472 |
*/ |
| 1473 |
MOZ_ASSERT(stringifyBehavior != StringifyBehavior::RestrictedSafe || |
| 1474 |
vp.toObject().is<PlainObject>() || |
| 1475 |
vp.toObject().is<ArrayObject>(), |
| 1476 |
"input to JS::ToJSONMaybeSafely must be a plain object or array"); |
| 1477 |
|
| 1478 |
/* Step 5. */ |
| 1479 |
RootedIdVector propertyList(cx); |
| 1480 |
BailReason whySlow = BailReason::NO_REASON; |
| 1481 |
if (stringifyBehavior == StringifyBehavior::SlowOnly || |
| 1482 |
stringifyBehavior == StringifyBehavior::RestrictedSafe) { |
| 1483 |
whySlow = BailReason::API; |
| 1484 |
} |
| 1485 |
if (replacer) { |
| 1486 |
whySlow = BailReason::HAVE_REPLACER; |
| 1487 |
bool isArray; |
| 1488 |
if (replacer->isCallable()) { |
| 1489 |
/* Step 5a(i): use replacer to transform values. */ |
| 1490 |
} else if (!IsArray(cx, replacer, &isArray)) { |
| 1491 |
return false; |
| 1492 |
} else if (isArray) { |
| 1493 |
/* Step 5b(ii). */ |
| 1494 |
|
| 1495 |
/* Step 5b(ii)(2). */ |
| 1496 |
uint32_t len; |
| 1497 |
if (!GetLengthPropertyForArrayLike(cx, replacer, &len)) { |
| 1498 |
return false; |
| 1499 |
} |
| 1500 |
|
| 1501 |
// Cap the initial size to a moderately small value. This avoids |
| 1502 |
// ridiculous over-allocation if an array with bogusly-huge length |
| 1503 |
// is passed in. If we end up having to add elements past this |
| 1504 |
// size, the set will naturally resize to accommodate them. |
| 1505 |
const uint32_t MaxInitialSize = 32; |
| 1506 |
Rooted<GCHashSet<jsid>> idSet( |
| 1507 |
cx, GCHashSet<jsid>(cx, std::min(len, MaxInitialSize))); |
| 1508 |
|
| 1509 |
/* Step 5b(ii)(3). */ |
| 1510 |
uint32_t k = 0; |
| 1511 |
|
| 1512 |
/* Step 5b(ii)(4). */ |
| 1513 |
RootedValue item(cx); |
| 1514 |
for (; k < len; k++) { |
| 1515 |
if (!CheckForInterrupt(cx)) { |
| 1516 |
return false; |
| 1517 |
} |
| 1518 |
|
| 1519 |
/* Step 5b(ii)(4)(a-b). */ |
| 1520 |
if (!GetElement(cx, replacer, k, &item)) { |
| 1521 |
return false; |
| 1522 |
} |
| 1523 |
|
| 1524 |
/* Step 5b(ii)(4)(c-g). */ |
| 1525 |
RootedId id(cx); |
| 1526 |
if (item.isNumber() || item.isString()) { |
| 1527 |
if (!PrimitiveValueToId<CanGC>(cx, item, &id)) { |
| 1528 |
return false; |
| 1529 |
} |
| 1530 |
} else { |
| 1531 |
ESClass cls; |
| 1532 |
if (!GetClassOfValue(cx, item, &cls)) { |
| 1533 |
return false; |
| 1534 |
} |
| 1535 |
|
| 1536 |
if (cls != ESClass::String && cls != ESClass::Number) { |
| 1537 |
continue; |
| 1538 |
} |
| 1539 |
|
| 1540 |
JSAtom* atom = ToAtom<CanGC>(cx, item); |
| 1541 |
if (!atom) { |
| 1542 |
return false; |
| 1543 |
} |
| 1544 |
|
| 1545 |
id.set(AtomToId(atom)); |
| 1546 |
} |
| 1547 |
|
| 1548 |
/* Step 5b(ii)(4)(g). */ |
| 1549 |
auto p = idSet.lookupForAdd(id); |
| 1550 |
if (!p) { |
| 1551 |
/* Step 5b(ii)(4)(g)(i). */ |
| 1552 |
if (!idSet.add(p, id) || !propertyList.append(id)) { |
| 1553 |
return false; |
| 1554 |
} |
| 1555 |
} |
| 1556 |
} |
| 1557 |
} else { |
| 1558 |
replacer = nullptr; |
| 1559 |
} |
| 1560 |
} |
| 1561 |
|
| 1562 |
/* Step 6. */ |
| 1563 |
if (space.isObject()) { |
| 1564 |
RootedObject spaceObj(cx, &space.toObject()); |
| 1565 |
|
| 1566 |
ESClass cls; |
| 1567 |
if (!JS::GetBuiltinClass(cx, spaceObj, &cls)) { |
| 1568 |
return false; |
| 1569 |
} |
| 1570 |
|
| 1571 |
if (cls == ESClass::Number) { |
| 1572 |
double d; |
| 1573 |
if (!ToNumber(cx, space, &d)) { |
| 1574 |
return false; |
| 1575 |
} |
| 1576 |
space = NumberValue(d); |
| 1577 |
} else if (cls == ESClass::String) { |
| 1578 |
JSString* str = ToStringSlow<CanGC>(cx, space); |
| 1579 |
if (!str) { |
| 1580 |
return false; |
| 1581 |
} |
| 1582 |
space = StringValue(str); |
| 1583 |
} |
| 1584 |
} |
| 1585 |
|
| 1586 |
StringBuilder gap(cx); |
| 1587 |
|
| 1588 |
if (space.isNumber()) { |
| 1589 |
/* Step 7. */ |
| 1590 |
double d; |
| 1591 |
MOZ_ALWAYS_TRUE(ToInteger(cx, space, &d)); |
| 1592 |
d = std::min(10.0, d); |
| 1593 |
if (d >= 1 && !gap.appendN(' ', uint32_t(d))) { |
| 1594 |
return false; |
| 1595 |
} |
| 1596 |
} else if (space.isString()) { |
| 1597 |
/* Step 8. */ |
| 1598 |
JSLinearString* str = space.toString()->ensureLinear(cx); |
| 1599 |
if (!str) { |
| 1600 |
return false; |
| 1601 |
} |
| 1602 |
size_t len = std::min(size_t(10), str->length()); |
| 1603 |
if (!gap.appendSubstring(str, 0, len)) { |
| 1604 |
return false; |
| 1605 |
} |
| 1606 |
} else { |
| 1607 |
/* Step 9. */ |
| 1608 |
MOZ_ASSERT(gap.empty()); |
| 1609 |
} |
| 1610 |
if (!gap.empty()) { |
| 1611 |
whySlow = BailReason::HAVE_SPACE; |
| 1612 |
} |
| 1613 |
|
| 1614 |
Rooted<PlainObject*> wrapper(cx); |
| 1615 |
RootedId emptyId(cx, NameToId(cx->names().empty_)); |
| 1616 |
if (replacer && replacer->isCallable()) { |
| 1617 |
// We can skip creating the initial wrapper object if no replacer |
| 1618 |
// function is present. |
| 1619 |
|
| 1620 |
/* Step 10. */ |
| 1621 |
wrapper = NewPlainObject(cx); |
| 1622 |
if (!wrapper) { |
| 1623 |
return false; |
| 1624 |
} |
| 1625 |
|
| 1626 |
/* Step 11. */ |
| 1627 |
if (!NativeDefineDataProperty(cx, wrapper, emptyId, vp, JSPROP_ENUMERATE)) { |
| 1628 |
return false; |
| 1629 |
} |
| 1630 |
} |
| 1631 |
|
| 1632 |
/* Step 13. */ |
| 1633 |
Rooted<JSAtom*> fastJSON(cx); |
| 1634 |
if (whySlow == BailReason::NO_REASON) { |
| 1635 |
MOZ_ASSERT(propertyList.empty()); |
| 1636 |
MOZ_ASSERT(stringifyBehavior != StringifyBehavior::RestrictedSafe); |
| 1637 |
StringifyContext scx(cx, sb, gap, nullptr, propertyList, false); |
| 1638 |
if (!PreprocessFastValue(cx, vp.address(), &scx, &whySlow)) { |
| 1639 |
return false; |
| 1640 |
} |
| 1641 |
if (!vp.isObject()) { |
| 1642 |
// "Fast" stringify of primitives would create a wrapper object and thus |
| 1643 |
// be slower than regular stringify. |
| 1644 |
whySlow = BailReason::PRIMITIVE; |
| 1645 |
} |
| 1646 |
if (whySlow == BailReason::NO_REASON) { |
| 1647 |
if (!FastSerializeJSONProperty(cx, vp, &scx, &whySlow)) { |
| 1648 |
return false; |
| 1649 |
} |
| 1650 |
if (whySlow == BailReason::NO_REASON) { |
| 1651 |
// Fast stringify succeeded! |
| 1652 |
if (stringifyBehavior != StringifyBehavior::Compare) { |
| 1653 |
return true; |
| 1654 |
} |
| 1655 |
fastJSON = scx.sb.finishAtom(); |
| 1656 |
if (!fastJSON) { |
| 1657 |
return false; |
| 1658 |
} |
| 1659 |
} |
| 1660 |
scx.sb.clear(); // Preserves allocated space. |
| 1661 |
} |
| 1662 |
} |
| 1663 |
|
| 1664 |
if (MOZ_UNLIKELY((stringifyBehavior == StringifyBehavior::FastOnly) && |
| 1665 |
(whySlow != BailReason::NO_REASON))) { |
| 1666 |
JS_ReportErrorASCII(cx, "JSON stringify failed mandatory fast path: %s", |
| 1667 |
DescribeStringifyBailReason(whySlow)); |
| 1668 |
return false; |
| 1669 |
} |
| 1670 |
|
| 1671 |
// Slow, general path. |
| 1672 |
|
| 1673 |
StringifyContext scx(cx, sb, gap, replacer, propertyList, |
| 1674 |
stringifyBehavior == StringifyBehavior::RestrictedSafe); |
| 1675 |
if (!PreprocessValue(cx, wrapper, HandleId(emptyId), vp, &scx)) { |
| 1676 |
return false; |
| 1677 |
} |
| 1678 |
if (IsFilteredValue(vp)) { |
| 1679 |
return true; |
| 1680 |
} |
| 1681 |
|
| 1682 |
if (!SerializeJSONProperty(cx, vp, &scx)) { |
| 1683 |
return false; |
| 1684 |
} |
| 1685 |
|
| 1686 |
// For StringBehavior::Compare, when the fast path succeeded. |
| 1687 |
if (MOZ_UNLIKELY(fastJSON)) { |
| 1688 |
JSAtom* slowJSON = scx.sb.finishAtom(); |
| 1689 |
if (!slowJSON) { |
| 1690 |
return false; |
| 1691 |
} |
| 1692 |
if (fastJSON != slowJSON) { |
| 1693 |
MOZ_CRASH("JSON.stringify mismatch between fast and slow paths"); |
| 1694 |
} |
| 1695 |
// Put the JSON back into the StringBuilder for returning. |
| 1696 |
if (!sb.append(slowJSON)) { |
| 1697 |
return false; |
| 1698 |
} |
| 1699 |
} |
| 1700 |
|
| 1701 |
return true; |
| 1702 |
} |
| 1703 |
|
| 1704 |
/* https://262.ecma-international.org/14.0/#sec-internalizejsonproperty */ |
| 1705 |
static bool InternalizeJSONProperty(JSContext* cx, HandleObject holder, |
| 1706 |
HandleId name, HandleValue reviver, |
| 1707 |
Handle<ParseRecordObject*> parseRecord, |
| 1708 |
MutableHandleValue vp) { |
| 1709 |
AutoCheckRecursionLimit recursion(cx); |
| 1710 |
if (!recursion.check(cx)) { |
| 1711 |
return false; |
| 1712 |
} |
| 1713 |
|
| 1714 |
/* Step 1. */ |
| 1715 |
RootedValue val(cx); |
| 1716 |
if (!GetProperty(cx, holder, holder, name, &val)) { |
| 1717 |
return false; |
| 1718 |
} |
| 1719 |
|
| 1720 |
RootedObject context(cx); |
| 1721 |
Rooted<ParseRecordObject::EntryMap*> entries(cx); |
| 1722 |
if (JS::Prefs::experimental_json_parse_with_source()) { |
| 1723 |
// https://tc39.es/proposal-json-parse-with-source/#sec-internalizejsonproperty |
| 1724 |
if (parseRecord) { |
| 1725 |
bool sameVal = false; |
| 1726 |
Rooted<Value> parsedValue(cx, parseRecord->getValue()); |
| 1727 |
if (!SameValue(cx, parsedValue, val, &sameVal)) { |
| 1728 |
return false; |
| 1729 |
} |
| 1730 |
if (parseRecord->hasValue() && sameVal) { |
| 1731 |
if (parseRecord->getParseNode()) { |
| 1732 |
MOZ_ASSERT(!val.isObject()); |
| 1733 |
Rooted<IdValueVector> props(cx, cx); |
| 1734 |
if (!props.emplaceBack( |
| 1735 |
IdValuePair(NameToId(cx->names().source), |
| 1736 |
StringValue(parseRecord->getParseNode())))) { |
| 1737 |
return false; |
| 1738 |
} |
| 1739 |
context = NewPlainObjectWithUniqueNames(cx, props); |
| 1740 |
if (!context) { |
| 1741 |
return false; |
| 1742 |
} |
| 1743 |
} |
| 1744 |
parseRecord->getEntries(cx, &entries); |
| 1745 |
} |
| 1746 |
} |
| 1747 |
if (!context) { |
| 1748 |
context = NewPlainObject(cx); |
| 1749 |
if (!context) { |
| 1750 |
return false; |
| 1751 |
} |
| 1752 |
} |
| 1753 |
} |
| 1754 |
|
| 1755 |
/* Step 2. */ |
| 1756 |
if (val.isObject()) { |
| 1757 |
RootedObject obj(cx, &val.toObject()); |
| 1758 |
|
| 1759 |
bool isArray; |
| 1760 |
if (!IsArray(cx, obj, &isArray)) { |
| 1761 |
return false; |
| 1762 |
} |
| 1763 |
|
| 1764 |
if (isArray) { |
| 1765 |
/* Step 2b(i). */ |
| 1766 |
uint32_t length; |
| 1767 |
if (!GetLengthPropertyForArrayLike(cx, obj, &length)) { |
| 1768 |
return false; |
| 1769 |
} |
| 1770 |
|
| 1771 |
/* Steps 2b(ii-iii). */ |
| 1772 |
RootedId id(cx); |
| 1773 |
RootedValue newElement(cx); |
| 1774 |
for (uint32_t i = 0; i < length; i++) { |
| 1775 |
if (!CheckForInterrupt(cx)) { |
| 1776 |
return false; |
| 1777 |
} |
| 1778 |
|
| 1779 |
if (!IndexToId(cx, i, &id)) { |
| 1780 |
return false; |
| 1781 |
} |
| 1782 |
|
| 1783 |
/* Step 2a(iii)(1). */ |
| 1784 |
Rooted<ParseRecordObject*> elementRecord(cx); |
| 1785 |
if (entries) { |
| 1786 |
Rooted<Value> value(cx); |
| 1787 |
if (!JS_GetPropertyById(cx, entries, id, &value)) { |
| 1788 |
return false; |
| 1789 |
} |
| 1790 |
if (!value.isNullOrUndefined()) { |
| 1791 |
elementRecord = &value.toObject().as<ParseRecordObject>(); |
| 1792 |
} |
| 1793 |
} |
| 1794 |
if (!InternalizeJSONProperty(cx, obj, id, reviver, elementRecord, |
| 1795 |
&newElement)) { |
| 1796 |
return false; |
| 1797 |
} |
| 1798 |
|
| 1799 |
ObjectOpResult ignored; |
| 1800 |
if (newElement.isUndefined()) { |
| 1801 |
/* Step 2b(iii)(3). The spec deliberately ignores strict failure. */ |
| 1802 |
if (!DeleteProperty(cx, obj, id, ignored)) { |
| 1803 |
return false; |
| 1804 |
} |
| 1805 |
} else { |
| 1806 |
/* Step 2b(iii)(4). The spec deliberately ignores strict failure. */ |
| 1807 |
Rooted<PropertyDescriptor> desc( |
| 1808 |
cx, PropertyDescriptor::Data(newElement, |
| 1809 |
{JS::PropertyAttribute::Configurable, |
| 1810 |
JS::PropertyAttribute::Enumerable, |
| 1811 |
JS::PropertyAttribute::Writable})); |
| 1812 |
if (!DefineProperty(cx, obj, id, desc, ignored)) { |
| 1813 |
return false; |
| 1814 |
} |
| 1815 |
} |
| 1816 |
} |
| 1817 |
} else { |
| 1818 |
/* Step 2c(i). */ |
| 1819 |
RootedIdVector keys(cx); |
| 1820 |
if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, &keys)) { |
| 1821 |
return false; |
| 1822 |
} |
| 1823 |
|
| 1824 |
/* Step 2c(ii). */ |
| 1825 |
RootedId id(cx); |
| 1826 |
RootedValue newElement(cx); |
| 1827 |
for (size_t i = 0, len = keys.length(); i < len; i++) { |
| 1828 |
if (!CheckForInterrupt(cx)) { |
| 1829 |
return false; |
| 1830 |
} |
| 1831 |
|
| 1832 |
/* Step 2c(ii)(1). */ |
| 1833 |
id = keys[i]; |
| 1834 |
Rooted<ParseRecordObject*> entryRecord(cx); |
| 1835 |
if (entries) { |
| 1836 |
Rooted<Value> value(cx); |
| 1837 |
if (!JS_GetPropertyById(cx, entries, id, &value)) { |
| 1838 |
return false; |
| 1839 |
} |
| 1840 |
if (!value.isNullOrUndefined()) { |
| 1841 |
entryRecord = &value.toObject().as<ParseRecordObject>(); |
| 1842 |
} |
| 1843 |
} |
| 1844 |
if (!InternalizeJSONProperty(cx, obj, id, reviver, entryRecord, |
| 1845 |
&newElement)) { |
| 1846 |
return false; |
| 1847 |
} |
| 1848 |
|
| 1849 |
ObjectOpResult ignored; |
| 1850 |
if (newElement.isUndefined()) { |
| 1851 |
/* Step 2c(ii)(2). The spec deliberately ignores strict failure. */ |
| 1852 |
if (!DeleteProperty(cx, obj, id, ignored)) { |
| 1853 |
return false; |
| 1854 |
} |
| 1855 |
} else { |
| 1856 |
/* Step 2c(ii)(3). The spec deliberately ignores strict failure. */ |
| 1857 |
Rooted<PropertyDescriptor> desc( |
| 1858 |
cx, PropertyDescriptor::Data(newElement, |
| 1859 |
{JS::PropertyAttribute::Configurable, |
| 1860 |
JS::PropertyAttribute::Enumerable, |
| 1861 |
JS::PropertyAttribute::Writable})); |
| 1862 |
if (!DefineProperty(cx, obj, id, desc, ignored)) { |
| 1863 |
return false; |
| 1864 |
} |
| 1865 |
} |
| 1866 |
} |
| 1867 |
} |
| 1868 |
} |
| 1869 |
|
| 1870 |
/* Step 3. */ |
| 1871 |
RootedString key(cx, IdToString(cx, name)); |
| 1872 |
if (!key) { |
| 1873 |
return false; |
| 1874 |
} |
| 1875 |
|
| 1876 |
RootedValue keyVal(cx, StringValue(key)); |
| 1877 |
if (JS::Prefs::experimental_json_parse_with_source()) { |
| 1878 |
RootedValue contextVal(cx, ObjectValue(*context)); |
| 1879 |
return js::Call(cx, reviver, holder, keyVal, val, contextVal, vp); |
| 1880 |
} |
| 1881 |
return js::Call(cx, reviver, holder, keyVal, val, vp); |
| 1882 |
} |
| 1883 |
|
| 1884 |
static bool Revive(JSContext* cx, HandleValue reviver, |
| 1885 |
Handle<ParseRecordObject*> pro, MutableHandleValue vp) { |
| 1886 |
Rooted<PlainObject*> obj(cx, NewPlainObject(cx)); |
| 1887 |
if (!obj) { |
| 1888 |
return false; |
| 1889 |
} |
| 1890 |
|
| 1891 |
if (!DefineDataProperty(cx, obj, cx->names().empty_, vp)) { |
| 1892 |
return false; |
| 1893 |
} |
| 1894 |
|
| 1895 |
MOZ_ASSERT_IF(JS::Prefs::experimental_json_parse_with_source(), |
| 1896 |
pro->getValue() == vp.get()); |
| 1897 |
Rooted<jsid> id(cx, NameToId(cx->names().empty_)); |
| 1898 |
return InternalizeJSONProperty(cx, obj, id, reviver, pro, vp); |
| 1899 |
} |
| 1900 |
|
| 1901 |
template <typename CharT> |
| 1902 |
bool ParseJSON(JSContext* cx, const mozilla::Range<const CharT> chars, |
| 1903 |
MutableHandleValue vp) { |
| 1904 |
Rooted<JSONParser<CharT>> parser(cx, cx, chars, |
| 1905 |
JSONParser<CharT>::ParseType::JSONParse); |
| 1906 |
return parser.parse(vp); |
| 1907 |
} |
| 1908 |
|
| 1909 |
template <typename CharT> |
| 1910 |
bool js::ParseJSONWithReviver(JSContext* cx, |
| 1911 |
const mozilla::Range<const CharT> chars, |
| 1912 |
HandleValue reviver, MutableHandleValue vp) { |
| 1913 |
js::AutoGeckoProfilerEntry pseudoFrame(cx, "parse JSON", |
| 1914 |
JS::ProfilingCategoryPair::JS_Parsing); |
| 1915 |
/* https://262.ecma-international.org/14.0/#sec-json.parse steps 2-10. */ |
| 1916 |
Rooted<ParseRecordObject*> pro(cx); |
| 1917 |
if (JS::Prefs::experimental_json_parse_with_source() && IsCallable(reviver)) { |
| 1918 |
Rooted<JSONReviveParser<CharT>> parser(cx, cx, chars); |
| 1919 |
if (!parser.get().parse(vp, &pro)) { |
| 1920 |
return false; |
| 1921 |
} |
| 1922 |
} else if (!ParseJSON(cx, chars, vp)) { |
| 1923 |
return false; |
| 1924 |
} |
| 1925 |
|
| 1926 |
/* Steps 11-12. */ |
| 1927 |
if (IsCallable(reviver)) { |
| 1928 |
return Revive(cx, reviver, pro, vp); |
| 1929 |
} |
| 1930 |
return true; |
| 1931 |
} |
| 1932 |
|
| 1933 |
template bool js::ParseJSONWithReviver( |
| 1934 |
JSContext* cx, const mozilla::Range<const Latin1Char> chars, |
| 1935 |
HandleValue reviver, MutableHandleValue vp); |
| 1936 |
|
| 1937 |
template bool js::ParseJSONWithReviver( |
| 1938 |
JSContext* cx, const mozilla::Range<const char16_t> chars, |
| 1939 |
HandleValue reviver, MutableHandleValue vp); |
| 1940 |
|
| 1941 |
static bool json_toSource(JSContext* cx, unsigned argc, Value* vp) { |
| 1942 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1943 |
args.rval().setString(cx->names().JSON); |
| 1944 |
return true; |
| 1945 |
} |
| 1946 |
|
| 1947 |
/* https://262.ecma-international.org/14.0/#sec-json.parse */ |
| 1948 |
static bool json_parse(JSContext* cx, unsigned argc, Value* vp) { |
| 1949 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "JSON", "parse"); |
| 1950 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1951 |
|
| 1952 |
/* Step 1. */ |
| 1953 |
JSString* str = (args.length() >= 1) ? ToString<CanGC>(cx, args[0]) |
| 1954 |
: cx->names().undefined; |
| 1955 |
if (!str) { |
| 1956 |
return false; |
| 1957 |
} |
| 1958 |
|
| 1959 |
JSLinearString* linear = str->ensureLinear(cx); |
| 1960 |
if (!linear) { |
| 1961 |
return false; |
| 1962 |
} |
| 1963 |
|
| 1964 |
AutoStableStringChars linearChars(cx); |
| 1965 |
if (!linearChars.init(cx, linear)) { |
| 1966 |
return false; |
| 1967 |
} |
| 1968 |
|
| 1969 |
HandleValue reviver = args.get(1); |
| 1970 |
|
| 1971 |
/* Steps 2-12. */ |
| 1972 |
return linearChars.isLatin1() |
| 1973 |
? ParseJSONWithReviver(cx, linearChars.latin1Range(), reviver, |
| 1974 |
args.rval()) |
| 1975 |
: ParseJSONWithReviver(cx, linearChars.twoByteRange(), reviver, |
| 1976 |
args.rval()); |
| 1977 |
} |
| 1978 |
|
| 1979 |
/* https://tc39.es/proposal-json-parse-with-source/#sec-json.israwjson */ |
| 1980 |
static bool json_isRawJSON(JSContext* cx, unsigned argc, Value* vp) { |
| 1981 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "JSON", "isRawJSON"); |
| 1982 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1983 |
|
| 1984 |
/* Step 1. */ |
| 1985 |
if (args.get(0).isObject()) { |
| 1986 |
Rooted<JSObject*> obj(cx, &args[0].toObject()); |
| 1987 |
#ifdef DEBUG |
| 1988 |
if (obj->is<RawJSONObject>()) { |
| 1989 |
bool objIsFrozen = false; |
| 1990 |
MOZ_ASSERT(js::TestIntegrityLevel(cx, obj, IntegrityLevel::Frozen, |
| 1991 |
&objIsFrozen)); |
| 1992 |
MOZ_ASSERT(objIsFrozen); |
| 1993 |
} |
| 1994 |
#endif // DEBUG |
| 1995 |
args.rval().setBoolean(obj->is<RawJSONObject>() || |
| 1996 |
obj->canUnwrapAs<RawJSONObject>()); |
| 1997 |
return true; |
| 1998 |
} |
| 1999 |
|
| 2000 |
/* Step 2. */ |
| 2001 |
args.rval().setBoolean(false); |
| 2002 |
return true; |
| 2003 |
} |
| 2004 |
|
| 2005 |
static inline bool IsJSONWhitespace(char16_t ch) { |
| 2006 |
return ch == '\t' || ch == '\n' || ch == '\r' || ch == ' '; |
| 2007 |
} |
| 2008 |
|
| 2009 |
/* https://tc39.es/proposal-json-parse-with-source/#sec-json.rawjson */ |
| 2010 |
static bool json_rawJSON(JSContext* cx, unsigned argc, Value* vp) { |
| 2011 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "JSON", "rawJSON"); |
| 2012 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2013 |
|
| 2014 |
/* Step 1. */ |
| 2015 |
JSString* jsonString = ToString<CanGC>(cx, args.get(0)); |
| 2016 |
if (!jsonString) { |
| 2017 |
return false; |
| 2018 |
} |
| 2019 |
|
| 2020 |
Rooted<JSLinearString*> linear(cx, jsonString->ensureLinear(cx)); |
| 2021 |
if (!linear) { |
| 2022 |
return false; |
| 2023 |
} |
| 2024 |
|
| 2025 |
AutoStableStringChars linearChars(cx); |
| 2026 |
if (!linearChars.init(cx, linear)) { |
| 2027 |
return false; |
| 2028 |
} |
| 2029 |
|
| 2030 |
/* Step 2. */ |
| 2031 |
if (linear->empty()) { |
| 2032 |
JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr, |
| 2033 |
JSMSG_JSON_RAW_EMPTY); |
| 2034 |
return false; |
| 2035 |
} |
| 2036 |
if (IsJSONWhitespace(linear->latin1OrTwoByteChar(0)) || |
| 2037 |
IsJSONWhitespace(linear->latin1OrTwoByteChar(linear->length() - 1))) { |
| 2038 |
JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr, |
| 2039 |
JSMSG_JSON_RAW_WHITESPACE); |
| 2040 |
return false; |
| 2041 |
} |
| 2042 |
|
| 2043 |
/* Step 3. */ |
| 2044 |
RootedValue parsedValue(cx); |
| 2045 |
if (linearChars.isLatin1()) { |
| 2046 |
if (!ParseJSON(cx, linearChars.latin1Range(), &parsedValue)) { |
| 2047 |
return false; |
| 2048 |
} |
| 2049 |
} else { |
| 2050 |
if (!ParseJSON(cx, linearChars.twoByteRange(), &parsedValue)) { |
| 2051 |
return false; |
| 2052 |
} |
| 2053 |
} |
| 2054 |
|
| 2055 |
if (parsedValue.isObject()) { |
| 2056 |
JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr, |
| 2057 |
JSMSG_JSON_RAW_ARRAY_OR_OBJECT); |
| 2058 |
return false; |
| 2059 |
} |
| 2060 |
|
| 2061 |
/* Steps 4-6. */ |
| 2062 |
Rooted<RawJSONObject*> obj(cx, RawJSONObject::create(cx, linear)); |
| 2063 |
if (!obj) { |
| 2064 |
return false; |
| 2065 |
} |
| 2066 |
|
| 2067 |
/* Step 7. */ |
| 2068 |
if (!js::FreezeObject(cx, obj)) { |
| 2069 |
return false; |
| 2070 |
} |
| 2071 |
|
| 2072 |
args.rval().setObject(*obj); |
| 2073 |
return true; |
| 2074 |
} |
| 2075 |
|
| 2076 |
/* https://262.ecma-international.org/14.0/#sec-json.stringify */ |
| 2077 |
bool json_stringify(JSContext* cx, unsigned argc, Value* vp) { |
| 2078 |
AutoJSMethodProfilerEntry pseudoFrame(cx, "JSON", "stringify"); |
| 2079 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2080 |
|
| 2081 |
RootedObject replacer(cx, |
| 2082 |
args.get(1).isObject() ? &args[1].toObject() : nullptr); |
| 2083 |
RootedValue value(cx, args.get(0)); |
| 2084 |
RootedValue space(cx, args.get(2)); |
| 2085 |
|
| 2086 |
#ifdef DEBUG |
| 2087 |
StringifyBehavior behavior = StringifyBehavior::Compare; |
| 2088 |
#else |
| 2089 |
StringifyBehavior behavior = StringifyBehavior::Normal; |
| 2090 |
#endif |
| 2091 |
|
| 2092 |
JSStringBuilder sb(cx); |
| 2093 |
if (!Stringify(cx, &value, replacer, space, sb, behavior)) { |
| 2094 |
return false; |
| 2095 |
} |
| 2096 |
|
| 2097 |
// XXX This can never happen to nsJSON.cpp, but the JSON object |
| 2098 |
// needs to support returning undefined. So this is a little awkward |
| 2099 |
// for the API, because we want to support streaming writers. |
| 2100 |
if (!sb.empty()) { |
| 2101 |
JSString* str = sb.finishString(); |
| 2102 |
if (!str) { |
| 2103 |
return false; |
| 2104 |
} |
| 2105 |
args.rval().setString(str); |
| 2106 |
} else { |
| 2107 |
args.rval().setUndefined(); |
| 2108 |
} |
| 2109 |
|
| 2110 |
return true; |
| 2111 |
} |
| 2112 |
|
| 2113 |
static const JSFunctionSpec json_static_methods[] = { |
| 2114 |
JS_FN("toSource", json_toSource, 0, 0), |
| 2115 |
JS_FN("parse", json_parse, 2, 0), |
| 2116 |
JS_FN("stringify", json_stringify, 3, 0), |
| 2117 |
JS_FN("isRawJSON", json_isRawJSON, 1, 0), |
| 2118 |
JS_FN("rawJSON", json_rawJSON, 1, 0), |
| 2119 |
JS_FS_END, |
| 2120 |
}; |
| 2121 |
|
| 2122 |
static const JSPropertySpec json_static_properties[] = { |
| 2123 |
JS_STRING_SYM_PS(toStringTag, "JSON", JSPROP_READONLY), |
| 2124 |
JS_PS_END, |
| 2125 |
}; |
| 2126 |
|
| 2127 |
static JSObject* CreateJSONObject(JSContext* cx, JSProtoKey key) { |
| 2128 |
RootedObject proto(cx, &cx->global()->getObjectPrototype()); |
| 2129 |
return NewTenuredObjectWithGivenProto(cx, &JSONClass, proto); |
| 2130 |
} |
| 2131 |
|
| 2132 |
static const ClassSpec JSONClassSpec = { |
| 2133 |
CreateJSONObject, |
| 2134 |
nullptr, |
| 2135 |
json_static_methods, |
| 2136 |
json_static_properties, |
| 2137 |
}; |
| 2138 |
|
| 2139 |
const JSClass js::JSONClass = { |
| 2140 |
"JSON", |
| 2141 |
JSCLASS_HAS_CACHED_PROTO(JSProto_JSON), |
| 2142 |
JS_NULL_CLASS_OPS, |
| 2143 |
&JSONClassSpec, |
| 2144 |
}; |