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
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "builtin/Object.h"
#include "js/Object.h" // JS::GetBuiltinClass
#include "mozilla/Maybe.h"
#include "mozilla/Range.h"
#include "mozilla/RangedPtr.h"
#include <algorithm>
#include <string_view>
#include "jsapi.h"
#include "builtin/Eval.h"
#include "builtin/SelfHostingDefines.h"
#include "gc/GC.h"
#include "jit/InlinableNatives.h"
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
#include "js/PropertySpec.h"
#include "js/UniquePtr.h"
#include "util/Identifier.h" // js::IsIdentifier
#include "util/StringBuilder.h"
#include "util/Text.h"
#include "vm/BooleanObject.h"
#include "vm/DateObject.h"
#include "vm/EqualityOperations.h" // js::SameValue
#include "vm/ErrorObject.h"
#include "vm/Iteration.h"
#include "vm/JSContext.h"
#include "vm/NumberObject.h"
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/RegExpObject.h"
#include "vm/StringObject.h"
#include "vm/StringType.h"
#include "vm/ToSource.h" // js::ValueToSource
#include "vm/Watchtower.h"
#ifdef ENABLE_RECORD_TUPLE
# include "builtin/RecordObject.h"
# include "builtin/TupleObject.h"
#endif
#include "vm/GeckoProfiler-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Shape-inl.h"
#ifdef FUZZING
# include "builtin/TestingFunctions.h"
#endif
using namespace js;
using mozilla::Maybe;
using mozilla::Range;
using mozilla::RangedPtr;
static PlainObject* CreateThis(JSContext* cx, HandleObject newTarget) {
RootedObject proto(cx);
if (!GetPrototypeFromConstructor(cx, newTarget, JSProto_Object, &proto)) {
return nullptr;
}
gc::AllocKind allocKind = NewObjectGCKind();
if (proto) {
return NewPlainObjectWithProtoAndAllocKind(cx, proto, allocKind);
}
return NewPlainObjectWithAllocKind(cx, allocKind);
}
bool js::obj_construct(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
JSObject* obj;
if (args.isConstructing() &&
(&args.newTarget().toObject() != &args.callee())) {
RootedObject newTarget(cx, &args.newTarget().toObject());
obj = CreateThis(cx, newTarget);
} else if (args.length() > 0 && !args[0].isNullOrUndefined()) {
obj = ToObject(cx, args[0]);
} else {
/* Make an object whether this was called with 'new' or not. */
gc::AllocKind allocKind = NewObjectGCKind();
obj = NewPlainObjectWithAllocKind(cx, allocKind);
}
if (!obj) {
return false;
}
args.rval().setObject(*obj);
return true;
}
/* ES5 15.2.4.7. */
bool js::obj_propertyIsEnumerable(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
HandleValue idValue = args.get(0);
// As an optimization, provide a fast path when rooting is not necessary and
// we can safely retrieve the attributes from the object's shape.
/* Steps 1-2. */
jsid id;
if (args.thisv().isObject() && idValue.isPrimitive() &&
PrimitiveValueToId<NoGC>(cx, idValue, &id)) {
JSObject* obj = &args.thisv().toObject();
/* Step 3. */
PropertyResult prop;
if (obj->is<NativeObject>() &&
NativeLookupOwnProperty<NoGC>(cx, &obj->as<NativeObject>(), id,
&prop)) {
/* Step 4. */
if (prop.isNotFound()) {
args.rval().setBoolean(false);
return true;
}
/* Step 5. */
JS::PropertyAttributes attrs = GetPropertyAttributes(obj, prop);
args.rval().setBoolean(attrs.enumerable());
return true;
}
}
/* Step 1. */
RootedId idRoot(cx);
if (!ToPropertyKey(cx, idValue, &idRoot)) {
return false;
}
/* Step 2. */
RootedObject obj(cx, ToObject(cx, args.thisv()));
if (!obj) {
return false;
}
/* Step 3. */
Rooted<Maybe<PropertyDescriptor>> desc(cx);
if (!GetOwnPropertyDescriptor(cx, obj, idRoot, &desc)) {
return false;
}
/* Step 4. */
if (desc.isNothing()) {
args.rval().setBoolean(false);
return true;
}
/* Step 5. */
args.rval().setBoolean(desc->enumerable());
return true;
}
static bool obj_toSource(JSContext* cx, unsigned argc, Value* vp) {
AutoJSMethodProfilerEntry pseudoFrame(cx, "Object.prototype", "toSource");
CallArgs args = CallArgsFromVp(argc, vp);
AutoCheckRecursionLimit recursion(cx);
if (!recursion.check(cx)) {
return false;
}
RootedObject obj(cx, ToObject(cx, args.thisv()));
if (!obj) {
return false;
}
JSString* str = ObjectToSource(cx, obj);
if (!str) {
return false;
}
args.rval().setString(str);
return true;
}
template <typename CharT>
static bool Consume(RangedPtr<const CharT>& s, RangedPtr<const CharT> e,
std::string_view chars) {
MOZ_ASSERT(s <= e);
size_t len = chars.length();
if (e - s < len) {
return false;
}
if (!EqualChars(s.get(), chars.data(), len)) {
return false;
}
s += len;
return true;
}
template <typename CharT>
static bool ConsumeUntil(RangedPtr<const CharT>& s, RangedPtr<const CharT> e,
char16_t ch) {
MOZ_ASSERT(s <= e);
const CharT* result = js_strchr_limit(s.get(), ch, e.get());
if (!result) {
return false;
}
s += result - s.get();
MOZ_ASSERT(*s == ch);
return true;
}
template <typename CharT>
static void ConsumeSpaces(RangedPtr<const CharT>& s, RangedPtr<const CharT> e) {
while (s < e && *s == ' ') {
s++;
}
}
/*
* Given a function source string, return the offset and length of the part
* between '(function $name' and ')'.
*/
template <typename CharT>
static bool ArgsAndBodySubstring(Range<const CharT> chars, size_t* outOffset,
size_t* outLen) {
const RangedPtr<const CharT> start = chars.begin();
RangedPtr<const CharT> s = start;
RangedPtr<const CharT> e = chars.end();
if (s == e) {
return false;
}
// Remove enclosing parentheses.
if (*s == '(' && *(e - 1) == ')') {
s++;
e--;
}
// Support the following cases, with spaces between tokens:
//
// -+---------+-+------------+-+-----+-+- [ - <any> - ] - ( -+-
// | | | | | | | |
// +- async -+ +- function -+ +- * -+ +- <any> - ( ---------+
// | |
// +- get ------+
// | |
// +- set ------+
//
// This accepts some invalid syntax, but we don't care, since it's only
// used by the non-standard toSource, and we're doing a best-effort attempt
// here.
(void)Consume(s, e, "async");
ConsumeSpaces(s, e);
(void)(Consume(s, e, "function") || Consume(s, e, "get") ||
Consume(s, e, "set"));
ConsumeSpaces(s, e);
(void)Consume(s, e, "*");
ConsumeSpaces(s, e);
// Jump over the function's name.
if (Consume(s, e, "[")) {
if (!ConsumeUntil(s, e, ']')) {
return false;
}
s++; // Skip ']'.
ConsumeSpaces(s, e);
if (s >= e || *s != '(') {
return false;
}
} else {
if (!ConsumeUntil(s, e, '(')) {
return false;
}
}
MOZ_ASSERT(*s == '(');
*outOffset = s - start;
*outLen = e - s;
MOZ_ASSERT(*outOffset + *outLen <= chars.length());
return true;
}
enum class PropertyKind { Getter, Setter, Method, Normal };
JSString* js::ObjectToSource(JSContext* cx, HandleObject obj) {
/* If outermost, we need parentheses to be an expression, not a block. */
bool outermost = cx->cycleDetectorVector().empty();
AutoCycleDetector detector(cx, obj);
if (!detector.init()) {
return nullptr;
}
if (detector.foundCycle()) {
return NewStringCopyZ<CanGC>(cx, "{}");
}
JSStringBuilder buf(cx);
if (outermost && !buf.append('(')) {
return nullptr;
}
if (!buf.append('{')) {
return nullptr;
}
RootedIdVector idv(cx);
if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_SYMBOLS, &idv)) {
return nullptr;
}
#ifdef ENABLE_RECORD_TUPLE
if (IsExtendedPrimitiveWrapper(*obj)) {
if (obj->is<TupleObject>()) {
Rooted<TupleType*> tup(cx, &obj->as<TupleObject>().unbox());
return TupleToSource(cx, tup);
}
MOZ_ASSERT(obj->is<RecordObject>());
return RecordToSource(cx, obj->as<RecordObject>().unbox());
}
#endif
bool comma = false;
auto AddProperty = [cx, &comma, &buf](HandleId id, HandleValue val,
PropertyKind kind) -> bool {
/* Convert id to a string. */
RootedString idstr(cx);
if (id.isSymbol()) {
RootedValue v(cx, SymbolValue(id.toSymbol()));
idstr = ValueToSource(cx, v);
if (!idstr) {
return false;
}
} else {
RootedValue idv(cx, IdToValue(id));
idstr = ToString<CanGC>(cx, idv);
if (!idstr) {
return false;
}
/*
* If id is a string that's not an identifier, or if it's a
* negative integer, then it must be quoted.
*/
if (id.isAtom() ? !IsIdentifier(id.toAtom()) : id.toInt() < 0) {
UniqueChars quotedId = QuoteString(cx, idstr, '\'');
if (!quotedId) {
return false;
}
idstr = NewStringCopyZ<CanGC>(cx, quotedId.get());
if (!idstr) {
return false;
}
}
}
RootedString valsource(cx, ValueToSource(cx, val));
if (!valsource) {
return false;
}
Rooted<JSLinearString*> valstr(cx, valsource->ensureLinear(cx));
if (!valstr) {
return false;
}
if (comma && !buf.append(", ")) {
return false;
}
comma = true;
size_t voffset, vlength;
// Methods and accessors can return exact syntax of source, that fits
// into property without adding property name or "get"/"set" prefix.
// Use the exact syntax when the following conditions are met:
//
// * It's a function object
// (exclude proxies)
// * Function's kind and property's kind are same
// (this can be false for dynamically defined properties)
// * Function has explicit name
// (this can be false for computed property and dynamically defined
// properties)
// * Function's name and property's name are same
// (this can be false for dynamically defined properties)
if (kind == PropertyKind::Getter || kind == PropertyKind::Setter ||
kind == PropertyKind::Method) {
RootedFunction fun(cx);
if (val.toObject().is<JSFunction>()) {
fun = &val.toObject().as<JSFunction>();
// Method's case should be checked on caller.
if (((fun->isGetter() && kind == PropertyKind::Getter &&
!fun->isAccessorWithLazyName()) ||
(fun->isSetter() && kind == PropertyKind::Setter &&
!fun->isAccessorWithLazyName()) ||
kind == PropertyKind::Method) &&
fun->fullExplicitName()) {
bool result;
if (!EqualStrings(cx, fun->fullExplicitName(), idstr, &result)) {
return false;
}
if (result) {
if (!buf.append(valstr)) {
return false;
}
return true;
}
}
}
{
// When falling back try to generate a better string
// representation by skipping the prelude, and also removing
// the enclosing parentheses.
bool success;
JS::AutoCheckCannotGC nogc;
if (valstr->hasLatin1Chars()) {
success = ArgsAndBodySubstring(valstr->latin1Range(nogc), &voffset,
&vlength);
} else {
success = ArgsAndBodySubstring(valstr->twoByteRange(nogc), &voffset,
&vlength);
}
if (!success) {
kind = PropertyKind::Normal;
}
}
if (kind == PropertyKind::Getter) {
if (!buf.append("get ")) {
return false;
}
} else if (kind == PropertyKind::Setter) {
if (!buf.append("set ")) {
return false;
}
} else if (kind == PropertyKind::Method && fun) {
if (fun->isAsync()) {
if (!buf.append("async ")) {
return false;
}
}
if (fun->isGenerator()) {
if (!buf.append('*')) {
return false;
}
}
}
}
bool needsBracket = id.isSymbol();
if (needsBracket && !buf.append('[')) {
return false;
}
if (!buf.append(idstr)) {
return false;
}
if (needsBracket && !buf.append(']')) {
return false;
}
if (kind == PropertyKind::Getter || kind == PropertyKind::Setter ||
kind == PropertyKind::Method) {
if (!buf.appendSubstring(valstr, voffset, vlength)) {
return false;
}
} else {
if (!buf.append(':')) {
return false;
}
if (!buf.append(valstr)) {
return false;
}
}
return true;
};
RootedId id(cx);
Rooted<Maybe<PropertyDescriptor>> desc(cx);
RootedValue val(cx);
for (size_t i = 0; i < idv.length(); ++i) {
id = idv[i];
if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
return nullptr;
}
if (desc.isNothing()) {
continue;
}
if (desc->isAccessorDescriptor()) {
if (desc->hasGetter() && desc->getter()) {
val.setObject(*desc->getter());
if (!AddProperty(id, val, PropertyKind::Getter)) {
return nullptr;
}
}
if (desc->hasSetter() && desc->setter()) {
val.setObject(*desc->setter());
if (!AddProperty(id, val, PropertyKind::Setter)) {
return nullptr;
}
}
continue;
}
val.set(desc->value());
JSFunction* fun = nullptr;
if (IsFunctionObject(val, &fun) && fun->isMethod()) {
if (!AddProperty(id, val, PropertyKind::Method)) {
return nullptr;
}
continue;
}
if (!AddProperty(id, val, PropertyKind::Normal)) {
return nullptr;
}
}
if (!buf.append('}')) {
return nullptr;
}
if (outermost && !buf.append(')')) {
return nullptr;
}
return buf.finishString();
}
static JSString* GetBuiltinTagSlow(JSContext* cx, HandleObject obj) {
// Step 4.
bool isArray;
if (!IsArray(cx, obj, &isArray)) {
return nullptr;
}
// Step 5.
if (isArray) {
return cx->names().object_Array_;
}
// Steps 6-14.
ESClass cls;
if (!JS::GetBuiltinClass(cx, obj, &cls)) {
return nullptr;
}
switch (cls) {
case ESClass::String:
return cx->names().object_String_;
case ESClass::Arguments:
return cx->names().object_Arguments_;
case ESClass::Error:
return cx->names().object_Error_;
case ESClass::Boolean:
return cx->names().object_Boolean_;
case ESClass::Number:
return cx->names().object_Number_;
case ESClass::Date:
return cx->names().object_Date_;
case ESClass::RegExp:
return cx->names().object_RegExp_;
default:
if (obj->isCallable()) {
// Non-standard: Prevent <object> from showing up as Function.
JSObject* unwrapped = CheckedUnwrapDynamic(obj, cx);
if (!unwrapped || !unwrapped->getClass()->isDOMClass()) {
return cx->names().object_Function_;
}
}
return cx->names().object_Object_;
}
}
static MOZ_ALWAYS_INLINE JSString* GetBuiltinTagFast(JSObject* obj,
JSContext* cx) {
const JSClass* clasp = obj->getClass();
MOZ_ASSERT(!clasp->isProxyObject());
// Optimize the non-proxy case to bypass GetBuiltinClass.
if (clasp == &PlainObject::class_) {
// This case is by far the most common so we handle it first.
return cx->names().object_Object_;
}
if (clasp == &ArrayObject::class_) {
return cx->names().object_Array_;
}
if (clasp->isJSFunction()) {
return cx->names().object_Function_;
}
if (clasp == &StringObject::class_) {
return cx->names().object_String_;
}
if (clasp == &NumberObject::class_) {
return cx->names().object_Number_;
}
if (clasp == &BooleanObject::class_) {
return cx->names().object_Boolean_;
}
if (clasp == &DateObject::class_) {
return cx->names().object_Date_;
}
if (clasp == &RegExpObject::class_) {
return cx->names().object_RegExp_;
}
if (obj->is<ArgumentsObject>()) {
return cx->names().object_Arguments_;
}
if (obj->is<ErrorObject>()) {
return cx->names().object_Error_;
}
if (obj->isCallable() && !obj->getClass()->isDOMClass()) {
// Non-standard: Prevent <object> from showing up as Function.
return cx->names().object_Function_;
}
return cx->names().object_Object_;
}
// For primitive values we try to avoid allocating the object if we can
// determine that the prototype it would use does not define Symbol.toStringTag.
static JSAtom* MaybeObjectToStringPrimitive(JSContext* cx, const Value& v) {
JSProtoKey protoKey = js::PrimitiveToProtoKey(cx, v);
// If prototype doesn't exist yet, just fall through.
JSObject* proto = cx->global()->maybeGetPrototype(protoKey);
if (!proto) {
return nullptr;
}
// If determining this may have side-effects, we must instead create the
// object normally since it is the receiver while looking up
// Symbol.toStringTag.
if (MaybeHasInterestingSymbolProperty(
cx, proto, cx->wellKnownSymbols().toStringTag, nullptr)) {
return nullptr;
}
// Return the direct result.
switch (protoKey) {
case JSProto_String:
return cx->names().object_String_;
case JSProto_Number:
return cx->names().object_Number_;
case JSProto_Boolean:
return cx->names().object_Boolean_;
case JSProto_Symbol:
return cx->names().object_Symbol_;
case JSProto_BigInt:
return cx->names().object_BigInt_;
default:
break;
}
return nullptr;
}
// ES6 19.1.3.6
bool js::obj_toString(JSContext* cx, unsigned argc, Value* vp) {
AutoJSMethodProfilerEntry pseudoFrame(cx, "Object.prototype", "toString");
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject obj(cx);
if (args.thisv().isPrimitive()) {
// Step 1.
if (args.thisv().isUndefined()) {
args.rval().setString(cx->names().object_Undefined_);
return true;
}
// Step 2.
if (args.thisv().isNull()) {
args.rval().setString(cx->names().object_Null_);
return true;
}
// Try fast-path for primitives. This is unusual but we encounter code like
// this in the wild.
JSAtom* result = MaybeObjectToStringPrimitive(cx, args.thisv());
if (result) {
args.rval().setString(result);
return true;
}
// Step 3.
obj = ToObject(cx, args.thisv());
if (!obj) {
return false;
}
} else {
obj = &args.thisv().toObject();
}
// When |obj| is a non-proxy object, compute |builtinTag| only when needed.
RootedString builtinTag(cx);
if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
builtinTag = GetBuiltinTagSlow(cx, obj);
if (!builtinTag) {
return false;
}
}
// Step 15.
RootedValue tag(cx);
if (!GetInterestingSymbolProperty(cx, obj, cx->wellKnownSymbols().toStringTag,
&tag)) {
return false;
}
// Step 16.
if (!tag.isString()) {
if (!builtinTag) {
builtinTag = GetBuiltinTagFast(obj, cx);
#ifdef DEBUG
// Assert this fast path is correct and matches BuiltinTagSlow.
JSString* builtinTagSlow = GetBuiltinTagSlow(cx, obj);
if (!builtinTagSlow) {
return false;
}
MOZ_ASSERT(builtinTagSlow == builtinTag);
#endif
}
args.rval().setString(builtinTag);
return true;
}
// Step 17.
StringBuilder sb(cx);
if (!sb.append("[object ") || !sb.append(tag.toString()) || !sb.append(']')) {
return false;
}
JSString* str = sb.finishAtom();
if (!str) {
return false;
}
args.rval().setString(str);
return true;
}
JSString* js::ObjectClassToString(JSContext* cx, JSObject* obj) {
AutoUnsafeCallWithABI unsafe;
if (MaybeHasInterestingSymbolProperty(cx, obj,
cx->wellKnownSymbols().toStringTag)) {
return nullptr;
}
return GetBuiltinTagFast(obj, cx);
}
static bool obj_setPrototypeOf(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, "Object.setPrototypeOf", 2)) {
return false;
}
/* Step 1-2. */
if (args[0].isNullOrUndefined()) {
JS_ReportErrorNumberASCII(
cx, GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO,
args[0].isNull() ? "null" : "undefined", "object");
return false;
}
/* Step 3. */
if (!args[1].isObjectOrNull()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_NOT_EXPECTED_TYPE, "Object.setPrototypeOf",
"an object or null",
InformalValueTypeName(args[1]));
return false;
}
/* Step 4. */
if (!args[0].isObject()) {
args.rval().set(args[0]);
return true;
}
/* Step 5-7. */
RootedObject obj(cx, &args[0].toObject());
RootedObject newProto(cx, args[1].toObjectOrNull());
if (!SetPrototype(cx, obj, newProto)) {
return false;
}
/* Step 8. */
args.rval().set(args[0]);
return true;
}
static bool PropertyIsEnumerable(JSContext* cx, HandleObject obj, HandleId id,
bool* enumerable) {
PropertyResult prop;
if (obj->is<NativeObject>() &&
NativeLookupOwnProperty<NoGC>(cx, &obj->as<NativeObject>(), id, &prop)) {
if (prop.isNotFound()) {
*enumerable = false;
return true;
}
JS::PropertyAttributes attrs = GetPropertyAttributes(obj, prop);
*enumerable = attrs.enumerable();
return true;
}
Rooted<Maybe<PropertyDescriptor>> desc(cx);
if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
return false;
}
*enumerable = desc.isSome() && desc->enumerable();
return true;
}
// Returns true if properties not named "__proto__" can be added to |obj|
// with a fast path that doesn't check any properties on the prototype chain.
static bool CanAddNewPropertyExcludingProtoFast(PlainObject* obj) {
if (!obj->isExtensible() || obj->isUsedAsPrototype()) {
return false;
}
// Don't fastpath assign if we're watching for property modification.
if (Watchtower::watchesPropertyModification(obj)) {
return false;
}
// Ensure the object has no non-writable properties or getters/setters.
// For now only support PlainObjects so that we don't have to worry about
// resolve hooks and other JSClass hooks.
while (true) {
if (obj->hasNonWritableOrAccessorPropExclProto()) {
return false;
}
JSObject* proto = obj->staticPrototype();
if (!proto) {
return true;
}
if (!proto->is<PlainObject>()) {
return false;
}
obj = &proto->as<PlainObject>();
}
}
#ifdef DEBUG
void PlainObjectAssignCache::assertValid() const {
MOZ_ASSERT(emptyToShape_);
MOZ_ASSERT(fromShape_);
MOZ_ASSERT(newToShape_);
MOZ_ASSERT(emptyToShape_->propMapLength() == 0);
MOZ_ASSERT(emptyToShape_->base() == newToShape_->base());
MOZ_ASSERT(emptyToShape_->numFixedSlots() == newToShape_->numFixedSlots());
MOZ_ASSERT(emptyToShape_->getObjectClass() == &PlainObject::class_);
MOZ_ASSERT(fromShape_->getObjectClass() == &PlainObject::class_);
MOZ_ASSERT(fromShape_->slotSpan() == newToShape_->slotSpan());
}
#endif
[[nodiscard]] static bool TryAssignPlain(JSContext* cx, HandleObject to,
HandleObject from, bool* optimized) {
// Object.assign is used with PlainObjects most of the time. This is a fast
// path to optimize that case. This lets us avoid checks that are only
// relevant for other JSClasses.
MOZ_ASSERT(*optimized == false);
if (!from->is<PlainObject>() || !to->is<PlainObject>()) {
return true;
}
// Don't use the fast path if |from| may have extra indexed properties.
Handle<PlainObject*> fromPlain = from.as<PlainObject>();
if (fromPlain->getDenseInitializedLength() > 0 || fromPlain->isIndexed()) {
return true;
}
MOZ_ASSERT(!fromPlain->getClass()->getNewEnumerate());
MOZ_ASSERT(!fromPlain->getClass()->getEnumerate());
// Empty |from| objects are common, so check for this first.
if (fromPlain->empty()) {
*optimized = true;
return true;
}
Handle<PlainObject*> toPlain = to.as<PlainObject>();
if (!CanAddNewPropertyExcludingProtoFast(toPlain)) {
return true;
}
const bool toWasEmpty = toPlain->empty();
if (toWasEmpty) {
const PlainObjectAssignCache& cache = cx->realm()->plainObjectAssignCache;
SharedShape* newShape = cache.lookup(toPlain->shape(), fromPlain->shape());
if (newShape) {
*optimized = true;
uint32_t oldSpan = 0;
uint32_t newSpan = newShape->slotSpan();
if (!toPlain->setShapeAndAddNewSlots(cx, newShape, oldSpan, newSpan)) {
return false;
}
MOZ_ASSERT(fromPlain->slotSpan() == newSpan);
for (size_t i = 0; i < newSpan; i++) {
toPlain->initSlot(i, fromPlain->getSlot(i));
}
return true;
}
}
// Get a list of all enumerable |from| properties.
Rooted<PropertyInfoWithKeyVector> props(cx, PropertyInfoWithKeyVector(cx));
#ifdef DEBUG
Rooted<Shape*> fromShape(cx, fromPlain->shape());
#endif
bool hasPropsWithNonDefaultAttrs = false;
bool hasOnlyEnumerableProps = true;
for (ShapePropertyIter<NoGC> iter(fromPlain->shape()); !iter.done(); iter++) {
// Symbol properties need to be assigned last. For now fall back to the
// slow path if we see a symbol property.
jsid id = iter->key();
if (MOZ_UNLIKELY(id.isSymbol())) {
return true;
}
// __proto__ is not supported by CanAddNewPropertyExcludingProtoFast.
if (MOZ_UNLIKELY(id.isAtom(cx->names().proto_))) {
return true;
}
if (MOZ_UNLIKELY(!iter->isDataProperty())) {
return true;
}
if (iter->flags() != PropertyFlags::defaultDataPropFlags) {
hasPropsWithNonDefaultAttrs = true;
if (!iter->enumerable()) {
hasOnlyEnumerableProps = false;
continue;
}
}
if (MOZ_UNLIKELY(!props.append(*iter))) {
return false;
}
}
MOZ_ASSERT_IF(hasOnlyEnumerableProps && !fromPlain->inDictionaryMode(),
fromPlain->slotSpan() == props.length());
*optimized = true;
Rooted<Shape*> origToShape(cx, toPlain->shape());
// If the |to| object has no properties and the |from| object only has plain
// enumerable/writable/configurable data properties, try to use its shape or
// property map.
if (toWasEmpty && !hasPropsWithNonDefaultAttrs) {
CanReuseShape canReuse =
toPlain->canReuseShapeForNewProperties(fromPlain->shape());
if (canReuse != CanReuseShape::NoReuse) {
SharedShape* newShape;
if (canReuse == CanReuseShape::CanReuseShape) {
newShape = fromPlain->sharedShape();
} else {
// Get a shape with fromPlain's PropMap and ObjectFlags (because we need
// the HasEnumerable flag checked in canReuseShapeForNewProperties) and
// the other fields (BaseShape, numFixedSlots) unchanged.
MOZ_ASSERT(canReuse == CanReuseShape::CanReusePropMap);
ObjectFlags objectFlags = fromPlain->sharedShape()->objectFlags();
Rooted<SharedPropMap*> map(cx, fromPlain->sharedShape()->propMap());
uint32_t mapLength = fromPlain->sharedShape()->propMapLength();
BaseShape* base = toPlain->sharedShape()->base();
uint32_t nfixed = toPlain->sharedShape()->numFixedSlots();
newShape = SharedShape::getPropMapShape(cx, base, nfixed, map,
mapLength, objectFlags);
if (!newShape) {
return false;
}
}
uint32_t oldSpan = 0;
uint32_t newSpan = props.length();
if (!toPlain->setShapeAndAddNewSlots(cx, newShape, oldSpan, newSpan)) {
return false;
}
MOZ_ASSERT(fromPlain->slotSpan() == newSpan);
MOZ_ASSERT(toPlain->slotSpan() == newSpan);
for (size_t i = 0; i < newSpan; i++) {
toPlain->initSlot(i, fromPlain->getSlot(i));
}
PlainObjectAssignCache& cache = cx->realm()->plainObjectAssignCache;
cache.fill(&origToShape->asShared(), fromPlain->sharedShape(), newShape);
return true;
}
}
RootedValue propValue(cx);
RootedId nextKey(cx);
for (size_t i = props.length(); i > 0; i--) {
// Assert |from| still has the same properties.
MOZ_ASSERT(fromPlain->shape() == fromShape);
PropertyInfoWithKey fromProp = props[i - 1];
MOZ_ASSERT(fromProp.isDataProperty());
MOZ_ASSERT(fromProp.enumerable());
nextKey = fromProp.key();
propValue = fromPlain->getSlot(fromProp.slot());
if (!toWasEmpty) {
if (Maybe<PropertyInfo> toProp = toPlain->lookup(cx, nextKey)) {
MOZ_ASSERT(toProp->isDataProperty());
MOZ_ASSERT(toProp->writable());
toPlain->setSlot(toProp->slot(), propValue);
continue;
}
}
MOZ_ASSERT(!toPlain->containsPure(nextKey));
if (!AddDataPropertyToPlainObject(cx, toPlain, nextKey, propValue)) {
return false;
}
}
// Note: dictionary shapes are not supported by the cache because they have a
// more complicated slot layout (the slot numbers may not match the property
// definition order and the slots may contain holes).
if (toWasEmpty && hasOnlyEnumerableProps && !fromPlain->inDictionaryMode() &&
!toPlain->inDictionaryMode()) {
PlainObjectAssignCache& cache = cx->realm()->plainObjectAssignCache;
cache.fill(&origToShape->asShared(), fromPlain->sharedShape(),
toPlain->sharedShape());
}
return true;
}
static bool TryAssignNative(JSContext* cx, HandleObject to, HandleObject from,
bool* optimized) {
MOZ_ASSERT(*optimized == false);
if (!from->is<NativeObject>() || !to->is<NativeObject>()) {
return true;
}
// Don't use the fast path if |from| may have extra indexed or lazy
// properties.
NativeObject* fromNative = &from->as<NativeObject>();
if (fromNative->getDenseInitializedLength() > 0 || fromNative->isIndexed() ||
fromNative->is<TypedArrayObject>() ||
fromNative->getClass()->getNewEnumerate() ||
fromNative->getClass()->getEnumerate()) {
return true;
}
// Get a list of |from| properties. As long as from->shape() == fromShape
// we can use this to speed up both the enumerability check and the GetProp.
Rooted<PropertyInfoWithKeyVector> props(cx, PropertyInfoWithKeyVector(cx));
Rooted<NativeShape*> fromShape(cx, fromNative->shape());
for (ShapePropertyIter<NoGC> iter(fromShape); !iter.done(); iter++) {
// Symbol properties need to be assigned last. For now fall back to the
// slow path if we see a symbol property.
if (MOZ_UNLIKELY(iter->key().isSymbol())) {
return true;
}
if (MOZ_UNLIKELY(!props.append(*iter))) {
return false;
}
}
*optimized = true;
RootedValue propValue(cx);
RootedId nextKey(cx);
RootedValue toReceiver(cx, ObjectValue(*to));
for (size_t i = props.length(); i > 0; i--) {
PropertyInfoWithKey prop = props[i - 1];
nextKey = prop.key();
// If |from| still has the same shape, it must still be a NativeObject with
// the properties in |props|.
if (MOZ_LIKELY(from->shape() == fromShape && prop.isDataProperty())) {
if (!prop.enumerable()) {
continue;
}
propValue = from->as<NativeObject>().getSlot(prop.slot());
} else {
// |from| changed shape or the property is not a data property, so
// we have to do the slower enumerability check and GetProp.
bool enumerable;
if (!PropertyIsEnumerable(cx, from, nextKey, &enumerable)) {
return false;
}
if (!enumerable) {
continue;
}
if (!GetProperty(cx, from, from, nextKey, &propValue)) {
return false;
}
}
ObjectOpResult result;
if (MOZ_UNLIKELY(
!SetProperty(cx, to, nextKey, propValue, toReceiver, result))) {
return false;
}
if (MOZ_UNLIKELY(!result.checkStrict(cx, to, nextKey))) {
return false;
}
}
return true;
}
static bool AssignSlow(JSContext* cx, HandleObject to, HandleObject from) {
// Step 4.b.ii.
RootedIdVector keys(cx);
if (!GetPropertyKeys(
cx, from, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &keys)) {
return false;
}
// Step 4.c.
RootedId nextKey(cx);
RootedValue propValue(cx);
for (size_t i = 0, len = keys.length(); i < len; i++) {
nextKey = keys[i];
// Step 4.c.i.
bool enumerable;
if (MOZ_UNLIKELY(!PropertyIsEnumerable(cx, from, nextKey, &enumerable))) {
return false;
}
if (!enumerable) {
continue;
}
// Step