Source code
Revision control
Copy as Markdown
Other Tools
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
/*
* JS object implementation.
*/
#include "vm/JSObject-inl.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Try.h"
#include <string.h>
#include "jsapi.h"
#include "jsexn.h"
#include "jsfriendapi.h"
#include "jsnum.h"
#include "jstypes.h"
#include "builtin/BigInt.h"
#include "builtin/MapObject.h"
#include "builtin/Object.h"
#include "builtin/String.h"
#include "builtin/Symbol.h"
#include "builtin/WeakSetObject.h"
#include "gc/AllocKind.h"
#include "gc/GC.h"
#include "js/CharacterEncoding.h"
#include "js/friend/DumpFunctions.h" // js::DumpObject
#include "js/friend/ErrorMessages.h" // JSErrNum, js::GetErrorMessage, JSMSG_*
#include "js/friend/WindowProxy.h" // js::IsWindow, js::ToWindowProxyIfWindow
#include "js/MemoryMetrics.h"
#include "js/Prefs.h" // JS::Prefs
#include "js/Printer.h" // js::GenericPrinter, js::Fprinter
#include "js/PropertyDescriptor.h" // JS::FromPropertyDescriptor
#include "js/PropertySpec.h" // JSPropertySpec
#include "js/Proxy.h"
#include "js/Result.h"
#include "js/UbiNode.h"
#include "js/Wrapper.h"
#include "proxy/DeadObjectProxy.h"
#include "util/Memory.h"
#include "util/Text.h"
#include "util/WindowsWrapper.h"
#include "vm/ArgumentsObject.h"
#include "vm/ArrayBufferObject.h"
#include "vm/ArrayBufferViewObject.h"
#include "vm/BytecodeUtil.h"
#include "vm/Compartment.h"
#include "vm/DateObject.h"
#include "vm/Interpreter.h"
#include "vm/Iteration.h"
#include "vm/JSAtomUtils.h" // Atomize
#include "vm/JSContext.h"
#include "vm/JSFunction.h"
#include "vm/JSONPrinter.h" // js::JSONPrinter
#include "vm/JSScript.h"
#include "vm/PromiseObject.h"
#include "vm/ProxyObject.h"
#include "vm/RegExpObject.h"
#include "vm/SelfHosting.h"
#include "vm/Shape.h"
#include "vm/TypedArrayObject.h"
#include "vm/Watchtower.h"
#include "vm/WrapperObject.h"
#ifdef ENABLE_RECORD_TUPLE
# include "builtin/RecordObject.h"
# include "builtin/TupleObject.h"
# include "vm/RecordType.h"
# include "vm/TupleType.h"
#endif
#include "gc/StableCellHasher-inl.h"
#include "vm/BooleanObject-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/Interpreter-inl.h"
#include "vm/JSAtomUtils-inl.h" // AtomToId, PrimitiveValueToId, IndexToId
#include "vm/JSContext-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/NumberObject-inl.h"
#include "vm/ObjectFlags-inl.h"
#include "vm/Realm-inl.h"
#include "vm/StringObject-inl.h"
#include "vm/TypedArrayObject-inl.h"
#include "wasm/WasmGcObject-inl.h"
using namespace js;
using mozilla::Maybe;
void js::ReportNotObject(JSContext* cx, JSErrNum err, int spindex,
HandleValue v) {
MOZ_ASSERT(!v.isObject());
ReportValueError(cx, err, spindex, v, nullptr);
}
void js::ReportNotObject(JSContext* cx, JSErrNum err, HandleValue v) {
ReportNotObject(cx, err, JSDVG_SEARCH_STACK, v);
}
void js::ReportNotObject(JSContext* cx, const Value& v) {
RootedValue value(cx, v);
ReportNotObject(cx, JSMSG_OBJECT_REQUIRED, value);
}
void js::ReportNotObjectArg(JSContext* cx, const char* nth, const char* fun,
HandleValue v) {
MOZ_ASSERT(!v.isObject());
UniqueChars bytes;
if (const char* chars = ValueToSourceForError(cx, v, bytes)) {
JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
JSMSG_OBJECT_REQUIRED_ARG, nth, fun, chars);
}
}
JS_PUBLIC_API const char* JS::InformalValueTypeName(const Value& v) {
switch (v.type()) {
case ValueType::Double:
case ValueType::Int32:
return "number";
case ValueType::Boolean:
return "boolean";
case ValueType::Undefined:
return "undefined";
case ValueType::Null:
return "null";
case ValueType::String:
return "string";
case ValueType::Symbol:
return "symbol";
case ValueType::BigInt:
return "bigint";
case ValueType::Object:
#ifdef ENABLE_RECORD_TUPLE
case ValueType::ExtendedPrimitive:
#endif
return v.getObjectPayload().getClass()->name;
case ValueType::Magic:
return "magic";
case ValueType::PrivateGCThing:
break;
}
MOZ_CRASH("unexpected type");
}
// ES6 draft rev37 6.2.4.4 FromPropertyDescriptor
JS_PUBLIC_API bool JS::FromPropertyDescriptor(
JSContext* cx, Handle<Maybe<PropertyDescriptor>> desc_,
MutableHandleValue vp) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(desc_);
// Step 1.
if (desc_.isNothing()) {
vp.setUndefined();
return true;
}
Rooted<PropertyDescriptor> desc(cx, *desc_);
return FromPropertyDescriptorToObject(cx, desc, vp);
}
bool js::FromPropertyDescriptorToObject(JSContext* cx,
Handle<PropertyDescriptor> desc,
MutableHandleValue vp) {
// Step 2-3.
RootedObject obj(cx, NewPlainObject(cx));
if (!obj) {
return false;
}
const JSAtomState& names = cx->names();
// Step 4.
if (desc.hasValue()) {
if (!DefineDataProperty(cx, obj, names.value, desc.value())) {
return false;
}
}
// Step 5.
RootedValue v(cx);
if (desc.hasWritable()) {
v.setBoolean(desc.writable());
if (!DefineDataProperty(cx, obj, names.writable, v)) {
return false;
}
}
// Step 6.
if (desc.hasGetter()) {
if (JSObject* get = desc.getter()) {
v.setObject(*get);
} else {
v.setUndefined();
}
if (!DefineDataProperty(cx, obj, names.get, v)) {
return false;
}
}
// Step 7.
if (desc.hasSetter()) {
if (JSObject* set = desc.setter()) {
v.setObject(*set);
} else {
v.setUndefined();
}
if (!DefineDataProperty(cx, obj, names.set, v)) {
return false;
}
}
// Step 8.
if (desc.hasEnumerable()) {
v.setBoolean(desc.enumerable());
if (!DefineDataProperty(cx, obj, names.enumerable, v)) {
return false;
}
}
// Step 9.
if (desc.hasConfigurable()) {
v.setBoolean(desc.configurable());
if (!DefineDataProperty(cx, obj, names.configurable, v)) {
return false;
}
}
vp.setObject(*obj);
return true;
}
bool js::GetFirstArgumentAsObject(JSContext* cx, const CallArgs& args,
const char* method,
MutableHandleObject objp) {
if (!args.requireAtLeast(cx, method, 1)) {
return false;
}
HandleValue v = args[0];
if (!v.isObject()) {
UniqueChars bytes =
DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, v, nullptr);
if (!bytes) {
return false;
}
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
JSMSG_UNEXPECTED_TYPE, bytes.get(),
"not an object");
return false;
}
objp.set(&v.toObject());
return true;
}
static bool GetPropertyIfPresent(JSContext* cx, HandleObject obj, HandleId id,
MutableHandleValue vp, bool* foundp) {
if (!HasProperty(cx, obj, id, foundp)) {
return false;
}
if (!*foundp) {
vp.setUndefined();
return true;
}
return GetProperty(cx, obj, obj, id, vp);
}
bool js::Throw(JSContext* cx, HandleId id, unsigned errorNumber,
const char* details) {
MOZ_ASSERT(js_ErrorFormatString[errorNumber].argCount == (details ? 2 : 1));
MOZ_ASSERT_IF(details, JS::StringIsASCII(details));
UniqueChars bytes =
IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
if (!bytes) {
return false;
}
if (details) {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
bytes.get(), details);
} else {
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
bytes.get());
}
return false;
}
/*** PropertyDescriptor operations and DefineProperties *********************/
static Result<> CheckCallable(JSContext* cx, JSObject* obj,
const char* fieldName) {
if (obj && !obj->isCallable()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_GET_SET_FIELD, fieldName);
return cx->alreadyReportedError();
}
return Ok();
}
// 6.2.5.5 ToPropertyDescriptor(Obj)
bool js::ToPropertyDescriptor(JSContext* cx, HandleValue descval,
bool checkAccessors,
MutableHandle<PropertyDescriptor> desc_) {
// Step 1.
RootedObject obj(cx,
RequireObject(cx, JSMSG_OBJECT_REQUIRED_PROP_DESC, descval));
if (!obj) {
return false;
}
// Step 2.
Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Empty());
RootedId id(cx);
RootedValue v(cx);
// Steps 3-4.
id = NameToId(cx->names().enumerable);
bool hasEnumerable = false;
if (!GetPropertyIfPresent(cx, obj, id, &v, &hasEnumerable)) {
return false;
}
if (hasEnumerable) {
desc.setEnumerable(ToBoolean(v));
}
// Steps 5-6.
id = NameToId(cx->names().configurable);
bool hasConfigurable = false;
if (!GetPropertyIfPresent(cx, obj, id, &v, &hasConfigurable)) {
return false;
}
if (hasConfigurable) {
desc.setConfigurable(ToBoolean(v));
}
// Steps 7-8.
id = NameToId(cx->names().value);
bool hasValue = false;
if (!GetPropertyIfPresent(cx, obj, id, &v, &hasValue)) {
return false;
}
if (hasValue) {
desc.setValue(v);
}
// Steps 9-10.
id = NameToId(cx->names().writable);
bool hasWritable = false;
if (!GetPropertyIfPresent(cx, obj, id, &v, &hasWritable)) {
return false;
}
if (hasWritable) {
desc.setWritable(ToBoolean(v));
}
// Steps 11-12.
id = NameToId(cx->names().get);
bool hasGet = false;
if (!GetPropertyIfPresent(cx, obj, id, &v, &hasGet)) {
return false;
}
RootedObject getter(cx);
if (hasGet) {
if (v.isObject()) {
if (checkAccessors) {
JS_TRY_OR_RETURN_FALSE(cx, CheckCallable(cx, &v.toObject(), "getter"));
}
getter = &v.toObject();
} else if (v.isUndefined()) {
getter = nullptr;
} else {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_GET_SET_FIELD, "getter");
return false;
}
}
// Steps 13-14.
id = NameToId(cx->names().set);
bool hasSet = false;
if (!GetPropertyIfPresent(cx, obj, id, &v, &hasSet)) {
return false;
}
RootedObject setter(cx);
if (hasSet) {
if (v.isObject()) {
if (checkAccessors) {
JS_TRY_OR_RETURN_FALSE(cx, CheckCallable(cx, &v.toObject(), "setter"));
}
setter = &v.toObject();
} else if (v.isUndefined()) {
setter = nullptr;
} else {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_BAD_GET_SET_FIELD, "setter");
return false;
}
}
// Step 15.
if (hasGet || hasSet) {
if (hasValue || hasWritable) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_INVALID_DESCRIPTOR);
return false;
}
// We delay setGetter/setSetter after the previous check,
// because otherwise we would assert.
if (hasGet) {
desc.setGetter(getter);
}
if (hasSet) {
desc.setSetter(setter);
}
}
desc.assertValid();
desc_.set(desc);
return true;
}
Result<> js::CheckPropertyDescriptorAccessors(JSContext* cx,
Handle<PropertyDescriptor> desc) {
if (desc.hasGetter()) {
MOZ_TRY(CheckCallable(cx, desc.getter(), "getter"));
}
if (desc.hasSetter()) {
MOZ_TRY(CheckCallable(cx, desc.setter(), "setter"));
}
return Ok();
}
// 6.2.5.6 CompletePropertyDescriptor(Desc)
void js::CompletePropertyDescriptor(MutableHandle<PropertyDescriptor> desc) {
// Step 1.
desc.assertValid();
// Step 2.
// Let like be the Record { [[Value]]: undefined, [[Writable]]: false,
// [[Get]]: undefined, [[Set]]: undefined,
// [[Enumerable]]: false, [[Configurable]]: false }.
// Step 3.
if (desc.isGenericDescriptor() || desc.isDataDescriptor()) {
// Step 3.a.
if (!desc.hasValue()) {
desc.setValue(UndefinedHandleValue);
}
// Step 3.b.
if (!desc.hasWritable()) {
desc.setWritable(false);
}
} else {
// Step 4.a.
if (!desc.hasGetter()) {
desc.setGetter(nullptr);
}
// Step 4.b.
if (!desc.hasSetter()) {
desc.setSetter(nullptr);
}
}
// Step 5.
if (!desc.hasEnumerable()) {
desc.setEnumerable(false);
}
// Step 6.
if (!desc.hasConfigurable()) {
desc.setConfigurable(false);
}
desc.assertComplete();
}
bool js::ReadPropertyDescriptors(
JSContext* cx, HandleObject props, bool checkAccessors,
MutableHandleIdVector ids, MutableHandle<PropertyDescriptorVector> descs) {
if (!GetPropertyKeys(cx, props, JSITER_OWNONLY | JSITER_SYMBOLS, ids)) {
return false;
}
RootedId id(cx);
for (size_t i = 0, len = ids.length(); i < len; i++) {
id = ids[i];
Rooted<PropertyDescriptor> desc(cx);
RootedValue v(cx);
if (!GetProperty(cx, props, props, id, &v) ||
!ToPropertyDescriptor(cx, v, checkAccessors, &desc) ||
!descs.append(desc)) {
return false;
}
}
return true;
}
/*** Seal and freeze ********************************************************/
/* ES6 draft rev 29 (6 Dec 2014) 7.3.13. */
bool js::SetIntegrityLevel(JSContext* cx, HandleObject obj,
IntegrityLevel level) {
cx->check(obj);
// Steps 3-5. (Steps 1-2 are redundant assertions.)
if (!PreventExtensions(cx, obj)) {
return false;
}
// Steps 6-9, loosely interpreted.
if (obj->is<NativeObject>() && !obj->is<TypedArrayObject>() &&
!obj->is<MappedArgumentsObject>()) {
Handle<NativeObject*> nobj = obj.as<NativeObject>();
// Use a fast path to seal/freeze properties. This has the benefit of
// creating shared property maps if possible, whereas the slower/generic
// implementation below ends up converting non-empty objects to dictionary
// mode.
if (nobj->shape()->propMapLength() > 0) {
if (!NativeObject::freezeOrSealProperties(cx, nobj, level)) {
return false;
}
}
// Ordinarily ArraySetLength handles this, but we're going behind its back
// right now, so we must do this manually.
if (level == IntegrityLevel::Frozen && obj->is<ArrayObject>()) {
obj->as<ArrayObject>().setNonWritableLength(cx);
}
} else {
// Steps 6-7.
RootedIdVector keys(cx);
if (!GetPropertyKeys(
cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &keys)) {
return false;
}
RootedId id(cx);
Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Empty());
// 8.a/9.a. The two different loops are merged here.
for (size_t i = 0; i < keys.length(); i++) {
id = keys[i];
if (level == IntegrityLevel::Sealed) {
// 8.a.i.
desc.setConfigurable(false);
} else {
// 9.a.i-ii.
Rooted<Maybe<PropertyDescriptor>> currentDesc(cx);
if (!GetOwnPropertyDescriptor(cx, obj, id, ¤tDesc)) {
return false;
}
// 9.a.iii.
if (currentDesc.isNothing()) {
continue;
}
// 9.a.iii.1-2
desc = PropertyDescriptor::Empty();
if (currentDesc->isAccessorDescriptor()) {
desc.setConfigurable(false);
} else {
desc.setConfigurable(false);
desc.setWritable(false);
}
}
// 8.a.i-ii. / 9.a.iii.3-4
if (!DefineProperty(cx, obj, id, desc)) {
return false;
}
}
}
// Finally, freeze or seal the dense elements.
if (obj->is<NativeObject>()) {
if (!ObjectElements::FreezeOrSeal(cx, obj.as<NativeObject>(), level)) {
return false;
}
}
return true;
}
static bool ResolveLazyProperties(JSContext* cx, Handle<NativeObject*> obj) {
const JSClass* clasp = obj->getClass();
if (JSEnumerateOp enumerate = clasp->getEnumerate()) {
if (!enumerate(cx, obj)) {
return false;
}
}
if (clasp->getNewEnumerate() && clasp->getResolve()) {
RootedIdVector properties(cx);
if (!clasp->getNewEnumerate()(cx, obj, &properties,
/* enumerableOnly = */ false)) {
return false;
}
RootedId id(cx);
for (size_t i = 0; i < properties.length(); i++) {
id = properties[i];
bool found;
if (!HasOwnProperty(cx, obj, id, &found)) {
return false;
}
}
}
return true;
}
// ES6 draft rev33 (12 Feb 2015) 7.3.15
bool js::TestIntegrityLevel(JSContext* cx, HandleObject obj,
IntegrityLevel level, bool* result) {
// Steps 3-6. (Steps 1-2 are redundant assertions.)
bool status;
if (!IsExtensible(cx, obj, &status)) {
return false;
}
if (status) {
*result = false;
return true;
}
// Fast path for native objects.
if (obj->is<NativeObject>()) {
Handle<NativeObject*> nobj = obj.as<NativeObject>();
// Force lazy properties to be resolved.
if (!ResolveLazyProperties(cx, nobj)) {
return false;
}
// Typed array elements are configurable, writable properties, so if any
// elements are present, the typed array can neither be sealed nor frozen.
if (nobj->is<TypedArrayObject>() &&
nobj->as<TypedArrayObject>().length().valueOr(0) > 0) {
*result = false;
return true;
}
bool hasDenseElements = false;
for (size_t i = 0; i < nobj->getDenseInitializedLength(); i++) {
if (nobj->containsDenseElement(i)) {
hasDenseElements = true;
break;
}
}
if (hasDenseElements) {
// Unless the sealed flag is set, dense elements are configurable.
if (!nobj->denseElementsAreSealed()) {
*result = false;
return true;
}
// Unless the frozen flag is set, dense elements are writable.
if (level == IntegrityLevel::Frozen && !nobj->denseElementsAreFrozen()) {
*result = false;
return true;
}
}
// Steps 7-9.
for (ShapePropertyIter<NoGC> iter(nobj->shape()); !iter.done(); iter++) {
// Steps 9.c.i-ii.
if (iter->configurable() ||
(level == IntegrityLevel::Frozen && iter->isDataDescriptor() &&
iter->writable())) {
// Private fields on objects don't participate in the frozen state, and
// so should be elided from checking for frozen state.
if (iter->key().isPrivateName()) {
continue;
}
*result = false;
return true;
}
}
} else {
// Steps 7-8.
RootedIdVector props(cx);
if (!GetPropertyKeys(
cx, obj, JSITER_HIDDEN | JSITER_OWNONLY | JSITER_SYMBOLS, &props)) {
return false;
}
// Step 9.
RootedId id(cx);
Rooted<Maybe<PropertyDescriptor>> desc(cx);
for (size_t i = 0, len = props.length(); i < len; i++) {
id = props[i];
// Steps 9.a-b.
if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
return false;
}
// Step 9.c.
if (desc.isNothing()) {
continue;
}
// Steps 9.c.i-ii.
if (desc->configurable() ||
(level == IntegrityLevel::Frozen && desc->isDataDescriptor() &&
desc->writable())) {
// Since we don't request JSITER_PRIVATE in GetPropertyKeys above, we
// should never see a private name here.
MOZ_ASSERT(!id.isPrivateName());
*result = false;
return true;
}
}
}
// Step 10.
*result = true;
return true;
}
/* * */
static MOZ_ALWAYS_INLINE NativeObject* NewObject(
JSContext* cx, const JSClass* clasp, Handle<TaggedProto> proto,
gc::AllocKind kind, NewObjectKind newKind, ObjectFlags objFlags) {
MOZ_ASSERT(clasp->isNativeObject());
// Some classes have specialized allocation functions and shouldn't end up
// here.
MOZ_ASSERT(clasp != &ArrayObject::class_);
MOZ_ASSERT(clasp != &PlainObject::class_);
MOZ_ASSERT(!clasp->isJSFunction());
// Computing nfixed based on the AllocKind isn't right for objects which can
// store fixed data inline (TypedArrays and ArrayBuffers) so for simplicity
// and performance reasons we don't support such objects here.
MOZ_ASSERT(!ClassCanHaveFixedData(clasp));
size_t nfixed = GetGCKindSlots(kind);
if (CanChangeToBackgroundAllocKind(kind, clasp)) {
kind = ForegroundToBackgroundAllocKind(kind);
}
Rooted<SharedShape*> shape(
cx, SharedShape::getInitialShape(cx, clasp, cx->realm(), proto, nfixed,
objFlags));
if (!shape) {
return nullptr;
}
gc::Heap heap = GetInitialHeap(newKind, clasp);
NativeObject* obj = NativeObject::create(cx, kind, heap, shape);
if (!obj) {
return nullptr;
}
probes::CreateObject(cx, obj);
return obj;
}
NativeObject* js::NewObjectWithGivenTaggedProto(
JSContext* cx, const JSClass* clasp, Handle<TaggedProto> proto,
gc::AllocKind allocKind, NewObjectKind newKind, ObjectFlags objFlags) {
return NewObject(cx, clasp, proto, allocKind, newKind, objFlags);
}
NativeObject* js::NewObjectWithClassProto(JSContext* cx, const JSClass* clasp,
HandleObject protoArg,
gc::AllocKind allocKind,
NewObjectKind newKind,
ObjectFlags objFlags) {
if (protoArg) {
return NewObjectWithGivenTaggedProto(cx, clasp, AsTaggedProto(protoArg),
allocKind, newKind, objFlags);
}
// Find the appropriate proto for clasp. Built-in classes have a cached
// proto on cx->global(); all others get %ObjectPrototype%.
JSProtoKey protoKey = JSCLASS_CACHED_PROTO_KEY(clasp);
if (protoKey == JSProto_Null) {
protoKey = JSProto_Object;
}
JSObject* proto = GlobalObject::getOrCreatePrototype(cx, protoKey);
if (!proto) {
return nullptr;
}
Rooted<TaggedProto> taggedProto(cx, TaggedProto(proto));
return NewObject(cx, clasp, taggedProto, allocKind, newKind, objFlags);
}
bool js::GetPrototypeFromConstructor(JSContext* cx, HandleObject newTarget,
JSProtoKey intrinsicDefaultProto,
MutableHandleObject proto) {
RootedValue protov(cx);
if (!GetProperty(cx, newTarget, newTarget, cx->names().prototype, &protov)) {
return false;
}
if (protov.isObject()) {
proto.set(&protov.toObject());
} else if (newTarget->is<JSFunction>() &&
newTarget->as<JSFunction>().realm() == cx->realm()) {
// Steps 4.a-b fetch the builtin prototype of the current realm, which we
// represent as nullptr.
proto.set(nullptr);
} else if (intrinsicDefaultProto == JSProto_Null) {
// caller select a prototype object. Most likely they will choose one from
// the wrong realm.
proto.set(nullptr);
} else {
// Step 4.a: Let realm be ? GetFunctionRealm(constructor);
Realm* realm = JS::GetFunctionRealm(cx, newTarget);
if (!realm) {
return false;
}
// Step 4.b: Set proto to realm's intrinsic object named
// intrinsicDefaultProto.
{
Maybe<AutoRealm> ar;
if (cx->realm() != realm) {
ar.emplace(cx, realm->maybeGlobal());
}
proto.set(GlobalObject::getOrCreatePrototype(cx, intrinsicDefaultProto));
}
if (!proto) {
return false;
}
if (!cx->compartment()->wrap(cx, proto)) {
return false;
}
}
return true;
}
/* static */
bool JSObject::nonNativeSetProperty(JSContext* cx, HandleObject obj,
HandleId id, HandleValue v,
HandleValue receiver,
ObjectOpResult& result) {
return obj->getOpsSetProperty()(cx, obj, id, v, receiver, result);
}
/* static */
bool JSObject::nonNativeSetElement(JSContext* cx, HandleObject obj,
uint32_t index, HandleValue v,
HandleValue receiver,
ObjectOpResult& result) {
RootedId id(cx);
if (!IndexToId(cx, index, &id)) {
return false;
}
return nonNativeSetProperty(cx, obj, id, v, receiver, result);
}
static bool CopyPropertyFrom(JSContext* cx, HandleId id, HandleObject target,
HandleObject obj) {
// |target| must not be a CCW because we need to enter its realm below and
// CCWs are not associated with a single realm.
MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
// |obj| and |cx| are generally not same-compartment with |target| here.
cx->check(obj, id);
Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
return false;
}
MOZ_ASSERT(desc.isSome());
JSAutoRealm ar(cx, target);
cx->markId(id);
RootedId wrappedId(cx, id);
if (!cx->compartment()->wrap(cx, &desc)) {
return false;
}
Rooted<PropertyDescriptor> desc_(cx, *desc);
return DefineProperty(cx, target, wrappedId, desc_);
}
JS_PUBLIC_API bool JS_CopyOwnPropertiesAndPrivateFields(JSContext* cx,
HandleObject target,
HandleObject obj) {
// Both |obj| and |target| must not be CCWs because we need to enter their
// realms below and CCWs are not associated with a single realm.
MOZ_ASSERT(!IsCrossCompartmentWrapper(obj));
MOZ_ASSERT(!IsCrossCompartmentWrapper(target));
JSAutoRealm ar(cx, obj);
RootedIdVector props(cx);
if (!GetPropertyKeys(
cx, obj,
JSITER_PRIVATE | JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
&props)) {
return false;
}
for (size_t i = 0; i < props.length(); ++i) {
if (!CopyPropertyFrom(cx, props[i], target, obj)) {
return false;
}
}
return true;
}
static bool InitializePropertiesFromCompatibleNativeObject(
JSContext* cx, Handle<NativeObject*> dst, Handle<NativeObject*> src) {
cx->check(src, dst);
MOZ_ASSERT(src->getClass() == dst->getClass());
MOZ_ASSERT(dst->shape()->objectFlags().isEmpty());
MOZ_ASSERT(src->numFixedSlots() == dst->numFixedSlots());
MOZ_ASSERT(!src->inDictionaryMode());
MOZ_ASSERT(!dst->inDictionaryMode());
if (!dst->ensureElements(cx, src->getDenseInitializedLength())) {
return false;
}
uint32_t initialized = src->getDenseInitializedLength();
for (uint32_t i = 0; i < initialized; ++i) {
dst->setDenseInitializedLength(i + 1);
dst->initDenseElement(i, src->getDenseElement(i));
}
// If there are no properties to copy, we're done.
if (!src->sharedShape()->propMap()) {
return true;
}
Rooted<SharedShape*> shape(cx);
if (src->staticPrototype() == dst->staticPrototype()) {
shape = src->sharedShape();
} else {
// We need to generate a new shape for dst that has dst's proto but all
// the property information from src. Note that we asserted above that
// dst's object flags are empty.
SharedShape* srcShape = src->sharedShape();
ObjectFlags objFlags;
objFlags = CopyPropMapObjectFlags(objFlags, srcShape->objectFlags());
Rooted<SharedPropMap*> map(cx, srcShape->propMap());
uint32_t mapLength = srcShape->propMapLength();
shape = SharedShape::getPropMapShape(cx, dst->shape()->base(),
dst->numFixedSlots(), map, mapLength,
objFlags);
if (!shape) {
return false;
}
}
uint32_t oldSpan = dst->sharedShape()->slotSpan();
uint32_t newSpan = shape->slotSpan();
if (!dst->setShapeAndAddNewSlots(cx, shape, oldSpan, newSpan)) {
return false;
}
for (size_t i = JSCLASS_RESERVED_SLOTS(src->getClass()); i < newSpan; i++) {
dst->setSlot(i, src->getSlot(i));
}
return true;
}
JS_PUBLIC_API bool JS_InitializePropertiesFromCompatibleNativeObject(
JSContext* cx, HandleObject dst, HandleObject src) {
return InitializePropertiesFromCompatibleNativeObject(
cx, dst.as<NativeObject>(), src.as<NativeObject>());
}
bool js::ObjectMayBeSwapped(const JSObject* obj) {
const JSClass* clasp = obj->getClass();
// We want to optimize Window/globals and Gecko doesn't require transplanting
// them (only the WindowProxy around them). A Window may be a DOMClass, so we
// explicitly check if this is a global.
if (clasp->isGlobal()) {
return false;
}
// WindowProxy, Wrapper, DeadProxyObject, DOMProxy, and DOMClass (non-global)
// types may be swapped. It is hard to detect DOMProxy from shell, so target
// proxies in general.
return clasp->isProxyObject() || clasp->isDOMClass();
}
bool NativeObject::prepareForSwap(JSContext* cx,
MutableHandleValueVector slotValuesOut) {
MOZ_ASSERT(slotValuesOut.empty());
for (size_t i = 0; i < slotSpan(); i++) {
if (!slotValuesOut.append(getSlot(i))) {
return false;
}
}
if (hasDynamicSlots()) {
ObjectSlots* slotsHeader = getSlotsHeader();
size_t size = ObjectSlots::allocSize(slotsHeader->capacity());
RemoveCellMemory(this, size, MemoryUse::ObjectSlots);
if (!cx->nursery().isInside(slotsHeader)) {
if (!isTenured()) {
cx->nursery().removeMallocedBuffer(slotsHeader, size);
}
js_free(slotsHeader);
}
setEmptyDynamicSlots(0);
}
if (hasDynamicElements()) {
ObjectElements* elements = getElementsHeader();
void* allocatedElements = getUnshiftedElementsHeader();
size_t count = elements->numAllocatedElements();
size_t size = count * sizeof(HeapSlot);
if (isTenured()) {
RemoveCellMemory(this, size, MemoryUse::ObjectElements);
} else if (cx->nursery().isInside(allocatedElements)) {
// Move nursery allocated elements in case they end up in a tenured
// object.
ObjectElements* newElements =
reinterpret_cast<ObjectElements*>(js_pod_malloc<HeapSlot>(count));
if (!newElements) {
return false;
}
memmove(newElements, elements, size);
elements_ = newElements->elements();
} else {
cx->nursery().removeMallocedBuffer(allocatedElements, size);
}
MOZ_ASSERT(hasDynamicElements());
}
return true;
}
/* static */
bool NativeObject::fixupAfterSwap(JSContext* cx, Handle<NativeObject*> obj,
gc::AllocKind kind,
HandleValueVector slotValues) {
// This object has just been swapped with some other object, and its shape
// no longer reflects its allocated size. Correct this information and
// fill the slots in with the specified values.
MOZ_ASSERT_IF(!obj->inDictionaryMode(),
obj->slotSpan() == slotValues.length());
// Make sure the shape's numFixedSlots() is correct.
size_t nfixed = gc::GetGCKindSlots(kind);
if (nfixed != obj->shape()->numFixedSlots()) {
if (!NativeObject::changeNumFixedSlotsAfterSwap(cx, obj, nfixed)) {
return false;
}
MOZ_ASSERT(obj->shape()->numFixedSlots() == nfixed);
}
uint32_t oldDictionarySlotSpan =
obj->inDictionaryMode() ? slotValues.length() : 0;
MOZ_ASSERT(!obj->hasUniqueId());
size_t ndynamic =
calculateDynamicSlots(nfixed, slotValues.length(), obj->getClass());
size_t currentSlots = obj->getSlotsHeader()->capacity();
MOZ_ASSERT(ndynamic >= currentSlots);
if (ndynamic > currentSlots) {
if (!obj->growSlots(cx, currentSlots, ndynamic)) {
return false;
}
}
if (obj->inDictionaryMode()) {
obj->setDictionaryModeSlotSpan(oldDictionarySlotSpan);
}
for (size_t i = 0, len = slotValues.length(); i < len; i++) {
obj->initSlotUnchecked(i, slotValues[i]);
}
if (obj->hasDynamicElements()) {
ObjectElements* elements = obj->getElementsHeader();
void* allocatedElements = obj->getUnshiftedElementsHeader();
MOZ_ASSERT(!cx->nursery().isInside(allocatedElements));
size_t size = elements->numAllocatedElements() * sizeof(HeapSlot);
if (obj->isTenured()) {
AddCellMemory(obj, size, MemoryUse::ObjectElements);
} else if (!cx->nursery().registerMallocedBuffer(allocatedElements, size)) {
return false;
}
}
return true;
}
[[nodiscard]] bool ProxyObject::prepareForSwap(
JSContext* cx, MutableHandleValueVector valuesOut) {
MOZ_ASSERT(valuesOut.empty());
// Remove the GCPtr<Value>s we're about to swap from the store buffer, to
// ensure we don't trace bogus values.
gc::StoreBuffer& sb = cx->runtime()->gc.storeBuffer();
// Reserve space for the expando, private slot and the reserved slots.
if (!valuesOut.reserve(2 + numReservedSlots())) {
return false;
}
js::detail::ProxyValueArray* valArray = data.values();
sb.unputValue(&valArray->expandoSlot);
sb.unputValue(&valArray->privateSlot);
valuesOut.infallibleAppend(valArray->expandoSlot);
valuesOut.infallibleAppend(valArray->privateSlot);
for (size_t i = 0; i < numReservedSlots(); i++) {
sb.unputValue(&valArray->reservedSlots.slots[i]);
valuesOut.infallibleAppend(valArray->reservedSlots.slots[i]);
}
if (isTenured() && !usingInlineValueArray()) {
size_t count = detail::ProxyValueArray::allocCount(numReservedSlots());
RemoveCellMemory(this, count * sizeof(Value),
MemoryUse::ProxyExternalValueArray);
js_free(valArray);
data.reservedSlots = nullptr;
}
return true;
}
bool ProxyObject::fixupAfterSwap(JSContext* cx,
const HandleValueVector values) {
MOZ_ASSERT(getClass()->isProxyObject());
size_t nreserved = numReservedSlots();
// |values| contains the expando slot, private slot and the reserved slots.
MOZ_ASSERT(values.length() == 2 + nreserved);
// Allocate the external value array in malloc memory, even for nursery
// proxies.
size_t count = detail::ProxyValueArray::allocCount(nreserved);
auto* allocation = js_pod_malloc<JS::Value>(count);
if (!allocation) {
return false;
}
size_t size = count * sizeof(Value);
if (isTenured()) {
AddCellMemory(&asTenured(), size, MemoryUse::ProxyExternalValueArray);
} else if (!cx->nursery().registerMallocedBuffer(allocation, size)) {
js_free(allocation);
return false;
}
auto* valArray = reinterpret_cast<js::detail::ProxyValueArray*>(allocation);
valArray->expandoSlot = values[0];
valArray->privateSlot = values[1];
for (size_t i = 0; i < nreserved; i++) {
valArray->reservedSlots.slots[i] = values[i + 2];
}
data.reservedSlots = &valArray->reservedSlots;
MOZ_ASSERT(!usingInlineValueArray());
return true;
}
static gc::AllocKind SwappableObjectAllocKind(JSObject* obj) {
MOZ_ASSERT(ObjectMayBeSwapped(obj));
if (obj->isTenured()) {
return obj->asTenured().getAllocKind();
}
if (obj->is<NativeObject>()) {
return obj->as<NativeObject>().allocKindForTenure();
}
return obj->as<ProxyObject>().allocKindForTenure();
}
/* Use this method with extreme caution. It trades the guts of two objects. */