Debian Codegraph @

js/src/vm/JSObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * JS object implementation.
9 */
10
11 #include "vm/JSObject-inl.h"
12
13 #include "mozilla/MemoryReporting.h"
14 #include "mozilla/Try.h"
15
16 #include <string.h>
17
18 #include "jsapi.h"
19 #include "jsdate.h"
20 #include "jsexn.h"
21 #include "jsfriendapi.h"
22 #include "jsnum.h"
23 #include "jstypes.h"
24
25 #include "builtin/BigInt.h"
26 #include "builtin/MapObject.h"
27 #include "builtin/Object.h"
28 #include "builtin/String.h"
29 #include "builtin/Symbol.h"
30 #include "builtin/WeakSetObject.h"
31 #include "gc/AllocKind.h"
32 #include "gc/GC.h"
33 #include "js/CharacterEncoding.h"
34 #include "js/friend/DumpFunctions.h" // js::DumpObject
35 #include "js/friend/ErrorMessages.h" // JSErrNum, js::GetErrorMessage, JSMSG_*
36 #include "js/friend/WindowProxy.h" // js::IsWindow, js::ToWindowProxyIfWindow
37 #include "js/MemoryMetrics.h"
38 #include "js/Prefs.h" // JS::Prefs
39 #include "js/Printer.h" // js::GenericPrinter, js::Fprinter
40 #include "js/PropertyDescriptor.h" // JS::FromPropertyDescriptor
41 #include "js/PropertySpec.h" // JSPropertySpec
42 #include "js/Proxy.h"
43 #include "js/Result.h"
44 #include "js/UbiNode.h"
45 #include "js/Wrapper.h"
46 #include "proxy/DeadObjectProxy.h"
47 #include "util/Memory.h"
48 #include "util/Text.h"
49 #include "util/WindowsWrapper.h"
50 #include "vm/ArgumentsObject.h"
51 #include "vm/ArrayBufferObject.h"
52 #include "vm/ArrayBufferViewObject.h"
53 #include "vm/BytecodeUtil.h"
54 #include "vm/Compartment.h"
55 #include "vm/DateObject.h"
56 #include "vm/Interpreter.h"
57 #include "vm/Iteration.h"
58 #include "vm/JSAtomUtils.h" // Atomize
59 #include "vm/JSContext.h"
60 #include "vm/JSFunction.h"
61 #include "vm/JSONPrinter.h" // js::JSONPrinter
62 #include "vm/JSScript.h"
63 #include "vm/PromiseObject.h"
64 #include "vm/ProxyObject.h"
65 #include "vm/RegExpObject.h"
66 #include "vm/SelfHosting.h"
67 #include "vm/Shape.h"
68 #include "vm/TypedArrayObject.h"
69 #include "vm/Watchtower.h"
70 #include "vm/WrapperObject.h"
71 #include "gc/StableCellHasher-inl.h"
72 #include "vm/BooleanObject-inl.h"
73 #include "vm/EnvironmentObject-inl.h"
74 #include "vm/Interpreter-inl.h"
75 #include "vm/JSAtomUtils-inl.h" // AtomToId, PrimitiveValueToId, IndexToId
76 #include "vm/JSContext-inl.h"
77 #include "vm/NativeObject-inl.h"
78 #include "vm/NumberObject-inl.h"
79 #include "vm/ObjectFlags-inl.h"
80 #include "vm/Realm-inl.h"
81 #include "vm/StringObject-inl.h"
82 #include "vm/TypedArrayObject-inl.h"
83 #include "wasm/WasmGcObject-inl.h"
84
85 using namespace js;
86
87 using mozilla::Maybe;
88
89 void js::ReportNotObject(JSContext* cx, JSErrNum err, int spindex,
90 HandleValue v) {
91 MOZ_ASSERT(!v.isObject());
92 ReportValueError(cx, err, spindex, v, nullptr);
93 }
94
95 void js::ReportNotObject(JSContext* cx, JSErrNum err, HandleValue v) {
96 ReportNotObject(cx, err, JSDVG_SEARCH_STACK, v);
97 }
98
99 void js::ReportNotObject(JSContext* cx, const Value& v) {
100 RootedValue value(cx, v);
101 ReportNotObject(cx, JSMSG_OBJECT_REQUIRED, value);
102 }
103
104 void js::ReportNotObjectArg(JSContext* cx, const char* nth, const char* fun,
105 HandleValue v) {
106 MOZ_ASSERT(!v.isObject());
107
108 UniqueChars bytes;
109 const char* chars = ValueToSourceForError(cx, v, bytes);
110 MOZ_ASSERT(chars);
111 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
112 JSMSG_OBJECT_REQUIRED_ARG, nth, fun, chars);
113 }
114
115 JS_PUBLIC_API const char* JS::InformalValueTypeName(const Value& v) {
116 switch (v.type()) {
117 case ValueType::Double:
118 case ValueType::Int32:
119 return "number";
120 case ValueType::Boolean:
121 return "boolean";
122 case ValueType::Undefined:
123 return "undefined";
124 case ValueType::Null:
125 return "null";
126 case ValueType::String:
127 return "string";
128 case ValueType::Symbol:
129 return "symbol";
130 case ValueType::BigInt:
131 return "bigint";
132 case ValueType::Object:
133 return v.toObject().getClass()->name;
134 case ValueType::Magic:
135 return "magic";
136 case ValueType::PrivateGCThing:
137 break;
138 }
139
140 MOZ_CRASH("unexpected type");
141 }
142
143 // ES6 draft rev37 6.2.4.4 FromPropertyDescriptor
144 JS_PUBLIC_API bool JS::FromPropertyDescriptor(
145 JSContext* cx, Handle<Maybe<PropertyDescriptor>> desc_,
146 MutableHandleValue vp) {
147 AssertHeapIsIdle();
148 CHECK_THREAD(cx);
149 cx->check(desc_);
150
151 // Step 1.
152 if (desc_.isNothing()) {
153 vp.setUndefined();
154 return true;
155 }
156
157 Rooted<PropertyDescriptor> desc(cx, *desc_);
158 return FromPropertyDescriptorToObject(cx, desc, vp);
159 }
160
161 bool js::FromPropertyDescriptorToObject(JSContext* cx,
162 Handle<PropertyDescriptor> desc,
163 MutableHandleValue vp) {
164 // Step 2-3.
165 RootedObject obj(cx, NewPlainObject(cx));
166 if (!obj) {
167 return false;
168 }
169
170 const JSAtomState& names = cx->names();
171
172 // Step 4.
173 if (desc.hasValue()) {
174 if (!DefineDataProperty(cx, obj, names.value, desc.value())) {
175 return false;
176 }
177 }
178
179 // Step 5.
180 RootedValue v(cx);
181 if (desc.hasWritable()) {
182 v.setBoolean(desc.writable());
183 if (!DefineDataProperty(cx, obj, names.writable, v)) {
184 return false;
185 }
186 }
187
188 // Step 6.
189 if (desc.hasGetter()) {
190 if (JSObject* get = desc.getter()) {
191 v.setObject(*get);
192 } else {
193 v.setUndefined();
194 }
195 if (!DefineDataProperty(cx, obj, names.get, v)) {
196 return false;
197 }
198 }
199
200 // Step 7.
201 if (desc.hasSetter()) {
202 if (JSObject* set = desc.setter()) {
203 v.setObject(*set);
204 } else {
205 v.setUndefined();
206 }
207 if (!DefineDataProperty(cx, obj, names.set, v)) {
208 return false;
209 }
210 }
211
212 // Step 8.
213 if (desc.hasEnumerable()) {
214 v.setBoolean(desc.enumerable());
215 if (!DefineDataProperty(cx, obj, names.enumerable, v)) {
216 return false;
217 }
218 }
219
220 // Step 9.
221 if (desc.hasConfigurable()) {
222 v.setBoolean(desc.configurable());
223 if (!DefineDataProperty(cx, obj, names.configurable, v)) {
224 return false;
225 }
226 }
227
228 vp.setObject(*obj);
229 return true;
230 }
231
232 bool js::GetFirstArgumentAsObject(JSContext* cx, const CallArgs& args,
233 const char* method,
234 MutableHandleObject objp) {
235 if (!args.requireAtLeast(cx, method, 1)) {
236 return false;
237 }
238
239 HandleValue v = args[0];
240 if (!v.isObject()) {
241 UniqueChars bytes =
242 DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, v, nullptr);
243 if (!bytes) {
244 return false;
245 }
246 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
247 JSMSG_UNEXPECTED_TYPE, bytes.get(),
248 "not an object");
249 return false;
250 }
251
252 objp.set(&v.toObject());
253 return true;
254 }
255
256 static bool GetPropertyIfPresent(JSContext* cx, HandleObject obj, HandleId id,
257 MutableHandleValue vp, bool* foundp) {
258 if (!HasProperty(cx, obj, id, foundp)) {
259 return false;
260 }
261 if (!*foundp) {
262 vp.setUndefined();
263 return true;
264 }
265
266 return GetProperty(cx, obj, obj, id, vp);
267 }
268
269 bool js::Throw(JSContext* cx, HandleId id, unsigned errorNumber,
270 const char* details) {
271 MOZ_ASSERT(js_ErrorFormatString[errorNumber].argCount == (details ? 2 : 1));
272 MOZ_ASSERT_IF(details, JS::StringIsASCII(details));
273
274 UniqueChars bytes =
275 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
276 if (!bytes) {
277 return false;
278 }
279
280 if (details) {
281 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
282 bytes.get(), details);
283 } else {
284 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
285 bytes.get());
286 }
287
288 return false;
289 }
290
291 /*** PropertyDescriptor operations and DefineProperties *********************/
292
293 static Result<> CheckCallable(JSContext* cx, JSObject* obj,
294 const char* fieldName) {
295 if (obj && !obj->isCallable()) {
296 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
297 JSMSG_BAD_GET_SET_FIELD, fieldName);
298 return cx->alreadyReportedError();
299 }
300 return Ok();
301 }
302
303 // 6.2.5.5 ToPropertyDescriptor(Obj)
304 bool js::ToPropertyDescriptor(JSContext* cx, HandleValue descval,
305 bool checkAccessors,
306 MutableHandle<PropertyDescriptor> desc_) {
307 // Step 1.
308 RootedObject obj(cx,
309 RequireObject(cx, JSMSG_OBJECT_REQUIRED_PROP_DESC, descval));
310 if (!obj) {
311 return false;
312 }
313
314 // Step 2.
315 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Empty());
316
317 RootedId id(cx);
318 RootedValue v(cx);
319
320 // Steps 3-4.
321 id = NameToId(cx->names().enumerable);
322 bool hasEnumerable = false;
323 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasEnumerable)) {
324 return false;
325 }
326 if (hasEnumerable) {
327 desc.setEnumerable(ToBoolean(v));
328 }
329
330 // Steps 5-6.
331 id = NameToId(cx->names().configurable);
332 bool hasConfigurable = false;
333 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasConfigurable)) {
334 return false;
335 }
336 if (hasConfigurable) {
337 desc.setConfigurable(ToBoolean(v));
338 }
339
340 // Steps 7-8.
341 id = NameToId(cx->names().value);
342 bool hasValue = false;
343 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasValue)) {
344 return false;
345 }
346 if (hasValue) {
347 desc.setValue(v);
348 }
349
350 // Steps 9-10.
351 id = NameToId(cx->names().writable);
352 bool hasWritable = false;
353 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasWritable)) {
354 return false;
355 }
356 if (hasWritable) {
357 desc.setWritable(ToBoolean(v));
358 }
359
360 // Steps 11-12.
361 id = NameToId(cx->names().get);
362 bool hasGet = false;
363 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasGet)) {
364 return false;
365 }
366 RootedObject getter(cx);
367 if (hasGet) {
368 if (v.isObject()) {
369 if (checkAccessors) {
370 JS_TRY_OR_RETURN_FALSE(cx, CheckCallable(cx, &v.toObject(), "getter"));
371 }
372 getter = &v.toObject();
373 } else if (v.isUndefined()) {
374 getter = nullptr;
375 } else {
376 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
377 JSMSG_BAD_GET_SET_FIELD, "getter");
378 return false;
379 }
380 }
381
382 // Steps 13-14.
383 id = NameToId(cx->names().set);
384 bool hasSet = false;
385 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasSet)) {
386 return false;
387 }
388 RootedObject setter(cx);
389 if (hasSet) {
390 if (v.isObject()) {
391 if (checkAccessors) {
392 JS_TRY_OR_RETURN_FALSE(cx, CheckCallable(cx, &v.toObject(), "setter"));
393 }
394 setter = &v.toObject();
395 } else if (v.isUndefined()) {
396 setter = nullptr;
397 } else {
398 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
399 JSMSG_BAD_GET_SET_FIELD, "setter");
400 return false;
401 }
402 }
403
404 // Step 15.
405 if (hasGet || hasSet) {
406 if (hasValue || hasWritable) {
407 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
408 JSMSG_INVALID_DESCRIPTOR);
409 return false;
410 }
411
412 // We delay setGetter/setSetter after the previous check,
413 // because otherwise we would assert.
414 if (hasGet) {
415 desc.setGetter(getter);
416 }
417 if (hasSet) {
418 desc.setSetter(setter);
419 }
420 }
421
422 desc.assertValid();
423 desc_.set(desc);
424 return true;
425 }
426
427 Result<> js::CheckPropertyDescriptorAccessors(JSContext* cx,
428 Handle<PropertyDescriptor> desc) {
429 if (desc.hasGetter()) {
430 MOZ_TRY(CheckCallable(cx, desc.getter(), "getter"));
431 }
432
433 if (desc.hasSetter()) {
434 MOZ_TRY(CheckCallable(cx, desc.setter(), "setter"));
435 }
436
437 return Ok();
438 }
439
440 // 6.2.5.6 CompletePropertyDescriptor(Desc)
441 void js::CompletePropertyDescriptor(MutableHandle<PropertyDescriptor> desc) {
442 // Step 1.
443 desc.assertValid();
444
445 // Step 2.
446 // Let like be the Record { [[Value]]: undefined, [[Writable]]: false,
447 // [[Get]]: undefined, [[Set]]: undefined,
448 // [[Enumerable]]: false, [[Configurable]]: false }.
449
450 // Step 3.
451 if (desc.isGenericDescriptor() || desc.isDataDescriptor()) {
452 // Step 3.a.
453 if (!desc.hasValue()) {
454 desc.setValue(UndefinedHandleValue);
455 }
456 // Step 3.b.
457 if (!desc.hasWritable()) {
458 desc.setWritable(false);
459 }
460 } else {
461 // Step 4.a.
462 if (!desc.hasGetter()) {
463 desc.setGetter(nullptr);
464 }
465 // Step 4.b.
466 if (!desc.hasSetter()) {
467 desc.setSetter(nullptr);
468 }
469 }
470
471 // Step 5.
472 if (!desc.hasEnumerable()) {
473 desc.setEnumerable(false);
474 }
475
476 // Step 6.
477 if (!desc.hasConfigurable()) {
478 desc.setConfigurable(false);
479 }
480
481 desc.assertComplete();
482 }
483
484 bool js::ReadPropertyDescriptors(
485 JSContext* cx, HandleObject props, bool checkAccessors,
486 MutableHandleIdVector ids, MutableHandle<PropertyDescriptorVector> descs) {
487 if (!GetPropertyKeys(cx, props, JSITER_OWNONLY | JSITER_SYMBOLS, ids)) {
488 return false;
489 }
490
491 RootedId id(cx);
492 for (size_t i = 0, len = ids.length(); i < len; i++) {
493 id = ids[i];
494 Rooted<PropertyDescriptor> desc(cx);
495 RootedValue v(cx);
496 if (!GetProperty(cx, props, props, id, &v) ||
497 !ToPropertyDescriptor(cx, v, checkAccessors, &desc) ||
498 !descs.append(desc)) {
499 return false;
500 }
501 }
502 return true;
503 }
504
505 /*** Seal and freeze ********************************************************/
506
507 /* ES6 draft rev 29 (6 Dec 2014) 7.3.13. */
508 bool js::SetIntegrityLevel(JSContext* cx, HandleObject obj,
509 IntegrityLevel level) {
510 cx->check(obj);
511
512 // Steps 3-5. (Steps 1-2 are redundant assertions.)
513 if (!PreventExtensions(cx, obj)) {
514 return false;
515 }
516
517 // Steps 6-9, loosely interpreted.
518 if (obj->is<NativeObject>() && !obj->is<TypedArrayObject>() &&
519 !obj->is<MappedArgumentsObject>()) {
520 Handle<NativeObject*> nobj = obj.as<NativeObject>();
521
522 // Use a fast path to seal/freeze properties. This has the benefit of
523 // creating shared property maps if possible, whereas the slower/generic
524 // implementation below ends up converting non-empty objects to dictionary
525 // mode.
526 if (nobj->shape()->propMapLength() > 0) {
527 if (!NativeObject::freezeOrSealProperties(cx, nobj, level)) {
528 return false;
529 }
530 }
531
532 // Ordinarily ArraySetLength handles this, but we're going behind its back
533 // right now, so we must do this manually.
534 if (level == IntegrityLevel::Frozen && obj->is<ArrayObject>()) {
535 obj->as<ArrayObject>().setNonWritableLength(cx);
536 }
537 } else {
538 // Steps 6-7.
539 RootedIdVector keys(cx);
540 if (!GetPropertyKeys(
541 cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &keys)) {
542 return false;
543 }
544
545 RootedId id(cx);
546 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Empty());
547
548 // 8.a/9.a. The two different loops are merged here.
549 for (size_t i = 0; i < keys.length(); i++) {
550 id = keys[i];
551
552 if (level == IntegrityLevel::Sealed) {
553 // 8.a.i.
554 desc.setConfigurable(false);
555 } else {
556 // 9.a.i-ii.
557 Rooted<Maybe<PropertyDescriptor>> currentDesc(cx);
558 if (!GetOwnPropertyDescriptor(cx, obj, id, &currentDesc)) {
559 return false;
560 }
561
562 // 9.a.iii.
563 if (currentDesc.isNothing()) {
564 continue;
565 }
566
567 // 9.a.iii.1-2
568 desc = PropertyDescriptor::Empty();
569 if (currentDesc->isAccessorDescriptor()) {
570 desc.setConfigurable(false);
571 } else {
572 desc.setConfigurable(false);
573 desc.setWritable(false);
574 }
575 }
576
577 // 8.a.i-ii. / 9.a.iii.3-4
578 if (!DefineProperty(cx, obj, id, desc)) {
579 return false;
580 }
581 }
582 }
583
584 // Finally, freeze or seal the dense elements.
585 if (obj->is<NativeObject>()) {
586 if (!ObjectElements::FreezeOrSeal(cx, obj.as<NativeObject>(), level)) {
587 return false;
588 }
589 }
590
591 return true;
592 }
593
594 static bool ResolveLazyProperties(JSContext* cx, Handle<NativeObject*> obj) {
595 const JSClass* clasp = obj->getClass();
596 if (JSEnumerateOp enumerate = clasp->getEnumerate()) {
597 if (!enumerate(cx, obj)) {
598 return false;
599 }
600 }
601 if (clasp->getNewEnumerate() && clasp->getResolve()) {
602 RootedIdVector properties(cx);
603 if (!clasp->getNewEnumerate()(cx, obj, &properties,
604 /* enumerableOnly = */ false)) {
605 return false;
606 }
607
608 RootedId id(cx);
609 for (size_t i = 0; i < properties.length(); i++) {
610 id = properties[i];
611 bool found;
612 if (!HasOwnProperty(cx, obj, id, &found)) {
613 return false;
614 }
615 }
616 }
617 return true;
618 }
619
620 // ES6 draft rev33 (12 Feb 2015) 7.3.15
621 bool js::TestIntegrityLevel(JSContext* cx, HandleObject obj,
622 IntegrityLevel level, bool* result) {
623 // Steps 3-6. (Steps 1-2 are redundant assertions.)
624 bool status;
625 if (!IsExtensible(cx, obj, &status)) {
626 return false;
627 }
628 if (status) {
629 *result = false;
630 return true;
631 }
632
633 // Fast path for native objects.
634 if (obj->is<NativeObject>()) {
635 Handle<NativeObject*> nobj = obj.as<NativeObject>();
636
637 // Force lazy properties to be resolved.
638 if (!ResolveLazyProperties(cx, nobj)) {
639 return false;
640 }
641
642 // Typed array elements are configurable, writable properties, so if any
643 // elements are present, the typed array can neither be sealed nor frozen.
644 if (nobj->is<TypedArrayObject>() &&
645 nobj->as<TypedArrayObject>().length().valueOr(0) > 0) {
646 *result = false;
647 return true;
648 }
649
650 bool hasDenseElements = false;
651 for (size_t i = 0; i < nobj->getDenseInitializedLength(); i++) {
652 if (nobj->containsDenseElement(i)) {
653 hasDenseElements = true;
654 break;
655 }
656 }
657
658 if (hasDenseElements) {
659 // Unless the sealed flag is set, dense elements are configurable.
660 if (!nobj->denseElementsAreSealed()) {
661 *result = false;
662 return true;
663 }
664
665 // Unless the frozen flag is set, dense elements are writable.
666 if (level == IntegrityLevel::Frozen && !nobj->denseElementsAreFrozen()) {
667 *result = false;
668 return true;
669 }
670 }
671
672 // Steps 7-9.
673 for (ShapePropertyIter<NoGC> iter(nobj->shape()); !iter.done(); iter++) {
674 // Steps 9.c.i-ii.
675 if (iter->configurable() ||
676 (level == IntegrityLevel::Frozen && iter->isDataDescriptor() &&
677 iter->writable())) {
678 // Private fields on objects don't participate in the frozen state, and
679 // so should be elided from checking for frozen state.
680 if (iter->key().isPrivateName()) {
681 continue;
682 }
683
684 *result = false;
685 return true;
686 }
687 }
688 } else {
689 // Steps 7-8.
690 RootedIdVector props(cx);
691 if (!GetPropertyKeys(
692 cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &props)) {
693 return false;
694 }
695
696 // Step 9.
697 RootedId id(cx);
698 Rooted<Maybe<PropertyDescriptor>> desc(cx);
699 for (size_t i = 0, len = props.length(); i < len; i++) {
700 id = props[i];
701
702 // Steps 9.a-b.
703 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
704 return false;
705 }
706
707 // Step 9.c.
708 if (desc.isNothing()) {
709 continue;
710 }
711
712 // Steps 9.c.i-ii.
713 if (desc->configurable() ||
714 (level == IntegrityLevel::Frozen && desc->isDataDescriptor() &&
715 desc->writable())) {
716 // Since we don't request JSITER_PRIVATE in GetPropertyKeys above, we
717 // should never see a private name here.
718 MOZ_ASSERT(!id.isPrivateName());
719 *result = false;
720 return true;
721 }
722 }
723 }
724
725 // Step 10.
726 *result = true;
727 return true;
728 }
729
730 /* * */
731
732 static MOZ_ALWAYS_INLINE NativeObject* NewObject(
733 JSContext* cx, const JSClass* clasp, Handle<TaggedProto> proto,
734 gc::AllocKind kind, NewObjectKind newKind, ObjectFlags objFlags,
735 gc::AllocSite* allocSite = nullptr) {
736 MOZ_ASSERT(clasp->isNativeObject());
737
738 // Some classes have specialized allocation functions and shouldn't end up
739 // here.
740 MOZ_ASSERT(clasp != &ArrayObject::class_);
741 MOZ_ASSERT(clasp != &PlainObject::class_);
742 MOZ_ASSERT(!clasp->isJSFunction());
743
744 MOZ_ASSERT_IF(allocSite, allocSite->zone() == cx->zone());
745
746 // Computing nfixed based on the AllocKind isn't right for objects which can
747 // store fixed data inline (TypedArrays and ArrayBuffers) so for simplicity
748 // and performance reasons we don't support such objects here.
749 MOZ_ASSERT(!ClassCanHaveFixedData(clasp));
750 size_t nfixed = GetGCKindSlots(kind);
751
752 kind = gc::GetFinalizedAllocKindForClass(kind, clasp);
753
754 Rooted<SharedShape*> shape(
755 cx, SharedShape::getInitialShape(cx, clasp, cx->realm(), proto, nfixed,
756 objFlags));
757 if (!shape) {
758 return nullptr;
759 }
760
761 gc::Heap heap = GetInitialHeap(newKind, clasp, allocSite);
762 NativeObject* obj = NativeObject::create(cx, kind, heap, shape, allocSite);
763 if (!obj) {
764 return nullptr;
765 }
766
767 probes::CreateObject(cx, obj);
768 return obj;
769 }
770
771 NativeObject* js::NewObjectWithGivenTaggedProto(
772 JSContext* cx, const JSClass* clasp, Handle<TaggedProto> proto,
773 gc::AllocKind allocKind, NewObjectKind newKind, ObjectFlags objFlags) {
774 return NewObject(cx, clasp, proto, allocKind, newKind, objFlags);
775 }
776
777 NativeObject* js::NewObjectWithGivenTaggedProtoAndAllocSite(
778 JSContext* cx, const JSClass* clasp, Handle<TaggedProto> proto,
779 gc::AllocKind allocKind, NewObjectKind newKind, ObjectFlags objFlags,
780 gc::AllocSite* site) {
781 return NewObject(cx, clasp, proto, allocKind, newKind, objFlags, site);
782 }
783
784 NativeObject* js::NewObjectWithClassProto(JSContext* cx, const JSClass* clasp,
785 HandleObject protoArg,
786 gc::AllocKind allocKind,
787 NewObjectKind newKind,
788 ObjectFlags objFlags) {
789 if (protoArg) {
790 return NewObjectWithGivenTaggedProto(cx, clasp, AsTaggedProto(protoArg),
791 allocKind, newKind, objFlags);
792 }
793
794 // Find the appropriate proto for clasp. Built-in classes have a cached
795 // proto on cx->global(); all others get %ObjectPrototype%.
796 JSProtoKey protoKey = JSCLASS_CACHED_PROTO_KEY(clasp);
797 if (protoKey == JSProto_Null) {
798 protoKey = JSProto_Object;
799 }
800
801 JSObject* proto = GlobalObject::getOrCreatePrototype(cx, protoKey);
802 if (!proto) {
803 return nullptr;
804 }
805
806 Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
807 return NewObject(cx, clasp, taggedProto, allocKind, newKind, objFlags);
808 }
809
810 bool js::GetPrototypeFromConstructor(JSContext* cx, HandleObject newTarget,
811 JSProtoKey intrinsicDefaultProto,
812 MutableHandleObject proto) {
813 RootedValue protov(cx);
814 if (!GetProperty(cx, newTarget, newTarget, cx->names().prototype, &protov)) {
815 return false;
816 }
817 if (protov.isObject()) {
818 proto.set(&protov.toObject());
819 } else if (newTarget->is<JSFunction>() &&
820 newTarget->as<JSFunction>().realm() == cx->realm()) {
821 // Steps 4.a-b fetch the builtin prototype of the current realm, which we
822 // represent as nullptr.
823 proto.set(nullptr);
824 } else if (intrinsicDefaultProto == JSProto_Null) {
825 // Bug 1317416. The caller did not pass a reasonable JSProtoKey, so let the
826 // caller select a prototype object. Most likely they will choose one from
827 // the wrong realm.
828 proto.set(nullptr);
829 } else {
830 // Step 4.a: Let realm be ? GetFunctionRealm(constructor);
831 Realm* realm = JS::GetFunctionRealm(cx, newTarget);
832 if (!realm) {
833 return false;
834 }
835
836 // Step 4.b: Set proto to realm's intrinsic object named
837 // intrinsicDefaultProto.
838 {
839 Maybe<AutoRealm> ar;
840 if (cx->realm() != realm) {
841 ar.emplace(cx, realm->maybeGlobal());
842 }
843 proto.set(GlobalObject::getOrCreatePrototype(cx, intrinsicDefaultProto));
844 }
845 if (!proto) {
846 return false;
847 }
848 if (!cx->compartment()->wrap(cx, proto)) {
849 return false;
850 }
851 }
852 return true;
853 }
854
855 /* static */
856 bool JSObject::nonNativeSetProperty(JSContext* cx, HandleObject obj,
857 HandleId id, HandleValue v,
858 HandleValue receiver,
859 ObjectOpResult& result) {
860 return obj->getOpsSetProperty()(cx, obj, id, v, receiver, result);
861 }
862
863 /* static */
864 bool JSObject::nonNativeSetElement(JSContext* cx, HandleObject obj,
865 uint32_t index, HandleValue v,
866 HandleValue receiver,
867 ObjectOpResult& result) {
868 RootedId id(cx);
869 if (!IndexToId(cx, index, &id)) {
870 return false;
871 }
872 return nonNativeSetProperty(cx, obj, id, v, receiver, result);
873 }
874
875 static bool CopyPropertyFrom(JSContext* cx, HandleId id, HandleObject target,
876 HandleObject obj) {
877 // |target| must not be a CCW because we need to enter its realm below and
878 // CCWs are not associated with a single realm.
879 MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
880
881 // |obj| and |cx| are generally not same-compartment with |target| here.
882 cx->check(obj, id);
883 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
884
885 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
886 return false;
887 }
888 MOZ_ASSERT(desc.isSome());
889
890 JSAutoRealm ar(cx, target);
891 cx->markId(id);
892 RootedId wrappedId(cx, id);
893 if (!cx->compartment()->wrap(cx, &desc)) {
894 return false;
895 }
896
897 Rooted<PropertyDescriptor> desc_(cx, *desc);
898 return DefineProperty(cx, target, wrappedId, desc_);
899 }
900
901 JS_PUBLIC_API bool JS_CopyOwnPropertiesAndPrivateFields(JSContext* cx,
902 HandleObject target,
903 HandleObject obj) {
904 // Both |obj| and |target| must not be CCWs because we need to enter their
905 // realms below and CCWs are not associated with a single realm.
906 MOZ_ASSERT(!IsCrossCompartmentWrapper(obj));
907 MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
908
909 JSAutoRealm ar(cx, obj);
910
911 RootedIdVector props(cx);
912 if (!GetPropertyKeys(
913 cx, obj,
914 JSITER_PRIVATE | JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
915 &props)) {
916 return false;
917 }
918
919 for (size_t i = 0; i < props.length(); ++i) {
920 if (!CopyPropertyFrom(cx, props[i], target, obj)) {
921 return false;
922 }
923 }
924
925 return true;
926 }
927
928 static bool InitializePropertiesFromCompatibleNativeObject(
929 JSContext* cx, Handle<NativeObject*> dst, Handle<NativeObject*> src) {
930 cx->check(src, dst);
931 MOZ_ASSERT(src->getClass() == dst->getClass());
932 MOZ_ASSERT(dst->shape()->objectFlags().isEmpty());
933 MOZ_ASSERT(src->numFixedSlots() == dst->numFixedSlots());
934 MOZ_ASSERT(!src->inDictionaryMode());
935 MOZ_ASSERT(!dst->inDictionaryMode());
936
937 if (!dst->ensureElements(cx, src->getDenseInitializedLength())) {
938 return false;
939 }
940
941 uint32_t initialized = src->getDenseInitializedLength();
942 for (uint32_t i = 0; i < initialized; ++i) {
943 dst->setDenseInitializedLength(i + 1);
944 dst->initDenseElement(i, src->getDenseElement(i));
945 }
946
947 // If there are no properties to copy, we're done.
948 if (!src->sharedShape()->propMap()) {
949 return true;
950 }
951
952 Rooted<SharedShape*> shape(cx);
953 if (src->staticPrototype() == dst->staticPrototype()) {
954 shape = src->sharedShape();
955 } else {
956 // We need to generate a new shape for dst that has dst's proto but all
957 // the property information from src. Note that we asserted above that
958 // dst's object flags are empty.
959 SharedShape* srcShape = src->sharedShape();
960 ObjectFlags objFlags;
961 objFlags = CopyPropMapObjectFlags(objFlags, srcShape->objectFlags());
962 Rooted<SharedPropMap*> map(cx, srcShape->propMap());
963 uint32_t mapLength = srcShape->propMapLength();
964 shape = SharedShape::getPropMapShape(cx, dst->shape()->base(),
965 dst->numFixedSlots(), map, mapLength,
966 objFlags);
967 if (!shape) {
968 return false;
969 }
970 }
971
972 uint32_t oldSpan = dst->sharedShape()->slotSpan();
973 uint32_t newSpan = shape->slotSpan();
974 if (!dst->setShapeAndAddNewSlots(cx, shape, oldSpan, newSpan)) {
975 return false;
976 }
977 for (size_t i = JSCLASS_RESERVED_SLOTS(src->getClass()); i < newSpan; i++) {
978 dst->setSlot(i, src->getSlot(i));
979 }
980
981 return true;
982 }
983
984 JS_PUBLIC_API bool JS_InitializePropertiesFromCompatibleNativeObject(
985 JSContext* cx, HandleObject dst, HandleObject src) {
986 return InitializePropertiesFromCompatibleNativeObject(
987 cx, dst.as<NativeObject>(), src.as<NativeObject>());
988 }
989
990 bool js::ObjectMayBeSwapped(const JSObject* obj) {
991 const JSClass* clasp = obj->getClass();
992
993 // We want to optimize Window/globals and Gecko doesn't require transplanting
994 // them (only the WindowProxy around them). A Window may be a DOMClass, so we
995 // explicitly check if this is a global.
996 if (clasp->isGlobal()) {
997 return false;
998 }
999
1000 // WindowProxy, Wrapper, DeadProxyObject, DOMProxy, and DOMClass (non-global)
1001 // types may be swapped. It is hard to detect DOMProxy from shell, so target
1002 // proxies in general.
1003 return clasp->isProxyObject() || clasp->isDOMClass();
1004 }
1005
1006 bool NativeObject::prepareForSwap(JSContext* cx, JSObject* other,
1007 MutableHandleValueVector slotValuesOut) {
1008 MOZ_ASSERT(slotValuesOut.empty());
1009
1010 for (size_t i = 0; i < slotSpan(); i++) {
1011 if (!slotValuesOut.append(getSlot(i))) {
1012 return false;
1013 }
1014 }
1015
1016 if (hasDynamicSlots()) {
1017 setEmptyDynamicSlots(0);
1018 }
1019
1020 // Copy elements if we're swapping between tenured and nursery objects to
1021 // prevent:
1022 // 1. Tenured objects with pointers to direct nursery allocations
1023 // 2. Tenured objects with pointers to buffers marked as nursery-owned
1024 if (hasDynamicElements() && IsInsideNursery(this) != IsInsideNursery(other)) {
1025 ObjectElements* elements = getElementsHeader();
1026 size_t count = elements->numAllocatedElements();
1027 size_t size = count * sizeof(HeapSlot);
1028 void* buffer = AllocBuffer(cx->zone(), size, IsInsideNursery(other));
1029 if (!buffer) {
1030 return false;
1031 }
1032
1033 memmove(buffer, getUnshiftedElementsHeader(), size);
1034
1035 uint32_t numShifted = elements->numShiftedElements();
1036 auto* newElements = reinterpret_cast<ObjectElements*>(
1037 reinterpret_cast<HeapSlot*>(buffer) + numShifted);
1038
1039 elements_ = newElements->elements();
1040
1041 MOZ_ASSERT(hasDynamicElements());
1042 }
1043
1044 return true;
1045 }
1046
1047 /* static */
1048 bool NativeObject::fixupAfterSwap(JSContext* cx, Handle<NativeObject*> obj,
1049 gc::AllocKind kind,
1050 HandleValueVector slotValues) {
1051 // This object has just been swapped with some other object, and its shape
1052 // no longer reflects its allocated size. Correct this information and
1053 // fill the slots in with the specified values.
1054 MOZ_ASSERT_IF(!obj->inDictionaryMode(),
1055 obj->slotSpan() == slotValues.length());
1056
1057 // Make sure the shape's numFixedSlots() is correct.
1058 size_t nfixed = gc::GetGCKindSlots(kind);
1059 if (nfixed != obj->shape()->numFixedSlots()) {
1060 if (!NativeObject::changeNumFixedSlotsAfterSwap(cx, obj, nfixed)) {
1061 return false;
1062 }
1063 MOZ_ASSERT(obj->shape()->numFixedSlots() == nfixed);
1064 }
1065
1066 uint32_t oldDictionarySlotSpan =
1067 obj->inDictionaryMode() ? slotValues.length() : 0;
1068
1069 MOZ_ASSERT(!obj->hasUniqueId());
1070 size_t ndynamic =
1071 calculateDynamicSlots(nfixed, slotValues.length(), obj->getClass());
1072 size_t currentSlots = obj->getSlotsHeader()->capacity();
1073 MOZ_ASSERT(ndynamic >= currentSlots);
1074 if (ndynamic > currentSlots) {
1075 if (!obj->growSlots(cx, currentSlots, ndynamic)) {
1076 return false;
1077 }
1078 }
1079
1080 if (obj->inDictionaryMode()) {
1081 obj->setDictionaryModeSlotSpan(oldDictionarySlotSpan);
1082 }
1083
1084 for (size_t i = 0, len = slotValues.length(); i < len; i++) {
1085 obj->initSlotUnchecked(i, slotValues[i]);
1086 }
1087
1088 #ifdef DEBUG
1089 Zone* zone = obj->zone();
1090 if (obj->hasDynamicSlots() && gc::IsBufferAlloc(obj->getSlotsHeader())) {
1091 MOZ_ASSERT(gc::IsNurseryOwned(zone, obj->getSlotsHeader()) ==
1092 IsInsideNursery(obj));
1093 }
1094 if (obj->hasDynamicElements() &&
1095 gc::IsBufferAlloc(obj->getUnshiftedElementsHeader())) {
1096 MOZ_ASSERT(gc::IsNurseryOwned(zone, obj->getUnshiftedElementsHeader()) ==
1097 IsInsideNursery(obj));
1098 }
1099 #endif
1100
1101 return true;
1102 }
1103
1104 [[nodiscard]] bool ProxyObject::prepareForSwap(
1105 JSContext* cx, MutableHandleValueVector valuesOut) {
1106 MOZ_ASSERT(valuesOut.empty());
1107
1108 // Remove the GCPtr<Value>s we're about to swap from the store buffer, to
1109 // ensure we don't trace bogus values.
1110 gc::StoreBuffer& sb = cx->runtime()->gc.storeBuffer();
1111
1112 // Reserve space for the expando, private slot and the reserved slots.
1113 if (!valuesOut.reserve(2 + numReservedSlots())) {
1114 return false;
1115 }
1116
1117 js::detail::ProxyValueArray* valArray = data.values();
1118 sb.unputValue(&valArray->expandoSlot);
1119 sb.unputValue(&valArray->privateSlot);
1120 valuesOut.infallibleAppend(valArray->expandoSlot);
1121 valuesOut.infallibleAppend(valArray->privateSlot);
1122
1123 for (size_t i = 0; i < numReservedSlots(); i++) {
1124 sb.unputValue(&valArray->reservedSlots.slots[i]);
1125 valuesOut.infallibleAppend(valArray->reservedSlots.slots[i]);
1126 }
1127
1128 if (isTenured() && !usingInlineValueArray()) {
1129 size_t count = detail::ProxyValueArray::allocCount(numReservedSlots());
1130 RemoveCellMemory(this, count * sizeof(Value),
1131 MemoryUse::ProxyExternalValueArray);
1132 js_free(valArray);
1133 data.reservedSlots = nullptr;
1134 }
1135
1136 return true;
1137 }
1138
1139 bool ProxyObject::fixupAfterSwap(JSContext* cx,
1140 const HandleValueVector values) {
1141 MOZ_ASSERT(getClass()->isProxyObject());
1142
1143 size_t nreserved = numReservedSlots();
1144
1145 // |values| contains the expando slot, private slot and the reserved slots.
1146 MOZ_ASSERT(values.length() == 2 + nreserved);
1147
1148 // Allocate the external value array in malloc memory, even for nursery
1149 // proxies.
1150 size_t count = detail::ProxyValueArray::allocCount(nreserved);
1151 auto* allocation = js_pod_malloc<JS::Value>(count);
1152 if (!allocation) {
1153 return false;
1154 }
1155
1156 size_t size = count * sizeof(Value);
1157 if (isTenured()) {
1158 AddCellMemory(&asTenured(), size, MemoryUse::ProxyExternalValueArray);
1159 } else if (!cx->nursery().registerMallocedBuffer(allocation, size)) {
1160 js_free(allocation);
1161 return false;
1162 }
1163
1164 auto* valArray = reinterpret_cast<js::detail::ProxyValueArray*>(allocation);
1165
1166 valArray->expandoSlot = values[0];
1167 valArray->privateSlot = values[1];
1168
1169 for (size_t i = 0; i < nreserved; i++) {
1170 valArray->reservedSlots.slots[i] = values[i + 2];
1171 }
1172
1173 data.reservedSlots = &valArray->reservedSlots;
1174 MOZ_ASSERT(!usingInlineValueArray());
1175 return true;
1176 }
1177
1178 static gc::AllocKind SwappableObjectAllocKind(JSObject* obj) {
1179 MOZ_ASSERT(ObjectMayBeSwapped(obj));
1180
1181 if (obj->isTenured()) {
1182 return obj->asTenured().getAllocKind();
1183 }
1184
1185 if (obj->is<NativeObject>()) {
1186 return obj->as<NativeObject>().allocKindForTenure();
1187 }
1188
1189 return obj->as<ProxyObject>().allocKindForTenure();
1190 }
1191
1192 /* Use this method with extreme caution. It trades the guts of two objects. */
1193 void JSObject::swap(JSContext* cx, HandleObject a, HandleObject b,
1194 AutoEnterOOMUnsafeRegion& oomUnsafe) {
1195 // Ensure swap doesn't cause a finalizer to be run at the wrong time.
1196 MOZ_ASSERT(gc::GetFinalizeKind(a->allocKind()) ==
1197 gc::GetFinalizeKind(b->allocKind()));
1198
1199 MOZ_ASSERT(a->compartment() == b->compartment());
1200
1201 // You must have entered the objects' compartment before calling this.
1202 MOZ_ASSERT(cx->compartment() == a->compartment());
1203
1204 // Only certain types of objects are allowed to be swapped. This allows the
1205 // JITs to better optimize objects that can never swap and rules out most
1206 // builtin objects that have special behaviour.
1207 MOZ_RELEASE_ASSERT(js::ObjectMayBeSwapped(a));
1208 MOZ_RELEASE_ASSERT(js::ObjectMayBeSwapped(b));
1209
1210 // Don't allow a GC which may observe intermediate state or run before we
1211 // execute all necessary barriers.
1212 gc::AutoSuppressGC nogc(cx);
1213
1214 if (!Watchtower::watchObjectSwap(cx, a, b)) {
1215 oomUnsafe.crash("watchObjectSwap");
1216 }
1217
1218 // Ensure we update any embedded nursery pointers in either object.
1219 gc::StoreBuffer& storeBuffer = cx->runtime()->gc.storeBuffer();
1220 if (a->isTenured()) {
1221 storeBuffer.putWholeCell(a);
1222 }
1223 if (b->isTenured()) {
1224 storeBuffer.putWholeCell(b);
1225 }
1226 if (a->isTenured() || b->isTenured()) {
1227 if (a->zone()->wasGCStarted()) {
1228 storeBuffer.setMayHavePointersToDeadCells();
1229 }
1230 }
1231
1232 unsigned r = NotifyGCPreSwap(a, b);
1233
1234 ProxyObject* pa = a->is<ProxyObject>() ? &a->as<ProxyObject>() : nullptr;
1235 ProxyObject* pb = b->is<ProxyObject>() ? &b->as<ProxyObject>() : nullptr;
1236 bool aIsProxyWithInlineValues = pa && pa->usingInlineValueArray();
1237 bool bIsProxyWithInlineValues = pb && pb->usingInlineValueArray();
1238
1239 bool aIsUsedAsPrototype = a->isUsedAsPrototype();
1240 bool bIsUsedAsPrototype = b->isUsedAsPrototype();
1241
1242 // Swap element associations.
1243 Zone* zone = a->zone();
1244
1245 // Record any associated unique IDs and prepare for swap.
1246 //
1247 // Note that unique IDs are NOT swapped but remain associated with the
1248 // original address.
1249 uint64_t aid = 0;
1250 uint64_t bid = 0;
1251 (void)gc::MaybeGetUniqueId(a, &aid);
1252 (void)gc::MaybeGetUniqueId(b, &bid);
1253 NativeObject* na = a->is<NativeObject>() ? &a->as<NativeObject>() : nullptr;
1254 NativeObject* nb = b->is<NativeObject>() ? &b->as<NativeObject>() : nullptr;
1255 if ((aid || bid) && (na || nb)) {
1256 // We can't remove unique IDs from native objects when they are swapped with
1257 // objects without an ID. Instead ensure they both have IDs so we always
1258 // have something to overwrite the old ID with.
1259 if (!gc::GetOrCreateUniqueId(a, &aid) ||
1260 !gc::GetOrCreateUniqueId(b, &bid)) {
1261 oomUnsafe.crash("Failed to create unique ID during swap");
1262 }
1263
1264 // IDs stored in NativeObjects could shadow those stored in the zone
1265 // table. Remove any zone table IDs first.
1266 if (pa && aid) {
1267 gc::RemoveUniqueId(a);
1268 }
1269 if (pb && bid) {
1270 gc::RemoveUniqueId(b);
1271 }
1272 }
1273
1274 gc::AllocKind ka = SwappableObjectAllocKind(a);
1275 gc::AllocKind kb = SwappableObjectAllocKind(b);
1276
1277 size_t sa = gc::Arena::thingSize(ka);
1278 size_t sb = gc::Arena::thingSize(kb);
1279 if (sa == sb && a->isTenured() == b->isTenured()) {
1280 // When both objects are the same size and in the same heap, just do a plain
1281 // swap of their contents.
1282
1283 size_t size = sa;
1284 char tmp[sizeof(JSObject_Slots16)];
1285 MOZ_ASSERT(size <= sizeof(tmp));
1286
1287 js_memcpy(tmp, a, size);
1288 js_memcpy(a, b, size);
1289 js_memcpy(b, tmp, size);
1290
1291 zone->swapCellMemory(a, b, MemoryUse::ProxyExternalValueArray);
1292
1293 if (aIsProxyWithInlineValues) {
1294 b->as<ProxyObject>().setInlineValueArray();
1295 }
1296 if (bIsProxyWithInlineValues) {
1297 a->as<ProxyObject>().setInlineValueArray();
1298 }
1299 } else {
1300 // When the objects have different sizes, they will have different numbers
1301 // of fixed slots before and after the swap, so the slots for native objects
1302 // will need to be rearranged. Remember the original values from the
1303 // objects.
1304 RootedValueVector avals(cx);
1305 RootedValueVector bvals(cx);
1306 if (na && !na->prepareForSwap(cx, b, &avals)) {
1307 oomUnsafe.crash("NativeObject::prepareForSwap");
1308 }
1309 if (nb && !nb->prepareForSwap(cx, a, &bvals)) {
1310 oomUnsafe.crash("NativeObject::prepareForSwap");
1311 }
1312
1313 // Do the same for proxy value arrays.
1314 if (pa && !pa->prepareForSwap(cx, &avals)) {
1315 oomUnsafe.crash("ProxyObject::prepareForSwap");
1316 }
1317 if (pb && !pb->prepareForSwap(cx, &bvals)) {
1318 oomUnsafe.crash("ProxyObject::prepareForSwap");
1319 }
1320
1321 // Swap the main fields of the objects, whether they are native objects or
1322 // proxies.
1323 char tmp[sizeof(JSObject_Slots0)];
1324 js_memcpy(&tmp, a, sizeof tmp);
1325 js_memcpy(a, b, sizeof tmp);
1326 js_memcpy(b, &tmp, sizeof tmp);
1327
1328 if (na &&
1329 !NativeObject::fixupAfterSwap(cx, b.as<NativeObject>(), kb, avals)) {
1330 oomUnsafe.crash("NativeObject::fixupAfterSwap");
1331 }
1332 if (nb &&
1333 !NativeObject::fixupAfterSwap(cx, a.as<NativeObject>(), ka, bvals)) {
1334 oomUnsafe.crash("NativeObject::fixupAfterSwap");
1335 }
1336
1337 if (pa && !b->as<ProxyObject>().fixupAfterSwap(cx, avals)) {
1338 oomUnsafe.crash("ProxyObject::fixupAfterSwap");
1339 }
1340 if (pb && !a->as<ProxyObject>().fixupAfterSwap(cx, bvals)) {
1341 oomUnsafe.crash("ProxyObject::fixupAfterSwap");
1342 }
1343 }
1344
1345 // Restore original unique IDs.
1346 if ((aid || bid) && (na || nb)) {
1347 if ((aid && !gc::SetOrUpdateUniqueId(cx, a, aid)) ||
1348 (bid && !gc::SetOrUpdateUniqueId(cx, b, bid))) {
1349 oomUnsafe.crash("Failed to set unique ID after swap");
1350 }
1351 }
1352 MOZ_ASSERT_IF(aid, gc::GetUniqueIdInfallible(a) == aid);
1353 MOZ_ASSERT_IF(bid, gc::GetUniqueIdInfallible(b) == bid);
1354
1355 // Preserve the IsUsedAsPrototype flag on the objects.
1356 if (aIsUsedAsPrototype) {
1357 if (!JSObject::setIsUsedAsPrototype(cx, a)) {
1358 oomUnsafe.crash("setIsUsedAsPrototype");
1359 }
1360 }
1361 if (bIsUsedAsPrototype) {
1362 if (!JSObject::setIsUsedAsPrototype(cx, b)) {
1363 oomUnsafe.crash("setIsUsedAsPrototype");
1364 }
1365 }
1366
1367 /*
1368 * We need a write barrier here. If |a| was marked and |b| was not, then
1369 * after the swap, |b|'s guts would never be marked. The write barrier
1370 * solves this.
1371 *
1372 * Normally write barriers happen before the write. However, that's not
1373 * necessary here because nothing is being destroyed. We're just swapping.
1374 */
1375 PreWriteBarrier(zone, a.get(), [](JSTracer* trc, JSObject* obj) {
1376 obj->traceChildren(trc);
1377 });
1378 PreWriteBarrier(zone, b.get(), [](JSTracer* trc, JSObject* obj) {
1379 obj->traceChildren(trc);
1380 });
1381
1382 NotifyGCPostSwap(a, b, r);
1383 }
1384
1385 static NativeObject* DefineConstructorAndPrototype(
1386 JSContext* cx, HandleObject obj, Handle<JSAtom*> atom,
1387 HandleObject protoProto, const JSClass* clasp, Native constructor,
1388 unsigned nargs, const JSPropertySpec* ps, const JSFunctionSpec* fs,
1389 const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs,
1390 NativeObject** ctorp) {
1391 // Create the prototype object.
1392 Rooted<NativeObject*> proto(
1393 cx, GlobalObject::createBlankPrototypeInheriting(cx, clasp, protoProto));
1394 if (!proto) {
1395 return nullptr;
1396 }
1397
1398 Rooted<NativeObject*> ctor(cx);
1399 if (!constructor) {
1400 ctor = proto;
1401 } else {
1402 ctor = NewNativeConstructor(cx, constructor, nargs, atom);
1403 if (!ctor) {
1404 return nullptr;
1405 }
1406
1407 if (!LinkConstructorAndPrototype(cx, ctor, proto)) {
1408 return nullptr;
1409 }
1410 }
1411
1412 if (!DefinePropertiesAndFunctions(cx, proto, ps, fs) ||
1413 (ctor != proto &&
1414 !DefinePropertiesAndFunctions(cx, ctor, static_ps, static_fs))) {
1415 return nullptr;
1416 }
1417
1418 if (clasp->specShouldDefineConstructor()) {
1419 RootedId id(cx, AtomToId(atom));
1420 RootedValue value(cx, ObjectValue(*ctor));
1421 if (!DefineDataProperty(cx, obj, id, value, 0)) {
1422 return nullptr;
1423 }
1424 }
1425
1426 if (ctorp) {
1427 *ctorp = ctor;
1428 }
1429 return proto;
1430 }
1431
1432 NativeObject* js::InitClass(JSContext* cx, HandleObject obj,
1433 const JSClass* protoClass, HandleObject protoProto_,
1434 const char* name, Native constructor,
1435 unsigned nargs, const JSPropertySpec* ps,
1436 const JSFunctionSpec* fs,
1437 const JSPropertySpec* static_ps,
1438 const JSFunctionSpec* static_fs,
1439 NativeObject** ctorp) {
1440 Rooted<JSAtom*> atom(cx, Atomize(cx, name, strlen(name)));
1441 if (!atom) {
1442 return nullptr;
1443 }
1444
1445 /*
1446 * All instances of the class will inherit properties from the prototype
1447 * object we are about to create (in DefineConstructorAndPrototype), which
1448 * in turn will inherit from protoProto.
1449 *
1450 * If protoProto is nullptr, default to Object.prototype.
1451 * If protoClass is nullptr, default to PlainObject.
1452 */
1453 RootedObject protoProto(cx, protoProto_);
1454 if (!protoProto) {
1455 protoProto = &cx->global()->getObjectPrototype();
1456 }
1457 if (!protoClass) {
1458 protoClass = &PlainObject::class_;
1459 }
1460
1461 return DefineConstructorAndPrototype(cx, obj, atom, protoProto, protoClass,
1462 constructor, nargs, ps, fs, static_ps,
1463 static_fs, ctorp);
1464 }
1465
1466 /**
1467 * Returns the original Object.prototype from the embedding-provided incumbent
1468 * global.
1469 *
1470 * Really, we want the incumbent global itself so we can pass it to other
1471 * embedding hooks which need it. Specifically, the enqueue promise hook
1472 * takes an incumbent global so it can set that on the PromiseCallbackJob
1473 * it creates.
1474 *
1475 * The reason for not just returning the global itself is that we'd need to
1476 * wrap it into the current compartment, and later unwrap it. Unwrapping
1477 * globals is tricky, though: we might accidentally unwrap through an inner
1478 * to its outer window and end up with the wrong global. Plain objects don't
1479 * have this problem, so we use the global's Object.prototype. The code using
1480 * it - e.g. EnqueuePromiseReactionJob - can then unwrap the object and get
1481 * its global without fear of unwrapping too far.
1482 */
1483 bool js::GetObjectFromHostDefinedData(JSContext* cx, MutableHandleObject obj) {
1484 if (!cx->runtime()->getHostDefinedData(cx, obj)) {
1485 return false;
1486 }
1487
1488 // The object might be from a different compartment, so wrap it.
1489 if (obj && !cx->compartment()->wrap(cx, obj)) {
1490 return false;
1491 }
1492
1493 return true;
1494 }
1495
1496 static bool IsStandardPrototype(JSObject* obj, JSProtoKey key) {
1497 return obj->nonCCWGlobal().maybeGetPrototype(key) == obj;
1498 }
1499
1500 JSProtoKey JS::IdentifyStandardInstance(JSObject* obj) {
1501 // Note: The prototype shares its JSClass with instances.
1502 MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
1503 JSProtoKey key = StandardProtoKeyOrNull(obj);
1504 if (key != JSProto_Null && !IsStandardPrototype(obj, key)) {
1505 return key;
1506 }
1507 return JSProto_Null;
1508 }
1509
1510 JSProtoKey JS::IdentifyStandardPrototype(JSObject* obj) {
1511 // Note: The prototype shares its JSClass with instances.
1512 MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
1513 JSProtoKey key = StandardProtoKeyOrNull(obj);
1514 if (key != JSProto_Null && IsStandardPrototype(obj, key)) {
1515 return key;
1516 }
1517 return JSProto_Null;
1518 }
1519
1520 JSProtoKey JS::IdentifyStandardInstanceOrPrototype(JSObject* obj) {
1521 return StandardProtoKeyOrNull(obj);
1522 }
1523
1524 JSProtoKey JS::IdentifyStandardConstructor(JSObject* obj) {
1525 // Note that isNativeConstructor does not imply that we are a standard
1526 // constructor, but the converse is true (at least until we start having
1527 // self-hosted constructors for standard classes). This lets us avoid a costly
1528 // loop for many functions (which, depending on the call site, may be the
1529 // common case).
1530 if (!obj->is<JSFunction>() ||
1531 !(obj->as<JSFunction>().flags().isNativeConstructor())) {
1532 return JSProto_Null;
1533 }
1534
1535 static_assert(JSProto_Null == 0,
1536 "Loop below can start at 1 to skip JSProto_Null");
1537
1538 GlobalObject& global = obj->as<JSFunction>().global();
1539 for (size_t k = 1; k < JSProto_LIMIT; ++k) {
1540 JSProtoKey key = static_cast<JSProtoKey>(k);
1541 if (global.maybeGetConstructor(key) == obj) {
1542 return key;
1543 }
1544 }
1545
1546 return JSProto_Null;
1547 }
1548
1549 bool js::LookupProperty(JSContext* cx, HandleObject obj, js::HandleId id,
1550 MutableHandleObject objp, PropertyResult* propp) {
1551 if (LookupPropertyOp op = obj->getOpsLookupProperty()) {
1552 return op(cx, obj, id, objp, propp);
1553 }
1554 return NativeLookupPropertyInline<CanGC>(cx, obj.as<NativeObject>(), id, objp,
1555 propp);
1556 }
1557
1558 bool js::LookupName(JSContext* cx, Handle<PropertyName*> name,
1559 HandleObject envChain, MutableHandleObject objp,
1560 MutableHandleObject pobjp, PropertyResult* propp) {
1561 RootedId id(cx, NameToId(name));
1562
1563 for (RootedObject env(cx, envChain); env; env = env->enclosingEnvironment()) {
1564 if (!LookupProperty(cx, env, id, pobjp, propp)) {
1565 return false;
1566 }
1567 if (propp->isFound()) {
1568 objp.set(env);
1569 return true;
1570 }
1571 }
1572
1573 objp.set(nullptr);
1574 pobjp.set(nullptr);
1575 propp->setNotFound();
1576 return true;
1577 }
1578
1579 bool js::LookupNameNoGC(JSContext* cx, PropertyName* name, JSObject* envChain,
1580 NativeObject** pobjp, PropertyResult* propp) {
1581 AutoAssertNoPendingException nogc(cx);
1582
1583 MOZ_ASSERT(!*pobjp && propp->isNotFound());
1584
1585 for (JSObject* env = envChain; env; env = env->enclosingEnvironment()) {
1586 if (env->getOpsLookupProperty()) {
1587 return false;
1588 }
1589 if (!NativeLookupPropertyInline<NoGC>(cx, &env->as<NativeObject>(),
1590 NameToId(name), pobjp, propp)) {
1591 return false;
1592 }
1593 if (propp->isFound()) {
1594 return true;
1595 }
1596 }
1597
1598 return true;
1599 }
1600
1601 static bool IsTemporalDeadZone(JSContext* cx, HandleObject env, HandleId id,
1602 const PropertyResult& prop, bool* isTDZ) {
1603 MOZ_ASSERT(prop.isFound());
1604
1605 // We do our own explicit checking for |this|
1606 if (id.isAtom(cx->names().dot_this_)) {
1607 *isTDZ = false;
1608 return true;
1609 }
1610
1611 // Treat Debugger environments specially for TDZ checks, as they
1612 // look like non-native environments but in fact wrap native
1613 // environments.
1614 if (env->is<DebugEnvironmentProxy>()) {
1615 RootedValue v(cx);
1616 auto envProxy = env.as<DebugEnvironmentProxy>();
1617 if (!DebugEnvironmentProxy::getMaybeSentinelValue(cx, envProxy, id, &v)) {
1618 return false;
1619 }
1620 *isTDZ = IsUninitializedLexical(v);
1621 return true;
1622 }
1623
1624 *isTDZ = IsUninitializedLexicalSlot(env, prop);
1625 return true;
1626 }
1627
1628 JSObject* js::LookupNameWithGlobalDefault(JSContext* cx,
1629 Handle<PropertyName*> name,
1630 HandleObject envChain) {
1631 RootedId id(cx, NameToId(name));
1632
1633 RootedObject pobj(cx);
1634 PropertyResult prop;
1635
1636 RootedObject env(cx, envChain);
1637 for (; !env->is<GlobalObject>(); env = env->enclosingEnvironment()) {
1638 if (!LookupProperty(cx, env, id, &pobj, &prop)) {
1639 return nullptr;
1640 }
1641 if (prop.isFound()) {
1642 break;
1643 }
1644 }
1645
1646 // Uninitialized lexicals can't appear on the prototype chain, so only check
1647 // for TDZ when |pobj == env|.
1648 //
1649 // JSOp::BindName is always directly followed by JSOp::GetBoundName, so don't
1650 // bother to create a RuntimeLexicalErrorObject.
1651 if (pobj == env) {
1652 MOZ_ASSERT(prop.isFound());
1653
1654 bool isTDZ;
1655 if (!IsTemporalDeadZone(cx, env, id, prop, &isTDZ)) {
1656 return nullptr;
1657 }
1658 if (isTDZ) {
1659 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, name);
1660 return nullptr;
1661 }
1662 }
1663
1664 return env;
1665 }
1666
1667 JSObject* js::LookupNameUnqualified(JSContext* cx, Handle<PropertyName*> name,
1668 HandleObject envChain) {
1669 RootedId id(cx, NameToId(name));
1670
1671 RootedObject pobj(cx);
1672 PropertyResult prop;
1673
1674 RootedObject env(cx, envChain);
1675 for (; !env->isUnqualifiedVarObj(); env = env->enclosingEnvironment()) {
1676 if (!LookupProperty(cx, env, id, &pobj, &prop)) {
1677 return nullptr;
1678 }
1679 if (prop.isFound()) {
1680 break;
1681 }
1682 }
1683
1684 // Uninitialized lexicals can't appear on the prototype chain, so only check
1685 // for TDZ and `const` bindings when |pobj == env|.
1686 //
1687 // See note above RuntimeLexicalErrorObject.
1688 if (pobj == env) {
1689 MOZ_ASSERT(prop.isFound());
1690
1691 bool isTDZ;
1692 if (!IsTemporalDeadZone(cx, env, id, prop, &isTDZ)) {
1693 return nullptr;
1694 }
1695 if (isTDZ) {
1696 return RuntimeLexicalErrorObject::create(cx, env,
1697 JSMSG_UNINITIALIZED_LEXICAL);
1698 }
1699
1700 if (env->is<LexicalEnvironmentObject>() &&
1701 !prop.propertyInfo().writable()) {
1702 // Assigning to a named lambda callee name is a no-op in sloppy mode.
1703 if (!(env->is<BlockLexicalEnvironmentObject>() &&
1704 env->as<BlockLexicalEnvironmentObject>().scope().kind() ==
1705 ScopeKind::NamedLambda)) {
1706 MOZ_ASSERT(name != cx->names().dot_this_);
1707 return RuntimeLexicalErrorObject::create(cx, env,
1708 JSMSG_BAD_CONST_ASSIGN);
1709 }
1710 }
1711 }
1712
1713 return env;
1714 }
1715
1716 bool js::HasOwnProperty(JSContext* cx, HandleObject obj, HandleId id,
1717 bool* result) {
1718 if (obj->is<ProxyObject>()) {
1719 return Proxy::hasOwn(cx, obj, id, result);
1720 }
1721
1722 if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
1723 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
1724 if (!op(cx, obj, id, &desc)) {
1725 return false;
1726 }
1727 *result = desc.isSome();
1728 return true;
1729 }
1730
1731 PropertyResult prop;
1732 if (!NativeLookupOwnProperty<CanGC>(cx, obj.as<NativeObject>(), id, &prop)) {
1733 return false;
1734 }
1735 *result = prop.isFound();
1736 return true;
1737 }
1738
1739 bool js::LookupPropertyPure(JSContext* cx, JSObject* obj, jsid id,
1740 NativeObject** objp, PropertyResult* propp) {
1741 if (obj->getOpsLookupProperty()) {
1742 return false;
1743 }
1744 return NativeLookupPropertyInline<NoGC, LookupResolveMode::CheckMayResolve>(
1745 cx, &obj->as<NativeObject>(), id, objp, propp);
1746 }
1747
1748 bool js::LookupOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id,
1749 PropertyResult* propp) {
1750 if (obj->getOpsLookupProperty()) {
1751 return false;
1752 }
1753 return NativeLookupOwnPropertyInline<NoGC,
1754 LookupResolveMode::CheckMayResolve>(
1755 cx, &obj->as<NativeObject>(), id, propp);
1756 }
1757
1758 static inline bool NativeGetPureInline(NativeObject* pobj, jsid id,
1759 PropertyResult prop, Value* vp,
1760 JSContext* cx) {
1761 if (prop.isDenseElement()) {
1762 *vp = pobj->getDenseElement(prop.denseElementIndex());
1763 return true;
1764 }
1765 if (prop.isTypedArrayElement()) {
1766 size_t idx = prop.typedArrayElementIndex();
1767 return pobj->as<TypedArrayObject>().getElement<NoGC>(cx, idx, vp);
1768 }
1769
1770 // Fail if we have a custom getter.
1771 PropertyInfo propInfo = prop.propertyInfo();
1772 if (!propInfo.isDataProperty()) {
1773 return false;
1774 }
1775
1776 *vp = pobj->getSlot(propInfo.slot());
1777 MOZ_ASSERT(!vp->isMagic());
1778 return true;
1779 }
1780
1781 bool js::GetPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp) {
1782 NativeObject* pobj;
1783 PropertyResult prop;
1784 if (!LookupPropertyPure(cx, obj, id, &pobj, &prop)) {
1785 return false;
1786 }
1787
1788 if (prop.isNotFound()) {
1789 vp->setUndefined();
1790 return true;
1791 }
1792
1793 return NativeGetPureInline(pobj, id, prop, vp, cx);
1794 }
1795
1796 bool js::GetOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp,
1797 bool* found) {
1798 PropertyResult prop;
1799 if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
1800 return false;
1801 }
1802
1803 if (prop.isNotFound()) {
1804 *found = false;
1805 vp->setUndefined();
1806 return true;
1807 }
1808
1809 *found = true;
1810 return obj->is<NativeObject>() &&
1811 NativeGetPureInline(&obj->as<NativeObject>(), id, prop, vp, cx);
1812 }
1813
1814 static inline bool NativeGetGetterPureInline(NativeObject* holder,
1815 PropertyResult prop,
1816 JSFunction** fp) {
1817 MOZ_ASSERT(prop.isNativeProperty());
1818
1819 PropertyInfo propInfo = prop.propertyInfo();
1820 if (holder->hasGetter(propInfo)) {
1821 JSObject* getter = holder->getGetter(propInfo);
1822 if (getter->is<JSFunction>()) {
1823 *fp = &getter->as<JSFunction>();
1824 return true;
1825 }
1826 }
1827
1828 *fp = nullptr;
1829 return true;
1830 }
1831
1832 bool js::GetGetterPure(JSContext* cx, JSObject* obj, jsid id, JSFunction** fp) {
1833 /* Just like GetPropertyPure, but get getter function, without invoking
1834 * it. */
1835 NativeObject* pobj;
1836 PropertyResult prop;
1837 if (!LookupPropertyPure(cx, obj, id, &pobj, &prop)) {
1838 return false;
1839 }
1840
1841 if (prop.isNotFound()) {
1842 *fp = nullptr;
1843 return true;
1844 }
1845
1846 return prop.isNativeProperty() && NativeGetGetterPureInline(pobj, prop, fp);
1847 }
1848
1849 bool js::GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
1850 bool* isOrdinary, MutableHandleObject protop) {
1851 if (obj->is<js::ProxyObject>()) {
1852 return js::Proxy::getPrototypeIfOrdinary(cx, obj, isOrdinary, protop);
1853 }
1854
1855 *isOrdinary = true;
1856 protop.set(obj->staticPrototype());
1857 return true;
1858 }
1859
1860 /*** ES6 standard internal methods ******************************************/
1861
1862 bool js::SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto,
1863 JS::ObjectOpResult& result) {
1864 // The proxy trap subsystem fully handles prototype-setting for proxies
1865 // with dynamic [[Prototype]]s.
1866 if (obj->hasDynamicPrototype()) {
1867 MOZ_ASSERT(obj->is<ProxyObject>());
1868 return Proxy::setPrototype(cx, obj, proto, result);
1869 }
1870
1871 /*
1872 * ES6 9.1.2 step 3-4 if |obj.[[Prototype]]| has SameValue as |proto| return
1873 * true. Since the values in question are objects, we can just compare
1874 * pointers.
1875 */
1876 if (proto == obj->staticPrototype()) {
1877 return result.succeed();
1878 }
1879
1880 /* Disallow mutation of immutable [[Prototype]]s. */
1881 if (obj->staticPrototypeIsImmutable()) {
1882 return result.fail(JSMSG_CANT_SET_PROTO);
1883 }
1884
1885 /*
1886 * Disallow mutating the [[Prototype]] on WebAssembly GC objects.
1887 */
1888 if (obj->is<WasmGcObject>()) {
1889 return result.fail(JSMSG_CANT_SET_PROTO);
1890 }
1891
1892 /* ES6 9.1.2 step 5 forbids changing [[Prototype]] if not [[Extensible]]. */
1893 bool extensible;
1894 if (!IsExtensible(cx, obj, &extensible)) {
1895 return false;
1896 }
1897 if (!extensible) {
1898 return result.fail(JSMSG_CANT_SET_PROTO);
1899 }
1900
1901 /*
1902 * ES6 9.1.2 step 6 forbids generating cyclical prototype chains. But we
1903 * have to do this comparison on the observable WindowProxy, not on the
1904 * possibly-Window object we're setting the proto on.
1905 */
1906 RootedObject objMaybeWindowProxy(cx, ToWindowProxyIfWindow(obj));
1907 RootedObject obj2(cx, proto);
1908 while (obj2) {
1909 MOZ_ASSERT(!IsWindow(obj2));
1910 if (obj2 == objMaybeWindowProxy) {
1911 return result.fail(JSMSG_CANT_SET_PROTO_CYCLE);
1912 }
1913
1914 bool isOrdinary;
1915 if (!GetPrototypeIfOrdinary(cx, obj2, &isOrdinary, &obj2)) {
1916 return false;
1917 }
1918 if (!isOrdinary) {
1919 break;
1920 }
1921 }
1922
1923 Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
1924 if (!JSObject::setProtoUnchecked(cx, obj, taggedProto)) {
1925 return false;
1926 }
1927
1928 return result.succeed();
1929 }
1930
1931 bool js::SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto) {
1932 ObjectOpResult result;
1933 return SetPrototype(cx, obj, proto, result) && result.checkStrict(cx, obj);
1934 }
1935
1936 /**
1937 * IsTypedArrayFixedLength ( O )
1938 *
1939 * ES2025 draft rev 3e6f71c9402f91344ef9560425cc1e8fc45abf86
1940 */
1941 static bool IsTypedArrayFixedLength(ResizableTypedArrayObject* obj) {
1942 MOZ_ASSERT(obj->hasResizableBuffer());
1943
1944 // Step 1.
1945 if (obj->isAutoLength()) {
1946 return false;
1947 }
1948
1949 // Steps 2-4.
1950 return obj->isSharedMemory();
1951 }
1952
1953 bool js::PreventExtensions(JSContext* cx, HandleObject obj,
1954 ObjectOpResult& result) {
1955 if (obj->is<ProxyObject>()) {
1956 return js::Proxy::preventExtensions(cx, obj, result);
1957 }
1958
1959 if (obj->is<WasmGcObject>()) {
1960 return result.failCantPreventExtensions();
1961 }
1962
1963 if (obj->is<ResizableTypedArrayObject>() &&
1964 !IsTypedArrayFixedLength(&obj->as<ResizableTypedArrayObject>())) {
1965 return result.failCantPreventExtensions();
1966 }
1967
1968 if (!obj->nonProxyIsExtensible()) {
1969 // If the following assertion fails, there's somewhere else a missing
1970 // call to shrinkCapacityToInitializedLength() which needs to be found
1971 // and fixed.
1972 MOZ_ASSERT_IF(obj->is<NativeObject>(),
1973 obj->as<NativeObject>().getDenseInitializedLength() ==
1974 obj->as<NativeObject>().getDenseCapacity());
1975
1976 return result.succeed();
1977 }
1978
1979 if (obj->is<NativeObject>()) {
1980 // Force lazy properties to be resolved.
1981 Handle<NativeObject*> nobj = obj.as<NativeObject>();
1982 if (!ResolveLazyProperties(cx, nobj)) {
1983 return false;
1984 }
1985
1986 // Prepare the elements. We have to do this before we mark the object
1987 // non-extensible; that's fine because these changes are not observable.
1988 ObjectElements::PrepareForPreventExtensions(cx, nobj);
1989 }
1990
1991 // Finally, set the NotExtensible flag on the Shape and ObjectElements.
1992 if (!JSObject::setFlag(cx, obj, ObjectFlag::NotExtensible)) {
1993 return false;
1994 }
1995 if (obj->is<NativeObject>()) {
1996 ObjectElements::PreventExtensions(&obj->as<NativeObject>());
1997 }
1998
1999 return result.succeed();
2000 }
2001
2002 bool js::PreventExtensions(JSContext* cx, HandleObject obj) {
2003 ObjectOpResult result;
2004 return PreventExtensions(cx, obj, result) && result.checkStrict(cx, obj);
2005 }
2006
2007 bool js::GetOwnPropertyDescriptor(
2008 JSContext* cx, HandleObject obj, HandleId id,
2009 MutableHandle<Maybe<PropertyDescriptor>> desc) {
2010 if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
2011 bool ok = op(cx, obj, id, desc);
2012 if (ok && desc.isSome()) {
2013 desc->assertComplete();
2014 }
2015 return ok;
2016 }
2017
2018 return NativeGetOwnPropertyDescriptor(cx, obj.as<NativeObject>(), id, desc);
2019 }
2020
2021 bool js::DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
2022 Handle<PropertyDescriptor> desc) {
2023 ObjectOpResult result;
2024 return DefineProperty(cx, obj, id, desc, result) &&
2025 result.checkStrict(cx, obj, id);
2026 }
2027
2028 bool js::DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
2029 Handle<PropertyDescriptor> desc,
2030 ObjectOpResult& result) {
2031 desc.assertValid();
2032 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2033 return op(cx, obj, id, desc, result);
2034 }
2035 return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
2036 }
2037
2038 bool js::DefineAccessorProperty(JSContext* cx, HandleObject obj, HandleId id,
2039 HandleObject getter, HandleObject setter,
2040 unsigned attrs, ObjectOpResult& result) {
2041 Rooted<PropertyDescriptor> desc(
2042 cx, PropertyDescriptor::Accessor(
2043 getter ? mozilla::Some(getter) : mozilla::Nothing(),
2044 setter ? mozilla::Some(setter) : mozilla::Nothing(), attrs));
2045
2046 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2047 return op(cx, obj, id, desc, result);
2048 }
2049 return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
2050 }
2051
2052 bool js::DefineDataProperty(JSContext* cx, HandleObject obj, HandleId id,
2053 HandleValue value, unsigned attrs,
2054 ObjectOpResult& result) {
2055 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Data(value, attrs));
2056 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2057 return op(cx, obj, id, desc, result);
2058 }
2059 return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
2060 }
2061
2062 bool js::DefineAccessorProperty(JSContext* cx, HandleObject obj, HandleId id,
2063 HandleObject getter, HandleObject setter,
2064 unsigned attrs) {
2065 ObjectOpResult result;
2066 if (!DefineAccessorProperty(cx, obj, id, getter, setter, attrs, result)) {
2067 return false;
2068 }
2069 if (!result) {
2070 result.reportError(cx, obj, id);
2071 return false;
2072 }
2073 return true;
2074 }
2075
2076 bool js::DefineDataProperty(JSContext* cx, HandleObject obj, HandleId id,
2077 HandleValue value, unsigned attrs) {
2078 ObjectOpResult result;
2079 if (!DefineDataProperty(cx, obj, id, value, attrs, result)) {
2080 return false;
2081 }
2082 if (!result) {
2083 result.reportError(cx, obj, id);
2084 return false;
2085 }
2086 return true;
2087 }
2088
2089 bool js::DefineDataProperty(JSContext* cx, HandleObject obj, PropertyName* name,
2090 HandleValue value, unsigned attrs) {
2091 RootedId id(cx, NameToId(name));
2092 return DefineDataProperty(cx, obj, id, value, attrs);
2093 }
2094
2095 bool js::DefineDataElement(JSContext* cx, HandleObject obj, uint32_t index,
2096 HandleValue value, unsigned attrs) {
2097 RootedId id(cx);
2098 if (!IndexToId(cx, index, &id)) {
2099 return false;
2100 }
2101 return DefineDataProperty(cx, obj, id, value, attrs);
2102 }
2103
2104 /*** SpiderMonkey nonstandard internal methods ******************************/
2105
2106 // Mark an object as having an immutable prototype
2107 //
2108 // NOTE: This does not correspond to the SetImmutablePrototype ECMAScript
2109 // method.
2110 bool js::SetImmutablePrototype(JSContext* cx, HandleObject obj,
2111 bool* succeeded) {
2112 if (obj->hasDynamicPrototype()) {
2113 return Proxy::setImmutablePrototype(cx, obj, succeeded);
2114 }
2115
2116 if (!JSObject::setFlag(cx, obj, ObjectFlag::ImmutablePrototype)) {
2117 return false;
2118 }
2119 *succeeded = true;
2120 return true;
2121 }
2122
2123 bool js::GetPropertyDescriptor(
2124 JSContext* cx, HandleObject obj, HandleId id,
2125 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc,
2126 MutableHandleObject holder) {
2127 RootedObject pobj(cx);
2128 for (pobj = obj; pobj;) {
2129 if (!GetOwnPropertyDescriptor(cx, pobj, id, desc)) {
2130 return false;
2131 }
2132
2133 if (desc.isSome()) {
2134 holder.set(pobj);
2135 return true;
2136 }
2137
2138 if (!GetPrototype(cx, pobj, &pobj)) {
2139 return false;
2140 }
2141 }
2142
2143 MOZ_ASSERT(desc.isNothing());
2144 holder.set(nullptr);
2145 return true;
2146 }
2147
2148 /* * */
2149
2150 extern bool PropertySpecNameToId(JSContext* cx, JSPropertySpec::Name name,
2151 MutableHandleId id);
2152
2153 // If a property or method is part of an experimental feature that can be
2154 // disabled at run-time by a preference, we keep it in the JSFunctionSpec /
2155 // JSPropertySpec list, but omit the definition if the preference is off.
2156 JS_PUBLIC_API bool js::ShouldIgnorePropertyDefinition(JSContext* cx,
2157 JSProtoKey key, jsid id) {
2158 if (!cx->realm()->creationOptions().getToSourceEnabled() &&
2159 (id == NameToId(cx->names().toSource) ||
2160 id == NameToId(cx->names().uneval))) {
2161 return true;
2162 }
2163
2164 if (key == JSProto_FinalizationRegistry &&
2165 !JS::Prefs::experimental_weakrefs_expose_cleanupSome() &&
2166 id == NameToId(cx->names().cleanupSome)) {
2167 return true;
2168 }
2169
2170 // It's gently surprising that this is JSProto_Function, but the trick
2171 // to realize is that this is a -constructor function-, not a function
2172 // on the prototype; and the proto of the constructor is JSProto_Function.
2173 if (key == JSProto_Function) {
2174 if (!JS::Prefs::experimental_uint8array_base64() &&
2175 (id == NameToId(cx->names().fromBase64) ||
2176 id == NameToId(cx->names().fromHex))) {
2177 return true;
2178 }
2179 }
2180
2181 if (key == JSProto_Uint8Array &&
2182 !JS::Prefs::experimental_uint8array_base64() &&
2183 (id == NameToId(cx->names().setFromBase64) ||
2184 id == NameToId(cx->names().setFromHex) ||
2185 id == NameToId(cx->names().toBase64) ||
2186 id == NameToId(cx->names().toHex))) {
2187 return true;
2188 }
2189
2190 // It's gently surprising that this is JSProto_Function, but the trick
2191 // to realize is that this is a -constructor function-, not a function
2192 // on the prototype; and the proto of the constructor is JSProto_Function.
2193 if (key == JSProto_Function) {
2194 if (!JS::Prefs::experimental_uint8array_base64() &&
2195 (id == NameToId(cx->names().fromBase64) ||
2196 id == NameToId(cx->names().fromHex))) {
2197 return true;
2198 }
2199 if (!JS::Prefs::experimental_promise_try() &&
2200 id == NameToId(cx->names().try_)) {
2201 return true;
2202 }
2203 if (!JS::Prefs::experimental_error_iserror() &&
2204 id == NameToId(cx->names().isError)) {
2205 return true;
2206 }
2207 }
2208
2209 #ifdef JS_HAS_INTL_API
2210 if (key == JSProto_Date && !JS::Prefs::experimental_temporal() &&
2211 id == NameToId(cx->names().toTemporalInstant)) {
2212 return true;
2213 }
2214 #endif
2215
2216 #ifdef NIGHTLY_BUILD
2217 // It's gently surprising that this is JSProto_Function, but the trick
2218 // to realize is that this is a -constructor function-, not a function
2219 // on the prototype; and the proto of the constructor is JSProto_Function.
2220 if (key == JSProto_Function) {
2221 if (!JS::Prefs::experimental_iterator_range() &&
2222 (id == NameToId(cx->names().range))) {
2223 return true;
2224 }
2225 if (!JS::Prefs::experimental_joint_iteration() &&
2226 (id == NameToId(cx->names().zip) ||
2227 id == NameToId(cx->names().zipKeyed))) {
2228 return true;
2229 }
2230 if (!JS::Prefs::experimental_iterator_sequencing() &&
2231 id == NameToId(cx->names().concat)) {
2232 return true;
2233 }
2234 }
2235 if (key == JSProto_Map || key == JSProto_WeakMap) {
2236 if (!JS::Prefs::experimental_upsert() &&
2237 (id == NameToId(cx->names().getOrInsert) ||
2238 id == NameToId(cx->names().getOrInsertComputed))) {
2239 return true;
2240 }
2241 }
2242 #endif
2243
2244 if (key == JSProto_Function &&
2245 !JS::Prefs::experimental_error_capture_stack_trace() &&
2246 id == NameToId(cx->names().captureStackTrace)) {
2247 return true;
2248 }
2249
2250 if (key == JSProto_JSON &&
2251 !JS::Prefs::experimental_json_parse_with_source() &&
2252 (id == NameToId(cx->names().isRawJSON) ||
2253 id == NameToId(cx->names().rawJSON))) {
2254 return true;
2255 }
2256
2257 if (key == JSProto_Math && !JS::Prefs::experimental_math_sumprecise() &&
2258 id == NameToId(cx->names().sumPrecise)) {
2259 return true;
2260 }
2261
2262 if (key == JSProto_Atomics && !JS::Prefs::experimental_atomics_pause() &&
2263 id == NameToId(cx->names().pause)) {
2264 return true;
2265 }
2266 if (key == JSProto_Atomics && !JS::Prefs::atomics_wait_async() &&
2267 id == NameToId(cx->names().waitAsync)) {
2268 return true;
2269 }
2270
2271 return false;
2272 }
2273
2274 static bool DefineFunctionFromSpec(JSContext* cx, HandleObject obj,
2275 const JSFunctionSpec* fs) {
2276 RootedId id(cx);
2277 if (!PropertySpecNameToId(cx, fs->name, &id)) {
2278 return false;
2279 }
2280
2281 if (ShouldIgnorePropertyDefinition(cx, StandardProtoKeyOrNull(obj), id)) {
2282 return true;
2283 }
2284
2285 JSFunction* fun = NewFunctionFromSpec(cx, fs, id);
2286 if (!fun) {
2287 return false;
2288 }
2289
2290 RootedValue funVal(cx, ObjectValue(*fun));
2291 return DefineDataProperty(cx, obj, id, funVal, fs->flags & ~JSFUN_FLAGS_MASK);
2292 }
2293
2294 bool js::DefineFunctions(JSContext* cx, HandleObject obj,
2295 const JSFunctionSpec* fs) {
2296 for (; fs->name; fs++) {
2297 if (!DefineFunctionFromSpec(cx, obj, fs)) {
2298 return false;
2299 }
2300 }
2301 return true;
2302 }
2303
2304 /*** ToPrimitive ************************************************************/
2305
2306 /*
2307 * Gets |obj[id]|. If that value's not callable, returns true and stores an
2308 * object value in *vp. If it's callable, calls it with no arguments and |obj|
2309 * as |this|, returning the result in *vp.
2310 *
2311 * This is a mini-abstraction for ES6 draft rev 36 (2015 Mar 17),
2312 * 7.1.1, second algorithm (OrdinaryToPrimitive), steps 5.a-c.
2313 */
2314 static bool MaybeCallMethod(JSContext* cx, HandleObject obj, HandleId id,
2315 MutableHandleValue vp) {
2316 if (!GetProperty(cx, obj, obj, id, vp)) {
2317 return false;
2318 }
2319 if (!IsCallable(vp)) {
2320 vp.setObject(*obj);
2321 return true;
2322 }
2323
2324 return js::Call(cx, vp, obj, vp);
2325 }
2326
2327 static bool ReportCantConvert(JSContext* cx, unsigned errorNumber,
2328 HandleObject obj, JSType hint) {
2329 const JSClass* clasp = obj->getClass();
2330
2331 // Avoid recursive death when decompiling in ReportValueError.
2332 RootedString str(cx);
2333 if (hint == JSTYPE_STRING) {
2334 str = JS_AtomizeString(cx, clasp->name);
2335 if (!str) {
2336 return false;
2337 }
2338 } else {
2339 str = nullptr;
2340 }
2341
2342 RootedValue val(cx, ObjectValue(*obj));
2343 ReportValueError(cx, errorNumber, JSDVG_SEARCH_STACK, val, str,
2344 hint == JSTYPE_UNDEFINED ? "primitive type"
2345 : hint == JSTYPE_STRING ? "string"
2346 : "number");
2347 return false;
2348 }
2349
2350 bool JS::OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
2351 MutableHandleValue vp) {
2352 MOZ_ASSERT(hint == JSTYPE_NUMBER || hint == JSTYPE_STRING ||
2353 hint == JSTYPE_UNDEFINED);
2354
2355 Rooted<jsid> id(cx);
2356
2357 const JSClass* clasp = obj->getClass();
2358 if (hint == JSTYPE_STRING) {
2359 id = NameToId(cx->names().toString);
2360
2361 bool calledToString = false;
2362 if (clasp == &StringObject::class_) {
2363 // Optimize (new String(...)).toString().
2364 StringObject* nobj = &obj->as<StringObject>();
2365 if (HasNativeMethodPure(nobj, cx->names().toString, str_toString, cx)) {
2366 vp.setString(nobj->unbox());
2367 return true;
2368 }
2369 } else if (clasp == &PlainObject::class_) {
2370 JSFunction* fun;
2371 if (GetPropertyPure(cx, obj, id, vp.address()) &&
2372 IsFunctionObject(vp, &fun)) {
2373 // Common case: we have a toString function. Try to short-circuit if
2374 // it's Object.prototype.toString and there's no @@toStringTag.
2375 if (fun->maybeNative() == obj_toString &&
2376 !MaybeHasInterestingSymbolProperty(
2377 cx, obj, cx->wellKnownSymbols().toStringTag)) {
2378 vp.setString(cx->names().object_Object_);
2379 return true;
2380 }
2381 if (!js::Call(cx, vp, obj, vp)) {
2382 return false;
2383 }
2384 calledToString = true;
2385 }
2386 }
2387
2388 if (!calledToString) {
2389 if (!MaybeCallMethod(cx, obj, id, vp)) {
2390 return false;
2391 }
2392 }
2393 if (vp.isPrimitive()) {
2394 return true;
2395 }
2396
2397 id = NameToId(cx->names().valueOf);
2398 if (!MaybeCallMethod(cx, obj, id, vp)) {
2399 return false;
2400 }
2401 if (vp.isPrimitive()) {
2402 return true;
2403 }
2404 } else {
2405 id = NameToId(cx->names().valueOf);
2406
2407 if (clasp == &StringObject::class_) {
2408 // Optimize new String(...).valueOf().
2409 StringObject* nobj = &obj->as<StringObject>();
2410 if (HasNativeMethodPure(nobj, cx->names().valueOf, str_toString, cx)) {
2411 vp.setString(nobj->unbox());
2412 return true;
2413 }
2414 } else if (clasp == &NumberObject::class_) {
2415 // Optimize new Number(...).valueOf().
2416 NumberObject* nobj = &obj->as<NumberObject>();
2417 if (HasNativeMethodPure(nobj, cx->names().valueOf, num_valueOf, cx)) {
2418 vp.setNumber(nobj->unbox());
2419 return true;
2420 }
2421 } else if (clasp == &DateObject::class_) {
2422 DateObject* dateObj = &obj->as<DateObject>();
2423 if (HasNativeMethodPure(dateObj, cx->names().valueOf, date_valueOf, cx)) {
2424 vp.set(dateObj->UTCTime());
2425 return true;
2426 }
2427 }
2428
2429 if (!MaybeCallMethod(cx, obj, id, vp)) {
2430 return false;
2431 }
2432 if (vp.isPrimitive()) {
2433 return true;
2434 }
2435
2436 id = NameToId(cx->names().toString);
2437 if (!MaybeCallMethod(cx, obj, id, vp)) {
2438 return false;
2439 }
2440 if (vp.isPrimitive()) {
2441 return true;
2442 }
2443 }
2444
2445 return ReportCantConvert(cx, JSMSG_CANT_CONVERT_TO, obj, hint);
2446 }
2447
2448 bool js::ToPrimitiveSlow(JSContext* cx, JSType preferredType,
2449 MutableHandleValue vp) {
2450 // Step numbers refer to the first algorithm listed in ES6 draft rev 36
2451 // (2015 Mar 17) 7.1.1 ToPrimitive.
2452 MOZ_ASSERT(preferredType == JSTYPE_UNDEFINED ||
2453 preferredType == JSTYPE_STRING || preferredType == JSTYPE_NUMBER);
2454 RootedObject obj(cx, &vp.toObject());
2455
2456 // Steps 4-5.
2457 RootedValue method(cx);
2458 if (!GetInterestingSymbolProperty(cx, obj, cx->wellKnownSymbols().toPrimitive,
2459 &method)) {
2460 return false;
2461 }
2462
2463 // Step 6.
2464 if (!method.isNullOrUndefined()) {
2465 // Step 6 of GetMethod. js::Call() below would do this check and throw a
2466 // TypeError anyway, but this produces a better error message.
2467 if (!IsCallable(method)) {
2468 return ReportCantConvert(cx, JSMSG_TOPRIMITIVE_NOT_CALLABLE, obj,
2469 preferredType);
2470 }
2471
2472 // Steps 1-3, 6.a-b.
2473 RootedValue arg0(
2474 cx,
2475 StringValue(preferredType == JSTYPE_STRING ? cx->names().string
2476 : preferredType == JSTYPE_NUMBER ? cx->names().number
2477 : cx->names().default_));
2478
2479 if (!js::Call(cx, method, vp, arg0, vp)) {
2480 return false;
2481 }
2482
2483 // Steps 6.c-d.
2484 if (vp.isObject()) {
2485 return ReportCantConvert(cx, JSMSG_TOPRIMITIVE_RETURNED_OBJECT, obj,
2486 preferredType);
2487 }
2488 return true;
2489 }
2490
2491 return OrdinaryToPrimitive(cx, obj, preferredType, vp);
2492 }
2493
2494 /* ES6 draft rev 28 (2014 Oct 14) 7.1.14 */
2495 bool js::ToPropertyKeySlow(JSContext* cx, HandleValue argument,
2496 MutableHandleId result) {
2497 MOZ_ASSERT(argument.isObject());
2498
2499 // Steps 1-2.
2500 RootedValue key(cx, argument);
2501 if (!ToPrimitiveSlow(cx, JSTYPE_STRING, &key)) {
2502 return false;
2503 }
2504
2505 // Steps 3-4.
2506 return PrimitiveValueToId<CanGC>(cx, key, result);
2507 }
2508
2509 /* * */
2510
2511 bool js::IsPrototypeOf(JSContext* cx, HandleObject protoObj, JSObject* obj,
2512 bool* result) {
2513 RootedObject obj2(cx, obj);
2514 for (;;) {
2515 // The [[Prototype]] chain might be cyclic.
2516 if (!CheckForInterrupt(cx)) {
2517 return false;
2518 }
2519 if (!GetPrototype(cx, obj2, &obj2)) {
2520 return false;
2521 }
2522 if (!obj2) {
2523 *result = false;
2524 return true;
2525 }
2526 if (obj2 == protoObj) {
2527 *result = true;
2528 return true;
2529 }
2530 }
2531 }
2532
2533 JSObject* js::PrimitiveToObject(JSContext* cx, const Value& v) {
2534 MOZ_ASSERT(v.isPrimitive());
2535
2536 switch (v.type()) {
2537 case ValueType::String: {
2538 Rooted<JSString*> str(cx, v.toString());
2539 return StringObject::create(cx, str);
2540 }
2541 case ValueType::Double:
2542 case ValueType::Int32:
2543 return NumberObject::create(cx, v.toNumber());
2544 case ValueType::Boolean:
2545 return BooleanObject::create(cx, v.toBoolean());
2546 case ValueType::Symbol: {
2547 RootedSymbol symbol(cx, v.toSymbol());
2548 return SymbolObject::create(cx, symbol);
2549 }
2550 case ValueType::BigInt: {
2551 RootedBigInt bigInt(cx, v.toBigInt());
2552 return BigIntObject::create(cx, bigInt);
2553 }
2554 case ValueType::Undefined:
2555 case ValueType::Null:
2556 case ValueType::Magic:
2557 case ValueType::PrivateGCThing:
2558 case ValueType::Object:
2559 break;
2560 }
2561
2562 MOZ_CRASH("unexpected type");
2563 }
2564
2565 // Like PrimitiveToObject, but returns the JSProtoKey of the prototype that
2566 // would be used without actually creating the object.
2567 JSProtoKey js::PrimitiveToProtoKey(JSContext* cx, const Value& v) {
2568 MOZ_ASSERT(v.isPrimitive());
2569
2570 switch (v.type()) {
2571 case ValueType::String:
2572 return JSProto_String;
2573 case ValueType::Double:
2574 case ValueType::Int32:
2575 return JSProto_Number;
2576 case ValueType::Boolean:
2577 return JSProto_Boolean;
2578 case ValueType::Symbol:
2579 return JSProto_Symbol;
2580 case ValueType::BigInt:
2581 return JSProto_BigInt;
2582 case ValueType::Undefined:
2583 case ValueType::Null:
2584 case ValueType::Magic:
2585 case ValueType::PrivateGCThing:
2586 case ValueType::Object:
2587 break;
2588 }
2589
2590 MOZ_CRASH("unexpected type");
2591 }
2592
2593 /*
2594 * Invokes the ES5 ToObject algorithm on vp, returning the result. If vp might
2595 * already be an object, use ToObject. reportScanStack controls how null and
2596 * undefined errors are reported.
2597 *
2598 * Callers must handle the already-object case.
2599 */
2600 JSObject* js::ToObjectSlow(JSContext* cx, JS::HandleValue val,
2601 bool reportScanStack) {
2602 MOZ_ASSERT(!val.isMagic());
2603 MOZ_ASSERT(!val.isObject());
2604
2605 if (val.isNullOrUndefined()) {
2606 ReportIsNullOrUndefinedForPropertyAccess(
2607 cx, val, reportScanStack ? JSDVG_SEARCH_STACK : JSDVG_IGNORE_STACK);
2608 return nullptr;
2609 }
2610
2611 return PrimitiveToObject(cx, val);
2612 }
2613
2614 JSObject* js::ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
2615 int valIndex, HandleId key) {
2616 MOZ_ASSERT(!val.isMagic());
2617 MOZ_ASSERT(!val.isObject());
2618
2619 if (val.isNullOrUndefined()) {
2620 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex, key);
2621 return nullptr;
2622 }
2623
2624 return PrimitiveToObject(cx, val);
2625 }
2626
2627 JSObject* js::ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
2628 int valIndex,
2629 Handle<PropertyName*> key) {
2630 MOZ_ASSERT(!val.isMagic());
2631 MOZ_ASSERT(!val.isObject());
2632
2633 if (val.isNullOrUndefined()) {
2634 RootedId keyId(cx, NameToId(key));
2635 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex, keyId);
2636 return nullptr;
2637 }
2638
2639 return PrimitiveToObject(cx, val);
2640 }
2641
2642 JSObject* js::ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
2643 int valIndex,
2644 HandleValue keyValue) {
2645 MOZ_ASSERT(!val.isMagic());
2646 MOZ_ASSERT(!val.isObject());
2647
2648 if (val.isNullOrUndefined()) {
2649 RootedId key(cx);
2650 if (keyValue.isPrimitive()) {
2651 if (!PrimitiveValueToId<CanGC>(cx, keyValue, &key)) {
2652 return nullptr;
2653 }
2654 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex, key);
2655 } else {
2656 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex);
2657 }
2658 return nullptr;
2659 }
2660
2661 return PrimitiveToObject(cx, val);
2662 }
2663
2664 enum class SlotsKind { Fixed, Dynamic };
2665
2666 class GetObjectSlotNameFunctor : public JS::TracingContext::Functor {
2667 NativeObject* obj;
2668 SlotsKind kind;
2669
2670 public:
2671 explicit GetObjectSlotNameFunctor(NativeObject* obj, SlotsKind kind)
2672 : obj(obj), kind(kind) {}
2673 virtual void operator()(JS::TracingContext* trc, const char* name, char* buf,
2674 size_t bufsize) override;
2675 };
2676
2677 void GetObjectSlotNameFunctor::operator()(JS::TracingContext* tcx,
2678 const char* name, char* buf,
2679 size_t bufsize) {
2680 MOZ_ASSERT(tcx->index() != JS::TracingContext::InvalidIndex);
2681
2682 uint32_t slot = uint32_t(tcx->index());
2683 if (kind == SlotsKind::Dynamic) {
2684 slot += obj->numFixedSlots();
2685 }
2686
2687 Maybe<PropertyKey> key;
2688 NativeShape* shape = obj->as<NativeObject>().shape();
2689 for (ShapePropertyIter<NoGC> iter(shape); !iter.done(); iter++) {
2690 if (iter->hasSlot() && iter->slot() == slot) {
2691 key.emplace(iter->key());
2692 break;
2693 }
2694 }
2695
2696 if (key.isNothing()) {
2697 do {
2698 const char* slotname = nullptr;
2699 const char* pattern = nullptr;
2700 if (obj->is<GlobalObject>()) {
2701 pattern = "CLASS_OBJECT(%s)";
2702 if (false) {
2703 ;
2704 }
2705 #define TEST_SLOT_MATCHES_PROTOTYPE(name, clasp) \
2706 else if ((JSProto_##name) == slot) { \
2707 slotname = #name; \
2708 }
2709 JS_FOR_EACH_PROTOTYPE(TEST_SLOT_MATCHES_PROTOTYPE)
2710 #undef TEST_SLOT_MATCHES_PROTOTYPE
2711 } else {
2712 pattern = "%s";
2713 if (obj->is<EnvironmentObject>()) {
2714 if (slot == EnvironmentObject::enclosingEnvironmentSlot()) {
2715 slotname = "enclosing_environment";
2716 } else if (obj->is<CallObject>()) {
2717 if (slot == CallObject::calleeSlot()) {
2718 slotname = "callee_slot";
2719 }
2720 } else if (obj->is<WithEnvironmentObject>()) {
2721 if (slot == WithEnvironmentObject::objectSlot()) {
2722 slotname = "with_object";
2723 } else if (slot == WithEnvironmentObject::thisSlot()) {
2724 slotname = "with_this";
2725 }
2726 }
2727 }
2728 }
2729
2730 if (slotname) {
2731 snprintf(buf, bufsize, pattern, slotname);
2732 } else {
2733 snprintf(buf, bufsize, "**UNKNOWN SLOT %" PRIu32 "**", slot);
2734 }
2735 } while (false);
2736 } else {
2737 if (key->isInt()) {
2738 snprintf(buf, bufsize, "%" PRId32, key->toInt());
2739 } else if (key->isAtom()) {
2740 PutEscapedString(buf, bufsize, key->toAtom(), 0);
2741 } else if (key->isSymbol()) {
2742 snprintf(buf, bufsize, "**SYMBOL KEY**");
2743 } else {
2744 MOZ_CRASH("Unexpected key kind");
2745 }
2746 }
2747 }
2748
2749 /*** Debugging routines *****************************************************/
2750
2751 #if defined(DEBUG) || defined(JS_JITSPEW)
2752
2753 /*
2754 * Routines to print out values during debugging. These are JS_PUBLIC_API to
2755 * help the debugger find them and to support temporarily hacking js::Dump*
2756 * calls into other code.
2757 */
2758
2759 namespace js {
2760
2761 // We don't want jsfriendapi.h to depend on GenericPrinter,
2762 // so these functions are declared directly in the cpp.
2763
2764 JS_PUBLIC_API void DumpValue(const JS::Value& val, js::GenericPrinter& out);
2765
2766 JS_PUBLIC_API void DumpId(jsid id, js::GenericPrinter& out);
2767
2768 JS_PUBLIC_API void DumpInterpreterFrame(JSContext* cx, js::GenericPrinter& out,
2769 InterpreterFrame* start = nullptr);
2770
2771 } // namespace js
2772
2773 JS_PUBLIC_API void js::DumpValue(const Value& val, js::GenericPrinter& out) {
2774 val.dump(out);
2775 }
2776
2777 JS_PUBLIC_API void js::DumpId(jsid id, js::GenericPrinter& out) {
2778 out.printf("jsid %p = ", (void*)id.asRawBits());
2779 id.dump(out);
2780 }
2781
2782 bool JSObject::hasSameRealmAs(JSContext* cx) const {
2783 return nonCCWRealm() == cx->realm();
2784 }
2785
2786 bool JSObject::uninlinedIsProxyObject() const { return is<ProxyObject>(); }
2787
2788 bool JSObject::uninlinedNonProxyIsExtensible() const {
2789 return nonProxyIsExtensible();
2790 }
2791
2792 void JSObject::dump() const {
2793 js::Fprinter out(stderr);
2794 dump(out);
2795 }
2796
2797 void JSObject::dump(js::GenericPrinter& out) const {
2798 js::JSONPrinter json(out);
2799 dump(json);
2800 out.put("\n");
2801 }
2802
2803 void JSObject::dump(js::JSONPrinter& json) const {
2804 json.beginObject();
2805 dumpFields(json);
2806 json.endObject();
2807 }
2808
2809 # define FOR_EACH_CLASS(M) \
2810 M(ArrayBufferViewObject) \
2811 M(ArrayBufferObject) \
2812 M(JSFunction) \
2813 M(PromiseObject) \
2814 M(RegExpObject)
2815
2816 static void DumpOwnFields(const JSObject* obj, js::JSONPrinter& json) {
2817 # define CALL(CLASS) \
2818 if (obj->is<CLASS>()) { \
2819 obj->as<CLASS>().dumpOwnFields(json); \
2820 return; \
2821 }
2822 FOR_EACH_CLASS(CALL)
2823 # undef CALL
2824 }
2825
2826 static void DumpOwnStringContent(const JSObject* obj, js::GenericPrinter& out) {
2827 # define CALL(CLASS) \
2828 if (obj->is<CLASS>()) { \
2829 out.put(" "); \
2830 obj->as<CLASS>().dumpOwnStringContent(out); \
2831 return; \
2832 }
2833 FOR_EACH_CLASS(CALL)
2834 # undef CALL
2835 }
2836
2837 # undef FOR_EACH_CLASS
2838
2839 void JSObject::dumpFields(js::JSONPrinter& json) const {
2840 json.formatProperty("address", "(JSObject*)0x%p", this);
2841
2842 if (IsCrossCompartmentWrapper(this)) {
2843 json.formatProperty("compartment", "(JS::Compartment*)0x%p", compartment());
2844 } else {
2845 JSObject* globalObj = &nonCCWGlobal();
2846 js::GenericPrinter& out = json.beginStringProperty("nonCCWGlobal");
2847 globalObj->dumpStringContent(out);
2848 json.endStringProperty();
2849 }
2850
2851 const JSClass* clasp = getClass();
2852 json.formatProperty("clasp", "<%s @ (JSClass*)0x%p>", clasp->name, clasp);
2853
2854 js::GenericPrinter& out = json.beginStringProperty("shape");
2855 shape()->dumpStringContent(out);
2856 json.endStringProperty();
2857
2858 json.beginObjectProperty("shape.base");
2859 shape()->base()->dumpFields(json);
2860 json.endObject();
2861
2862 if (IsProxy(this)) {
2863 const js::BaseProxyHandler* handler = GetProxyHandler(this);
2864 if (IsDeadProxyObject(this)) {
2865 json.formatProperty("handler", "(js::DeadObjectProxy*)0x%p", handler);
2866 } else if (IsCrossCompartmentWrapper(this)) {
2867 json.formatProperty("handler", "(js::CrossCompartmentWrapper*)0x%p",
2868 handler);
2869 } else {
2870 json.formatProperty("handler", "(js::BaseProxyHandler*)0x%p", handler);
2871 }
2872
2873 Value priv = GetProxyPrivate(this);
2874 if (!priv.isUndefined()) {
2875 js::GenericPrinter& out = json.beginStringProperty("private");
2876 priv.dumpStringContent(out);
2877 json.endStringProperty();
2878 }
2879
2880 Value expando = GetProxyExpando(this);
2881 if (!expando.isNull()) {
2882 js::GenericPrinter& out = json.beginStringProperty("expando");
2883 expando.dumpStringContent(out);
2884 json.endStringProperty();
2885 }
2886
2887 if (is<DebugEnvironmentProxy>()) {
2888 json.boolProperty("isQualifiedVarObj", isQualifiedVarObj());
2889 json.boolProperty("isUnqualifiedVarObj", isUnqualifiedVarObj());
2890 }
2891 }
2892
2893 DumpOwnFields(this, json);
2894
2895 if (is<NativeObject>()) {
2896 const auto* nobj = &as<NativeObject>();
2897
2898 js::GenericPrinter& out = json.beginStringProperty("elementsHeader");
2899 nobj->getElementsHeader()->dumpStringContent(out);
2900 json.endStringProperty();
2901
2902 uint32_t reserved = JSCLASS_RESERVED_SLOTS(clasp);
2903 if (reserved) {
2904 char name[256];
2905 json.beginObjectProperty("reservedSlots");
2906 for (uint32_t i = 0; i < reserved; i++) {
2907 SprintfLiteral(name, "%u", i);
2908 js::GenericPrinter& out = json.beginStringProperty(name);
2909 nobj->getSlot(i).dumpStringContent(out);
2910 json.endStringProperty();
2911 }
2912 json.endObject();
2913 }
2914
2915 json.beginObjectProperty("properties");
2916 if (PropMap* map = nobj->shape()->propMap()) {
2917 Vector<PropMap*, 8, SystemAllocPolicy> maps;
2918 while (true) {
2919 if (!maps.append(map)) {
2920 json.property("error", "*oom in JSObject::dumpFields*");
2921 break;
2922 }
2923 if (!map->hasPrevious()) {
2924 break;
2925 }
2926 map = map->asLinked()->previous();
2927 }
2928
2929 for (size_t i = maps.length(); i > 0; i--) {
2930 size_t index = i - 1;
2931 PropMap* map = maps[index];
2932 uint32_t len = (index == 0) ? shape()->asNative().propMapLength()
2933 : PropMap::Capacity;
2934 for (uint32_t j = 0; j < len; j++) {
2935 if (!map->hasKey(j)) {
2936 MOZ_ASSERT(map->isDictionary());
2937 continue;
2938 }
2939
2940 JS::UniqueChars propChars = map->getPropertyNameAt(j);
2941 if (!propChars) {
2942 json.property("error", "*oom in PropMap::getPropertyNameAt*");
2943 continue;
2944 }
2945
2946 js::GenericPrinter& out = json.beginStringProperty(propChars.get());
2947
2948 PropertyInfoWithKey prop = map->getPropertyInfoWithKey(j);
2949 if (prop.isDataProperty()) {
2950 nobj->getSlot(prop.slot()).dumpStringContent(out);
2951 out.put(" ");
2952 } else if (prop.isAccessorProperty()) {
2953 out.printf("getter=0x%p, setter=0x%p", nobj->getGetter(prop),
2954 nobj->getSetter(prop));
2955 out.put(" ");
2956 }
2957
2958 out.put("(");
2959 map->dumpDescriptorStringContentAt(out, j);
2960 out.put(")");
2961
2962 json.endStringProperty();
2963 }
2964 }
2965 }
2966 json.endObject();
2967
2968 uint32_t slots = nobj->getDenseInitializedLength();
2969 if (slots) {
2970 char name[64];
2971 json.beginObjectProperty("elements");
2972 for (uint32_t i = 0; i < slots; i++) {
2973 SprintfLiteral(name, "%u", i);
2974 js::GenericPrinter& out = json.beginStringProperty(name);
2975 nobj->getDenseElement(i).dumpStringContent(out);
2976 json.endStringProperty();
2977 }
2978 json.endObject();
2979 }
2980 }
2981 }
2982
2983 void JSObject::dumpStringContent(js::GenericPrinter& out) const {
2984 out.printf("<%s", getClass()->name);
2985
2986 DumpOwnStringContent(this, out);
2987
2988 out.printf(" @ (JSObject*)0x%p>", this);
2989 }
2990
2991 static void MaybeDumpScope(Scope* scope, js::GenericPrinter& out) {
2992 if (scope) {
2993 out.printf(" scope: %s\n", ScopeKindString(scope->kind()));
2994 for (BindingIter bi(scope); bi; bi++) {
2995 out.put(" ");
2996 StringValue(bi.name()).dump(out);
2997 }
2998 }
2999 }
3000
3001 static void MaybeDumpValue(const char* name, const Value& v,
3002 js::GenericPrinter& out) {
3003 if (!v.isNull()) {
3004 out.printf(" %s: ", name);
3005 v.dump(out);
3006 }
3007 }
3008
3009 JS_PUBLIC_API void js::DumpInterpreterFrame(JSContext* cx,
3010 js::GenericPrinter& out,
3011 InterpreterFrame* start) {
3012 /* This should only called during live debugging. */
3013 ScriptFrameIter i(cx);
3014 if (!start) {
3015 if (i.done()) {
3016 out.printf("no stack for cx = %p\n", (void*)cx);
3017 return;
3018 }
3019 } else {
3020 while (!i.done() && !i.isJSJit() && i.interpFrame() != start) {
3021 ++i;
3022 }
3023
3024 if (i.done()) {
3025 out.printf("fp = %p not found in cx = %p\n", (void*)start, (void*)cx);
3026 return;
3027 }
3028 }
3029
3030 for (; !i.done(); ++i) {
3031 if (i.isJSJit()) {
3032 out.put("JIT frame\n");
3033 } else {
3034 out.printf("InterpreterFrame at %p\n", (void*)i.interpFrame());
3035 }
3036
3037 if (i.isFunctionFrame()) {
3038 out.put("callee fun: ");
3039 RootedValue v(cx);
3040 JSObject* fun = i.callee(cx);
3041 v.setObject(*fun);
3042 v.get().dump(out);
3043 } else {
3044 out.put("global or eval frame, no callee\n");
3045 }
3046
3047 out.printf("file %s line %u\n", i.script()->filename(),
3048 i.script()->lineno());
3049
3050 if (jsbytecode* pc = i.pc()) {
3051 out.printf(" pc = %p\n", pc);
3052 out.printf(" current op: %s\n", CodeName(JSOp(*pc)));
3053 MaybeDumpScope(i.script()->lookupScope(pc), out);
3054 }
3055 if (i.isFunctionFrame()) {
3056 MaybeDumpValue("this", i.thisArgument(cx), out);
3057 }
3058 if (!i.isJSJit()) {
3059 out.put(" rval: ");
3060 i.interpFrame()->returnValue().get().dump(out);
3061 }
3062
3063 out.put(" flags:");
3064 if (i.isConstructing()) {
3065 out.put(" constructing");
3066 }
3067 if (!i.isJSJit() && i.interpFrame()->isDebuggerEvalFrame()) {
3068 out.put(" debugger eval");
3069 }
3070 if (i.isEvalFrame()) {
3071 out.put(" eval");
3072 }
3073 out.putChar('\n');
3074
3075 out.printf(" envChain: (JSObject*) %p\n", (void*)i.environmentChain(cx));
3076
3077 out.putChar('\n');
3078 }
3079 }
3080
3081 #endif /* defined(DEBUG) || defined(JS_JITSPEW) */
3082
3083 JS_PUBLIC_API void js::DumpBacktrace(JSContext* cx, FILE* fp) {
3084 Fprinter out(fp);
3085 js::DumpBacktrace(cx, out);
3086 }
3087
3088 JS_PUBLIC_API void js::DumpBacktrace(JSContext* cx, js::GenericPrinter& out) {
3089 size_t depth = 0;
3090 for (AllFramesIter i(cx); !i.done(); ++i, ++depth) {
3091 const char* filename;
3092 unsigned line;
3093 if (i.hasScript()) {
3094 filename = JS_GetScriptFilename(i.script());
3095 line = PCToLineNumber(i.script(), i.pc());
3096 } else {
3097 filename = i.filename();
3098 line = i.computeLine();
3099 }
3100 char frameType = i.isInterp() ? 'i'
3101 : i.isBaseline() ? 'b'
3102 : i.isIon() ? 'I'
3103 : i.isWasm() ? 'W'
3104 : '?';
3105
3106 out.printf("#%zu %14p %c %s:%u", depth, i.rawFramePtr(), frameType,
3107 filename, line);
3108
3109 if (i.hasScript()) {
3110 out.printf(" (%p @ %zu)\n", i.script(), i.script()->pcToOffset(i.pc()));
3111 } else {
3112 out.printf(" (%p)\n", i.pc());
3113 }
3114 }
3115 }
3116
3117 JS_PUBLIC_API void js::DumpBacktrace(JSContext* cx) {
3118 DumpBacktrace(cx, stdout);
3119 }
3120
3121 /* * */
3122
3123 bool JSObject::isBackgroundFinalized() const {
3124 if (isTenured()) {
3125 return js::gc::IsBackgroundFinalized(asTenured().getAllocKind());
3126 }
3127
3128 js::Nursery& nursery = runtimeFromMainThread()->gc.nursery();
3129 return js::gc::IsBackgroundFinalized(allocKindForTenure(nursery));
3130 }
3131
3132 js::gc::AllocKind JSObject::allocKind() const {
3133 if (isTenured()) {
3134 return asTenured().getAllocKind();
3135 }
3136
3137 Nursery& nursery = runtimeFromMainThread()->gc.nursery();
3138 return allocKindForTenure(nursery);
3139 }
3140
3141 js::gc::AllocKind JSObject::allocKindForTenure(
3142 const js::Nursery& nursery) const {
3143 using namespace js::gc;
3144
3145 MOZ_ASSERT(IsInsideNursery(this));
3146
3147 if (is<NativeObject>()) {
3148 if (canHaveFixedElements()) {
3149 const NativeObject& nobj = as<NativeObject>();
3150 MOZ_ASSERT(nobj.numFixedSlots() == 0);
3151
3152 /* Use minimal size object if we are just going to copy the pointer. */
3153 if (!nursery.isInside(nobj.getUnshiftedElementsHeader())) {
3154 return gc::AllocKind::OBJECT0;
3155 }
3156
3157 size_t nelements = nobj.getDenseCapacity();
3158 AllocKind kind = GetGCArrayKind(nelements);
3159 MOZ_ASSERT(GetObjectFinalizeKind(getClass()) == gc::FinalizeKind::None);
3160 MOZ_ASSERT(!IsFinalizedKind(kind));
3161 return kind;
3162 }
3163
3164 if (is<JSFunction>()) {
3165 return as<JSFunction>().getAllocKind();
3166 }
3167
3168 if (is<FixedLengthTypedArrayObject>()) {
3169 return as<FixedLengthTypedArrayObject>().allocKindForTenure();
3170 }
3171
3172 return as<NativeObject>().allocKindForTenure();
3173 }
3174
3175 // Handle all non-native objects.
3176
3177 // Proxies that are CrossCompartmentWrappers may be nursery allocated.
3178 if (is<ProxyObject>()) {
3179 return as<ProxyObject>().allocKindForTenure();
3180 }
3181
3182 // WasmStructObjects have a variable-length tail which contains the first
3183 // few data fields, so make sure we copy it all over to the new object.
3184 if (is<WasmStructObject>()) {
3185 // Figure out the size of this object, from the object's TypeDef.
3186 const wasm::TypeDef* typeDef = &as<WasmStructObject>().typeDef();
3187 AllocKind kind = WasmStructObject::allocKindForTypeDef(typeDef);
3188 return GetFinalizedAllocKindForClass(kind, getClass());
3189 }
3190
3191 // WasmArrayObjects sometimes have a variable-length tail which contains the
3192 // data for small arrays. Make sure we copy it all over to the new object.
3193 MOZ_ASSERT(is<WasmArrayObject>());
3194 gc::AllocKind allocKind = as<WasmArrayObject>().allocKind();
3195 return allocKind;
3196 }
3197
3198 void JSObject::addSizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf,
3199 JS::ClassInfo* info,
3200 JS::RuntimeSizes* runtimeSizes) {
3201 // TODO: These will eventually count as GC heap memory.
3202 if (is<NativeObject>() && as<NativeObject>().hasDynamicSlots()) {
3203 info->objectsMallocHeapSlots +=
3204 gc::GetAllocSize(zone(), as<NativeObject>().getSlotsHeader());
3205 }
3206
3207 if (is<NativeObject>() && as<NativeObject>().hasDynamicElements()) {
3208 void* allocatedElements = as<NativeObject>().getUnshiftedElementsHeader();
3209 info->objectsMallocHeapElementsNormal +=
3210 gc::GetAllocSize(zone(), allocatedElements);
3211 }
3212
3213 // Other things may be measured in the future if DMD indicates it is
3214 // worthwhile.
3215 if (is<JSFunction>() || is<PlainObject>() || is<ArrayObject>() ||
3216 is<CallObject>() || is<RegExpObject>() || is<ProxyObject>()) {
3217 // Do nothing. But this function is hot, and we win by getting the
3218 // common cases out of the way early. Some stats on the most common
3219 // classes, as measured during a vanilla browser session:
3220 // - (53.7%, 53.7%): Function
3221 // - (18.0%, 71.7%): Object
3222 // - (16.9%, 88.6%): Array
3223 // - ( 3.9%, 92.5%): Call
3224 // - ( 2.8%, 95.3%): RegExp
3225 // - ( 1.0%, 96.4%): Proxy
3226
3227 // Note that any JSClass that is special cased below likely needs to
3228 // specify the JSCLASS_DELAY_METADATA_BUILDER flag, or else we will
3229 // probably crash if the object metadata callback attempts to get the
3230 // size of the new object (which Debugger code does) before private
3231 // slots are initialized.
3232 } else if (is<ArgumentsObject>()) {
3233 info->objectsMallocHeapMisc +=
3234 as<ArgumentsObject>().sizeOfMisc(mallocSizeOf);
3235 } else if (is<MapObject>()) {
3236 info->objectsMallocHeapMisc += as<MapObject>().sizeOfData(mallocSizeOf);
3237 } else if (is<SetObject>()) {
3238 info->objectsMallocHeapMisc += as<SetObject>().sizeOfData(mallocSizeOf);
3239 } else if (is<PropertyIteratorObject>()) {
3240 info->objectsMallocHeapMisc +=
3241 as<PropertyIteratorObject>().sizeOfMisc(mallocSizeOf);
3242 } else if (is<ArrayBufferObject>()) {
3243 ArrayBufferObject::addSizeOfExcludingThis(this, mallocSizeOf, info,
3244 runtimeSizes);
3245 } else if (is<SharedArrayBufferObject>()) {
3246 SharedArrayBufferObject::addSizeOfExcludingThis(this, mallocSizeOf, info,
3247 runtimeSizes);
3248 } else if (is<GlobalObject>()) {
3249 as<GlobalObject>().addSizeOfData(mallocSizeOf, info);
3250 } else if (is<WeakCollectionObject>()) {
3251 info->objectsMallocHeapMisc +=
3252 as<WeakCollectionObject>().sizeOfExcludingThis(mallocSizeOf);
3253 }
3254 #ifdef JS_HAS_CTYPES
3255 else {
3256 // This must be the last case.
3257 info->objectsMallocHeapMisc += ctypes::SizeOfDataIfCDataObject(
3258 mallocSizeOf, const_cast<JSObject*>(this));
3259 }
3260 #endif
3261 }
3262
3263 size_t JSObject::sizeOfIncludingThisInNursery() const {
3264 // This function doesn't concern itself yet with typed objects (bug 1133593).
3265
3266 MOZ_ASSERT(!isTenured());
3267
3268 const Nursery& nursery = runtimeFromMainThread()->gc.nursery();
3269 size_t size = gc::Arena::thingSize(allocKindForTenure(nursery));
3270
3271 if (is<NativeObject>()) {
3272 const NativeObject& native = as<NativeObject>();
3273
3274 size += native.numDynamicSlots() * sizeof(Value);
3275
3276 if (native.hasDynamicElements()) {
3277 js::ObjectElements& elements = *native.getElementsHeader();
3278 size += (elements.capacity + elements.numShiftedElements()) *
3279 sizeof(HeapSlot);
3280 }
3281
3282 if (is<ArgumentsObject>()) {
3283 size += as<ArgumentsObject>().sizeOfData();
3284 }
3285 }
3286
3287 return size;
3288 }
3289
3290 JS::ubi::Node::Size JS::ubi::Concrete<JSObject>::size(
3291 mozilla::MallocSizeOf mallocSizeOf) const {
3292 JSObject& obj = get();
3293
3294 if (!obj.isTenured()) {
3295 return obj.sizeOfIncludingThisInNursery();
3296 }
3297
3298 JS::ClassInfo info;
3299 obj.addSizeOfExcludingThis(mallocSizeOf, &info, nullptr);
3300 return obj.tenuredSizeOfThis() + info.sizeOfAllThings();
3301 }
3302
3303 const char16_t JS::ubi::Concrete<JSObject>::concreteTypeName[] = u"JSObject";
3304
3305 void JSObject::traceChildren(JSTracer* trc) {
3306 TraceCellHeaderEdge(trc, this, "shape");
3307
3308 Shape* objShape = shape();
3309 if (objShape->isNative()) {
3310 NativeObject* nobj = &as<NativeObject>();
3311
3312 if (nobj->hasDynamicSlots()) {
3313 ObjectSlots* slots = nobj->getSlotsHeader();
3314 MOZ_ASSERT(nobj->slots_ == slots->slots());
3315 TraceBufferEdge(trc, nobj, &slots, "objectDynamicSlots buffer");
3316 if (slots != nobj->getSlotsHeader()) {
3317 nobj->slots_ = slots->slots();
3318 }
3319 }
3320
3321 if (nobj->hasDynamicElements()) {
3322 void* buffer = nobj->getUnshiftedElementsHeader();
3323 uint32_t numShifted = nobj->getElementsHeader()->numShiftedElements();
3324 TraceBufferEdge(trc, nobj, &buffer, "objectDynamicElements buffer");
3325 if (buffer != nobj->getUnshiftedElementsHeader()) {
3326 nobj->elements_ =
3327 reinterpret_cast<ObjectElements*>(buffer)->elements() + numShifted;
3328 }
3329 }
3330
3331 const uint32_t nslots = nobj->slotSpan();
3332 const uint32_t nfixed = nobj->numFixedSlots();
3333
3334 {
3335 GetObjectSlotNameFunctor func(nobj, SlotsKind::Fixed);
3336 JS::AutoTracingDetails ctx(trc, func);
3337 TraceRange(trc, std::min(nslots, nfixed), nobj->fixedSlots(),
3338 "objectFixedSlots");
3339 }
3340
3341 if (nslots > nfixed) {
3342 MOZ_ASSERT(nobj->hasDynamicSlots());
3343 GetObjectSlotNameFunctor func(nobj, SlotsKind::Dynamic);
3344 JS::AutoTracingDetails ctx(trc, func);
3345 TraceRange(trc, nslots - nfixed, nobj->slots_, "objectDynamicSlots");
3346 }
3347
3348 TraceRange(trc, nobj->getDenseInitializedLength(),
3349 nobj->getDenseElements().begin(), "objectElements");
3350 }
3351
3352 // Call the trace hook at the end so that during a moving GC the trace hook
3353 // will see updated fields and slots.
3354 const JSClass* clasp = objShape->getObjectClass();
3355 if (clasp->hasTrace()) {
3356 clasp->doTrace(trc, this);
3357 }
3358 }
3359
3360 // ES 2016 7.3.20.
3361 [[nodiscard]] JSObject* js::SpeciesConstructor(
3362 JSContext* cx, HandleObject obj, HandleObject defaultCtor,
3363 bool (*isDefaultSpecies)(JSContext*, JSFunction*)) {
3364 // Step 1 (implicit).
3365
3366 // Fast-path for steps 2 - 8. Applies if all of the following conditions
3367 // are met:
3368 // - obj.constructor can be retrieved without side-effects.
3369 // - obj.constructor[[@@species]] can be retrieved without side-effects.
3370 // - obj.constructor[[@@species]] is the builtin's original @@species
3371 // getter.
3372 RootedValue ctor(cx);
3373 bool ctorGetSucceeded = GetPropertyPure(
3374 cx, obj, NameToId(cx->names().constructor), ctor.address());
3375 if (ctorGetSucceeded && ctor.isObject() && &ctor.toObject() == defaultCtor) {
3376 jsid speciesId = PropertyKey::Symbol(cx->wellKnownSymbols().species);
3377 JSFunction* getter;
3378 if (GetGetterPure(cx, defaultCtor, speciesId, &getter) && getter &&
3379 isDefaultSpecies(cx, getter)) {
3380 return defaultCtor;
3381 }
3382 }
3383
3384 // Step 2.
3385 if (!ctorGetSucceeded &&
3386 !GetProperty(cx, obj, obj, cx->names().constructor, &ctor)) {
3387 return nullptr;
3388 }
3389
3390 // Step 3.
3391 if (ctor.isUndefined()) {
3392 return defaultCtor;
3393 }
3394
3395 // Step 4.
3396 if (!ctor.isObject()) {
3397 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3398 JSMSG_OBJECT_REQUIRED,
3399 "object's 'constructor' property");
3400 return nullptr;
3401 }
3402
3403 // Step 5.
3404 RootedObject ctorObj(cx, &ctor.toObject());
3405 RootedValue s(cx);
3406 RootedId speciesId(cx, PropertyKey::Symbol(cx->wellKnownSymbols().species));
3407 if (!GetProperty(cx, ctorObj, ctor, speciesId, &s)) {
3408 return nullptr;
3409 }
3410
3411 // Step 6.
3412 if (s.isNullOrUndefined()) {
3413 return defaultCtor;
3414 }
3415
3416 // Step 7.
3417 if (IsConstructor(s)) {
3418 return &s.toObject();
3419 }
3420
3421 // Step 8.
3422 JS_ReportErrorNumberASCII(
3423 cx, GetErrorMessage, nullptr, JSMSG_NOT_CONSTRUCTOR,
3424 "[Symbol.species] property of object's constructor");
3425 return nullptr;
3426 }
3427
3428 [[nodiscard]] JSObject* js::SpeciesConstructor(
3429 JSContext* cx, HandleObject obj, JSProtoKey ctorKey,
3430 bool (*isDefaultSpecies)(JSContext*, JSFunction*)) {
3431 RootedObject defaultCtor(cx,
3432 GlobalObject::getOrCreateConstructor(cx, ctorKey));
3433 if (!defaultCtor) {
3434 return nullptr;
3435 }
3436 return SpeciesConstructor(cx, obj, defaultCtor, isDefaultSpecies);
3437 }
3438
3439 bool js::Unbox(JSContext* cx, HandleObject obj, MutableHandleValue vp) {
3440 if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
3441 return Proxy::boxedValue_unbox(cx, obj, vp);
3442 }
3443
3444 if (obj->is<BooleanObject>()) {
3445 vp.setBoolean(obj->as<BooleanObject>().unbox());
3446 } else if (obj->is<NumberObject>()) {
3447 vp.setNumber(obj->as<NumberObject>().unbox());
3448 } else if (obj->is<StringObject>()) {
3449 vp.setString(obj->as<StringObject>().unbox());
3450 } else if (obj->is<DateObject>()) {
3451 vp.set(obj->as<DateObject>().UTCTime());
3452 } else if (obj->is<SymbolObject>()) {
3453 vp.setSymbol(obj->as<SymbolObject>().unbox());
3454 } else if (obj->is<BigIntObject>()) {
3455 vp.setBigInt(obj->as<BigIntObject>().unbox());
3456 } else {
3457 vp.setUndefined();
3458 }
3459
3460 return true;
3461 }
3462
3463 #ifdef DEBUG
3464 void js::AssertJSClassInvariants(const JSClass* clasp) {
3465 MOZ_ASSERT(JS::StringIsASCII(clasp->name));
3466
3467 // Native objects shouldn't use the property operation hooks in ObjectOps.
3468 // Doing so could violate JIT invariants.
3469 //
3470 // Environment objects unfortunately use these hooks, but environment objects
3471 // are not exposed directly to script so they're generally less of an issue.
3472 if (clasp->isNativeObject() && clasp != &WithEnvironmentObject::class_ &&
3473 clasp != &ModuleEnvironmentObject::class_ &&
3474 clasp != &RuntimeLexicalErrorObject::class_) {
3475 MOZ_ASSERT(!clasp->getOpsLookupProperty());
3476 MOZ_ASSERT_IF(clasp != &MappedArgumentsObject::class_,
3477 !clasp->getOpsDefineProperty());
3478 MOZ_ASSERT(!clasp->getOpsHasProperty());
3479 MOZ_ASSERT(!clasp->getOpsGetProperty());
3480 MOZ_ASSERT(!clasp->getOpsSetProperty());
3481 MOZ_ASSERT(!clasp->getOpsGetOwnPropertyDescriptor());
3482 MOZ_ASSERT(!clasp->getOpsDeleteProperty());
3483 }
3484 }
3485
3486 /* static */
3487 void JSObject::debugCheckNewObject(Shape* shape, js::gc::AllocKind allocKind,
3488 js::gc::Heap heap) {
3489 const JSClass* clasp = shape->getObjectClass();
3490
3491 if (!ClassCanHaveFixedData(clasp)) {
3492 NativeShape* nshape = &shape->asNative();
3493 if (clasp == &ArrayObject::class_) {
3494 // Arrays can store the ObjectElements header inline.
3495 MOZ_ASSERT(nshape->numFixedSlots() == 0);
3496 } else {
3497 MOZ_ASSERT(gc::GetGCKindSlots(allocKind) == nshape->numFixedSlots());
3498 }
3499 }
3500
3501 using namespace gc;
3502 if (!clasp->isProxyObject()) {
3503 // Check |allocKind| has the correct finalization kind for the class.
3504 gc::FinalizeKind finalizeKind = GetObjectFinalizeKind(clasp);
3505 MOZ_ASSERT_IF(finalizeKind == gc::FinalizeKind::None,
3506 !IsFinalizedKind(allocKind));
3507 MOZ_ASSERT_IF(finalizeKind == gc::FinalizeKind::Background,
3508 IsBackgroundFinalized(allocKind));
3509 MOZ_ASSERT_IF(finalizeKind == gc::FinalizeKind::Foreground,
3510 IsForegroundFinalized(allocKind));
3511 }
3512
3513 // Classes with a finalizer must specify whether instances will be finalized
3514 // on the main thread or in the background, except proxies whose behaviour
3515 // depends on the target object.
3516 static const uint32_t FinalizeMask =
3517 JSCLASS_FOREGROUND_FINALIZE | JSCLASS_BACKGROUND_FINALIZE;
3518 uint32_t flags = clasp->flags;
3519 uint32_t finalizeFlags = flags & FinalizeMask;
3520 if (clasp->hasFinalize() && !clasp->isProxyObject()) {
3521 MOZ_ASSERT(finalizeFlags == JSCLASS_FOREGROUND_FINALIZE ||
3522 finalizeFlags == JSCLASS_BACKGROUND_FINALIZE);
3523 } else {
3524 MOZ_ASSERT(finalizeFlags == 0);
3525 }
3526
3527 MOZ_ASSERT_IF(clasp->hasFinalize(),
3528 heap == gc::Heap::Tenured ||
3529 CanNurseryAllocateFinalizedClass(clasp) ||
3530 clasp->isProxyObject());
3531
3532 MOZ_ASSERT(!shape->isDictionary());
3533
3534 // If the class has the JSCLASS_DELAY_METADATA_BUILDER flag, the caller must
3535 // use AutoSetNewObjectMetadata. Ignore Wasm GC objects for now (bug 1963323).
3536 MOZ_ASSERT_IF(
3537 clasp->shouldDelayMetadataBuilder() && !IsWasmGcObjectClass(clasp),
3538 shape->realm()->hasActiveAutoSetNewObjectMetadata());
3539 MOZ_ASSERT(!shape->realm()->hasObjectPendingMetadata());
3540
3541 // Non-native classes manage their own data and slots, so numFixedSlots is
3542 // always 0. Note that proxy classes can have reserved slots but they're not
3543 // included in numFixedSlots.
3544 if (!clasp->isNativeObject()) {
3545 MOZ_ASSERT_IF(!clasp->isProxyObject(), JSCLASS_RESERVED_SLOTS(clasp) == 0);
3546 }
3547 }
3548 #endif