Bug 1832284 - Fix rooting hazard in JSObject::swap r=sfink
[gecko.git] / js / src / vm / JSObject.cpp
blobb2d59b017c701999ff495b8191be15f993b081cd
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/. */
7 /*
8 * JS object implementation.
9 */
11 #include "vm/JSObject-inl.h"
13 #include "mozilla/MemoryReporting.h"
15 #include <string.h>
17 #include "jsapi.h"
18 #include "jsexn.h"
19 #include "jsfriendapi.h"
20 #include "jsnum.h"
21 #include "jstypes.h"
23 #include "builtin/BigInt.h"
24 #include "builtin/MapObject.h"
25 #include "builtin/Object.h"
26 #include "builtin/String.h"
27 #include "builtin/Symbol.h"
28 #include "builtin/WeakSetObject.h"
29 #include "gc/GC.h"
30 #include "js/CharacterEncoding.h"
31 #include "js/friend/DumpFunctions.h" // js::DumpObject
32 #include "js/friend/ErrorMessages.h" // JSErrNum, js::GetErrorMessage, JSMSG_*
33 #include "js/friend/WindowProxy.h" // js::IsWindow, js::ToWindowProxyIfWindow
34 #include "js/MemoryMetrics.h"
35 #include "js/PropertyDescriptor.h" // JS::FromPropertyDescriptor
36 #include "js/PropertySpec.h" // JSPropertySpec
37 #include "js/Proxy.h"
38 #include "js/Result.h"
39 #include "js/UbiNode.h"
40 #include "js/Wrapper.h"
41 #include "proxy/DeadObjectProxy.h"
42 #include "util/Memory.h"
43 #include "util/Text.h"
44 #include "util/WindowsWrapper.h"
45 #include "vm/ArgumentsObject.h"
46 #include "vm/BytecodeUtil.h"
47 #include "vm/Compartment.h"
48 #include "vm/DateObject.h"
49 #include "vm/Interpreter.h"
50 #include "vm/Iteration.h"
51 #include "vm/JSAtom.h"
52 #include "vm/JSContext.h"
53 #include "vm/JSFunction.h"
54 #include "vm/JSScript.h"
55 #include "vm/ProxyObject.h"
56 #include "vm/RegExpObject.h"
57 #include "vm/Shape.h"
58 #include "vm/TypedArrayObject.h"
59 #include "vm/Watchtower.h"
60 #include "vm/WellKnownAtom.h" // js_*_str
61 #include "vm/WrapperObject.h"
62 #ifdef ENABLE_RECORD_TUPLE
63 # include "builtin/RecordObject.h"
64 # include "builtin/TupleObject.h"
65 # include "vm/RecordType.h"
66 # include "vm/TupleType.h"
67 #endif
68 #include "wasm/WasmGcObject.h"
70 #include "gc/StableCellHasher-inl.h"
71 #include "vm/BooleanObject-inl.h"
72 #include "vm/EnvironmentObject-inl.h"
73 #include "vm/Interpreter-inl.h"
74 #include "vm/JSAtom-inl.h"
75 #include "vm/JSContext-inl.h"
76 #include "vm/NativeObject-inl.h"
77 #include "vm/NumberObject-inl.h"
78 #include "vm/ObjectFlags-inl.h"
79 #include "vm/Realm-inl.h"
80 #include "vm/StringObject-inl.h"
81 #include "vm/TypedArrayObject-inl.h"
83 using namespace js;
85 using mozilla::Maybe;
87 void js::ReportNotObject(JSContext* cx, JSErrNum err, int spindex,
88 HandleValue v) {
89 MOZ_ASSERT(!v.isObject());
90 ReportValueError(cx, err, spindex, v, nullptr);
93 void js::ReportNotObject(JSContext* cx, JSErrNum err, HandleValue v) {
94 ReportNotObject(cx, err, JSDVG_SEARCH_STACK, v);
97 void js::ReportNotObject(JSContext* cx, const Value& v) {
98 RootedValue value(cx, v);
99 ReportNotObject(cx, JSMSG_OBJECT_REQUIRED, value);
102 void js::ReportNotObjectArg(JSContext* cx, const char* nth, const char* fun,
103 HandleValue v) {
104 MOZ_ASSERT(!v.isObject());
106 UniqueChars bytes;
107 if (const char* chars = ValueToSourceForError(cx, v, bytes)) {
108 JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
109 JSMSG_OBJECT_REQUIRED_ARG, nth, fun, chars);
113 JS_PUBLIC_API const char* JS::InformalValueTypeName(const Value& v) {
114 switch (v.type()) {
115 case ValueType::Double:
116 case ValueType::Int32:
117 return "number";
118 case ValueType::Boolean:
119 return "boolean";
120 case ValueType::Undefined:
121 return "undefined";
122 case ValueType::Null:
123 return "null";
124 case ValueType::String:
125 return "string";
126 case ValueType::Symbol:
127 return "symbol";
128 case ValueType::BigInt:
129 return "bigint";
130 case ValueType::Object:
131 #ifdef ENABLE_RECORD_TUPLE
132 case ValueType::ExtendedPrimitive:
133 #endif
134 return v.getObjectPayload().getClass()->name;
135 case ValueType::Magic:
136 return "magic";
137 case ValueType::PrivateGCThing:
138 break;
141 MOZ_CRASH("unexpected type");
144 // ES6 draft rev37 6.2.4.4 FromPropertyDescriptor
145 JS_PUBLIC_API bool JS::FromPropertyDescriptor(
146 JSContext* cx, Handle<Maybe<PropertyDescriptor>> desc_,
147 MutableHandleValue vp) {
148 AssertHeapIsIdle();
149 CHECK_THREAD(cx);
150 cx->check(desc_);
152 // Step 1.
153 if (desc_.isNothing()) {
154 vp.setUndefined();
155 return true;
158 Rooted<PropertyDescriptor> desc(cx, *desc_);
159 return FromPropertyDescriptorToObject(cx, desc, vp);
162 bool js::FromPropertyDescriptorToObject(JSContext* cx,
163 Handle<PropertyDescriptor> desc,
164 MutableHandleValue vp) {
165 // Step 2-3.
166 RootedObject obj(cx, NewPlainObject(cx));
167 if (!obj) {
168 return false;
171 const JSAtomState& names = cx->names();
173 // Step 4.
174 if (desc.hasValue()) {
175 if (!DefineDataProperty(cx, obj, names.value, desc.value())) {
176 return false;
180 // Step 5.
181 RootedValue v(cx);
182 if (desc.hasWritable()) {
183 v.setBoolean(desc.writable());
184 if (!DefineDataProperty(cx, obj, names.writable, v)) {
185 return false;
189 // Step 6.
190 if (desc.hasGetter()) {
191 if (JSObject* get = desc.getter()) {
192 v.setObject(*get);
193 } else {
194 v.setUndefined();
196 if (!DefineDataProperty(cx, obj, names.get, v)) {
197 return false;
201 // Step 7.
202 if (desc.hasSetter()) {
203 if (JSObject* set = desc.setter()) {
204 v.setObject(*set);
205 } else {
206 v.setUndefined();
208 if (!DefineDataProperty(cx, obj, names.set, v)) {
209 return false;
213 // Step 8.
214 if (desc.hasEnumerable()) {
215 v.setBoolean(desc.enumerable());
216 if (!DefineDataProperty(cx, obj, names.enumerable, v)) {
217 return false;
221 // Step 9.
222 if (desc.hasConfigurable()) {
223 v.setBoolean(desc.configurable());
224 if (!DefineDataProperty(cx, obj, names.configurable, v)) {
225 return false;
229 vp.setObject(*obj);
230 return true;
233 bool js::GetFirstArgumentAsObject(JSContext* cx, const CallArgs& args,
234 const char* method,
235 MutableHandleObject objp) {
236 if (!args.requireAtLeast(cx, method, 1)) {
237 return false;
240 HandleValue v = args[0];
241 if (!v.isObject()) {
242 UniqueChars bytes =
243 DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, v, nullptr);
244 if (!bytes) {
245 return false;
247 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
248 JSMSG_UNEXPECTED_TYPE, bytes.get(),
249 "not an object");
250 return false;
253 objp.set(&v.toObject());
254 return true;
257 static bool GetPropertyIfPresent(JSContext* cx, HandleObject obj, HandleId id,
258 MutableHandleValue vp, bool* foundp) {
259 if (!HasProperty(cx, obj, id, foundp)) {
260 return false;
262 if (!*foundp) {
263 vp.setUndefined();
264 return true;
267 return GetProperty(cx, obj, obj, id, vp);
270 bool js::Throw(JSContext* cx, HandleId id, unsigned errorNumber,
271 const char* details) {
272 MOZ_ASSERT(js_ErrorFormatString[errorNumber].argCount == (details ? 2 : 1));
273 MOZ_ASSERT_IF(details, JS::StringIsASCII(details));
275 UniqueChars bytes =
276 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
277 if (!bytes) {
278 return false;
281 if (details) {
282 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
283 bytes.get(), details);
284 } else {
285 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
286 bytes.get());
289 return false;
292 /*** PropertyDescriptor operations and DefineProperties *********************/
294 #ifndef ENABLE_DECORATORS
295 // These are defined by CommonPropertyNames.h and WellKnownAtom.{cpp,h}
296 // when decorators are enabled.
297 static const char js_getter_str[] = "getter";
298 static const char js_setter_str[] = "setter";
299 #endif
301 static Result<> CheckCallable(JSContext* cx, JSObject* obj,
302 const char* fieldName) {
303 if (obj && !obj->isCallable()) {
304 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
305 JSMSG_BAD_GET_SET_FIELD, fieldName);
306 return cx->alreadyReportedError();
308 return Ok();
311 // 6.2.5.5 ToPropertyDescriptor(Obj)
312 bool js::ToPropertyDescriptor(JSContext* cx, HandleValue descval,
313 bool checkAccessors,
314 MutableHandle<PropertyDescriptor> desc_) {
315 // Step 1.
316 RootedObject obj(cx,
317 RequireObject(cx, JSMSG_OBJECT_REQUIRED_PROP_DESC, descval));
318 if (!obj) {
319 return false;
322 // Step 2.
323 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Empty());
325 RootedId id(cx);
326 RootedValue v(cx);
328 // Steps 3-4.
329 id = NameToId(cx->names().enumerable);
330 bool hasEnumerable = false;
331 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasEnumerable)) {
332 return false;
334 if (hasEnumerable) {
335 desc.setEnumerable(ToBoolean(v));
338 // Steps 5-6.
339 id = NameToId(cx->names().configurable);
340 bool hasConfigurable = false;
341 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasConfigurable)) {
342 return false;
344 if (hasConfigurable) {
345 desc.setConfigurable(ToBoolean(v));
348 // Steps 7-8.
349 id = NameToId(cx->names().value);
350 bool hasValue = false;
351 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasValue)) {
352 return false;
354 if (hasValue) {
355 desc.setValue(v);
358 // Steps 9-10.
359 id = NameToId(cx->names().writable);
360 bool hasWritable = false;
361 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasWritable)) {
362 return false;
364 if (hasWritable) {
365 desc.setWritable(ToBoolean(v));
368 // Steps 11-12.
369 id = NameToId(cx->names().get);
370 bool hasGet = false;
371 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasGet)) {
372 return false;
374 RootedObject getter(cx);
375 if (hasGet) {
376 if (v.isObject()) {
377 if (checkAccessors) {
378 JS_TRY_OR_RETURN_FALSE(cx,
379 CheckCallable(cx, &v.toObject(), js_getter_str));
381 getter = &v.toObject();
382 } else if (v.isUndefined()) {
383 getter = nullptr;
384 } else {
385 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
386 JSMSG_BAD_GET_SET_FIELD, js_getter_str);
387 return false;
391 // Steps 13-14.
392 id = NameToId(cx->names().set);
393 bool hasSet = false;
394 if (!GetPropertyIfPresent(cx, obj, id, &v, &hasSet)) {
395 return false;
397 RootedObject setter(cx);
398 if (hasSet) {
399 if (v.isObject()) {
400 if (checkAccessors) {
401 JS_TRY_OR_RETURN_FALSE(cx,
402 CheckCallable(cx, &v.toObject(), js_setter_str));
404 setter = &v.toObject();
405 } else if (v.isUndefined()) {
406 setter = nullptr;
407 } else {
408 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
409 JSMSG_BAD_GET_SET_FIELD, js_setter_str);
410 return false;
414 // Step 15.
415 if (hasGet || hasSet) {
416 if (hasValue || hasWritable) {
417 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
418 JSMSG_INVALID_DESCRIPTOR);
419 return false;
422 // We delay setGetter/setSetter after the previous check,
423 // because otherwise we would assert.
424 if (hasGet) {
425 desc.setGetter(getter);
427 if (hasSet) {
428 desc.setSetter(setter);
432 desc.assertValid();
433 desc_.set(desc);
434 return true;
437 Result<> js::CheckPropertyDescriptorAccessors(JSContext* cx,
438 Handle<PropertyDescriptor> desc) {
439 if (desc.hasGetter()) {
440 MOZ_TRY(CheckCallable(cx, desc.getter(), js_getter_str));
443 if (desc.hasSetter()) {
444 MOZ_TRY(CheckCallable(cx, desc.setter(), js_setter_str));
447 return Ok();
450 // 6.2.5.6 CompletePropertyDescriptor(Desc)
451 void js::CompletePropertyDescriptor(MutableHandle<PropertyDescriptor> desc) {
452 // Step 1.
453 desc.assertValid();
455 // Step 2.
456 // Let like be the Record { [[Value]]: undefined, [[Writable]]: false,
457 // [[Get]]: undefined, [[Set]]: undefined,
458 // [[Enumerable]]: false, [[Configurable]]: false }.
460 // Step 3.
461 if (desc.isGenericDescriptor() || desc.isDataDescriptor()) {
462 // Step 3.a.
463 if (!desc.hasValue()) {
464 desc.setValue(UndefinedHandleValue);
466 // Step 3.b.
467 if (!desc.hasWritable()) {
468 desc.setWritable(false);
470 } else {
471 // Step 4.a.
472 if (!desc.hasGetter()) {
473 desc.setGetter(nullptr);
475 // Step 4.b.
476 if (!desc.hasSetter()) {
477 desc.setSetter(nullptr);
481 // Step 5.
482 if (!desc.hasEnumerable()) {
483 desc.setEnumerable(false);
486 // Step 6.
487 if (!desc.hasConfigurable()) {
488 desc.setConfigurable(false);
491 desc.assertComplete();
494 bool js::ReadPropertyDescriptors(
495 JSContext* cx, HandleObject props, bool checkAccessors,
496 MutableHandleIdVector ids, MutableHandle<PropertyDescriptorVector> descs) {
497 if (!GetPropertyKeys(cx, props, JSITER_OWNONLY | JSITER_SYMBOLS, ids)) {
498 return false;
501 RootedId id(cx);
502 for (size_t i = 0, len = ids.length(); i < len; i++) {
503 id = ids[i];
504 Rooted<PropertyDescriptor> desc(cx);
505 RootedValue v(cx);
506 if (!GetProperty(cx, props, props, id, &v) ||
507 !ToPropertyDescriptor(cx, v, checkAccessors, &desc) ||
508 !descs.append(desc)) {
509 return false;
512 return true;
515 /*** Seal and freeze ********************************************************/
517 /* ES6 draft rev 29 (6 Dec 2014) 7.3.13. */
518 bool js::SetIntegrityLevel(JSContext* cx, HandleObject obj,
519 IntegrityLevel level) {
520 cx->check(obj);
522 // Steps 3-5. (Steps 1-2 are redundant assertions.)
523 if (!PreventExtensions(cx, obj)) {
524 return false;
527 // Steps 6-9, loosely interpreted.
528 if (obj->is<NativeObject>() && !obj->is<TypedArrayObject>() &&
529 !obj->is<MappedArgumentsObject>()) {
530 Handle<NativeObject*> nobj = obj.as<NativeObject>();
532 // Use a fast path to seal/freeze properties. This has the benefit of
533 // creating shared property maps if possible, whereas the slower/generic
534 // implementation below ends up converting non-empty objects to dictionary
535 // mode.
536 if (nobj->shape()->propMapLength() > 0) {
537 if (!NativeObject::freezeOrSealProperties(cx, nobj, level)) {
538 return false;
542 // Ordinarily ArraySetLength handles this, but we're going behind its back
543 // right now, so we must do this manually.
544 if (level == IntegrityLevel::Frozen && obj->is<ArrayObject>()) {
545 obj->as<ArrayObject>().setNonWritableLength(cx);
547 } else {
548 // Steps 6-7.
549 RootedIdVector keys(cx);
550 if (!GetPropertyKeys(
551 cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &keys)) {
552 return false;
555 RootedId id(cx);
556 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Empty());
558 // 8.a/9.a. The two different loops are merged here.
559 for (size_t i = 0; i < keys.length(); i++) {
560 id = keys[i];
562 if (level == IntegrityLevel::Sealed) {
563 // 8.a.i.
564 desc.setConfigurable(false);
565 } else {
566 // 9.a.i-ii.
567 Rooted<Maybe<PropertyDescriptor>> currentDesc(cx);
568 if (!GetOwnPropertyDescriptor(cx, obj, id, &currentDesc)) {
569 return false;
572 // 9.a.iii.
573 if (currentDesc.isNothing()) {
574 continue;
577 // 9.a.iii.1-2
578 desc = PropertyDescriptor::Empty();
579 if (currentDesc->isAccessorDescriptor()) {
580 desc.setConfigurable(false);
581 } else {
582 desc.setConfigurable(false);
583 desc.setWritable(false);
587 // 8.a.i-ii. / 9.a.iii.3-4
588 if (!DefineProperty(cx, obj, id, desc)) {
589 return false;
594 // Finally, freeze or seal the dense elements.
595 if (obj->is<NativeObject>()) {
596 if (!ObjectElements::FreezeOrSeal(cx, obj.as<NativeObject>(), level)) {
597 return false;
601 return true;
604 static bool ResolveLazyProperties(JSContext* cx, Handle<NativeObject*> obj) {
605 const JSClass* clasp = obj->getClass();
606 if (JSEnumerateOp enumerate = clasp->getEnumerate()) {
607 if (!enumerate(cx, obj)) {
608 return false;
611 if (clasp->getNewEnumerate() && clasp->getResolve()) {
612 RootedIdVector properties(cx);
613 if (!clasp->getNewEnumerate()(cx, obj, &properties,
614 /* enumerableOnly = */ false)) {
615 return false;
618 RootedId id(cx);
619 for (size_t i = 0; i < properties.length(); i++) {
620 id = properties[i];
621 bool found;
622 if (!HasOwnProperty(cx, obj, id, &found)) {
623 return false;
627 return true;
630 // ES6 draft rev33 (12 Feb 2015) 7.3.15
631 bool js::TestIntegrityLevel(JSContext* cx, HandleObject obj,
632 IntegrityLevel level, bool* result) {
633 // Steps 3-6. (Steps 1-2 are redundant assertions.)
634 bool status;
635 if (!IsExtensible(cx, obj, &status)) {
636 return false;
638 if (status) {
639 *result = false;
640 return true;
643 // Fast path for native objects.
644 if (obj->is<NativeObject>()) {
645 Handle<NativeObject*> nobj = obj.as<NativeObject>();
647 // Force lazy properties to be resolved.
648 if (!ResolveLazyProperties(cx, nobj)) {
649 return false;
652 // Typed array elements are configurable, writable properties, so if any
653 // elements are present, the typed array can neither be sealed nor frozen.
654 if (nobj->is<TypedArrayObject>() &&
655 nobj->as<TypedArrayObject>().length() > 0) {
656 *result = false;
657 return true;
660 bool hasDenseElements = false;
661 for (size_t i = 0; i < nobj->getDenseInitializedLength(); i++) {
662 if (nobj->containsDenseElement(i)) {
663 hasDenseElements = true;
664 break;
668 if (hasDenseElements) {
669 // Unless the sealed flag is set, dense elements are configurable.
670 if (!nobj->denseElementsAreSealed()) {
671 *result = false;
672 return true;
675 // Unless the frozen flag is set, dense elements are writable.
676 if (level == IntegrityLevel::Frozen && !nobj->denseElementsAreFrozen()) {
677 *result = false;
678 return true;
682 // Steps 7-9.
683 for (ShapePropertyIter<NoGC> iter(nobj->shape()); !iter.done(); iter++) {
684 // Steps 9.c.i-ii.
685 if (iter->configurable() ||
686 (level == IntegrityLevel::Frozen && iter->isDataDescriptor() &&
687 iter->writable())) {
688 // Private fields on objects don't participate in the frozen state, and
689 // so should be elided from checking for frozen state.
690 if (iter->key().isPrivateName()) {
691 continue;
694 *result = false;
695 return true;
698 } else {
699 // Steps 7-8.
700 RootedIdVector props(cx);
701 if (!GetPropertyKeys(
702 cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &props)) {
703 return false;
706 // Step 9.
707 RootedId id(cx);
708 Rooted<Maybe<PropertyDescriptor>> desc(cx);
709 for (size_t i = 0, len = props.length(); i < len; i++) {
710 id = props[i];
712 // Steps 9.a-b.
713 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
714 return false;
717 // Step 9.c.
718 if (desc.isNothing()) {
719 continue;
722 // Steps 9.c.i-ii.
723 if (desc->configurable() ||
724 (level == IntegrityLevel::Frozen && desc->isDataDescriptor() &&
725 desc->writable())) {
726 // Since we don't request JSITER_PRIVATE in GetPropertyKeys above, we
727 // should never see a private name here.
728 MOZ_ASSERT(!id.isPrivateName());
729 *result = false;
730 return true;
735 // Step 10.
736 *result = true;
737 return true;
740 /* * */
742 static MOZ_ALWAYS_INLINE NativeObject* NewObject(JSContext* cx,
743 const JSClass* clasp,
744 Handle<TaggedProto> proto,
745 gc::AllocKind kind,
746 NewObjectKind newKind) {
747 MOZ_ASSERT(clasp->isNativeObject());
749 // Some classes have specialized allocation functions and shouldn't end up
750 // here.
751 MOZ_ASSERT(clasp != &ArrayObject::class_);
752 MOZ_ASSERT(clasp != &PlainObject::class_);
753 MOZ_ASSERT(!clasp->isJSFunction());
755 // Computing nfixed based on the AllocKind isn't right for objects which can
756 // store fixed data inline (TypedArrays and ArrayBuffers) so for simplicity
757 // and performance reasons we don't support such objects here.
758 MOZ_ASSERT(!ClassCanHaveFixedData(clasp));
759 size_t nfixed = GetGCKindSlots(kind);
761 if (CanChangeToBackgroundAllocKind(kind, clasp)) {
762 kind = ForegroundToBackgroundAllocKind(kind);
765 Rooted<SharedShape*> shape(
766 cx, SharedShape::getInitialShape(cx, clasp, cx->realm(), proto, nfixed,
767 ObjectFlags()));
768 if (!shape) {
769 return nullptr;
772 gc::InitialHeap heap = GetInitialHeap(newKind, clasp);
773 NativeObject* obj = NativeObject::create(cx, kind, heap, shape);
774 if (!obj) {
775 return nullptr;
778 probes::CreateObject(cx, obj);
779 return obj;
782 NativeObject* js::NewObjectWithGivenTaggedProto(JSContext* cx,
783 const JSClass* clasp,
784 Handle<TaggedProto> proto,
785 gc::AllocKind allocKind,
786 NewObjectKind newKind) {
787 return NewObject(cx, clasp, proto, allocKind, newKind);
790 NativeObject* js::NewObjectWithClassProto(JSContext* cx, const JSClass* clasp,
791 HandleObject protoArg,
792 gc::AllocKind allocKind,
793 NewObjectKind newKind) {
794 if (protoArg) {
795 return NewObjectWithGivenTaggedProto(cx, clasp, AsTaggedProto(protoArg),
796 allocKind, newKind);
799 // Find the appropriate proto for clasp. Built-in classes have a cached
800 // proto on cx->global(); all others get %ObjectPrototype%.
801 JSProtoKey protoKey = JSCLASS_CACHED_PROTO_KEY(clasp);
802 if (protoKey == JSProto_Null) {
803 protoKey = JSProto_Object;
806 JSObject* proto = GlobalObject::getOrCreatePrototype(cx, protoKey);
807 if (!proto) {
808 return nullptr;
811 Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
812 return NewObject(cx, clasp, taggedProto, allocKind, newKind);
815 bool js::GetPrototypeFromConstructor(JSContext* cx, HandleObject newTarget,
816 JSProtoKey intrinsicDefaultProto,
817 MutableHandleObject proto) {
818 RootedValue protov(cx);
819 if (!GetProperty(cx, newTarget, newTarget, cx->names().prototype, &protov)) {
820 return false;
822 if (protov.isObject()) {
823 proto.set(&protov.toObject());
824 } else if (newTarget->is<JSFunction>() &&
825 newTarget->as<JSFunction>().realm() == cx->realm()) {
826 // Steps 4.a-b fetch the builtin prototype of the current realm, which we
827 // represent as nullptr.
828 proto.set(nullptr);
829 } else if (intrinsicDefaultProto == JSProto_Null) {
830 // Bug 1317416. The caller did not pass a reasonable JSProtoKey, so let the
831 // caller select a prototype object. Most likely they will choose one from
832 // the wrong realm.
833 proto.set(nullptr);
834 } else {
835 // Step 4.a: Let realm be ? GetFunctionRealm(constructor);
836 Realm* realm = JS::GetFunctionRealm(cx, newTarget);
837 if (!realm) {
838 return false;
841 // Step 4.b: Set proto to realm's intrinsic object named
842 // intrinsicDefaultProto.
844 Maybe<AutoRealm> ar;
845 if (cx->realm() != realm) {
846 ar.emplace(cx, realm->maybeGlobal());
848 proto.set(GlobalObject::getOrCreatePrototype(cx, intrinsicDefaultProto));
850 if (!proto) {
851 return false;
853 if (!cx->compartment()->wrap(cx, proto)) {
854 return false;
857 return true;
860 /* static */
861 bool JSObject::nonNativeSetProperty(JSContext* cx, HandleObject obj,
862 HandleId id, HandleValue v,
863 HandleValue receiver,
864 ObjectOpResult& result) {
865 return obj->getOpsSetProperty()(cx, obj, id, v, receiver, result);
868 /* static */
869 bool JSObject::nonNativeSetElement(JSContext* cx, HandleObject obj,
870 uint32_t index, HandleValue v,
871 HandleValue receiver,
872 ObjectOpResult& result) {
873 RootedId id(cx);
874 if (!IndexToId(cx, index, &id)) {
875 return false;
877 return nonNativeSetProperty(cx, obj, id, v, receiver, result);
880 static bool CopyPropertyFrom(JSContext* cx, HandleId id, HandleObject target,
881 HandleObject obj) {
882 // |target| must not be a CCW because we need to enter its realm below and
883 // CCWs are not associated with a single realm.
884 MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
886 // |obj| and |cx| are generally not same-compartment with |target| here.
887 cx->check(obj, id);
888 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
890 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
891 return false;
893 MOZ_ASSERT(desc.isSome());
895 JSAutoRealm ar(cx, target);
896 cx->markId(id);
897 RootedId wrappedId(cx, id);
898 if (!cx->compartment()->wrap(cx, &desc)) {
899 return false;
902 Rooted<PropertyDescriptor> desc_(cx, *desc);
903 return DefineProperty(cx, target, wrappedId, desc_);
906 JS_PUBLIC_API bool JS_CopyOwnPropertiesAndPrivateFields(JSContext* cx,
907 HandleObject target,
908 HandleObject obj) {
909 // Both |obj| and |target| must not be CCWs because we need to enter their
910 // realms below and CCWs are not associated with a single realm.
911 MOZ_ASSERT(!IsCrossCompartmentWrapper(obj));
912 MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
914 JSAutoRealm ar(cx, obj);
916 RootedIdVector props(cx);
917 if (!GetPropertyKeys(
918 cx, obj,
919 JSITER_PRIVATE | JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
920 &props)) {
921 return false;
924 for (size_t i = 0; i < props.length(); ++i) {
925 if (!CopyPropertyFrom(cx, props[i], target, obj)) {
926 return false;
930 return true;
933 static bool InitializePropertiesFromCompatibleNativeObject(
934 JSContext* cx, Handle<NativeObject*> dst, Handle<NativeObject*> src) {
935 cx->check(src, dst);
936 MOZ_ASSERT(src->getClass() == dst->getClass());
937 MOZ_ASSERT(dst->shape()->objectFlags().isEmpty());
938 MOZ_ASSERT(src->numFixedSlots() == dst->numFixedSlots());
939 MOZ_ASSERT(!src->inDictionaryMode());
940 MOZ_ASSERT(!dst->inDictionaryMode());
942 if (!dst->ensureElements(cx, src->getDenseInitializedLength())) {
943 return false;
946 uint32_t initialized = src->getDenseInitializedLength();
947 for (uint32_t i = 0; i < initialized; ++i) {
948 dst->setDenseInitializedLength(i + 1);
949 dst->initDenseElement(i, src->getDenseElement(i));
952 // If there are no properties to copy, we're done.
953 if (!src->sharedShape()->propMap()) {
954 return true;
957 Rooted<SharedShape*> shape(cx);
958 if (src->staticPrototype() == dst->staticPrototype()) {
959 shape = src->sharedShape();
960 } else {
961 // We need to generate a new shape for dst that has dst's proto but all
962 // the property information from src. Note that we asserted above that
963 // dst's object flags are empty.
964 SharedShape* srcShape = src->sharedShape();
965 ObjectFlags objFlags;
966 objFlags = CopyPropMapObjectFlags(objFlags, srcShape->objectFlags());
967 Rooted<SharedPropMap*> map(cx, srcShape->propMap());
968 uint32_t mapLength = srcShape->propMapLength();
969 shape = SharedShape::getPropMapShape(cx, dst->shape()->base(),
970 dst->numFixedSlots(), map, mapLength,
971 objFlags);
972 if (!shape) {
973 return false;
977 uint32_t oldSpan = dst->sharedShape()->slotSpan();
978 uint32_t newSpan = shape->slotSpan();
979 if (!dst->setShapeAndAddNewSlots(cx, shape, oldSpan, newSpan)) {
980 return false;
982 for (size_t i = JSCLASS_RESERVED_SLOTS(src->getClass()); i < newSpan; i++) {
983 dst->setSlot(i, src->getSlot(i));
986 return true;
989 JS_PUBLIC_API bool JS_InitializePropertiesFromCompatibleNativeObject(
990 JSContext* cx, HandleObject dst, HandleObject src) {
991 return InitializePropertiesFromCompatibleNativeObject(
992 cx, dst.as<NativeObject>(), src.as<NativeObject>());
995 bool js::ObjectMayBeSwapped(const JSObject* obj) {
996 const JSClass* clasp = obj->getClass();
998 // We want to optimize Window/globals and Gecko doesn't require transplanting
999 // them (only the WindowProxy around them). A Window may be a DOMClass, so we
1000 // explicitly check if this is a global.
1001 if (clasp->isGlobal()) {
1002 return false;
1005 // WindowProxy, Wrapper, DeadProxyObject, DOMProxy, and DOMClass (non-global)
1006 // types may be swapped. It is hard to detect DOMProxy from shell, so target
1007 // proxies in general.
1008 return clasp->isProxyObject() || clasp->isDOMClass();
1011 bool NativeObject::prepareForSwap(JSContext* cx,
1012 MutableHandleValueVector slotValuesOut) {
1013 MOZ_ASSERT(slotValuesOut.empty());
1015 for (size_t i = 0; i < slotSpan(); i++) {
1016 if (!slotValuesOut.append(getSlot(i))) {
1017 return false;
1021 if (hasDynamicSlots()) {
1022 ObjectSlots* slotsHeader = getSlotsHeader();
1023 size_t size = ObjectSlots::allocSize(slotsHeader->capacity());
1024 RemoveCellMemory(this, size, MemoryUse::ObjectSlots);
1025 if (!cx->nursery().isInside(slotsHeader)) {
1026 if (!isTenured()) {
1027 cx->nursery().removeMallocedBuffer(slotsHeader, size);
1029 js_free(slotsHeader);
1031 setEmptyDynamicSlots(0);
1034 if (hasDynamicElements()) {
1035 ObjectElements* elements = getElementsHeader();
1036 void* allocatedElements = getUnshiftedElementsHeader();
1037 size_t count = elements->numAllocatedElements();
1038 size_t size = count * sizeof(HeapSlot);
1040 if (isTenured()) {
1041 RemoveCellMemory(this, size, MemoryUse::ObjectElements);
1042 } else if (cx->nursery().isInside(allocatedElements)) {
1043 // Move nursery allocated elements in case they end up in a tenured
1044 // object.
1045 ObjectElements* newElements =
1046 reinterpret_cast<ObjectElements*>(js_pod_malloc<HeapSlot>(count));
1047 if (!newElements) {
1048 return false;
1051 memmove(newElements, elements, size);
1052 elements_ = newElements->elements();
1053 } else {
1054 cx->nursery().removeMallocedBuffer(allocatedElements, size);
1056 MOZ_ASSERT(hasDynamicElements());
1059 return true;
1062 /* static */
1063 bool NativeObject::fixupAfterSwap(JSContext* cx, Handle<NativeObject*> obj,
1064 gc::AllocKind kind,
1065 HandleValueVector slotValues) {
1066 // This object has just been swapped with some other object, and its shape
1067 // no longer reflects its allocated size. Correct this information and
1068 // fill the slots in with the specified values.
1069 MOZ_ASSERT_IF(!obj->inDictionaryMode(),
1070 obj->slotSpan() == slotValues.length());
1072 // Make sure the shape's numFixedSlots() is correct.
1073 size_t nfixed = gc::GetGCKindSlots(kind);
1074 if (nfixed != obj->shape()->numFixedSlots()) {
1075 if (!NativeObject::changeNumFixedSlotsAfterSwap(cx, obj, nfixed)) {
1076 return false;
1078 MOZ_ASSERT(obj->shape()->numFixedSlots() == nfixed);
1081 uint32_t oldDictionarySlotSpan =
1082 obj->inDictionaryMode() ? slotValues.length() : 0;
1084 MOZ_ASSERT(!obj->hasUniqueId());
1085 size_t ndynamic =
1086 calculateDynamicSlots(nfixed, slotValues.length(), obj->getClass());
1087 size_t currentSlots = obj->getSlotsHeader()->capacity();
1088 MOZ_ASSERT(ndynamic >= currentSlots);
1089 if (ndynamic > currentSlots) {
1090 if (!obj->growSlots(cx, currentSlots, ndynamic)) {
1091 return false;
1095 if (obj->inDictionaryMode()) {
1096 obj->setDictionaryModeSlotSpan(oldDictionarySlotSpan);
1099 for (size_t i = 0, len = slotValues.length(); i < len; i++) {
1100 obj->initSlotUnchecked(i, slotValues[i]);
1103 if (obj->hasDynamicElements()) {
1104 ObjectElements* elements = obj->getElementsHeader();
1105 void* allocatedElements = obj->getUnshiftedElementsHeader();
1106 MOZ_ASSERT(!cx->nursery().isInside(allocatedElements));
1107 size_t size = elements->numAllocatedElements() * sizeof(HeapSlot);
1108 if (obj->isTenured()) {
1109 AddCellMemory(obj, size, MemoryUse::ObjectElements);
1110 } else if (!cx->nursery().registerMallocedBuffer(allocatedElements, size)) {
1111 return false;
1115 return true;
1118 [[nodiscard]] bool ProxyObject::prepareForSwap(
1119 JSContext* cx, MutableHandleValueVector valuesOut) {
1120 MOZ_ASSERT(valuesOut.empty());
1122 // Remove the GCPtr<Value>s we're about to swap from the store buffer, to
1123 // ensure we don't trace bogus values.
1124 gc::StoreBuffer& sb = cx->runtime()->gc.storeBuffer();
1126 // Reserve space for the expando, private slot and the reserved slots.
1127 if (!valuesOut.reserve(2 + numReservedSlots())) {
1128 return false;
1131 js::detail::ProxyValueArray* valArray = data.values();
1132 sb.unputValue(&valArray->expandoSlot);
1133 sb.unputValue(&valArray->privateSlot);
1134 valuesOut.infallibleAppend(valArray->expandoSlot);
1135 valuesOut.infallibleAppend(valArray->privateSlot);
1137 for (size_t i = 0; i < numReservedSlots(); i++) {
1138 sb.unputValue(&valArray->reservedSlots.slots[i]);
1139 valuesOut.infallibleAppend(valArray->reservedSlots.slots[i]);
1142 if (isTenured() && !usingInlineValueArray()) {
1143 size_t count = detail::ProxyValueArray::allocCount(numReservedSlots());
1144 RemoveCellMemory(this, count * sizeof(Value),
1145 MemoryUse::ProxyExternalValueArray);
1146 js_free(valArray);
1147 data.reservedSlots = nullptr;
1150 return true;
1153 bool ProxyObject::fixupAfterSwap(JSContext* cx,
1154 const HandleValueVector values) {
1155 MOZ_ASSERT(getClass()->isProxyObject());
1157 size_t nreserved = numReservedSlots();
1159 // |values| contains the expando slot, private slot and the reserved slots.
1160 MOZ_ASSERT(values.length() == 2 + nreserved);
1162 // Allocate the external value array in malloc memory, even for nursery
1163 // proxies.
1164 size_t count = detail::ProxyValueArray::allocCount(nreserved);
1165 auto* allocation = js_pod_malloc<JS::Value>(count);
1166 if (!allocation) {
1167 return false;
1170 size_t size = count * sizeof(Value);
1171 if (isTenured()) {
1172 AddCellMemory(&asTenured(), size, MemoryUse::ProxyExternalValueArray);
1173 } else if (!cx->nursery().registerMallocedBuffer(allocation, size)) {
1174 js_free(allocation);
1175 return false;
1178 auto* valArray = reinterpret_cast<js::detail::ProxyValueArray*>(allocation);
1180 valArray->expandoSlot = values[0];
1181 valArray->privateSlot = values[1];
1183 for (size_t i = 0; i < nreserved; i++) {
1184 valArray->reservedSlots.slots[i] = values[i + 2];
1187 data.reservedSlots = &valArray->reservedSlots;
1188 MOZ_ASSERT(!usingInlineValueArray());
1189 return true;
1192 #ifdef DEBUG
1193 static bool IsBackgroundFinalizedWhenTenured(JSObject* obj) {
1194 if (obj->isTenured()) {
1195 return gc::IsBackgroundFinalized(obj->asTenured().getAllocKind());
1198 if (obj->is<ProxyObject>()) {
1199 return gc::IsBackgroundFinalized(
1200 obj->as<ProxyObject>().allocKindForTenure());
1203 return js::gc::CanUseBackgroundAllocKind(obj->getClass());
1205 #endif
1207 static gc::AllocKind SwappableObjectAllocKind(JSObject* obj) {
1208 MOZ_ASSERT(ObjectMayBeSwapped(obj));
1210 if (obj->isTenured()) {
1211 return obj->asTenured().getAllocKind();
1214 if (obj->is<NativeObject>()) {
1215 return obj->as<NativeObject>().allocKindForTenure();
1218 return obj->as<ProxyObject>().allocKindForTenure();
1221 /* Use this method with extreme caution. It trades the guts of two objects. */
1222 void JSObject::swap(JSContext* cx, HandleObject a, HandleObject b,
1223 AutoEnterOOMUnsafeRegion& oomUnsafe) {
1224 // Ensure swap doesn't cause a finalizer to be run at the wrong time.
1225 MOZ_ASSERT(IsBackgroundFinalizedWhenTenured(a) ==
1226 IsBackgroundFinalizedWhenTenured(b));
1228 MOZ_ASSERT(a->compartment() == b->compartment());
1230 // You must have entered the objects' compartment before calling this.
1231 MOZ_ASSERT(cx->compartment() == a->compartment());
1233 // Only certain types of objects are allowed to be swapped. This allows the
1234 // JITs to better optimize objects that can never swap and rules out most
1235 // builtin objects that have special behaviour.
1236 MOZ_RELEASE_ASSERT(js::ObjectMayBeSwapped(a));
1237 MOZ_RELEASE_ASSERT(js::ObjectMayBeSwapped(b));
1239 if (!Watchtower::watchObjectSwap(cx, a, b)) {
1240 oomUnsafe.crash("watchObjectSwap");
1243 // Ensure we update any embedded nursery pointers in either object.
1244 gc::StoreBuffer& storeBuffer = cx->runtime()->gc.storeBuffer();
1245 if (a->isTenured()) {
1246 storeBuffer.putWholeCell(a);
1248 if (b->isTenured()) {
1249 storeBuffer.putWholeCell(b);
1251 if (a->isTenured() || b->isTenured()) {
1252 if (a->zone()->wasGCStarted()) {
1253 storeBuffer.setMayHavePointersToDeadCells();
1257 unsigned r = NotifyGCPreSwap(a, b);
1259 ProxyObject* pa = a->is<ProxyObject>() ? &a->as<ProxyObject>() : nullptr;
1260 ProxyObject* pb = b->is<ProxyObject>() ? &b->as<ProxyObject>() : nullptr;
1261 bool aIsProxyWithInlineValues = pa && pa->usingInlineValueArray();
1262 bool bIsProxyWithInlineValues = pb && pb->usingInlineValueArray();
1264 bool aIsUsedAsPrototype = a->isUsedAsPrototype();
1265 bool bIsUsedAsPrototype = b->isUsedAsPrototype();
1267 // Swap element associations.
1268 Zone* zone = a->zone();
1270 // Record any associated unique IDs and prepare for swap.
1272 // Note that unique IDs are NOT swapped but remain associated with the
1273 // original address.
1274 uint64_t aid = 0;
1275 uint64_t bid = 0;
1276 (void)gc::MaybeGetUniqueId(a, &aid);
1277 (void)gc::MaybeGetUniqueId(b, &bid);
1278 NativeObject* na = a->is<NativeObject>() ? &a->as<NativeObject>() : nullptr;
1279 NativeObject* nb = b->is<NativeObject>() ? &b->as<NativeObject>() : nullptr;
1280 if ((aid || bid) && (na || nb)) {
1281 // We can't remove unique IDs from native objects when they are swapped with
1282 // objects without an ID. Instead ensure they both have IDs so we always
1283 // have something to overwrite the old ID with.
1284 if (!gc::GetOrCreateUniqueId(a, &aid) ||
1285 !gc::GetOrCreateUniqueId(b, &bid)) {
1286 oomUnsafe.crash("Failed to create unique ID during swap");
1289 // IDs stored in NativeObjects could shadow those stored in the zone
1290 // table. Remove any zone table IDs first.
1291 if (pa && aid) {
1292 gc::RemoveUniqueId(a);
1294 if (pb && bid) {
1295 gc::RemoveUniqueId(b);
1299 gc::AllocKind ka = SwappableObjectAllocKind(a);
1300 gc::AllocKind kb = SwappableObjectAllocKind(b);
1302 size_t sa = gc::Arena::thingSize(ka);
1303 size_t sb = gc::Arena::thingSize(kb);
1304 if (sa == sb && a->isTenured() == b->isTenured()) {
1305 // When both objects are the same size and in the same heap, just do a plain
1306 // swap of their contents.
1308 // Swap slot associations.
1309 zone->swapCellMemory(a, b, MemoryUse::ObjectSlots);
1311 size_t size = sa;
1312 char tmp[sizeof(JSObject_Slots16)];
1313 MOZ_ASSERT(size <= sizeof(tmp));
1315 js_memcpy(tmp, a, size);
1316 js_memcpy(a, b, size);
1317 js_memcpy(b, tmp, size);
1319 zone->swapCellMemory(a, b, MemoryUse::ObjectElements);
1320 zone->swapCellMemory(a, b, MemoryUse::ProxyExternalValueArray);
1322 if (aIsProxyWithInlineValues) {
1323 b->as<ProxyObject>().setInlineValueArray();
1325 if (bIsProxyWithInlineValues) {
1326 a->as<ProxyObject>().setInlineValueArray();
1328 } else {
1329 // Avoid GC in here to avoid confusing the tracing code with our
1330 // intermediate state.
1331 gc::AutoSuppressGC suppress(cx);
1333 // When the objects have different sizes, they will have different numbers
1334 // of fixed slots before and after the swap, so the slots for native objects
1335 // will need to be rearranged. Remember the original values from the
1336 // objects.
1337 RootedValueVector avals(cx);
1338 RootedValueVector bvals(cx);
1339 if (na && !na->prepareForSwap(cx, &avals)) {
1340 oomUnsafe.crash("NativeObject::prepareForSwap");
1342 if (nb && !nb->prepareForSwap(cx, &bvals)) {
1343 oomUnsafe.crash("NativeObject::prepareForSwap");
1346 // Do the same for proxy value arrays.
1347 if (pa && !pa->prepareForSwap(cx, &avals)) {
1348 oomUnsafe.crash("ProxyObject::prepareForSwap");
1350 if (pb && !pb->prepareForSwap(cx, &bvals)) {
1351 oomUnsafe.crash("ProxyObject::prepareForSwap");
1354 // Swap the main fields of the objects, whether they are native objects or
1355 // proxies.
1356 char tmp[sizeof(JSObject_Slots0)];
1357 js_memcpy(&tmp, a, sizeof tmp);
1358 js_memcpy(a, b, sizeof tmp);
1359 js_memcpy(b, &tmp, sizeof tmp);
1361 if (na &&
1362 !NativeObject::fixupAfterSwap(cx, b.as<NativeObject>(), kb, avals)) {
1363 oomUnsafe.crash("NativeObject::fixupAfterSwap");
1365 if (nb &&
1366 !NativeObject::fixupAfterSwap(cx, a.as<NativeObject>(), ka, bvals)) {
1367 oomUnsafe.crash("NativeObject::fixupAfterSwap");
1370 if (pa && !b->as<ProxyObject>().fixupAfterSwap(cx, avals)) {
1371 oomUnsafe.crash("ProxyObject::fixupAfterSwap");
1373 if (pb && !a->as<ProxyObject>().fixupAfterSwap(cx, bvals)) {
1374 oomUnsafe.crash("ProxyObject::fixupAfterSwap");
1378 // Restore original unique IDs.
1379 if ((aid || bid) && (na || nb)) {
1380 if ((aid && !gc::SetOrUpdateUniqueId(cx, a, aid)) ||
1381 (bid && !gc::SetOrUpdateUniqueId(cx, b, bid))) {
1382 oomUnsafe.crash("Failed to set unique ID after swap");
1385 MOZ_ASSERT_IF(aid, gc::GetUniqueIdInfallible(a) == aid);
1386 MOZ_ASSERT_IF(bid, gc::GetUniqueIdInfallible(b) == bid);
1388 // Preserve the IsUsedAsPrototype flag on the objects.
1389 if (aIsUsedAsPrototype) {
1390 if (!JSObject::setIsUsedAsPrototype(cx, a)) {
1391 oomUnsafe.crash("setIsUsedAsPrototype");
1394 if (bIsUsedAsPrototype) {
1395 if (!JSObject::setIsUsedAsPrototype(cx, b)) {
1396 oomUnsafe.crash("setIsUsedAsPrototype");
1401 * We need a write barrier here. If |a| was marked and |b| was not, then
1402 * after the swap, |b|'s guts would never be marked. The write barrier
1403 * solves this.
1405 * Normally write barriers happen before the write. However, that's not
1406 * necessary here because nothing is being destroyed. We're just swapping.
1408 PreWriteBarrier(zone, a.get(), [](JSTracer* trc, JSObject* obj) {
1409 obj->traceChildren(trc);
1411 PreWriteBarrier(zone, b.get(), [](JSTracer* trc, JSObject* obj) {
1412 obj->traceChildren(trc);
1415 NotifyGCPostSwap(a, b, r);
1418 static NativeObject* DefineConstructorAndPrototype(
1419 JSContext* cx, HandleObject obj, Handle<JSAtom*> atom,
1420 HandleObject protoProto, const JSClass* clasp, Native constructor,
1421 unsigned nargs, const JSPropertySpec* ps, const JSFunctionSpec* fs,
1422 const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs,
1423 NativeObject** ctorp) {
1424 // Create the prototype object.
1425 Rooted<NativeObject*> proto(
1426 cx, GlobalObject::createBlankPrototypeInheriting(cx, clasp, protoProto));
1427 if (!proto) {
1428 return nullptr;
1431 Rooted<NativeObject*> ctor(cx);
1432 if (!constructor) {
1433 ctor = proto;
1434 } else {
1435 ctor = NewNativeConstructor(cx, constructor, nargs, atom);
1436 if (!ctor) {
1437 return nullptr;
1440 if (!LinkConstructorAndPrototype(cx, ctor, proto)) {
1441 return nullptr;
1445 if (!DefinePropertiesAndFunctions(cx, proto, ps, fs) ||
1446 (ctor != proto &&
1447 !DefinePropertiesAndFunctions(cx, ctor, static_ps, static_fs))) {
1448 return nullptr;
1451 RootedId id(cx, AtomToId(atom));
1452 RootedValue value(cx, ObjectValue(*ctor));
1453 if (!DefineDataProperty(cx, obj, id, value, 0)) {
1454 return nullptr;
1457 if (ctorp) {
1458 *ctorp = ctor;
1460 return proto;
1463 NativeObject* js::InitClass(JSContext* cx, HandleObject obj,
1464 const JSClass* protoClass, HandleObject protoProto_,
1465 const char* name, Native constructor,
1466 unsigned nargs, const JSPropertySpec* ps,
1467 const JSFunctionSpec* fs,
1468 const JSPropertySpec* static_ps,
1469 const JSFunctionSpec* static_fs,
1470 NativeObject** ctorp) {
1471 Rooted<JSAtom*> atom(cx, Atomize(cx, name, strlen(name)));
1472 if (!atom) {
1473 return nullptr;
1477 * All instances of the class will inherit properties from the prototype
1478 * object we are about to create (in DefineConstructorAndPrototype), which
1479 * in turn will inherit from protoProto.
1481 * If protoProto is nullptr, default to Object.prototype.
1482 * If protoClass is nullptr, default to PlainObject.
1484 RootedObject protoProto(cx, protoProto_);
1485 if (!protoProto) {
1486 protoProto = &cx->global()->getObjectPrototype();
1488 if (!protoClass) {
1489 protoClass = &PlainObject::class_;
1492 return DefineConstructorAndPrototype(cx, obj, atom, protoProto, protoClass,
1493 constructor, nargs, ps, fs, static_ps,
1494 static_fs, ctorp);
1498 * Returns the original Object.prototype from the embedding-provided incumbent
1499 * global.
1501 * Really, we want the incumbent global itself so we can pass it to other
1502 * embedding hooks which need it. Specifically, the enqueue promise hook
1503 * takes an incumbent global so it can set that on the PromiseCallbackJob
1504 * it creates.
1506 * The reason for not just returning the global itself is that we'd need to
1507 * wrap it into the current compartment, and later unwrap it. Unwrapping
1508 * globals is tricky, though: we might accidentally unwrap through an inner
1509 * to its outer window and end up with the wrong global. Plain objects don't
1510 * have this problem, so we use the global's Object.prototype. The code using
1511 * it - e.g. EnqueuePromiseReactionJob - can then unwrap the object and get
1512 * its global without fear of unwrapping too far.
1514 bool js::GetObjectFromIncumbentGlobal(JSContext* cx, MutableHandleObject obj) {
1515 Rooted<GlobalObject*> globalObj(cx, cx->runtime()->getIncumbentGlobal(cx));
1516 if (!globalObj) {
1517 obj.set(nullptr);
1518 return true;
1521 obj.set(&globalObj->getObjectPrototype());
1523 // The object might be from a different compartment, so wrap it.
1524 if (obj && !cx->compartment()->wrap(cx, obj)) {
1525 return false;
1528 return true;
1531 static bool IsStandardPrototype(JSObject* obj, JSProtoKey key) {
1532 return obj->nonCCWGlobal().maybeGetPrototype(key) == obj;
1535 JSProtoKey JS::IdentifyStandardInstance(JSObject* obj) {
1536 // Note: The prototype shares its JSClass with instances.
1537 MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
1538 JSProtoKey key = StandardProtoKeyOrNull(obj);
1539 if (key != JSProto_Null && !IsStandardPrototype(obj, key)) {
1540 return key;
1542 return JSProto_Null;
1545 JSProtoKey JS::IdentifyStandardPrototype(JSObject* obj) {
1546 // Note: The prototype shares its JSClass with instances.
1547 MOZ_ASSERT(!obj->is<CrossCompartmentWrapperObject>());
1548 JSProtoKey key = StandardProtoKeyOrNull(obj);
1549 if (key != JSProto_Null && IsStandardPrototype(obj, key)) {
1550 return key;
1552 return JSProto_Null;
1555 JSProtoKey JS::IdentifyStandardInstanceOrPrototype(JSObject* obj) {
1556 return StandardProtoKeyOrNull(obj);
1559 JSProtoKey JS::IdentifyStandardConstructor(JSObject* obj) {
1560 // Note that isNativeConstructor does not imply that we are a standard
1561 // constructor, but the converse is true (at least until we start having
1562 // self-hosted constructors for standard classes). This lets us avoid a costly
1563 // loop for many functions (which, depending on the call site, may be the
1564 // common case).
1565 if (!obj->is<JSFunction>() ||
1566 !(obj->as<JSFunction>().flags().isNativeConstructor())) {
1567 return JSProto_Null;
1570 static_assert(JSProto_Null == 0,
1571 "Loop below can start at 1 to skip JSProto_Null");
1573 GlobalObject& global = obj->as<JSFunction>().global();
1574 for (size_t k = 1; k < JSProto_LIMIT; ++k) {
1575 JSProtoKey key = static_cast<JSProtoKey>(k);
1576 if (global.maybeGetConstructor(key) == obj) {
1577 return key;
1581 return JSProto_Null;
1584 bool js::LookupProperty(JSContext* cx, HandleObject obj, js::HandleId id,
1585 MutableHandleObject objp, PropertyResult* propp) {
1586 if (LookupPropertyOp op = obj->getOpsLookupProperty()) {
1587 return op(cx, obj, id, objp, propp);
1589 return NativeLookupPropertyInline<CanGC>(cx, obj.as<NativeObject>(), id, objp,
1590 propp);
1593 bool js::LookupName(JSContext* cx, Handle<PropertyName*> name,
1594 HandleObject envChain, MutableHandleObject objp,
1595 MutableHandleObject pobjp, PropertyResult* propp) {
1596 RootedId id(cx, NameToId(name));
1598 for (RootedObject env(cx, envChain); env; env = env->enclosingEnvironment()) {
1599 if (!LookupProperty(cx, env, id, pobjp, propp)) {
1600 return false;
1602 if (propp->isFound()) {
1603 objp.set(env);
1604 return true;
1608 objp.set(nullptr);
1609 pobjp.set(nullptr);
1610 propp->setNotFound();
1611 return true;
1614 bool js::LookupNameNoGC(JSContext* cx, PropertyName* name, JSObject* envChain,
1615 JSObject** objp, NativeObject** pobjp,
1616 PropertyResult* propp) {
1617 AutoAssertNoPendingException nogc(cx);
1619 MOZ_ASSERT(!*objp && !*pobjp && propp->isNotFound());
1621 for (JSObject* env = envChain; env; env = env->enclosingEnvironment()) {
1622 if (env->getOpsLookupProperty()) {
1623 return false;
1625 if (!NativeLookupPropertyInline<NoGC>(cx, &env->as<NativeObject>(),
1626 NameToId(name), pobjp, propp)) {
1627 return false;
1629 if (propp->isFound()) {
1630 *objp = env;
1631 return true;
1635 return true;
1638 bool js::LookupNameWithGlobalDefault(JSContext* cx, Handle<PropertyName*> name,
1639 HandleObject envChain,
1640 MutableHandleObject objp) {
1641 RootedId id(cx, NameToId(name));
1643 RootedObject pobj(cx);
1644 PropertyResult prop;
1646 RootedObject env(cx, envChain);
1647 for (; !env->is<GlobalObject>(); env = env->enclosingEnvironment()) {
1648 if (!LookupProperty(cx, env, id, &pobj, &prop)) {
1649 return false;
1651 if (prop.isFound()) {
1652 break;
1656 objp.set(env);
1657 return true;
1660 bool js::LookupNameUnqualified(JSContext* cx, Handle<PropertyName*> name,
1661 HandleObject envChain,
1662 MutableHandleObject objp) {
1663 RootedId id(cx, NameToId(name));
1665 RootedObject pobj(cx);
1666 PropertyResult prop;
1668 RootedObject env(cx, envChain);
1669 for (; !env->isUnqualifiedVarObj(); env = env->enclosingEnvironment()) {
1670 if (!LookupProperty(cx, env, id, &pobj, &prop)) {
1671 return false;
1673 if (prop.isFound()) {
1674 break;
1678 // See note above RuntimeLexicalErrorObject.
1679 if (pobj == env) {
1680 bool isTDZ = false;
1681 if (prop.isFound() && name != cx->names().dotThis) {
1682 // Treat Debugger environments specially for TDZ checks, as they
1683 // look like non-native environments but in fact wrap native
1684 // environments.
1685 if (env->is<DebugEnvironmentProxy>()) {
1686 RootedValue v(cx);
1687 Rooted<DebugEnvironmentProxy*> envProxy(
1688 cx, &env->as<DebugEnvironmentProxy>());
1689 if (!DebugEnvironmentProxy::getMaybeSentinelValue(cx, envProxy, id,
1690 &v)) {
1691 return false;
1693 isTDZ = IsUninitializedLexical(v);
1694 } else {
1695 isTDZ = IsUninitializedLexicalSlot(env, prop);
1699 if (isTDZ) {
1700 env = RuntimeLexicalErrorObject::create(cx, env,
1701 JSMSG_UNINITIALIZED_LEXICAL);
1702 if (!env) {
1703 return false;
1705 } else if (env->is<LexicalEnvironmentObject>() &&
1706 !prop.propertyInfo().writable()) {
1707 // Assigning to a named lambda callee name is a no-op in sloppy mode.
1708 if (!(env->is<BlockLexicalEnvironmentObject>() &&
1709 env->as<BlockLexicalEnvironmentObject>().scope().kind() ==
1710 ScopeKind::NamedLambda)) {
1711 MOZ_ASSERT(name != cx->names().dotThis);
1712 env =
1713 RuntimeLexicalErrorObject::create(cx, env, JSMSG_BAD_CONST_ASSIGN);
1714 if (!env) {
1715 return false;
1721 objp.set(env);
1722 return true;
1725 bool js::HasOwnProperty(JSContext* cx, HandleObject obj, HandleId id,
1726 bool* result) {
1727 if (obj->is<ProxyObject>()) {
1728 return Proxy::hasOwn(cx, obj, id, result);
1731 if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
1732 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
1733 if (!op(cx, obj, id, &desc)) {
1734 return false;
1736 *result = desc.isSome();
1737 return true;
1740 PropertyResult prop;
1741 if (!NativeLookupOwnProperty<CanGC>(cx, obj.as<NativeObject>(), id, &prop)) {
1742 return false;
1744 *result = prop.isFound();
1745 return true;
1748 bool js::LookupPropertyPure(JSContext* cx, JSObject* obj, jsid id,
1749 NativeObject** objp, PropertyResult* propp) {
1750 if (obj->getOpsLookupProperty()) {
1751 return false;
1753 return NativeLookupPropertyInline<NoGC, LookupResolveMode::CheckMayResolve>(
1754 cx, &obj->as<NativeObject>(), id, objp, propp);
1757 bool js::LookupOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id,
1758 PropertyResult* propp) {
1759 if (obj->getOpsLookupProperty()) {
1760 return false;
1762 return NativeLookupOwnPropertyInline<NoGC,
1763 LookupResolveMode::CheckMayResolve>(
1764 cx, &obj->as<NativeObject>(), id, propp);
1767 static inline bool NativeGetPureInline(NativeObject* pobj, jsid id,
1768 PropertyResult prop, Value* vp,
1769 JSContext* cx) {
1770 if (prop.isDenseElement()) {
1771 *vp = pobj->getDenseElement(prop.denseElementIndex());
1772 return true;
1774 if (prop.isTypedArrayElement()) {
1775 size_t idx = prop.typedArrayElementIndex();
1776 return pobj->as<TypedArrayObject>().getElement<NoGC>(cx, idx, vp);
1779 // Fail if we have a custom getter.
1780 PropertyInfo propInfo = prop.propertyInfo();
1781 if (!propInfo.isDataProperty()) {
1782 return false;
1785 *vp = pobj->getSlot(propInfo.slot());
1786 MOZ_ASSERT(!vp->isMagic());
1787 return true;
1790 bool js::GetPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp) {
1791 NativeObject* pobj;
1792 PropertyResult prop;
1793 if (!LookupPropertyPure(cx, obj, id, &pobj, &prop)) {
1794 return false;
1797 if (prop.isNotFound()) {
1798 vp->setUndefined();
1799 return true;
1802 return NativeGetPureInline(pobj, id, prop, vp, cx);
1805 bool js::GetOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp,
1806 bool* found) {
1807 PropertyResult prop;
1808 if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
1809 return false;
1812 if (prop.isNotFound()) {
1813 *found = false;
1814 vp->setUndefined();
1815 return true;
1818 *found = true;
1819 return obj->is<NativeObject>() &&
1820 NativeGetPureInline(&obj->as<NativeObject>(), id, prop, vp, cx);
1823 static inline bool NativeGetGetterPureInline(NativeObject* holder,
1824 PropertyResult prop,
1825 JSFunction** fp) {
1826 MOZ_ASSERT(prop.isNativeProperty());
1828 PropertyInfo propInfo = prop.propertyInfo();
1829 if (holder->hasGetter(propInfo)) {
1830 JSObject* getter = holder->getGetter(propInfo);
1831 if (getter->is<JSFunction>()) {
1832 *fp = &getter->as<JSFunction>();
1833 return true;
1837 *fp = nullptr;
1838 return true;
1841 bool js::GetGetterPure(JSContext* cx, JSObject* obj, jsid id, JSFunction** fp) {
1842 /* Just like GetPropertyPure, but get getter function, without invoking
1843 * it. */
1844 NativeObject* pobj;
1845 PropertyResult prop;
1846 if (!LookupPropertyPure(cx, obj, id, &pobj, &prop)) {
1847 return false;
1850 if (prop.isNotFound()) {
1851 *fp = nullptr;
1852 return true;
1855 return prop.isNativeProperty() && NativeGetGetterPureInline(pobj, prop, fp);
1858 bool js::GetOwnGetterPure(JSContext* cx, JSObject* obj, jsid id,
1859 JSFunction** fp) {
1860 JS::AutoCheckCannotGC nogc;
1861 PropertyResult prop;
1862 if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
1863 return false;
1866 if (prop.isNotFound()) {
1867 *fp = nullptr;
1868 return true;
1871 return prop.isNativeProperty() &&
1872 NativeGetGetterPureInline(&obj->as<NativeObject>(), prop, fp);
1875 bool js::GetOwnNativeGetterPure(JSContext* cx, JSObject* obj, jsid id,
1876 JSNative* native) {
1877 JS::AutoCheckCannotGC nogc;
1878 *native = nullptr;
1879 PropertyResult prop;
1880 if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
1881 return false;
1884 if (!prop.isNativeProperty()) {
1885 return true;
1888 PropertyInfo propInfo = prop.propertyInfo();
1890 NativeObject* nobj = &obj->as<NativeObject>();
1891 if (!nobj->hasGetter(propInfo)) {
1892 return true;
1895 JSObject* getterObj = nobj->getGetter(propInfo);
1896 if (!getterObj->is<JSFunction>()) {
1897 return true;
1900 JSFunction* getter = &getterObj->as<JSFunction>();
1901 if (!getter->isNativeFun()) {
1902 return true;
1905 *native = getter->native();
1906 return true;
1909 bool js::HasOwnDataPropertyPure(JSContext* cx, JSObject* obj, jsid id,
1910 bool* result) {
1911 PropertyResult prop;
1912 if (!LookupOwnPropertyPure(cx, obj, id, &prop)) {
1913 return false;
1916 *result = prop.isNativeProperty() && prop.propertyInfo().isDataProperty();
1917 return true;
1920 bool js::GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
1921 bool* isOrdinary, MutableHandleObject protop) {
1922 if (obj->is<js::ProxyObject>()) {
1923 return js::Proxy::getPrototypeIfOrdinary(cx, obj, isOrdinary, protop);
1926 *isOrdinary = true;
1927 protop.set(obj->staticPrototype());
1928 return true;
1931 /*** ES6 standard internal methods ******************************************/
1933 bool js::SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto,
1934 JS::ObjectOpResult& result) {
1935 // The proxy trap subsystem fully handles prototype-setting for proxies
1936 // with dynamic [[Prototype]]s.
1937 if (obj->hasDynamicPrototype()) {
1938 MOZ_ASSERT(obj->is<ProxyObject>());
1939 return Proxy::setPrototype(cx, obj, proto, result);
1943 * ES6 9.1.2 step 3-4 if |obj.[[Prototype]]| has SameValue as |proto| return
1944 * true. Since the values in question are objects, we can just compare
1945 * pointers.
1947 if (proto == obj->staticPrototype()) {
1948 return result.succeed();
1951 /* Disallow mutation of immutable [[Prototype]]s. */
1952 if (obj->staticPrototypeIsImmutable()) {
1953 return result.fail(JSMSG_CANT_SET_PROTO);
1957 * Disallow mutating the [[Prototype]] on Typed Objects, per the spec.
1959 if (obj->is<WasmGcObject>()) {
1960 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1961 JSMSG_CANT_SET_PROTO_OF,
1962 "incompatible WebAssembly object");
1963 return false;
1966 /* ES6 9.1.2 step 5 forbids changing [[Prototype]] if not [[Extensible]]. */
1967 bool extensible;
1968 if (!IsExtensible(cx, obj, &extensible)) {
1969 return false;
1971 if (!extensible) {
1972 return result.fail(JSMSG_CANT_SET_PROTO);
1976 * ES6 9.1.2 step 6 forbids generating cyclical prototype chains. But we
1977 * have to do this comparison on the observable WindowProxy, not on the
1978 * possibly-Window object we're setting the proto on.
1980 RootedObject objMaybeWindowProxy(cx, ToWindowProxyIfWindow(obj));
1981 RootedObject obj2(cx, proto);
1982 while (obj2) {
1983 MOZ_ASSERT(!IsWindow(obj2));
1984 if (obj2 == objMaybeWindowProxy) {
1985 return result.fail(JSMSG_CANT_SET_PROTO_CYCLE);
1988 bool isOrdinary;
1989 if (!GetPrototypeIfOrdinary(cx, obj2, &isOrdinary, &obj2)) {
1990 return false;
1992 if (!isOrdinary) {
1993 break;
1997 Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
1998 if (!JSObject::setProtoUnchecked(cx, obj, taggedProto)) {
1999 return false;
2002 return result.succeed();
2005 bool js::SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto) {
2006 ObjectOpResult result;
2007 return SetPrototype(cx, obj, proto, result) && result.checkStrict(cx, obj);
2010 bool js::PreventExtensions(JSContext* cx, HandleObject obj,
2011 ObjectOpResult& result) {
2012 if (obj->is<ProxyObject>()) {
2013 return js::Proxy::preventExtensions(cx, obj, result);
2016 if (!obj->nonProxyIsExtensible()) {
2017 // If the following assertion fails, there's somewhere else a missing
2018 // call to shrinkCapacityToInitializedLength() which needs to be found
2019 // and fixed.
2020 MOZ_ASSERT_IF(obj->is<NativeObject>(),
2021 obj->as<NativeObject>().getDenseInitializedLength() ==
2022 obj->as<NativeObject>().getDenseCapacity());
2024 return result.succeed();
2027 if (obj->is<NativeObject>()) {
2028 // Force lazy properties to be resolved.
2029 Handle<NativeObject*> nobj = obj.as<NativeObject>();
2030 if (!ResolveLazyProperties(cx, nobj)) {
2031 return false;
2034 // Prepare the elements. We have to do this before we mark the object
2035 // non-extensible; that's fine because these changes are not observable.
2036 ObjectElements::PrepareForPreventExtensions(cx, nobj);
2039 // Finally, set the NotExtensible flag on the Shape and ObjectElements.
2040 if (!JSObject::setFlag(cx, obj, ObjectFlag::NotExtensible)) {
2041 return false;
2043 if (obj->is<NativeObject>()) {
2044 ObjectElements::PreventExtensions(&obj->as<NativeObject>());
2047 return result.succeed();
2050 bool js::PreventExtensions(JSContext* cx, HandleObject obj) {
2051 ObjectOpResult result;
2052 return PreventExtensions(cx, obj, result) && result.checkStrict(cx, obj);
2055 bool js::GetOwnPropertyDescriptor(
2056 JSContext* cx, HandleObject obj, HandleId id,
2057 MutableHandle<Maybe<PropertyDescriptor>> desc) {
2058 if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
2059 bool ok = op(cx, obj, id, desc);
2060 if (ok && desc.isSome()) {
2061 desc->assertComplete();
2063 return ok;
2066 return NativeGetOwnPropertyDescriptor(cx, obj.as<NativeObject>(), id, desc);
2069 bool js::DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
2070 Handle<PropertyDescriptor> desc) {
2071 ObjectOpResult result;
2072 return DefineProperty(cx, obj, id, desc, result) &&
2073 result.checkStrict(cx, obj, id);
2076 bool js::DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
2077 Handle<PropertyDescriptor> desc,
2078 ObjectOpResult& result) {
2079 desc.assertValid();
2080 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2081 return op(cx, obj, id, desc, result);
2083 return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
2086 bool js::DefineAccessorProperty(JSContext* cx, HandleObject obj, HandleId id,
2087 HandleObject getter, HandleObject setter,
2088 unsigned attrs, ObjectOpResult& result) {
2089 Rooted<PropertyDescriptor> desc(
2090 cx, PropertyDescriptor::Accessor(
2091 getter ? mozilla::Some(getter) : mozilla::Nothing(),
2092 setter ? mozilla::Some(setter) : mozilla::Nothing(), attrs));
2094 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2095 MOZ_ASSERT(!cx->isHelperThreadContext());
2096 return op(cx, obj, id, desc, result);
2098 return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
2101 bool js::DefineDataProperty(JSContext* cx, HandleObject obj, HandleId id,
2102 HandleValue value, unsigned attrs,
2103 ObjectOpResult& result) {
2104 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Data(value, attrs));
2105 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2106 MOZ_ASSERT(!cx->isHelperThreadContext());
2107 return op(cx, obj, id, desc, result);
2109 return NativeDefineProperty(cx, obj.as<NativeObject>(), id, desc, result);
2112 bool js::DefineAccessorProperty(JSContext* cx, HandleObject obj, HandleId id,
2113 HandleObject getter, HandleObject setter,
2114 unsigned attrs) {
2115 ObjectOpResult result;
2116 if (!DefineAccessorProperty(cx, obj, id, getter, setter, attrs, result)) {
2117 return false;
2119 if (!result) {
2120 MOZ_ASSERT(!cx->isHelperThreadContext());
2121 result.reportError(cx, obj, id);
2122 return false;
2124 return true;
2127 bool js::DefineDataProperty(JSContext* cx, HandleObject obj, HandleId id,
2128 HandleValue value, unsigned attrs) {
2129 ObjectOpResult result;
2130 if (!DefineDataProperty(cx, obj, id, value, attrs, result)) {
2131 return false;
2133 if (!result) {
2134 MOZ_ASSERT(!cx->isHelperThreadContext());
2135 result.reportError(cx, obj, id);
2136 return false;
2138 return true;
2141 bool js::DefineDataProperty(JSContext* cx, HandleObject obj, PropertyName* name,
2142 HandleValue value, unsigned attrs) {
2143 RootedId id(cx, NameToId(name));
2144 return DefineDataProperty(cx, obj, id, value, attrs);
2147 bool js::DefineDataElement(JSContext* cx, HandleObject obj, uint32_t index,
2148 HandleValue value, unsigned attrs) {
2149 RootedId id(cx);
2150 if (!IndexToId(cx, index, &id)) {
2151 return false;
2153 return DefineDataProperty(cx, obj, id, value, attrs);
2156 /*** SpiderMonkey nonstandard internal methods ******************************/
2158 // Mark an object as having an immutable prototype
2160 // NOTE: This does not correspond to the SetImmutablePrototype ECMAScript
2161 // method.
2162 bool js::SetImmutablePrototype(JSContext* cx, HandleObject obj,
2163 bool* succeeded) {
2164 if (obj->hasDynamicPrototype()) {
2165 MOZ_ASSERT(!cx->isHelperThreadContext());
2166 return Proxy::setImmutablePrototype(cx, obj, succeeded);
2169 if (!JSObject::setFlag(cx, obj, ObjectFlag::ImmutablePrototype)) {
2170 return false;
2172 *succeeded = true;
2173 return true;
2176 bool js::GetPropertyDescriptor(
2177 JSContext* cx, HandleObject obj, HandleId id,
2178 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc,
2179 MutableHandleObject holder) {
2180 RootedObject pobj(cx);
2181 for (pobj = obj; pobj;) {
2182 if (!GetOwnPropertyDescriptor(cx, pobj, id, desc)) {
2183 return false;
2186 if (desc.isSome()) {
2187 holder.set(pobj);
2188 return true;
2191 if (!GetPrototype(cx, pobj, &pobj)) {
2192 return false;
2196 MOZ_ASSERT(desc.isNothing());
2197 holder.set(nullptr);
2198 return true;
2201 /* * */
2203 extern bool PropertySpecNameToId(JSContext* cx, JSPropertySpec::Name name,
2204 MutableHandleId id);
2206 // If a property or method is part of an experimental feature that can be
2207 // disabled at run-time by a preference, we keep it in the JSFunctionSpec /
2208 // JSPropertySpec list, but omit the definition if the preference is off.
2209 JS_PUBLIC_API bool js::ShouldIgnorePropertyDefinition(JSContext* cx,
2210 JSProtoKey key, jsid id) {
2211 if (!cx->realm()->creationOptions().getToSourceEnabled() &&
2212 (id == NameToId(cx->names().toSource) ||
2213 id == NameToId(cx->names().uneval))) {
2214 return true;
2217 if (key == JSProto_FinalizationRegistry &&
2218 cx->realm()->creationOptions().getWeakRefsEnabled() ==
2219 JS::WeakRefSpecifier::EnabledWithoutCleanupSome &&
2220 id == NameToId(cx->names().cleanupSome)) {
2221 return true;
2224 #ifdef NIGHTLY_BUILD
2225 if (key == JSProto_Array &&
2226 !cx->realm()->creationOptions().getArrayGroupingEnabled() &&
2227 (id == NameToId(cx->names().group) ||
2228 id == NameToId(cx->names().groupToMap))) {
2229 return true;
2231 #endif
2233 // It's gently surprising that this is JSProto_Function, but the trick
2234 // to realize is that this is a -constructor function-, not a function
2235 // on the prototype; and the proto of the constructor is JSProto_Function.
2236 if (key == JSProto_Function &&
2237 !cx->realm()->creationOptions().getArrayFromAsyncEnabled() &&
2238 id == NameToId(cx->names().fromAsync)) {
2239 return true;
2242 if (key == JSProto_Array &&
2243 !cx->realm()->creationOptions().getChangeArrayByCopyEnabled() &&
2244 (id == NameToId(cx->names().with) ||
2245 id == NameToId(cx->names().toReversed) ||
2246 id == NameToId(cx->names().toSorted) ||
2247 id == NameToId(cx->names().toSpliced))) {
2248 return true;
2251 if (key == JSProto_TypedArray &&
2252 !cx->realm()->creationOptions().getChangeArrayByCopyEnabled() &&
2253 (id == NameToId(cx->names().with) ||
2254 id == NameToId(cx->names().toReversed) ||
2255 id == NameToId(cx->names().toSorted))) {
2256 return true;
2259 #ifdef ENABLE_NEW_SET_METHODS
2260 if (key == JSProto_Set &&
2261 !cx->realm()->creationOptions().getNewSetMethodsEnabled() &&
2262 (id == NameToId(cx->names().union_) ||
2263 id == NameToId(cx->names().difference) ||
2264 id == NameToId(cx->names().intersection) ||
2265 id == NameToId(cx->names().isSubsetOf) ||
2266 id == NameToId(cx->names().isSupersetOf) ||
2267 id == NameToId(cx->names().isDisjointFrom) ||
2268 id == NameToId(cx->names().symmetricDifference))) {
2269 return true;
2271 #endif
2273 return false;
2276 static bool DefineFunctionFromSpec(JSContext* cx, HandleObject obj,
2277 const JSFunctionSpec* fs) {
2278 RootedId id(cx);
2279 if (!PropertySpecNameToId(cx, fs->name, &id)) {
2280 return false;
2283 if (ShouldIgnorePropertyDefinition(cx, StandardProtoKeyOrNull(obj), id)) {
2284 return true;
2287 JSFunction* fun = NewFunctionFromSpec(cx, fs, id);
2288 if (!fun) {
2289 return false;
2292 RootedValue funVal(cx, ObjectValue(*fun));
2293 return DefineDataProperty(cx, obj, id, funVal, fs->flags & ~JSFUN_FLAGS_MASK);
2296 bool js::DefineFunctions(JSContext* cx, HandleObject obj,
2297 const JSFunctionSpec* fs) {
2298 for (; fs->name; fs++) {
2299 if (!DefineFunctionFromSpec(cx, obj, fs)) {
2300 return false;
2303 return true;
2306 /*** ToPrimitive ************************************************************/
2309 * Gets |obj[id]|. If that value's not callable, returns true and stores an
2310 * object value in *vp. If it's callable, calls it with no arguments and |obj|
2311 * as |this|, returning the result in *vp.
2313 * This is a mini-abstraction for ES6 draft rev 36 (2015 Mar 17),
2314 * 7.1.1, second algorithm (OrdinaryToPrimitive), steps 5.a-c.
2316 static bool MaybeCallMethod(JSContext* cx, HandleObject obj, HandleId id,
2317 MutableHandleValue vp) {
2318 if (!GetProperty(cx, obj, obj, id, vp)) {
2319 return false;
2321 if (!IsCallable(vp)) {
2322 vp.setObject(*obj);
2323 return true;
2326 return js::Call(cx, vp, obj, vp);
2329 static bool ReportCantConvert(JSContext* cx, unsigned errorNumber,
2330 HandleObject obj, JSType hint) {
2331 const JSClass* clasp = obj->getClass();
2333 // Avoid recursive death when decompiling in ReportValueError.
2334 RootedString str(cx);
2335 if (hint == JSTYPE_STRING) {
2336 str = JS_AtomizeString(cx, clasp->name);
2337 if (!str) {
2338 return false;
2340 } else {
2341 str = nullptr;
2344 RootedValue val(cx, ObjectValue(*obj));
2345 ReportValueError(cx, errorNumber, JSDVG_SEARCH_STACK, val, str,
2346 hint == JSTYPE_UNDEFINED ? "primitive type"
2347 : hint == JSTYPE_STRING ? "string"
2348 : "number");
2349 return false;
2352 bool JS::OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
2353 MutableHandleValue vp) {
2354 MOZ_ASSERT(hint == JSTYPE_NUMBER || hint == JSTYPE_STRING ||
2355 hint == JSTYPE_UNDEFINED);
2357 Rooted<jsid> id(cx);
2359 const JSClass* clasp = obj->getClass();
2360 if (hint == JSTYPE_STRING) {
2361 id = NameToId(cx->names().toString);
2363 bool calledToString = false;
2364 if (clasp == &StringObject::class_) {
2365 // Optimize (new String(...)).toString().
2366 StringObject* nobj = &obj->as<StringObject>();
2367 if (HasNativeMethodPure(nobj, cx->names().toString, str_toString, cx)) {
2368 vp.setString(nobj->unbox());
2369 return true;
2371 } else if (clasp == &PlainObject::class_) {
2372 JSFunction* fun;
2373 if (GetPropertyPure(cx, obj, id, vp.address()) &&
2374 IsFunctionObject(vp, &fun)) {
2375 // Common case: we have a toString function. Try to short-circuit if
2376 // it's Object.prototype.toString and there's no @@toStringTag.
2377 if (fun->maybeNative() == obj_toString &&
2378 !MaybeHasInterestingSymbolProperty(
2379 cx, obj, cx->wellKnownSymbols().toStringTag)) {
2380 vp.setString(cx->names().objectObject);
2381 return true;
2383 if (!js::Call(cx, vp, obj, vp)) {
2384 return false;
2386 calledToString = true;
2390 if (!calledToString) {
2391 if (!MaybeCallMethod(cx, obj, id, vp)) {
2392 return false;
2395 if (vp.isPrimitive()) {
2396 return true;
2399 id = NameToId(cx->names().valueOf);
2400 if (!MaybeCallMethod(cx, obj, id, vp)) {
2401 return false;
2403 if (vp.isPrimitive()) {
2404 return true;
2406 } else {
2407 id = NameToId(cx->names().valueOf);
2409 if (clasp == &StringObject::class_) {
2410 // Optimize new String(...).valueOf().
2411 StringObject* nobj = &obj->as<StringObject>();
2412 if (HasNativeMethodPure(nobj, cx->names().valueOf, str_toString, cx)) {
2413 vp.setString(nobj->unbox());
2414 return true;
2416 } else if (clasp == &NumberObject::class_) {
2417 // Optimize new Number(...).valueOf().
2418 NumberObject* nobj = &obj->as<NumberObject>();
2419 if (HasNativeMethodPure(nobj, cx->names().valueOf, num_valueOf, cx)) {
2420 vp.setNumber(nobj->unbox());
2421 return true;
2425 if (!MaybeCallMethod(cx, obj, id, vp)) {
2426 return false;
2428 if (vp.isPrimitive()) {
2429 return true;
2432 id = NameToId(cx->names().toString);
2433 if (!MaybeCallMethod(cx, obj, id, vp)) {
2434 return false;
2436 if (vp.isPrimitive()) {
2437 return true;
2441 return ReportCantConvert(cx, JSMSG_CANT_CONVERT_TO, obj, hint);
2444 bool js::ToPrimitiveSlow(JSContext* cx, JSType preferredType,
2445 MutableHandleValue vp) {
2446 // Step numbers refer to the first algorithm listed in ES6 draft rev 36
2447 // (2015 Mar 17) 7.1.1 ToPrimitive.
2448 MOZ_ASSERT(preferredType == JSTYPE_UNDEFINED ||
2449 preferredType == JSTYPE_STRING || preferredType == JSTYPE_NUMBER);
2450 RootedObject obj(cx, &vp.toObject());
2452 // Steps 4-5.
2453 RootedValue method(cx);
2454 if (!GetInterestingSymbolProperty(cx, obj, cx->wellKnownSymbols().toPrimitive,
2455 &method)) {
2456 return false;
2459 // Step 6.
2460 if (!method.isNullOrUndefined()) {
2461 // Step 6 of GetMethod. js::Call() below would do this check and throw a
2462 // TypeError anyway, but this produces a better error message.
2463 if (!IsCallable(method)) {
2464 return ReportCantConvert(cx, JSMSG_TOPRIMITIVE_NOT_CALLABLE, obj,
2465 preferredType);
2468 // Steps 1-3, 6.a-b.
2469 RootedValue arg0(
2471 StringValue(preferredType == JSTYPE_STRING ? cx->names().string
2472 : preferredType == JSTYPE_NUMBER ? cx->names().number
2473 : cx->names().default_));
2475 if (!js::Call(cx, method, vp, arg0, vp)) {
2476 return false;
2479 // Steps 6.c-d.
2480 if (vp.isObject()) {
2481 return ReportCantConvert(cx, JSMSG_TOPRIMITIVE_RETURNED_OBJECT, obj,
2482 preferredType);
2484 return true;
2487 return OrdinaryToPrimitive(cx, obj, preferredType, vp);
2490 /* ES6 draft rev 28 (2014 Oct 14) 7.1.14 */
2491 bool js::ToPropertyKeySlow(JSContext* cx, HandleValue argument,
2492 MutableHandleId result) {
2493 MOZ_ASSERT(argument.isObject());
2495 // Steps 1-2.
2496 RootedValue key(cx, argument);
2497 if (!ToPrimitiveSlow(cx, JSTYPE_STRING, &key)) {
2498 return false;
2501 // Steps 3-4.
2502 return PrimitiveValueToId<CanGC>(cx, key, result);
2505 /* * */
2507 bool js::IsPrototypeOf(JSContext* cx, HandleObject protoObj, JSObject* obj,
2508 bool* result) {
2509 RootedObject obj2(cx, obj);
2510 for (;;) {
2511 // The [[Prototype]] chain might be cyclic.
2512 if (!CheckForInterrupt(cx)) {
2513 return false;
2515 if (!GetPrototype(cx, obj2, &obj2)) {
2516 return false;
2518 if (!obj2) {
2519 *result = false;
2520 return true;
2522 if (obj2 == protoObj) {
2523 *result = true;
2524 return true;
2529 JSObject* js::PrimitiveToObject(JSContext* cx, const Value& v) {
2530 MOZ_ASSERT(v.isPrimitive());
2532 switch (v.type()) {
2533 case ValueType::String: {
2534 Rooted<JSString*> str(cx, v.toString());
2535 return StringObject::create(cx, str);
2537 case ValueType::Double:
2538 case ValueType::Int32:
2539 return NumberObject::create(cx, v.toNumber());
2540 case ValueType::Boolean:
2541 return BooleanObject::create(cx, v.toBoolean());
2542 case ValueType::Symbol: {
2543 RootedSymbol symbol(cx, v.toSymbol());
2544 return SymbolObject::create(cx, symbol);
2546 case ValueType::BigInt: {
2547 RootedBigInt bigInt(cx, v.toBigInt());
2548 return BigIntObject::create(cx, bigInt);
2550 #ifdef ENABLE_RECORD_TUPLE
2551 case ValueType::ExtendedPrimitive: {
2552 JSObject& obj = v.toExtendedPrimitive();
2554 if (obj.is<RecordType>()) {
2555 Rooted<RecordType*> rec(cx, &obj.as<RecordType>());
2556 return RecordObject::create(cx, rec);
2558 if (obj.is<TupleType>()) {
2559 Rooted<TupleType*> tuple(cx, &obj.as<TupleType>());
2560 return TupleObject::create(cx, tuple);
2563 MOZ_CRASH("Unexpected ExtendedPrimitive type.");
2565 #endif
2566 case ValueType::Undefined:
2567 case ValueType::Null:
2568 case ValueType::Magic:
2569 case ValueType::PrivateGCThing:
2570 case ValueType::Object:
2571 break;
2574 MOZ_CRASH("unexpected type");
2577 // Like PrimitiveToObject, but returns the JSProtoKey of the prototype that
2578 // would be used without actually creating the object.
2579 JSProtoKey js::PrimitiveToProtoKey(JSContext* cx, const Value& v) {
2580 MOZ_ASSERT(v.isPrimitive());
2582 switch (v.type()) {
2583 case ValueType::String:
2584 return JSProto_String;
2585 case ValueType::Double:
2586 case ValueType::Int32:
2587 return JSProto_Number;
2588 case ValueType::Boolean:
2589 return JSProto_Boolean;
2590 case ValueType::Symbol:
2591 return JSProto_Symbol;
2592 case ValueType::BigInt:
2593 return JSProto_BigInt;
2594 #ifdef ENABLE_RECORD_TUPLE
2595 case ValueType::ExtendedPrimitive:
2596 if (v.toExtendedPrimitive().is<TupleType>()) {
2597 return JSProto_Tuple;
2599 if (v.toExtendedPrimitive().is<RecordType>()) {
2600 return JSProto_Null;
2602 MOZ_CRASH("Unsupported ExtendedPrimitive");
2603 #endif
2604 case ValueType::Undefined:
2605 case ValueType::Null:
2606 case ValueType::Magic:
2607 case ValueType::PrivateGCThing:
2608 case ValueType::Object:
2609 break;
2612 MOZ_CRASH("unexpected type");
2616 * Invokes the ES5 ToObject algorithm on vp, returning the result. If vp might
2617 * already be an object, use ToObject. reportScanStack controls how null and
2618 * undefined errors are reported.
2620 * Callers must handle the already-object case.
2622 JSObject* js::ToObjectSlow(JSContext* cx, JS::HandleValue val,
2623 bool reportScanStack) {
2624 MOZ_ASSERT(!val.isMagic());
2625 MOZ_ASSERT(!val.isObject());
2627 if (val.isNullOrUndefined()) {
2628 ReportIsNullOrUndefinedForPropertyAccess(
2629 cx, val, reportScanStack ? JSDVG_SEARCH_STACK : JSDVG_IGNORE_STACK);
2630 return nullptr;
2633 return PrimitiveToObject(cx, val);
2636 JSObject* js::ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
2637 int valIndex, HandleId key) {
2638 MOZ_ASSERT(!val.isMagic());
2639 MOZ_ASSERT(!val.isObject());
2641 if (val.isNullOrUndefined()) {
2642 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex, key);
2643 return nullptr;
2646 return PrimitiveToObject(cx, val);
2649 JSObject* js::ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
2650 int valIndex,
2651 Handle<PropertyName*> key) {
2652 MOZ_ASSERT(!val.isMagic());
2653 MOZ_ASSERT(!val.isObject());
2655 if (val.isNullOrUndefined()) {
2656 RootedId keyId(cx, NameToId(key));
2657 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex, keyId);
2658 return nullptr;
2661 return PrimitiveToObject(cx, val);
2664 JSObject* js::ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
2665 int valIndex,
2666 HandleValue keyValue) {
2667 MOZ_ASSERT(!val.isMagic());
2668 MOZ_ASSERT(!val.isObject());
2670 if (val.isNullOrUndefined()) {
2671 RootedId key(cx);
2672 if (keyValue.isPrimitive()) {
2673 if (!PrimitiveValueToId<CanGC>(cx, keyValue, &key)) {
2674 return nullptr;
2676 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex, key);
2677 } else {
2678 ReportIsNullOrUndefinedForPropertyAccess(cx, val, valIndex);
2680 return nullptr;
2683 return PrimitiveToObject(cx, val);
2686 JSObject* js::GetThisObject(JSObject* obj) {
2687 // Use the WindowProxy if the global is a Window, as Window must never be
2688 // exposed to script.
2689 if (obj->is<GlobalObject>()) {
2690 return ToWindowProxyIfWindow(obj);
2693 // We should not expose any environments except NSVOs to script. The NSVO is
2694 // pretending to be the global object in this case.
2695 MOZ_ASSERT(obj->is<NonSyntacticVariablesObject>() ||
2696 !obj->is<EnvironmentObject>());
2698 return obj;
2701 JSObject* js::GetThisObjectOfLexical(JSObject* env) {
2702 return env->as<ExtensibleLexicalEnvironmentObject>().thisObject();
2705 JSObject* js::GetThisObjectOfWith(JSObject* env) {
2706 MOZ_ASSERT(env->is<WithEnvironmentObject>());
2707 return GetThisObject(env->as<WithEnvironmentObject>().withThis());
2710 class GetObjectSlotNameFunctor : public JS::TracingContext::Functor {
2711 JSObject* obj;
2713 public:
2714 explicit GetObjectSlotNameFunctor(JSObject* ctx) : obj(ctx) {}
2715 virtual void operator()(JS::TracingContext* trc, char* buf,
2716 size_t bufsize) override;
2719 void GetObjectSlotNameFunctor::operator()(JS::TracingContext* tcx, char* buf,
2720 size_t bufsize) {
2721 MOZ_ASSERT(tcx->index() != JS::TracingContext::InvalidIndex);
2723 uint32_t slot = uint32_t(tcx->index());
2725 Maybe<PropertyKey> key;
2726 if (obj->is<NativeObject>()) {
2727 NativeShape* shape = obj->as<NativeObject>().shape();
2728 for (ShapePropertyIter<NoGC> iter(shape); !iter.done(); iter++) {
2729 if (iter->hasSlot() && iter->slot() == slot) {
2730 key.emplace(iter->key());
2731 break;
2736 if (key.isNothing()) {
2737 do {
2738 const char* slotname = nullptr;
2739 const char* pattern = nullptr;
2740 if (obj->is<GlobalObject>()) {
2741 pattern = "CLASS_OBJECT(%s)";
2742 if (false) {
2745 #define TEST_SLOT_MATCHES_PROTOTYPE(name, clasp) \
2746 else if ((JSProto_##name) == slot) { \
2747 slotname = js_##name##_str; \
2749 JS_FOR_EACH_PROTOTYPE(TEST_SLOT_MATCHES_PROTOTYPE)
2750 #undef TEST_SLOT_MATCHES_PROTOTYPE
2751 } else {
2752 pattern = "%s";
2753 if (obj->is<EnvironmentObject>()) {
2754 if (slot == EnvironmentObject::enclosingEnvironmentSlot()) {
2755 slotname = "enclosing_environment";
2756 } else if (obj->is<CallObject>()) {
2757 if (slot == CallObject::calleeSlot()) {
2758 slotname = "callee_slot";
2760 } else if (obj->is<WithEnvironmentObject>()) {
2761 if (slot == WithEnvironmentObject::objectSlot()) {
2762 slotname = "with_object";
2763 } else if (slot == WithEnvironmentObject::thisSlot()) {
2764 slotname = "with_this";
2770 if (slotname) {
2771 snprintf(buf, bufsize, pattern, slotname);
2772 } else {
2773 snprintf(buf, bufsize, "**UNKNOWN SLOT %" PRIu32 "**", slot);
2775 } while (false);
2776 } else {
2777 if (key->isInt()) {
2778 snprintf(buf, bufsize, "%" PRId32, key->toInt());
2779 } else if (key->isAtom()) {
2780 PutEscapedString(buf, bufsize, key->toAtom(), 0);
2781 } else if (key->isSymbol()) {
2782 snprintf(buf, bufsize, "**SYMBOL KEY**");
2783 } else {
2784 snprintf(buf, bufsize, "**FINALIZED ATOM KEY**");
2789 /*** Debugging routines *****************************************************/
2791 #if defined(DEBUG) || defined(JS_JITSPEW)
2794 * Routines to print out values during debugging. These are FRIEND_API to help
2795 * the debugger find them and to support temporarily hacking js::Dump* calls
2796 * into other code.
2799 static void dumpValue(const Value& v, js::GenericPrinter& out) {
2800 switch (v.type()) {
2801 case ValueType::Null:
2802 out.put("null");
2803 break;
2804 case ValueType::Undefined:
2805 out.put("undefined");
2806 break;
2807 case ValueType::Int32:
2808 out.printf("%d", v.toInt32());
2809 break;
2810 case ValueType::Double:
2811 out.printf("%g", v.toDouble());
2812 break;
2813 case ValueType::String:
2814 v.toString()->dumpNoNewline(out);
2815 break;
2816 case ValueType::Symbol:
2817 v.toSymbol()->dump(out);
2818 break;
2819 case ValueType::BigInt:
2820 v.toBigInt()->dump(out);
2821 break;
2822 case ValueType::Object:
2823 if (v.toObject().is<JSFunction>()) {
2824 JSFunction* fun = &v.toObject().as<JSFunction>();
2825 if (fun->displayAtom()) {
2826 out.put("<function ");
2827 EscapedStringPrinter(out, fun->displayAtom(), 0);
2828 } else {
2829 out.put("<unnamed function");
2831 if (fun->hasBaseScript()) {
2832 BaseScript* script = fun->baseScript();
2833 out.printf(" (%s:%u)", script->filename() ? script->filename() : "",
2834 script->lineno());
2836 out.printf(" at %p>", (void*)fun);
2837 } else {
2838 JSObject* obj = &v.toObject();
2839 const JSClass* clasp = obj->getClass();
2840 out.printf("<%s%s at %p>", clasp->name,
2841 (clasp == &PlainObject::class_) ? "" : " object",
2842 (void*)obj);
2844 break;
2845 # ifdef ENABLE_RECORD_TUPLE
2846 case ValueType::ExtendedPrimitive: {
2847 JSObject* obj = &v.toExtendedPrimitive();
2848 out.printf("<%s at %p>", obj->getClass()->name, (void*)obj);
2849 break;
2851 # endif
2852 case ValueType::Boolean:
2853 if (v.toBoolean()) {
2854 out.put("true");
2855 } else {
2856 out.put("false");
2858 break;
2859 case ValueType::Magic:
2860 out.put("<magic");
2861 switch (v.whyMagic()) {
2862 case JS_ELEMENTS_HOLE:
2863 out.put(" elements hole");
2864 break;
2865 case JS_NO_ITER_VALUE:
2866 out.put(" no iter value");
2867 break;
2868 case JS_GENERATOR_CLOSING:
2869 out.put(" generator closing");
2870 break;
2871 case JS_OPTIMIZED_OUT:
2872 out.put(" optimized out");
2873 break;
2874 default:
2875 out.put(" ?!");
2876 break;
2878 out.putChar('>');
2879 break;
2880 case ValueType::PrivateGCThing:
2881 out.printf("<PrivateGCThing %p>", v.toGCThing());
2882 break;
2886 namespace js {
2888 // We don't want jsfriendapi.h to depend on GenericPrinter,
2889 // so these functions are declared directly in the cpp.
2891 JS_PUBLIC_API void DumpValue(const JS::Value& val, js::GenericPrinter& out);
2893 JS_PUBLIC_API void DumpId(jsid id, js::GenericPrinter& out);
2895 JS_PUBLIC_API void DumpInterpreterFrame(JSContext* cx, js::GenericPrinter& out,
2896 InterpreterFrame* start = nullptr);
2898 } // namespace js
2900 JS_PUBLIC_API void js::DumpValue(const Value& val, js::GenericPrinter& out) {
2901 dumpValue(val, out);
2902 out.putChar('\n');
2905 JS_PUBLIC_API void js::DumpId(jsid id, js::GenericPrinter& out) {
2906 out.printf("jsid %p = ", (void*)id.asRawBits());
2907 dumpValue(IdToValue(id), out);
2908 out.putChar('\n');
2911 static void DumpProperty(const NativeObject* obj, PropMap* map, uint32_t index,
2912 js::GenericPrinter& out) {
2913 PropertyInfoWithKey prop = map->getPropertyInfoWithKey(index);
2914 jsid id = prop.key();
2915 if (id.isAtom()) {
2916 id.toAtom()->dumpCharsNoNewline(out);
2917 } else if (id.isInt()) {
2918 out.printf("%d", id.toInt());
2919 } else if (id.isSymbol()) {
2920 id.toSymbol()->dump(out);
2921 } else {
2922 out.printf("id %p", reinterpret_cast<void*>(id.asRawBits()));
2925 if (prop.isDataProperty()) {
2926 out.printf(": ");
2927 dumpValue(obj->getSlot(prop.slot()), out);
2928 } else if (prop.isAccessorProperty()) {
2929 out.printf(": getter %p setter %p", obj->getGetter(prop),
2930 obj->getSetter(prop));
2933 out.printf(" (map %p/%u", map, index);
2935 if (prop.enumerable()) {
2936 out.put(" enumerable");
2938 if (prop.configurable()) {
2939 out.put(" configurable");
2941 if (prop.isDataDescriptor() && prop.writable()) {
2942 out.put(" writable");
2945 if (prop.isCustomDataProperty()) {
2946 out.printf(" <custom-data-prop>");
2949 if (prop.hasSlot()) {
2950 out.printf(" slot %u", prop.slot());
2953 out.printf(")\n");
2956 bool JSObject::hasSameRealmAs(JSContext* cx) const {
2957 return nonCCWRealm() == cx->realm();
2960 bool JSObject::uninlinedIsProxyObject() const { return is<ProxyObject>(); }
2962 bool JSObject::uninlinedNonProxyIsExtensible() const {
2963 return nonProxyIsExtensible();
2966 void JSObject::dump(js::GenericPrinter& out) const {
2967 const JSObject* obj = this;
2968 out.printf("object %p\n", obj);
2970 if (IsCrossCompartmentWrapper(this)) {
2971 out.printf(" compartment %p\n", compartment());
2972 } else {
2973 JSObject* globalObj = &nonCCWGlobal();
2974 out.printf(" global %p [%s]\n", globalObj, globalObj->getClass()->name);
2977 const JSClass* clasp = obj->getClass();
2978 out.printf(" class %p %s\n", clasp, clasp->name);
2980 if (IsProxy(obj)) {
2981 auto* handler = GetProxyHandler(obj);
2982 out.printf(" handler %p", handler);
2983 if (IsDeadProxyObject(obj)) {
2984 out.printf(" (DeadObjectProxy)");
2985 } else if (IsCrossCompartmentWrapper(obj)) {
2986 out.printf(" (CCW)");
2988 out.putChar('\n');
2990 Value priv = GetProxyPrivate(obj);
2991 if (!priv.isUndefined()) {
2992 out.printf(" private ");
2993 dumpValue(priv, out);
2994 out.putChar('\n');
2997 Value expando = GetProxyExpando(obj);
2998 if (!expando.isNull()) {
2999 out.printf(" expando ");
3000 dumpValue(expando, out);
3001 out.putChar('\n');
3005 const Shape* shape = obj->shape();
3006 out.printf(" shape %p\n", shape);
3008 out.put(" flags:");
3009 if (obj->isUsedAsPrototype()) {
3010 out.put(" used_as_prototype");
3012 if (!obj->is<ProxyObject>() && !obj->nonProxyIsExtensible()) {
3013 out.put(" not_extensible");
3015 if (obj->maybeHasInterestingSymbolProperty()) {
3016 out.put(" maybe_has_interesting_symbol");
3018 if (obj->isQualifiedVarObj()) {
3019 out.put(" varobj");
3021 if (obj->isUnqualifiedVarObj()) {
3022 out.put(" unqualified_varobj");
3024 if (obj->hasInvalidatedTeleporting()) {
3025 out.put(" invalidated_teleporting");
3027 if (obj->hasStaticPrototype() && obj->staticPrototypeIsImmutable()) {
3028 out.put(" immutable_prototype");
3031 const NativeObject* nobj =
3032 obj->is<NativeObject>() ? &obj->as<NativeObject>() : nullptr;
3033 if (nobj) {
3034 if (nobj->inDictionaryMode()) {
3035 out.put(" inDictionaryMode");
3037 if (nobj->hadGetterSetterChange()) {
3038 out.put(" had_getter_setter_change");
3040 if (nobj->isIndexed()) {
3041 out.put(" indexed");
3043 if (nobj->hasEnumerableProperty()) {
3044 out.put(" has_enumerable");
3046 if (nobj->is<PlainObject>() &&
3047 nobj->as<PlainObject>().hasNonWritableOrAccessorPropExclProto()) {
3048 out.put(" has_non_writable_or_accessor_prop_excl_proto");
3050 if (!nobj->denseElementsArePacked()) {
3051 out.put(" non_packed_elements");
3053 if (nobj->getElementsHeader()->isNotExtensible()) {
3054 out.put(" not_extensible");
3056 if (nobj->getElementsHeader()->isSealed()) {
3057 out.put(" sealed_elements");
3059 if (nobj->getElementsHeader()->isFrozen()) {
3060 out.put(" frozen_elements");
3062 if (nobj->getElementsHeader()->maybeInIteration()) {
3063 out.put(" elements_maybe_in_iteration");
3065 } else {
3066 out.put(" not_native");
3068 out.putChar('\n');
3070 out.put(" proto ");
3071 TaggedProto proto = obj->taggedProto();
3072 if (proto.isDynamic()) {
3073 out.put("<dynamic>");
3074 } else {
3075 dumpValue(ObjectOrNullValue(proto.toObjectOrNull()), out);
3077 out.putChar('\n');
3079 if (nobj) {
3080 uint32_t reserved = JSCLASS_RESERVED_SLOTS(clasp);
3081 if (reserved) {
3082 out.printf(" reserved slots:\n");
3083 for (uint32_t i = 0; i < reserved; i++) {
3084 out.printf(" %3u ", i);
3085 out.put(": ");
3086 dumpValue(nobj->getSlot(i), out);
3087 out.putChar('\n');
3091 out.put(" properties:\n");
3093 if (PropMap* map = nobj->shape()->propMap()) {
3094 Vector<PropMap*, 8, SystemAllocPolicy> maps;
3095 while (true) {
3096 if (!maps.append(map)) {
3097 out.printf("(OOM while appending maps)\n");
3098 break;
3100 if (!map->hasPrevious()) {
3101 break;
3103 map = map->asLinked()->previous();
3106 for (size_t i = maps.length(); i > 0; i--) {
3107 size_t index = i - 1;
3108 uint32_t len =
3109 (index == 0) ? nobj->shape()->propMapLength() : PropMap::Capacity;
3110 for (uint32_t j = 0; j < len; j++) {
3111 PropMap* map = maps[index];
3112 if (!map->hasKey(j)) {
3113 MOZ_ASSERT(map->isDictionary());
3114 continue;
3116 out.printf(" ");
3117 DumpProperty(nobj, map, j, out);
3122 uint32_t slots = nobj->getDenseInitializedLength();
3123 if (slots) {
3124 out.put(" elements:\n");
3125 for (uint32_t i = 0; i < slots; i++) {
3126 out.printf(" %3u: ", i);
3127 dumpValue(nobj->getDenseElement(i), out);
3128 out.putChar('\n');
3134 // For debuggers.
3135 void JSObject::dump() const {
3136 Fprinter out(stderr);
3137 dump(out);
3140 static void MaybeDumpScope(Scope* scope, js::GenericPrinter& out) {
3141 if (scope) {
3142 out.printf(" scope: %s\n", ScopeKindString(scope->kind()));
3143 for (BindingIter bi(scope); bi; bi++) {
3144 out.put(" ");
3145 dumpValue(StringValue(bi.name()), out);
3146 out.putChar('\n');
3151 static void MaybeDumpValue(const char* name, const Value& v,
3152 js::GenericPrinter& out) {
3153 if (!v.isNull()) {
3154 out.printf(" %s: ", name);
3155 dumpValue(v, out);
3156 out.putChar('\n');
3160 JS_PUBLIC_API void js::DumpInterpreterFrame(JSContext* cx,
3161 js::GenericPrinter& out,
3162 InterpreterFrame* start) {
3163 /* This should only called during live debugging. */
3164 ScriptFrameIter i(cx);
3165 if (!start) {
3166 if (i.done()) {
3167 out.printf("no stack for cx = %p\n", (void*)cx);
3168 return;
3170 } else {
3171 while (!i.done() && !i.isJSJit() && i.interpFrame() != start) {
3172 ++i;
3175 if (i.done()) {
3176 out.printf("fp = %p not found in cx = %p\n", (void*)start, (void*)cx);
3177 return;
3181 for (; !i.done(); ++i) {
3182 if (i.isJSJit()) {
3183 out.put("JIT frame\n");
3184 } else {
3185 out.printf("InterpreterFrame at %p\n", (void*)i.interpFrame());
3188 if (i.isFunctionFrame()) {
3189 out.put("callee fun: ");
3190 RootedValue v(cx);
3191 JSObject* fun = i.callee(cx);
3192 v.setObject(*fun);
3193 dumpValue(v, out);
3194 } else {
3195 out.put("global or eval frame, no callee");
3197 out.putChar('\n');
3199 out.printf("file %s line %u\n", i.script()->filename(),
3200 i.script()->lineno());
3202 if (jsbytecode* pc = i.pc()) {
3203 out.printf(" pc = %p\n", pc);
3204 out.printf(" current op: %s\n", CodeName(JSOp(*pc)));
3205 MaybeDumpScope(i.script()->lookupScope(pc), out);
3207 if (i.isFunctionFrame()) {
3208 MaybeDumpValue("this", i.thisArgument(cx), out);
3210 if (!i.isJSJit()) {
3211 out.put(" rval: ");
3212 dumpValue(i.interpFrame()->returnValue(), out);
3213 out.putChar('\n');
3216 out.put(" flags:");
3217 if (i.isConstructing()) {
3218 out.put(" constructing");
3220 if (!i.isJSJit() && i.interpFrame()->isDebuggerEvalFrame()) {
3221 out.put(" debugger eval");
3223 if (i.isEvalFrame()) {
3224 out.put(" eval");
3226 out.putChar('\n');
3228 out.printf(" envChain: (JSObject*) %p\n", (void*)i.environmentChain(cx));
3230 out.putChar('\n');
3234 #endif /* defined(DEBUG) || defined(JS_JITSPEW) */
3236 JS_PUBLIC_API void js::DumpBacktrace(JSContext* cx, FILE* fp) {
3237 Fprinter out(fp);
3238 js::DumpBacktrace(cx, out);
3241 JS_PUBLIC_API void js::DumpBacktrace(JSContext* cx, js::GenericPrinter& out) {
3242 size_t depth = 0;
3243 for (AllFramesIter i(cx); !i.done(); ++i, ++depth) {
3244 const char* filename;
3245 unsigned line;
3246 if (i.hasScript()) {
3247 filename = JS_GetScriptFilename(i.script());
3248 line = PCToLineNumber(i.script(), i.pc());
3249 } else {
3250 filename = i.filename();
3251 line = i.computeLine();
3253 char frameType = i.isInterp() ? 'i'
3254 : i.isBaseline() ? 'b'
3255 : i.isIon() ? 'I'
3256 : i.isWasm() ? 'W'
3257 : '?';
3259 out.printf("#%zu %14p %c %s:%u", depth, i.rawFramePtr(), frameType,
3260 filename, line);
3262 if (i.hasScript()) {
3263 out.printf(" (%p @ %zu)\n", i.script(), i.script()->pcToOffset(i.pc()));
3264 } else {
3265 out.printf(" (%p)\n", i.pc());
3270 JS_PUBLIC_API void js::DumpBacktrace(JSContext* cx) {
3271 DumpBacktrace(cx, stdout);
3274 /* * */
3276 js::gc::AllocKind JSObject::allocKindForTenure(
3277 const js::Nursery& nursery) const {
3278 using namespace js::gc;
3280 MOZ_ASSERT(IsInsideNursery(this));
3282 if (canHaveFixedElements()) {
3283 const NativeObject& nobj = as<NativeObject>();
3284 MOZ_ASSERT(nobj.numFixedSlots() == 0);
3286 /* Use minimal size object if we are just going to copy the pointer. */
3287 if (!nursery.isInside(nobj.getUnshiftedElementsHeader())) {
3288 return gc::AllocKind::OBJECT0_BACKGROUND;
3291 size_t nelements = nobj.getDenseCapacity();
3292 return ForegroundToBackgroundAllocKind(GetGCArrayKind(nelements));
3295 if (is<JSFunction>()) {
3296 return as<JSFunction>().getAllocKind();
3300 * Typed arrays in the nursery may have a lazily allocated buffer, make
3301 * sure there is room for the array's fixed data when moving the array.
3303 if (is<TypedArrayObject>() && !as<TypedArrayObject>().hasBuffer()) {
3304 gc::AllocKind allocKind;
3305 if (as<TypedArrayObject>().hasInlineElements()) {
3306 size_t nbytes = as<TypedArrayObject>().byteLength();
3307 allocKind = TypedArrayObject::AllocKindForLazyBuffer(nbytes);
3308 } else {
3309 allocKind = GetGCObjectKind(getClass());
3311 return ForegroundToBackgroundAllocKind(allocKind);
3314 // Proxies that are CrossCompartmentWrappers may be nursery allocated.
3315 if (is<ProxyObject>()) {
3316 return as<ProxyObject>().allocKindForTenure();
3319 // WasmStructObjects have a variable-length tail which contains the first
3320 // few data fields, so make sure we copy it all over to the new object.
3321 if (is<WasmStructObject>()) {
3322 // Figure out the size of this object, from the object's TypeDef.
3323 const wasm::TypeDef* typeDef = &as<WasmStructObject>().typeDef();
3324 return WasmStructObject::allocKindForTypeDef(typeDef);
3327 if (is<WasmArrayObject>()) {
3328 return WasmArrayObject::allocKind();
3331 // All nursery allocatable non-native objects are handled above.
3332 return as<NativeObject>().allocKindForTenure();
3335 void JSObject::addSizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf,
3336 JS::ClassInfo* info,
3337 JS::RuntimeSizes* runtimeSizes) {
3338 if (is<NativeObject>() && as<NativeObject>().hasDynamicSlots()) {
3339 info->objectsMallocHeapSlots +=
3340 mallocSizeOf(as<NativeObject>().getSlotsHeader());
3343 if (is<NativeObject>() && as<NativeObject>().hasDynamicElements()) {
3344 void* allocatedElements = as<NativeObject>().getUnshiftedElementsHeader();
3345 info->objectsMallocHeapElementsNormal += mallocSizeOf(allocatedElements);
3348 // Other things may be measured in the future if DMD indicates it is
3349 // worthwhile.
3350 if (is<JSFunction>() || is<PlainObject>() || is<ArrayObject>() ||
3351 is<CallObject>() || is<RegExpObject>() || is<ProxyObject>()) {
3352 // Do nothing. But this function is hot, and we win by getting the
3353 // common cases out of the way early. Some stats on the most common
3354 // classes, as measured during a vanilla browser session:
3355 // - (53.7%, 53.7%): Function
3356 // - (18.0%, 71.7%): Object
3357 // - (16.9%, 88.6%): Array
3358 // - ( 3.9%, 92.5%): Call
3359 // - ( 2.8%, 95.3%): RegExp
3360 // - ( 1.0%, 96.4%): Proxy
3362 // Note that any JSClass that is special cased below likely needs to
3363 // specify the JSCLASS_DELAY_METADATA_BUILDER flag, or else we will
3364 // probably crash if the object metadata callback attempts to get the
3365 // size of the new object (which Debugger code does) before private
3366 // slots are initialized.
3367 } else if (is<ArgumentsObject>()) {
3368 info->objectsMallocHeapMisc +=
3369 as<ArgumentsObject>().sizeOfMisc(mallocSizeOf);
3370 } else if (is<MapObject>()) {
3371 info->objectsMallocHeapMisc += as<MapObject>().sizeOfData(mallocSizeOf);
3372 } else if (is<SetObject>()) {
3373 info->objectsMallocHeapMisc += as<SetObject>().sizeOfData(mallocSizeOf);
3374 } else if (is<PropertyIteratorObject>()) {
3375 info->objectsMallocHeapMisc +=
3376 as<PropertyIteratorObject>().sizeOfMisc(mallocSizeOf);
3377 } else if (is<ArrayBufferObject>()) {
3378 ArrayBufferObject::addSizeOfExcludingThis(this, mallocSizeOf, info,
3379 runtimeSizes);
3380 } else if (is<SharedArrayBufferObject>()) {
3381 SharedArrayBufferObject::addSizeOfExcludingThis(this, mallocSizeOf, info,
3382 runtimeSizes);
3383 } else if (is<GlobalObject>()) {
3384 as<GlobalObject>().addSizeOfData(mallocSizeOf, info);
3385 } else if (is<WeakCollectionObject>()) {
3386 info->objectsMallocHeapMisc +=
3387 as<WeakCollectionObject>().sizeOfExcludingThis(mallocSizeOf);
3389 #ifdef JS_HAS_CTYPES
3390 else {
3391 // This must be the last case.
3392 info->objectsMallocHeapMisc += ctypes::SizeOfDataIfCDataObject(
3393 mallocSizeOf, const_cast<JSObject*>(this));
3395 #endif
3398 size_t JSObject::sizeOfIncludingThisInNursery() const {
3399 // This function doesn't concern itself yet with typed objects (bug 1133593).
3401 MOZ_ASSERT(!isTenured());
3403 const Nursery& nursery = runtimeFromMainThread()->gc.nursery();
3404 size_t size = gc::Arena::thingSize(allocKindForTenure(nursery));
3406 if (is<NativeObject>()) {
3407 const NativeObject& native = as<NativeObject>();
3409 size += native.numDynamicSlots() * sizeof(Value);
3411 if (native.hasDynamicElements()) {
3412 js::ObjectElements& elements = *native.getElementsHeader();
3413 size += (elements.capacity + elements.numShiftedElements()) *
3414 sizeof(HeapSlot);
3417 if (is<ArgumentsObject>()) {
3418 size += as<ArgumentsObject>().sizeOfData();
3422 return size;
3425 JS::ubi::Node::Size JS::ubi::Concrete<JSObject>::size(
3426 mozilla::MallocSizeOf mallocSizeOf) const {
3427 JSObject& obj = get();
3429 if (!obj.isTenured()) {
3430 return obj.sizeOfIncludingThisInNursery();
3433 JS::ClassInfo info;
3434 obj.addSizeOfExcludingThis(mallocSizeOf, &info, nullptr);
3435 return obj.tenuredSizeOfThis() + info.sizeOfAllThings();
3438 const char16_t JS::ubi::Concrete<JSObject>::concreteTypeName[] = u"JSObject";
3440 void JSObject::traceChildren(JSTracer* trc) {
3441 TraceCellHeaderEdge(trc, this, "shape");
3443 Shape* objShape = shape();
3444 if (objShape->isNative()) {
3445 NativeObject* nobj = &as<NativeObject>();
3448 GetObjectSlotNameFunctor func(nobj);
3449 JS::AutoTracingDetails ctx(trc, func);
3450 JS::AutoTracingIndex index(trc);
3451 // Tracing can mutate the target but cannot change the slot count,
3452 // but the compiler has no way of knowing this.
3453 const uint32_t nslots = nobj->slotSpan();
3454 for (uint32_t i = 0; i < nslots; ++i) {
3455 TraceEdge(trc, &nobj->getSlotRef(i), "object slot");
3456 ++index;
3458 MOZ_ASSERT(nslots == nobj->slotSpan());
3461 TraceRange(trc, nobj->getDenseInitializedLength(),
3462 static_cast<HeapSlot*>(nobj->getDenseElements()),
3463 "objectElements");
3466 // Call the trace hook at the end so that during a moving GC the trace hook
3467 // will see updated fields and slots.
3468 const JSClass* clasp = objShape->getObjectClass();
3469 if (clasp->hasTrace()) {
3470 clasp->doTrace(trc, this);
3474 // ES 2016 7.3.20.
3475 [[nodiscard]] JSObject* js::SpeciesConstructor(
3476 JSContext* cx, HandleObject obj, HandleObject defaultCtor,
3477 bool (*isDefaultSpecies)(JSContext*, JSFunction*)) {
3478 // Step 1 (implicit).
3480 // Fast-path for steps 2 - 8. Applies if all of the following conditions
3481 // are met:
3482 // - obj.constructor can be retrieved without side-effects.
3483 // - obj.constructor[[@@species]] can be retrieved without side-effects.
3484 // - obj.constructor[[@@species]] is the builtin's original @@species
3485 // getter.
3486 RootedValue ctor(cx);
3487 bool ctorGetSucceeded = GetPropertyPure(
3488 cx, obj, NameToId(cx->names().constructor), ctor.address());
3489 if (ctorGetSucceeded && ctor.isObject() && &ctor.toObject() == defaultCtor) {
3490 jsid speciesId = PropertyKey::Symbol(cx->wellKnownSymbols().species);
3491 JSFunction* getter;
3492 if (GetGetterPure(cx, defaultCtor, speciesId, &getter) && getter &&
3493 isDefaultSpecies(cx, getter)) {
3494 return defaultCtor;
3498 // Step 2.
3499 if (!ctorGetSucceeded &&
3500 !GetProperty(cx, obj, obj, cx->names().constructor, &ctor)) {
3501 return nullptr;
3504 // Step 3.
3505 if (ctor.isUndefined()) {
3506 return defaultCtor;
3509 // Step 4.
3510 if (!ctor.isObject()) {
3511 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3512 JSMSG_OBJECT_REQUIRED,
3513 "object's 'constructor' property");
3514 return nullptr;
3517 // Step 5.
3518 RootedObject ctorObj(cx, &ctor.toObject());
3519 RootedValue s(cx);
3520 RootedId speciesId(cx, PropertyKey::Symbol(cx->wellKnownSymbols().species));
3521 if (!GetProperty(cx, ctorObj, ctor, speciesId, &s)) {
3522 return nullptr;
3525 // Step 6.
3526 if (s.isNullOrUndefined()) {
3527 return defaultCtor;
3530 // Step 7.
3531 if (IsConstructor(s)) {
3532 return &s.toObject();
3535 // Step 8.
3536 JS_ReportErrorNumberASCII(
3537 cx, GetErrorMessage, nullptr, JSMSG_NOT_CONSTRUCTOR,
3538 "[Symbol.species] property of object's constructor");
3539 return nullptr;
3542 [[nodiscard]] JSObject* js::SpeciesConstructor(
3543 JSContext* cx, HandleObject obj, JSProtoKey ctorKey,
3544 bool (*isDefaultSpecies)(JSContext*, JSFunction*)) {
3545 RootedObject defaultCtor(cx,
3546 GlobalObject::getOrCreateConstructor(cx, ctorKey));
3547 if (!defaultCtor) {
3548 return nullptr;
3550 return SpeciesConstructor(cx, obj, defaultCtor, isDefaultSpecies);
3553 bool js::Unbox(JSContext* cx, HandleObject obj, MutableHandleValue vp) {
3554 if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
3555 return Proxy::boxedValue_unbox(cx, obj, vp);
3558 if (obj->is<BooleanObject>()) {
3559 vp.setBoolean(obj->as<BooleanObject>().unbox());
3560 } else if (obj->is<NumberObject>()) {
3561 vp.setNumber(obj->as<NumberObject>().unbox());
3562 } else if (obj->is<StringObject>()) {
3563 vp.setString(obj->as<StringObject>().unbox());
3564 } else if (obj->is<DateObject>()) {
3565 vp.set(obj->as<DateObject>().UTCTime());
3566 } else if (obj->is<SymbolObject>()) {
3567 vp.setSymbol(obj->as<SymbolObject>().unbox());
3568 } else if (obj->is<BigIntObject>()) {
3569 vp.setBigInt(obj->as<BigIntObject>().unbox());
3570 #ifdef ENABLE_RECORD_TUPLE
3571 } else if (obj->is<RecordObject>()) {
3572 vp.setExtendedPrimitive(*obj->as<RecordObject>().unbox());
3573 } else if (obj->is<TupleObject>()) {
3574 vp.setExtendedPrimitive(obj->as<TupleObject>().unbox());
3575 #endif
3576 } else {
3577 vp.setUndefined();
3580 return true;
3583 #ifdef DEBUG
3584 void js::AssertJSClassInvariants(const JSClass* clasp) {
3585 MOZ_ASSERT(JS::StringIsASCII(clasp->name));
3587 // Native objects shouldn't use the property operation hooks in ObjectOps.
3588 // Doing so could violate JIT invariants.
3590 // Environment objects unfortunately use these hooks, but environment objects
3591 // are not exposed directly to script so they're generally less of an issue.
3592 if (clasp->isNativeObject() && clasp != &WithEnvironmentObject::class_ &&
3593 clasp != &ModuleEnvironmentObject::class_ &&
3594 clasp != &RuntimeLexicalErrorObject::class_) {
3595 MOZ_ASSERT(!clasp->getOpsLookupProperty());
3596 MOZ_ASSERT_IF(clasp != &MappedArgumentsObject::class_,
3597 !clasp->getOpsDefineProperty());
3598 MOZ_ASSERT(!clasp->getOpsHasProperty());
3599 MOZ_ASSERT(!clasp->getOpsGetProperty());
3600 MOZ_ASSERT(!clasp->getOpsSetProperty());
3601 MOZ_ASSERT(!clasp->getOpsGetOwnPropertyDescriptor());
3602 MOZ_ASSERT(!clasp->getOpsDeleteProperty());
3606 /* static */
3607 void JSObject::debugCheckNewObject(Shape* shape, js::gc::AllocKind allocKind,
3608 js::gc::InitialHeap heap) {
3609 const JSClass* clasp = shape->getObjectClass();
3611 if (!ClassCanHaveFixedData(clasp)) {
3612 NativeShape* nshape = &shape->asNative();
3613 if (clasp == &ArrayObject::class_) {
3614 // Arrays can store the ObjectElements header inline.
3615 MOZ_ASSERT(nshape->numFixedSlots() == 0);
3616 } else {
3617 MOZ_ASSERT(gc::GetGCKindSlots(allocKind) == nshape->numFixedSlots());
3621 // Assert background finalization is used when possible.
3622 MOZ_ASSERT(!CanChangeToBackgroundAllocKind(allocKind, clasp));
3624 // Classes with a finalizer must specify whether instances will be finalized
3625 // on the main thread or in the background, except proxies whose behaviour
3626 // depends on the target object.
3627 static const uint32_t FinalizeMask =
3628 JSCLASS_FOREGROUND_FINALIZE | JSCLASS_BACKGROUND_FINALIZE;
3629 uint32_t flags = clasp->flags;
3630 uint32_t finalizeFlags = flags & FinalizeMask;
3631 if (clasp->hasFinalize() && !clasp->isProxyObject()) {
3632 MOZ_ASSERT(finalizeFlags == JSCLASS_FOREGROUND_FINALIZE ||
3633 finalizeFlags == JSCLASS_BACKGROUND_FINALIZE);
3634 MOZ_ASSERT((finalizeFlags == JSCLASS_BACKGROUND_FINALIZE) ==
3635 IsBackgroundFinalized(allocKind));
3636 } else {
3637 MOZ_ASSERT(finalizeFlags == 0);
3640 MOZ_ASSERT_IF(clasp->hasFinalize(),
3641 heap == gc::TenuredHeap ||
3642 CanNurseryAllocateFinalizedClass(clasp) ||
3643 clasp->isProxyObject());
3645 MOZ_ASSERT(!shape->isDictionary());
3646 MOZ_ASSERT(!shape->realm()->hasObjectPendingMetadata());
3648 // Non-native classes manage their own data and slots, so numFixedSlots is
3649 // always 0. Note that proxy classes can have reserved slots but they're not
3650 // included in numFixedSlots.
3651 if (!clasp->isNativeObject()) {
3652 MOZ_ASSERT_IF(!clasp->isProxyObject(), JSCLASS_RESERVED_SLOTS(clasp) == 0);
3655 #endif