// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/objects.h" #include #include #include #include #include #include #include "src/objects-inl.h" #include "src/accessors.h" #include "src/allocation-site-scopes.h" #include "src/api-arguments-inl.h" #include "src/api-natives.h" #include "src/api.h" #include "src/arguments.h" #include "src/base/bits.h" #include "src/base/utils/random-number-generator.h" #include "src/bootstrapper.h" #include "src/code-stubs.h" #include "src/codegen.h" #include "src/compilation-dependencies.h" #include "src/compiler.h" #include "src/counters-inl.h" #include "src/counters.h" #include "src/date.h" #include "src/debug/debug-evaluate.h" #include "src/debug/debug.h" #include "src/deoptimizer.h" #include "src/elements.h" #include "src/execution.h" #include "src/field-index-inl.h" #include "src/field-index.h" #include "src/field-type.h" #include "src/frames-inl.h" #include "src/full-codegen/full-codegen.h" #include "src/globals.h" #include "src/ic/ic.h" #include "src/identity-map.h" #include "src/interpreter/bytecode-array-iterator.h" #include "src/interpreter/bytecode-decoder.h" #include "src/interpreter/interpreter.h" #include "src/isolate-inl.h" #include "src/keys.h" #include "src/list.h" #include "src/log.h" #include "src/lookup.h" #include "src/macro-assembler.h" #include "src/map-updater.h" #include "src/messages.h" #include "src/objects-body-descriptors-inl.h" #include "src/property-descriptor.h" #include "src/prototype.h" #include "src/regexp/jsregexp.h" #include "src/safepoint-table.h" #include "src/snapshot/code-serializer.h" #include "src/source-position-table.h" #include "src/string-builder.h" #include "src/string-search.h" #include "src/string-stream.h" #include "src/utils.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-objects.h" #include "src/zone/zone.h" #ifdef ENABLE_DISASSEMBLER #include "src/disasm.h" #include "src/disassembler.h" #include "src/eh-frame.h" #endif namespace v8 { namespace internal { std::ostream& operator<<(std::ostream& os, InstanceType instance_type) { switch (instance_type) { #define WRITE_TYPE(TYPE) \ case TYPE: \ return os << #TYPE; INSTANCE_TYPE_LIST(WRITE_TYPE) #undef WRITE_TYPE } UNREACHABLE(); return os << "UNKNOWN"; // Keep the compiler happy. } Handle Object::OptimalType(Isolate* isolate, Representation representation) { if (representation.IsNone()) return FieldType::None(isolate); if (FLAG_track_field_types) { if (representation.IsHeapObject() && IsHeapObject()) { // We can track only JavaScript objects with stable maps. Handle map(HeapObject::cast(this)->map(), isolate); if (map->is_stable() && map->IsJSReceiverMap()) { return FieldType::Class(map, isolate); } } } return FieldType::Any(isolate); } MaybeHandle Object::ToObject(Isolate* isolate, Handle object, Handle native_context) { if (object->IsJSReceiver()) return Handle::cast(object); Handle constructor; if (object->IsSmi()) { constructor = handle(native_context->number_function(), isolate); } else { int constructor_function_index = Handle::cast(object)->map()->GetConstructorFunctionIndex(); if (constructor_function_index == Map::kNoConstructorFunctionIndex) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kUndefinedOrNullToObject), JSReceiver); } constructor = handle( JSFunction::cast(native_context->get(constructor_function_index)), isolate); } Handle result = isolate->factory()->NewJSObject(constructor); Handle::cast(result)->set_value(*object); return result; } // ES6 section 9.2.1.2, OrdinaryCallBindThis for sloppy callee. // static MaybeHandle Object::ConvertReceiver(Isolate* isolate, Handle object) { if (object->IsJSReceiver()) return Handle::cast(object); if (*object == isolate->heap()->null_value() || object->IsUndefined(isolate)) { return isolate->global_proxy(); } return Object::ToObject(isolate, object); } // static MaybeHandle Object::ConvertToNumber(Isolate* isolate, Handle input) { while (true) { if (input->IsNumber()) { return input; } if (input->IsString()) { return String::ToNumber(Handle::cast(input)); } if (input->IsOddball()) { return Oddball::ToNumber(Handle::cast(input)); } if (input->IsSymbol()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kSymbolToNumber), Object); } ASSIGN_RETURN_ON_EXCEPTION( isolate, input, JSReceiver::ToPrimitive(Handle::cast(input), ToPrimitiveHint::kNumber), Object); } } // static MaybeHandle Object::ConvertToInteger(Isolate* isolate, Handle input) { ASSIGN_RETURN_ON_EXCEPTION(isolate, input, ConvertToNumber(isolate, input), Object); if (input->IsSmi()) return input; return isolate->factory()->NewNumber(DoubleToInteger(input->Number())); } // static MaybeHandle Object::ConvertToInt32(Isolate* isolate, Handle input) { ASSIGN_RETURN_ON_EXCEPTION(isolate, input, ConvertToNumber(isolate, input), Object); if (input->IsSmi()) return input; return isolate->factory()->NewNumberFromInt(DoubleToInt32(input->Number())); } // static MaybeHandle Object::ConvertToUint32(Isolate* isolate, Handle input) { ASSIGN_RETURN_ON_EXCEPTION(isolate, input, ConvertToNumber(isolate, input), Object); if (input->IsSmi()) return handle(Smi::cast(*input)->ToUint32Smi(), isolate); return isolate->factory()->NewNumberFromUint(DoubleToUint32(input->Number())); } // static MaybeHandle Object::ConvertToName(Isolate* isolate, Handle input) { ASSIGN_RETURN_ON_EXCEPTION( isolate, input, Object::ToPrimitive(input, ToPrimitiveHint::kString), Name); if (input->IsName()) return Handle::cast(input); return ToString(isolate, input); } // ES6 7.1.14 // static MaybeHandle Object::ConvertToPropertyKey(Isolate* isolate, Handle value) { // 1. Let key be ToPrimitive(argument, hint String). MaybeHandle maybe_key = Object::ToPrimitive(value, ToPrimitiveHint::kString); // 2. ReturnIfAbrupt(key). Handle key; if (!maybe_key.ToHandle(&key)) return key; // 3. If Type(key) is Symbol, then return key. if (key->IsSymbol()) return key; // 4. Return ToString(key). // Extending spec'ed behavior, we'd be happy to return an element index. if (key->IsSmi()) return key; if (key->IsHeapNumber()) { uint32_t uint_value; if (value->ToArrayLength(&uint_value) && uint_value <= static_cast(Smi::kMaxValue)) { return handle(Smi::FromInt(static_cast(uint_value)), isolate); } } return Object::ToString(isolate, key); } // static MaybeHandle Object::ConvertToString(Isolate* isolate, Handle input) { while (true) { if (input->IsOddball()) { return handle(Handle::cast(input)->to_string(), isolate); } if (input->IsNumber()) { return isolate->factory()->NumberToString(input); } if (input->IsSymbol()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kSymbolToString), String); } ASSIGN_RETURN_ON_EXCEPTION( isolate, input, JSReceiver::ToPrimitive(Handle::cast(input), ToPrimitiveHint::kString), String); // The previous isString() check happened in Object::ToString and thus we // put it at the end of the loop in this helper. if (input->IsString()) { return Handle::cast(input); } } } namespace { bool IsErrorObject(Isolate* isolate, Handle object) { if (!object->IsJSReceiver()) return false; Handle symbol = isolate->factory()->stack_trace_symbol(); return JSReceiver::HasOwnProperty(Handle::cast(object), symbol) .FromMaybe(false); } Handle AsStringOrEmpty(Isolate* isolate, Handle object) { return object->IsString() ? Handle::cast(object) : isolate->factory()->empty_string(); } Handle NoSideEffectsErrorToString(Isolate* isolate, Handle input) { Handle receiver = Handle::cast(input); Handle name_key = isolate->factory()->name_string(); Handle name = JSReceiver::GetDataProperty(receiver, name_key); Handle name_str = AsStringOrEmpty(isolate, name); Handle msg_key = isolate->factory()->message_string(); Handle msg = JSReceiver::GetDataProperty(receiver, msg_key); Handle msg_str = AsStringOrEmpty(isolate, msg); if (name_str->length() == 0) return msg_str; if (msg_str->length() == 0) return name_str; IncrementalStringBuilder builder(isolate); builder.AppendString(name_str); builder.AppendCString(": "); builder.AppendString(msg_str); return builder.Finish().ToHandleChecked(); } } // namespace // static Handle Object::NoSideEffectsToString(Isolate* isolate, Handle input) { DisallowJavascriptExecution no_js(isolate); if (input->IsString() || input->IsNumber() || input->IsOddball()) { return Object::ToString(isolate, input).ToHandleChecked(); } else if (input->IsFunction()) { // -- F u n c t i o n Handle fun_str; if (input->IsJSBoundFunction()) { fun_str = JSBoundFunction::ToString(Handle::cast(input)); } else { DCHECK(input->IsJSFunction()); fun_str = JSFunction::ToString(Handle::cast(input)); } if (fun_str->length() > 128) { IncrementalStringBuilder builder(isolate); builder.AppendString(isolate->factory()->NewSubString(fun_str, 0, 111)); builder.AppendCString("......"); builder.AppendString(isolate->factory()->NewSubString( fun_str, fun_str->length() - 2, fun_str->length())); return builder.Finish().ToHandleChecked(); } return fun_str; } else if (input->IsSymbol()) { // -- S y m b o l Handle symbol = Handle::cast(input); IncrementalStringBuilder builder(isolate); builder.AppendCString("Symbol("); if (symbol->name()->IsString()) { builder.AppendString(handle(String::cast(symbol->name()), isolate)); } builder.AppendCharacter(')'); return builder.Finish().ToHandleChecked(); } else if (input->IsJSReceiver()) { // -- J S R e c e i v e r Handle receiver = Handle::cast(input); Handle to_string = JSReceiver::GetDataProperty( receiver, isolate->factory()->toString_string()); if (IsErrorObject(isolate, input) || *to_string == *isolate->error_to_string()) { // When internally formatting error objects, use a side-effects-free // version of Error.prototype.toString independent of the actually // installed toString method. return NoSideEffectsErrorToString(isolate, input); } else if (*to_string == *isolate->object_to_string()) { Handle ctor = JSReceiver::GetDataProperty( receiver, isolate->factory()->constructor_string()); if (ctor->IsFunction()) { Handle ctor_name; if (ctor->IsJSBoundFunction()) { ctor_name = JSBoundFunction::GetName( isolate, Handle::cast(ctor)) .ToHandleChecked(); } else if (ctor->IsJSFunction()) { Handle ctor_name_obj = JSFunction::GetName(isolate, Handle::cast(ctor)); ctor_name = AsStringOrEmpty(isolate, ctor_name_obj); } if (ctor_name->length() != 0) { IncrementalStringBuilder builder(isolate); builder.AppendCString("#<"); builder.AppendString(ctor_name); builder.AppendCString(">"); return builder.Finish().ToHandleChecked(); } } } } // At this point, input is either none of the above or a JSReceiver. Handle receiver; if (input->IsJSReceiver()) { receiver = Handle::cast(input); } else { // This is the only case where Object::ToObject throws. DCHECK(!input->IsSmi()); int constructor_function_index = Handle::cast(input)->map()->GetConstructorFunctionIndex(); if (constructor_function_index == Map::kNoConstructorFunctionIndex) { return isolate->factory()->NewStringFromAsciiChecked("[object Unknown]"); } receiver = Object::ToObject(isolate, input, isolate->native_context()) .ToHandleChecked(); } Handle builtin_tag = handle(receiver->class_name(), isolate); Handle tag_obj = JSReceiver::GetDataProperty( receiver, isolate->factory()->to_string_tag_symbol()); Handle tag = tag_obj->IsString() ? Handle::cast(tag_obj) : builtin_tag; IncrementalStringBuilder builder(isolate); builder.AppendCString("[object "); builder.AppendString(tag); builder.AppendCString("]"); return builder.Finish().ToHandleChecked(); } // static MaybeHandle Object::ConvertToLength(Isolate* isolate, Handle input) { ASSIGN_RETURN_ON_EXCEPTION(isolate, input, ToNumber(input), Object); if (input->IsSmi()) { int value = std::max(Smi::cast(*input)->value(), 0); return handle(Smi::FromInt(value), isolate); } double len = DoubleToInteger(input->Number()); if (len <= 0.0) { return handle(Smi::kZero, isolate); } else if (len >= kMaxSafeInteger) { len = kMaxSafeInteger; } return isolate->factory()->NewNumber(len); } // static MaybeHandle Object::ConvertToIndex( Isolate* isolate, Handle input, MessageTemplate::Template error_index) { if (input->IsUndefined(isolate)) return handle(Smi::kZero, isolate); ASSIGN_RETURN_ON_EXCEPTION(isolate, input, ToNumber(input), Object); if (input->IsSmi() && Smi::cast(*input)->value() >= 0) return input; double len = DoubleToInteger(input->Number()) + 0.0; auto js_len = isolate->factory()->NewNumber(len); if (len < 0.0 || len > kMaxSafeInteger) { THROW_NEW_ERROR(isolate, NewRangeError(error_index, js_len), Object); } return js_len; } bool Object::BooleanValue() { if (IsSmi()) return Smi::cast(this)->value() != 0; DCHECK(IsHeapObject()); Isolate* isolate = HeapObject::cast(this)->GetIsolate(); if (IsBoolean()) return IsTrue(isolate); if (IsNullOrUndefined(isolate)) return false; if (IsUndetectable()) return false; // Undetectable object is false. if (IsString()) return String::cast(this)->length() != 0; if (IsHeapNumber()) return HeapNumber::cast(this)->HeapNumberBooleanValue(); return true; } namespace { // TODO(bmeurer): Maybe we should introduce a marker interface Number, // where we put all these methods at some point? ComparisonResult NumberCompare(double x, double y) { if (std::isnan(x) || std::isnan(y)) { return ComparisonResult::kUndefined; } else if (x < y) { return ComparisonResult::kLessThan; } else if (x > y) { return ComparisonResult::kGreaterThan; } else { return ComparisonResult::kEqual; } } bool NumberEquals(double x, double y) { // Must check explicitly for NaN's on Windows, but -0 works fine. if (std::isnan(x)) return false; if (std::isnan(y)) return false; return x == y; } bool NumberEquals(const Object* x, const Object* y) { return NumberEquals(x->Number(), y->Number()); } bool NumberEquals(Handle x, Handle y) { return NumberEquals(*x, *y); } } // namespace // static Maybe Object::Compare(Handle x, Handle y) { // ES6 section 7.2.11 Abstract Relational Comparison step 3 and 4. if (!Object::ToPrimitive(x, ToPrimitiveHint::kNumber).ToHandle(&x) || !Object::ToPrimitive(y, ToPrimitiveHint::kNumber).ToHandle(&y)) { return Nothing(); } if (x->IsString() && y->IsString()) { // ES6 section 7.2.11 Abstract Relational Comparison step 5. return Just( String::Compare(Handle::cast(x), Handle::cast(y))); } // ES6 section 7.2.11 Abstract Relational Comparison step 6. if (!Object::ToNumber(x).ToHandle(&x) || !Object::ToNumber(y).ToHandle(&y)) { return Nothing(); } return Just(NumberCompare(x->Number(), y->Number())); } // static Maybe Object::Equals(Handle x, Handle y) { // This is the generic version of Abstract Equality Comparison; a version in // JavaScript land is available in the EqualStub and NotEqualStub. Whenever // you change something functionality wise in here, remember to update the // TurboFan code stubs as well. while (true) { if (x->IsNumber()) { if (y->IsNumber()) { return Just(NumberEquals(x, y)); } else if (y->IsBoolean()) { return Just(NumberEquals(*x, Handle::cast(y)->to_number())); } else if (y->IsString()) { return Just(NumberEquals(x, String::ToNumber(Handle::cast(y)))); } else if (y->IsJSReceiver()) { if (!JSReceiver::ToPrimitive(Handle::cast(y)) .ToHandle(&y)) { return Nothing(); } } else { return Just(false); } } else if (x->IsString()) { if (y->IsString()) { return Just( String::Equals(Handle::cast(x), Handle::cast(y))); } else if (y->IsNumber()) { x = String::ToNumber(Handle::cast(x)); return Just(NumberEquals(x, y)); } else if (y->IsBoolean()) { x = String::ToNumber(Handle::cast(x)); return Just(NumberEquals(*x, Handle::cast(y)->to_number())); } else if (y->IsJSReceiver()) { if (!JSReceiver::ToPrimitive(Handle::cast(y)) .ToHandle(&y)) { return Nothing(); } } else { return Just(false); } } else if (x->IsBoolean()) { if (y->IsOddball()) { return Just(x.is_identical_to(y)); } else if (y->IsNumber()) { return Just(NumberEquals(Handle::cast(x)->to_number(), *y)); } else if (y->IsString()) { y = String::ToNumber(Handle::cast(y)); return Just(NumberEquals(Handle::cast(x)->to_number(), *y)); } else if (y->IsJSReceiver()) { if (!JSReceiver::ToPrimitive(Handle::cast(y)) .ToHandle(&y)) { return Nothing(); } x = Oddball::ToNumber(Handle::cast(x)); } else { return Just(false); } } else if (x->IsSymbol()) { if (y->IsSymbol()) { return Just(x.is_identical_to(y)); } else if (y->IsJSReceiver()) { if (!JSReceiver::ToPrimitive(Handle::cast(y)) .ToHandle(&y)) { return Nothing(); } } else { return Just(false); } } else if (x->IsJSReceiver()) { if (y->IsJSReceiver()) { return Just(x.is_identical_to(y)); } else if (y->IsUndetectable()) { return Just(x->IsUndetectable()); } else if (y->IsBoolean()) { y = Oddball::ToNumber(Handle::cast(y)); } else if (!JSReceiver::ToPrimitive(Handle::cast(x)) .ToHandle(&x)) { return Nothing(); } } else { return Just(x->IsUndetectable() && y->IsUndetectable()); } } } bool Object::StrictEquals(Object* that) { if (this->IsNumber()) { if (!that->IsNumber()) return false; return NumberEquals(this, that); } else if (this->IsString()) { if (!that->IsString()) return false; return String::cast(this)->Equals(String::cast(that)); } return this == that; } // static Handle Object::TypeOf(Isolate* isolate, Handle object) { if (object->IsNumber()) return isolate->factory()->number_string(); if (object->IsOddball()) return handle(Oddball::cast(*object)->type_of()); if (object->IsUndetectable()) { return isolate->factory()->undefined_string(); } if (object->IsString()) return isolate->factory()->string_string(); if (object->IsSymbol()) return isolate->factory()->symbol_string(); if (object->IsString()) return isolate->factory()->string_string(); if (object->IsCallable()) return isolate->factory()->function_string(); return isolate->factory()->object_string(); } // static MaybeHandle Object::Multiply(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumber(lhs->Number() * rhs->Number()); } // static MaybeHandle Object::Divide(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumber(lhs->Number() / rhs->Number()); } // static MaybeHandle Object::Modulus(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumber(modulo(lhs->Number(), rhs->Number())); } // static MaybeHandle Object::Add(Isolate* isolate, Handle lhs, Handle rhs) { if (lhs->IsNumber() && rhs->IsNumber()) { return isolate->factory()->NewNumber(lhs->Number() + rhs->Number()); } else if (lhs->IsString() && rhs->IsString()) { return isolate->factory()->NewConsString(Handle::cast(lhs), Handle::cast(rhs)); } ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToPrimitive(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToPrimitive(rhs), Object); if (lhs->IsString() || rhs->IsString()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToString(isolate, rhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToString(isolate, lhs), Object); return isolate->factory()->NewConsString(Handle::cast(lhs), Handle::cast(rhs)); } ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); return isolate->factory()->NewNumber(lhs->Number() + rhs->Number()); } // static MaybeHandle Object::Subtract(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumber(lhs->Number() - rhs->Number()); } // static MaybeHandle Object::ShiftLeft(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumberFromInt(NumberToInt32(*lhs) << (NumberToUint32(*rhs) & 0x1F)); } // static MaybeHandle Object::ShiftRight(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumberFromInt(NumberToInt32(*lhs) >> (NumberToUint32(*rhs) & 0x1F)); } // static MaybeHandle Object::ShiftRightLogical(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumberFromUint(NumberToUint32(*lhs) >> (NumberToUint32(*rhs) & 0x1F)); } // static MaybeHandle Object::BitwiseAnd(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumberFromInt(NumberToInt32(*lhs) & NumberToInt32(*rhs)); } // static MaybeHandle Object::BitwiseOr(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumberFromInt(NumberToInt32(*lhs) | NumberToInt32(*rhs)); } // static MaybeHandle Object::BitwiseXor(Isolate* isolate, Handle lhs, Handle rhs) { if (!lhs->IsNumber() || !rhs->IsNumber()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, lhs, Object::ToNumber(lhs), Object); ASSIGN_RETURN_ON_EXCEPTION(isolate, rhs, Object::ToNumber(rhs), Object); } return isolate->factory()->NewNumberFromInt(NumberToInt32(*lhs) ^ NumberToInt32(*rhs)); } // static MaybeHandle Object::OrdinaryHasInstance(Isolate* isolate, Handle callable, Handle object) { // The {callable} must have a [[Call]] internal method. if (!callable->IsCallable()) return isolate->factory()->false_value(); // Check if {callable} is a bound function, and if so retrieve its // [[BoundTargetFunction]] and use that instead of {callable}. if (callable->IsJSBoundFunction()) { Handle bound_callable( Handle::cast(callable)->bound_target_function(), isolate); return Object::InstanceOf(isolate, object, bound_callable); } // If {object} is not a receiver, return false. if (!object->IsJSReceiver()) return isolate->factory()->false_value(); // Get the "prototype" of {callable}; raise an error if it's not a receiver. Handle prototype; ASSIGN_RETURN_ON_EXCEPTION( isolate, prototype, Object::GetProperty(callable, isolate->factory()->prototype_string()), Object); if (!prototype->IsJSReceiver()) { THROW_NEW_ERROR( isolate, NewTypeError(MessageTemplate::kInstanceofNonobjectProto, prototype), Object); } // Return whether or not {prototype} is in the prototype chain of {object}. Maybe result = JSReceiver::HasInPrototypeChain( isolate, Handle::cast(object), prototype); if (result.IsNothing()) return MaybeHandle(); return isolate->factory()->ToBoolean(result.FromJust()); } // static MaybeHandle Object::InstanceOf(Isolate* isolate, Handle object, Handle callable) { // The {callable} must be a receiver. if (!callable->IsJSReceiver()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kNonObjectInInstanceOfCheck), Object); } // Lookup the @@hasInstance method on {callable}. Handle inst_of_handler; ASSIGN_RETURN_ON_EXCEPTION( isolate, inst_of_handler, JSReceiver::GetMethod(Handle::cast(callable), isolate->factory()->has_instance_symbol()), Object); if (!inst_of_handler->IsUndefined(isolate)) { // Call the {inst_of_handler} on the {callable}. Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, Execution::Call(isolate, inst_of_handler, callable, 1, &object), Object); return isolate->factory()->ToBoolean(result->BooleanValue()); } // The {callable} must have a [[Call]] internal method. if (!callable->IsCallable()) { THROW_NEW_ERROR( isolate, NewTypeError(MessageTemplate::kNonCallableInInstanceOfCheck), Object); } // Fall back to OrdinaryHasInstance with {callable} and {object}. Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, JSReceiver::OrdinaryHasInstance(isolate, callable, object), Object); return result; } Maybe Object::IsArray(Handle object) { if (object->IsJSArray()) return Just(true); if (object->IsJSProxy()) { Handle proxy = Handle::cast(object); Isolate* isolate = proxy->GetIsolate(); if (proxy->IsRevoked()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyRevoked, isolate->factory()->NewStringFromAsciiChecked("IsArray"))); return Nothing(); } return Object::IsArray(handle(proxy->target(), isolate)); } return Just(false); } // static MaybeHandle Object::GetMethod(Handle receiver, Handle name) { Handle func; Isolate* isolate = receiver->GetIsolate(); ASSIGN_RETURN_ON_EXCEPTION(isolate, func, JSReceiver::GetProperty(receiver, name), Object); if (func->IsNullOrUndefined(isolate)) { return isolate->factory()->undefined_value(); } if (!func->IsCallable()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kPropertyNotFunction, func, name, receiver), Object); } return func; } namespace { MaybeHandle CreateListFromArrayLikeFastPath( Isolate* isolate, Handle object, ElementTypes element_types) { if (element_types != ElementTypes::kAll || !object->IsJSArray()) { return MaybeHandle(); } Handle array = Handle::cast(object); uint32_t length; if (!array->HasArrayPrototype(isolate) || !array->length()->ToUint32(&length) || !array->HasFastElements() || !JSObject::PrototypeHasNoElements(isolate, *array)) { return MaybeHandle(); } return array->GetElementsAccessor()->CreateListFromArray(isolate, array); } } // namespace // static MaybeHandle Object::CreateListFromArrayLike( Isolate* isolate, Handle object, ElementTypes element_types) { // Fast-path for JS_ARRAY_TYPE. MaybeHandle fast_result = CreateListFromArrayLikeFastPath(isolate, object, element_types); if (!fast_result.is_null()) return fast_result; // 1. ReturnIfAbrupt(object). // 2. (default elementTypes -- not applicable.) // 3. If Type(obj) is not Object, throw a TypeError exception. if (!object->IsJSReceiver()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kCalledOnNonObject, isolate->factory()->NewStringFromAsciiChecked( "CreateListFromArrayLike")), FixedArray); } // 4. Let len be ? ToLength(? Get(obj, "length")). Handle receiver = Handle::cast(object); Handle raw_length_number; ASSIGN_RETURN_ON_EXCEPTION(isolate, raw_length_number, Object::GetLengthFromArrayLike(isolate, receiver), FixedArray); uint32_t len; if (!raw_length_number->ToUint32(&len) || len > static_cast(FixedArray::kMaxLength)) { THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kInvalidArrayLength), FixedArray); } // 5. Let list be an empty List. Handle list = isolate->factory()->NewFixedArray(len); // 6. Let index be 0. // 7. Repeat while index < len: for (uint32_t index = 0; index < len; ++index) { // 7a. Let indexName be ToString(index). // 7b. Let next be ? Get(obj, indexName). Handle next; ASSIGN_RETURN_ON_EXCEPTION(isolate, next, JSReceiver::GetElement(isolate, receiver, index), FixedArray); switch (element_types) { case ElementTypes::kAll: // Nothing to do. break; case ElementTypes::kStringAndSymbol: { // 7c. If Type(next) is not an element of elementTypes, throw a // TypeError exception. if (!next->IsName()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kNotPropertyName, next), FixedArray); } // 7d. Append next as the last element of list. // Internalize on the fly so we can use pointer identity later. next = isolate->factory()->InternalizeName(Handle::cast(next)); break; } } list->set(index, *next); // 7e. Set index to index + 1. (See loop header.) } // 8. Return list. return list; } // static MaybeHandle Object::GetLengthFromArrayLike(Isolate* isolate, Handle object) { Handle val; Handle key = isolate->factory()->length_string(); ASSIGN_RETURN_ON_EXCEPTION( isolate, val, Runtime::GetObjectProperty(isolate, object, key), Object); return Object::ToLength(isolate, val); } // static Maybe JSReceiver::HasProperty(LookupIterator* it) { for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::JSPROXY: return JSProxy::HasProperty(it->isolate(), it->GetHolder(), it->GetName()); case LookupIterator::INTERCEPTOR: { Maybe result = JSObject::GetPropertyAttributesWithInterceptor(it); if (result.IsNothing()) return Nothing(); if (result.FromJust() != ABSENT) return Just(true); break; } case LookupIterator::ACCESS_CHECK: { if (it->HasAccess()) break; Maybe result = JSObject::GetPropertyAttributesWithFailedAccessCheck(it); if (result.IsNothing()) return Nothing(); return Just(result.FromJust() != ABSENT); } case LookupIterator::INTEGER_INDEXED_EXOTIC: // TypedArray out-of-bounds access. return Just(false); case LookupIterator::ACCESSOR: case LookupIterator::DATA: return Just(true); } } return Just(false); } // static MaybeHandle Object::GetProperty(LookupIterator* it) { for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::JSPROXY: { bool was_found; MaybeHandle result = JSProxy::GetProperty(it->isolate(), it->GetHolder(), it->GetName(), it->GetReceiver(), &was_found); if (!was_found) it->NotFound(); return result; } case LookupIterator::INTERCEPTOR: { bool done; Handle result; ASSIGN_RETURN_ON_EXCEPTION( it->isolate(), result, JSObject::GetPropertyWithInterceptor(it, &done), Object); if (done) return result; break; } case LookupIterator::ACCESS_CHECK: if (it->HasAccess()) break; return JSObject::GetPropertyWithFailedAccessCheck(it); case LookupIterator::ACCESSOR: return GetPropertyWithAccessor(it); case LookupIterator::INTEGER_INDEXED_EXOTIC: return it->isolate()->factory()->undefined_value(); case LookupIterator::DATA: return it->GetDataValue(); } } return it->isolate()->factory()->undefined_value(); } // static MaybeHandle JSProxy::GetProperty(Isolate* isolate, Handle proxy, Handle name, Handle receiver, bool* was_found) { *was_found = true; if (receiver->IsJSGlobalObject()) { THROW_NEW_ERROR( isolate, NewTypeError(MessageTemplate::kReadGlobalReferenceThroughProxy, name), Object); } DCHECK(!name->IsPrivate()); STACK_CHECK(isolate, MaybeHandle()); Handle trap_name = isolate->factory()->get_string(); // 1. Assert: IsPropertyKey(P) is true. // 2. Let handler be the value of the [[ProxyHandler]] internal slot of O. Handle handler(proxy->handler(), isolate); // 3. If handler is null, throw a TypeError exception. // 4. Assert: Type(handler) is Object. if (proxy->IsRevoked()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyRevoked, trap_name), Object); } // 5. Let target be the value of the [[ProxyTarget]] internal slot of O. Handle target(proxy->target(), isolate); // 6. Let trap be ? GetMethod(handler, "get"). Handle trap; ASSIGN_RETURN_ON_EXCEPTION( isolate, trap, Object::GetMethod(Handle::cast(handler), trap_name), Object); // 7. If trap is undefined, then if (trap->IsUndefined(isolate)) { // 7.a Return target.[[Get]](P, Receiver). LookupIterator it = LookupIterator::PropertyOrElement(isolate, receiver, name, target); MaybeHandle result = Object::GetProperty(&it); *was_found = it.IsFound(); return result; } // 8. Let trapResult be ? Call(trap, handler, «target, P, Receiver»). Handle trap_result; Handle args[] = {target, name, receiver}; ASSIGN_RETURN_ON_EXCEPTION( isolate, trap_result, Execution::Call(isolate, trap, handler, arraysize(args), args), Object); // 9. Let targetDesc be ? target.[[GetOwnProperty]](P). PropertyDescriptor target_desc; Maybe target_found = JSReceiver::GetOwnPropertyDescriptor(isolate, target, name, &target_desc); MAYBE_RETURN_NULL(target_found); // 10. If targetDesc is not undefined, then if (target_found.FromJust()) { // 10.a. If IsDataDescriptor(targetDesc) and targetDesc.[[Configurable]] is // false and targetDesc.[[Writable]] is false, then // 10.a.i. If SameValue(trapResult, targetDesc.[[Value]]) is false, // throw a TypeError exception. bool inconsistent = PropertyDescriptor::IsDataDescriptor(&target_desc) && !target_desc.configurable() && !target_desc.writable() && !trap_result->SameValue(*target_desc.value()); if (inconsistent) { THROW_NEW_ERROR( isolate, NewTypeError(MessageTemplate::kProxyGetNonConfigurableData, name, target_desc.value(), trap_result), Object); } // 10.b. If IsAccessorDescriptor(targetDesc) and targetDesc.[[Configurable]] // is false and targetDesc.[[Get]] is undefined, then // 10.b.i. If trapResult is not undefined, throw a TypeError exception. inconsistent = PropertyDescriptor::IsAccessorDescriptor(&target_desc) && !target_desc.configurable() && target_desc.get()->IsUndefined(isolate) && !trap_result->IsUndefined(isolate); if (inconsistent) { THROW_NEW_ERROR( isolate, NewTypeError(MessageTemplate::kProxyGetNonConfigurableAccessor, name, trap_result), Object); } } // 11. Return trap_result return trap_result; } Handle JSReceiver::GetDataProperty(LookupIterator* it) { for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::INTERCEPTOR: case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::ACCESS_CHECK: // Support calling this method without an active context, but refuse // access to access-checked objects in that case. if (it->isolate()->context() != nullptr && it->HasAccess()) continue; // Fall through. case LookupIterator::JSPROXY: it->NotFound(); return it->isolate()->factory()->undefined_value(); case LookupIterator::ACCESSOR: // TODO(verwaest): For now this doesn't call into AccessorInfo, since // clients don't need it. Update once relevant. it->NotFound(); return it->isolate()->factory()->undefined_value(); case LookupIterator::INTEGER_INDEXED_EXOTIC: return it->isolate()->factory()->undefined_value(); case LookupIterator::DATA: return it->GetDataValue(); } } return it->isolate()->factory()->undefined_value(); } bool Object::ToInt32(int32_t* value) { if (IsSmi()) { *value = Smi::cast(this)->value(); return true; } if (IsHeapNumber()) { double num = HeapNumber::cast(this)->value(); if (FastI2D(FastD2I(num)) == num) { *value = FastD2I(num); return true; } } return false; } Handle FunctionTemplateInfo::GetOrCreateSharedFunctionInfo( Isolate* isolate, Handle info) { Object* current_info = info->shared_function_info(); if (current_info->IsSharedFunctionInfo()) { return handle(SharedFunctionInfo::cast(current_info), isolate); } Handle class_name(info->class_name(), isolate); Handle name = class_name->IsString() ? Handle::cast(class_name) : isolate->factory()->empty_string(); Handle code; if (info->call_code()->IsCallHandlerInfo() && CallHandlerInfo::cast(info->call_code())->fast_handler()->IsCode()) { code = isolate->builtins()->HandleFastApiCall(); } else { code = isolate->builtins()->HandleApiCall(); } bool is_constructor = !info->remove_prototype(); Handle result = isolate->factory()->NewSharedFunctionInfo(name, code, is_constructor); if (is_constructor) { result->SetConstructStub(*isolate->builtins()->JSConstructStubApi()); } result->set_length(info->length()); if (class_name->IsString()) result->set_instance_class_name(*class_name); result->set_api_func_data(*info); result->DontAdaptArguments(); DCHECK(result->IsApiFunction()); info->set_shared_function_info(*result); return result; } bool FunctionTemplateInfo::IsTemplateFor(Map* map) { // There is a constraint on the object; check. if (!map->IsJSObjectMap()) return false; // Fetch the constructor function of the object. Object* cons_obj = map->GetConstructor(); if (!cons_obj->IsJSFunction()) return false; JSFunction* fun = JSFunction::cast(cons_obj); // Iterate through the chain of inheriting function templates to // see if the required one occurs. for (Object* type = fun->shared()->function_data(); type->IsFunctionTemplateInfo(); type = FunctionTemplateInfo::cast(type)->parent_template()) { if (type == this) return true; } // Didn't find the required type in the inheritance chain. return false; } // static Handle TemplateList::New(Isolate* isolate, int size) { Handle list = isolate->factory()->NewFixedArray(kLengthIndex + size); list->set(kLengthIndex, Smi::kZero); return Handle::cast(list); } // static Handle TemplateList::Add(Isolate* isolate, Handle list, Handle value) { STATIC_ASSERT(kFirstElementIndex == 1); int index = list->length() + 1; Handle fixed_array = Handle::cast(list); fixed_array = FixedArray::SetAndGrow(fixed_array, index, value); fixed_array->set(kLengthIndex, Smi::FromInt(index)); return Handle::cast(fixed_array); } // static MaybeHandle JSObject::New(Handle constructor, Handle new_target, Handle site) { // If called through new, new.target can be: // - a subclass of constructor, // - a proxy wrapper around constructor, or // - the constructor itself. // If called through Reflect.construct, it's guaranteed to be a constructor. Isolate* const isolate = constructor->GetIsolate(); DCHECK(constructor->IsConstructor()); DCHECK(new_target->IsConstructor()); DCHECK(!constructor->has_initial_map() || constructor->initial_map()->instance_type() != JS_FUNCTION_TYPE); Handle initial_map; ASSIGN_RETURN_ON_EXCEPTION( isolate, initial_map, JSFunction::GetDerivedMap(isolate, constructor, new_target), JSObject); Handle result = isolate->factory()->NewJSObjectFromMap(initial_map, NOT_TENURED, site); isolate->counters()->constructed_objects()->Increment(); isolate->counters()->constructed_objects_runtime()->Increment(); return result; } void JSObject::EnsureWritableFastElements(Handle object) { DCHECK(object->HasFastSmiOrObjectElements() || object->HasFastStringWrapperElements()); FixedArray* raw_elems = FixedArray::cast(object->elements()); Heap* heap = object->GetHeap(); if (raw_elems->map() != heap->fixed_cow_array_map()) return; Isolate* isolate = heap->isolate(); Handle elems(raw_elems, isolate); Handle writable_elems = isolate->factory()->CopyFixedArrayWithMap( elems, isolate->factory()->fixed_array_map()); object->set_elements(*writable_elems); isolate->counters()->cow_arrays_converted()->Increment(); } // ES6 9.5.1 // static MaybeHandle JSProxy::GetPrototype(Handle proxy) { Isolate* isolate = proxy->GetIsolate(); Handle trap_name = isolate->factory()->getPrototypeOf_string(); STACK_CHECK(isolate, MaybeHandle()); // 1. Let handler be the value of the [[ProxyHandler]] internal slot. // 2. If handler is null, throw a TypeError exception. // 3. Assert: Type(handler) is Object. // 4. Let target be the value of the [[ProxyTarget]] internal slot. if (proxy->IsRevoked()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyRevoked, trap_name), Object); } Handle target(proxy->target(), isolate); Handle handler(JSReceiver::cast(proxy->handler()), isolate); // 5. Let trap be ? GetMethod(handler, "getPrototypeOf"). Handle trap; ASSIGN_RETURN_ON_EXCEPTION(isolate, trap, GetMethod(handler, trap_name), Object); // 6. If trap is undefined, then return target.[[GetPrototypeOf]](). if (trap->IsUndefined(isolate)) { return JSReceiver::GetPrototype(isolate, target); } // 7. Let handlerProto be ? Call(trap, handler, «target»). Handle argv[] = {target}; Handle handler_proto; ASSIGN_RETURN_ON_EXCEPTION( isolate, handler_proto, Execution::Call(isolate, trap, handler, arraysize(argv), argv), Object); // 8. If Type(handlerProto) is neither Object nor Null, throw a TypeError. if (!(handler_proto->IsJSReceiver() || handler_proto->IsNull(isolate))) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyGetPrototypeOfInvalid), Object); } // 9. Let extensibleTarget be ? IsExtensible(target). Maybe is_extensible = JSReceiver::IsExtensible(target); MAYBE_RETURN_NULL(is_extensible); // 10. If extensibleTarget is true, return handlerProto. if (is_extensible.FromJust()) return handler_proto; // 11. Let targetProto be ? target.[[GetPrototypeOf]](). Handle target_proto; ASSIGN_RETURN_ON_EXCEPTION(isolate, target_proto, JSReceiver::GetPrototype(isolate, target), Object); // 12. If SameValue(handlerProto, targetProto) is false, throw a TypeError. if (!handler_proto->SameValue(*target_proto)) { THROW_NEW_ERROR( isolate, NewTypeError(MessageTemplate::kProxyGetPrototypeOfNonExtensible), Object); } // 13. Return handlerProto. return handler_proto; } MaybeHandle Object::GetPropertyWithAccessor(LookupIterator* it) { Isolate* isolate = it->isolate(); Handle structure = it->GetAccessors(); Handle receiver = it->GetReceiver(); // We should never get here to initialize a const with the hole value since a // const declaration would conflict with the getter. DCHECK(!structure->IsForeign()); // API style callbacks. if (structure->IsAccessorInfo()) { Handle holder = it->GetHolder(); Handle name = it->GetName(); Handle info = Handle::cast(structure); if (!info->IsCompatibleReceiver(*receiver)) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kIncompatibleMethodReceiver, name, receiver), Object); } v8::AccessorNameGetterCallback call_fun = v8::ToCData(info->getter()); if (call_fun == nullptr) return isolate->factory()->undefined_value(); if (info->is_sloppy() && !receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION(isolate, receiver, Object::ConvertReceiver(isolate, receiver), Object); } PropertyCallbackArguments args(isolate, info->data(), *receiver, *holder, Object::DONT_THROW); Handle result = args.Call(call_fun, name); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); if (result.is_null()) return isolate->factory()->undefined_value(); Handle reboxed_result = handle(*result, isolate); if (info->replace_on_access() && receiver->IsJSReceiver()) { args.Call(reinterpret_cast( &Accessors::ReconfigureToDataProperty), name, result); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); } return reboxed_result; } // AccessorPair with 'cached' private property. if (it->TryLookupCachedProperty()) { return Object::GetProperty(it); } // Regular accessor. Handle getter(AccessorPair::cast(*structure)->getter(), isolate); if (getter->IsFunctionTemplateInfo()) { return Builtins::InvokeApiFunction( isolate, false, Handle::cast(getter), receiver, 0, nullptr, isolate->factory()->undefined_value()); } else if (getter->IsCallable()) { // TODO(rossberg): nicer would be to cast to some JSCallable here... return Object::GetPropertyWithDefinedGetter( receiver, Handle::cast(getter)); } // Getter is not a function. return isolate->factory()->undefined_value(); } // static Address AccessorInfo::redirect(Isolate* isolate, Address address, AccessorComponent component) { ApiFunction fun(address); DCHECK_EQ(ACCESSOR_GETTER, component); ExternalReference::Type type = ExternalReference::DIRECT_GETTER_CALL; return ExternalReference(&fun, type, isolate).address(); } Address AccessorInfo::redirected_getter() const { Address accessor = v8::ToCData
(getter()); if (accessor == nullptr) return nullptr; return redirect(GetIsolate(), accessor, ACCESSOR_GETTER); } bool AccessorInfo::IsCompatibleReceiverMap(Isolate* isolate, Handle info, Handle map) { if (!info->HasExpectedReceiverType()) return true; if (!map->IsJSObjectMap()) return false; return FunctionTemplateInfo::cast(info->expected_receiver_type()) ->IsTemplateFor(*map); } Maybe Object::SetPropertyWithAccessor(LookupIterator* it, Handle value, ShouldThrow should_throw) { Isolate* isolate = it->isolate(); Handle structure = it->GetAccessors(); Handle receiver = it->GetReceiver(); // We should never get here to initialize a const with the hole value since a // const declaration would conflict with the setter. DCHECK(!structure->IsForeign()); // API style callbacks. if (structure->IsAccessorInfo()) { Handle holder = it->GetHolder(); Handle name = it->GetName(); Handle info = Handle::cast(structure); if (!info->IsCompatibleReceiver(*receiver)) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kIncompatibleMethodReceiver, name, receiver)); return Nothing(); } // The actual type of call_fun is either v8::AccessorNameSetterCallback or // i::Accesors::AccessorNameBooleanSetterCallback, depending on whether the // AccessorInfo was created by the API or internally (see accessors.cc). // Here we handle both cases using GenericNamedPropertySetterCallback and // its Call method. GenericNamedPropertySetterCallback call_fun = v8::ToCData(info->setter()); if (call_fun == nullptr) { // TODO(verwaest): We should not get here anymore once all AccessorInfos // are marked as special_data_property. They cannot both be writable and // not have a setter. return Just(true); } if (info->is_sloppy() && !receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, receiver, Object::ConvertReceiver(isolate, receiver), Nothing()); } PropertyCallbackArguments args(isolate, info->data(), *receiver, *holder, should_throw); Handle result = args.Call(call_fun, name, value); // In the case of AccessorNameSetterCallback, we know that the result value // cannot have been set, so the result of Call will be null. In the case of // AccessorNameBooleanSetterCallback, the result will either be null // (signalling an exception) or a boolean Oddball. RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); if (result.is_null()) return Just(true); DCHECK(result->BooleanValue() || should_throw == DONT_THROW); return Just(result->BooleanValue()); } // Regular accessor. Handle setter(AccessorPair::cast(*structure)->setter(), isolate); if (setter->IsFunctionTemplateInfo()) { Handle argv[] = {value}; RETURN_ON_EXCEPTION_VALUE( isolate, Builtins::InvokeApiFunction( isolate, false, Handle::cast(setter), receiver, arraysize(argv), argv, isolate->factory()->undefined_value()), Nothing()); return Just(true); } else if (setter->IsCallable()) { // TODO(rossberg): nicer would be to cast to some JSCallable here... return SetPropertyWithDefinedSetter( receiver, Handle::cast(setter), value, should_throw); } RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kNoSetterInCallback, it->GetName(), it->GetHolder())); } MaybeHandle Object::GetPropertyWithDefinedGetter( Handle receiver, Handle getter) { Isolate* isolate = getter->GetIsolate(); // Platforms with simulators like arm/arm64 expose a funny issue. If the // simulator has a separate JS stack pointer from the C++ stack pointer, it // can miss C++ stack overflows in the stack guard at the start of JavaScript // functions. It would be very expensive to check the C++ stack pointer at // that location. The best solution seems to be to break the impasse by // adding checks at possible recursion points. What's more, we don't put // this stack check behind the USE_SIMULATOR define in order to keep // behavior the same between hardware and simulators. StackLimitCheck check(isolate); if (check.JsHasOverflowed()) { isolate->StackOverflow(); return MaybeHandle(); } return Execution::Call(isolate, getter, receiver, 0, NULL); } Maybe Object::SetPropertyWithDefinedSetter(Handle receiver, Handle setter, Handle value, ShouldThrow should_throw) { Isolate* isolate = setter->GetIsolate(); Handle argv[] = { value }; RETURN_ON_EXCEPTION_VALUE(isolate, Execution::Call(isolate, setter, receiver, arraysize(argv), argv), Nothing()); return Just(true); } // static bool JSObject::AllCanRead(LookupIterator* it) { // Skip current iteration, it's in state ACCESS_CHECK or INTERCEPTOR, both of // which have already been checked. DCHECK(it->state() == LookupIterator::ACCESS_CHECK || it->state() == LookupIterator::INTERCEPTOR); for (it->Next(); it->IsFound(); it->Next()) { if (it->state() == LookupIterator::ACCESSOR) { auto accessors = it->GetAccessors(); if (accessors->IsAccessorInfo()) { if (AccessorInfo::cast(*accessors)->all_can_read()) return true; } } else if (it->state() == LookupIterator::INTERCEPTOR) { if (it->GetInterceptor()->all_can_read()) return true; } else if (it->state() == LookupIterator::JSPROXY) { // Stop lookupiterating. And no, AllCanNotRead. return false; } } return false; } namespace { MaybeHandle GetPropertyWithInterceptorInternal( LookupIterator* it, Handle interceptor, bool* done) { *done = false; Isolate* isolate = it->isolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); if (interceptor->getter()->IsUndefined(isolate)) { return isolate->factory()->undefined_value(); } Handle holder = it->GetHolder(); Handle result; Handle receiver = it->GetReceiver(); if (!receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, receiver, Object::ConvertReceiver(isolate, receiver), Object); } PropertyCallbackArguments args(isolate, interceptor->data(), *receiver, *holder, Object::DONT_THROW); if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertyGetterCallback getter = v8::ToCData(interceptor->getter()); result = args.Call(getter, index); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); if (name->IsSymbol() && !interceptor->can_intercept_symbols()) { return isolate->factory()->undefined_value(); } v8::GenericNamedPropertyGetterCallback getter = v8::ToCData( interceptor->getter()); result = args.Call(getter, name); } RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); if (result.is_null()) return isolate->factory()->undefined_value(); *done = true; // Rebox handle before return return handle(*result, isolate); } Maybe GetPropertyAttributesWithInterceptorInternal( LookupIterator* it, Handle interceptor) { Isolate* isolate = it->isolate(); // Make sure that the top context does not change when doing // callbacks or interceptor calls. AssertNoContextChange ncc(isolate); HandleScope scope(isolate); Handle holder = it->GetHolder(); if (!it->IsElement() && it->name()->IsSymbol() && !interceptor->can_intercept_symbols()) { return Just(ABSENT); } Handle receiver = it->GetReceiver(); if (!receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, receiver, Object::ConvertReceiver(isolate, receiver), Nothing()); } PropertyCallbackArguments args(isolate, interceptor->data(), *receiver, *holder, Object::DONT_THROW); if (!interceptor->query()->IsUndefined(isolate)) { Handle result; if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertyQueryCallback query = v8::ToCData(interceptor->query()); result = args.Call(query, index); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); v8::GenericNamedPropertyQueryCallback query = v8::ToCData( interceptor->query()); result = args.Call(query, name); } if (!result.is_null()) { int32_t value; CHECK(result->ToInt32(&value)); return Just(static_cast(value)); } } else if (!interceptor->getter()->IsUndefined(isolate)) { // TODO(verwaest): Use GetPropertyWithInterceptor? Handle result; if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertyGetterCallback getter = v8::ToCData(interceptor->getter()); result = args.Call(getter, index); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); v8::GenericNamedPropertyGetterCallback getter = v8::ToCData( interceptor->getter()); result = args.Call(getter, name); } if (!result.is_null()) return Just(DONT_ENUM); } RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); return Just(ABSENT); } Maybe SetPropertyWithInterceptorInternal( LookupIterator* it, Handle interceptor, Object::ShouldThrow should_throw, Handle value) { Isolate* isolate = it->isolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); if (interceptor->setter()->IsUndefined(isolate)) return Just(false); Handle holder = it->GetHolder(); bool result; Handle receiver = it->GetReceiver(); if (!receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, receiver, Object::ConvertReceiver(isolate, receiver), Nothing()); } PropertyCallbackArguments args(isolate, interceptor->data(), *receiver, *holder, should_throw); if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertySetterCallback setter = v8::ToCData(interceptor->setter()); // TODO(neis): In the future, we may want to actually return the // interceptor's result, which then should be a boolean. result = !args.Call(setter, index, value).is_null(); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); if (name->IsSymbol() && !interceptor->can_intercept_symbols()) { return Just(false); } v8::GenericNamedPropertySetterCallback setter = v8::ToCData( interceptor->setter()); result = !args.Call(setter, name, value).is_null(); } RETURN_VALUE_IF_SCHEDULED_EXCEPTION(it->isolate(), Nothing()); return Just(result); } Maybe DefinePropertyWithInterceptorInternal( LookupIterator* it, Handle interceptor, Object::ShouldThrow should_throw, PropertyDescriptor& desc) { Isolate* isolate = it->isolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); if (interceptor->definer()->IsUndefined(isolate)) return Just(false); Handle holder = it->GetHolder(); bool result; Handle receiver = it->GetReceiver(); if (!receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, receiver, Object::ConvertReceiver(isolate, receiver), Nothing()); } PropertyCallbackArguments args(isolate, interceptor->data(), *receiver, *holder, should_throw); std::unique_ptr descriptor( new v8::PropertyDescriptor()); if (PropertyDescriptor::IsAccessorDescriptor(&desc)) { descriptor.reset(new v8::PropertyDescriptor( v8::Utils::ToLocal(desc.get()), v8::Utils::ToLocal(desc.set()))); } else if (PropertyDescriptor::IsDataDescriptor(&desc)) { if (desc.has_writable()) { descriptor.reset(new v8::PropertyDescriptor( v8::Utils::ToLocal(desc.value()), desc.writable())); } else { descriptor.reset( new v8::PropertyDescriptor(v8::Utils::ToLocal(desc.value()))); } } if (desc.has_enumerable()) { descriptor->set_enumerable(desc.enumerable()); } if (desc.has_configurable()) { descriptor->set_configurable(desc.configurable()); } if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertyDefinerCallback definer = v8::ToCData(interceptor->definer()); result = !args.Call(definer, index, *descriptor).is_null(); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); if (name->IsSymbol() && !interceptor->can_intercept_symbols()) { return Just(false); } v8::GenericNamedPropertyDefinerCallback definer = v8::ToCData( interceptor->definer()); result = !args.Call(definer, name, *descriptor).is_null(); } RETURN_VALUE_IF_SCHEDULED_EXCEPTION(it->isolate(), Nothing()); return Just(result); } } // namespace MaybeHandle JSObject::GetPropertyWithFailedAccessCheck( LookupIterator* it) { Isolate* isolate = it->isolate(); Handle checked = it->GetHolder(); Handle interceptor = it->GetInterceptorForFailedAccessCheck(); if (interceptor.is_null()) { while (AllCanRead(it)) { if (it->state() == LookupIterator::ACCESSOR) { return GetPropertyWithAccessor(it); } DCHECK_EQ(LookupIterator::INTERCEPTOR, it->state()); bool done; Handle result; ASSIGN_RETURN_ON_EXCEPTION(isolate, result, GetPropertyWithInterceptor(it, &done), Object); if (done) return result; } } else { Handle result; bool done; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, GetPropertyWithInterceptorInternal(it, interceptor, &done), Object); if (done) return result; } // Cross-Origin [[Get]] of Well-Known Symbols does not throw, and returns // undefined. Handle name = it->GetName(); if (name->IsSymbol() && Symbol::cast(*name)->is_well_known_symbol()) { return it->factory()->undefined_value(); } isolate->ReportFailedAccessCheck(checked); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return it->factory()->undefined_value(); } Maybe JSObject::GetPropertyAttributesWithFailedAccessCheck( LookupIterator* it) { Isolate* isolate = it->isolate(); Handle checked = it->GetHolder(); Handle interceptor = it->GetInterceptorForFailedAccessCheck(); if (interceptor.is_null()) { while (AllCanRead(it)) { if (it->state() == LookupIterator::ACCESSOR) { return Just(it->property_attributes()); } DCHECK_EQ(LookupIterator::INTERCEPTOR, it->state()); auto result = GetPropertyAttributesWithInterceptor(it); if (isolate->has_scheduled_exception()) break; if (result.IsJust() && result.FromJust() != ABSENT) return result; } } else { Maybe result = GetPropertyAttributesWithInterceptorInternal(it, interceptor); if (isolate->has_pending_exception()) return Nothing(); if (result.FromMaybe(ABSENT) != ABSENT) return result; } isolate->ReportFailedAccessCheck(checked); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); return Just(ABSENT); } // static bool JSObject::AllCanWrite(LookupIterator* it) { for (; it->IsFound() && it->state() != LookupIterator::JSPROXY; it->Next()) { if (it->state() == LookupIterator::ACCESSOR) { Handle accessors = it->GetAccessors(); if (accessors->IsAccessorInfo()) { if (AccessorInfo::cast(*accessors)->all_can_write()) return true; } } } return false; } Maybe JSObject::SetPropertyWithFailedAccessCheck( LookupIterator* it, Handle value, ShouldThrow should_throw) { Isolate* isolate = it->isolate(); Handle checked = it->GetHolder(); Handle interceptor = it->GetInterceptorForFailedAccessCheck(); if (interceptor.is_null()) { if (AllCanWrite(it)) { return SetPropertyWithAccessor(it, value, should_throw); } } else { Maybe result = SetPropertyWithInterceptorInternal( it, interceptor, should_throw, value); if (isolate->has_pending_exception()) return Nothing(); if (result.IsJust()) return result; } isolate->ReportFailedAccessCheck(checked); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); return Just(true); } void JSObject::SetNormalizedProperty(Handle object, Handle name, Handle value, PropertyDetails details) { DCHECK(!object->HasFastProperties()); if (!name->IsUniqueName()) { name = object->GetIsolate()->factory()->InternalizeString( Handle::cast(name)); } if (object->IsJSGlobalObject()) { Handle dictionary(object->global_dictionary()); int entry = dictionary->FindEntry(name); if (entry == GlobalDictionary::kNotFound) { Isolate* isolate = object->GetIsolate(); auto cell = isolate->factory()->NewPropertyCell(); cell->set_value(*value); auto cell_type = value->IsUndefined(isolate) ? PropertyCellType::kUndefined : PropertyCellType::kConstant; details = details.set_cell_type(cell_type); value = cell; dictionary = GlobalDictionary::Add(dictionary, name, value, details); object->set_properties(*dictionary); } else { Handle cell = PropertyCell::PrepareForValue(dictionary, entry, value, details); cell->set_value(*value); } } else { Handle dictionary(object->property_dictionary()); int entry = dictionary->FindEntry(name); if (entry == NameDictionary::kNotFound) { dictionary = NameDictionary::Add(dictionary, name, value, details); object->set_properties(*dictionary); } else { PropertyDetails original_details = dictionary->DetailsAt(entry); int enumeration_index = original_details.dictionary_index(); DCHECK(enumeration_index > 0); details = details.set_index(enumeration_index); dictionary->SetEntry(entry, name, value, details); } } } // static Maybe JSReceiver::HasInPrototypeChain(Isolate* isolate, Handle object, Handle proto) { PrototypeIterator iter(isolate, object, kStartAtReceiver); while (true) { if (!iter.AdvanceFollowingProxies()) return Nothing(); if (iter.IsAtEnd()) return Just(false); if (PrototypeIterator::GetCurrent(iter).is_identical_to(proto)) { return Just(true); } } } namespace { bool HasExcludedProperty( const ScopedVector>* excluded_properties, Handle search_element) { // TODO(gsathya): Change this to be a hashtable. for (int i = 0; i < excluded_properties->length(); i++) { if (search_element->SameValue(*excluded_properties->at(i))) { return true; } } return false; } MUST_USE_RESULT Maybe FastAssign( Handle target, Handle source, const ScopedVector>* excluded_properties, bool use_set) { // Non-empty strings are the only non-JSReceivers that need to be handled // explicitly by Object.assign. if (!source->IsJSReceiver()) { return Just(!source->IsString() || String::cast(*source)->length() == 0); } // If the target is deprecated, the object will be updated on first store. If // the source for that store equals the target, this will invalidate the // cached representation of the source. Preventively upgrade the target. // Do this on each iteration since any property load could cause deprecation. if (target->map()->is_deprecated()) { JSObject::MigrateInstance(Handle::cast(target)); } Isolate* isolate = target->GetIsolate(); Handle map(JSReceiver::cast(*source)->map(), isolate); if (!map->IsJSObjectMap()) return Just(false); if (!map->OnlyHasSimpleProperties()) return Just(false); Handle from = Handle::cast(source); if (from->elements() != isolate->heap()->empty_fixed_array()) { return Just(false); } Handle descriptors(map->instance_descriptors(), isolate); int length = map->NumberOfOwnDescriptors(); bool stable = true; for (int i = 0; i < length; i++) { Handle next_key(descriptors->GetKey(i), isolate); Handle prop_value; // Directly decode from the descriptor array if |from| did not change shape. if (stable) { PropertyDetails details = descriptors->GetDetails(i); if (!details.IsEnumerable()) continue; if (details.kind() == kData) { if (details.location() == kDescriptor) { prop_value = handle(descriptors->GetValue(i), isolate); } else { Representation representation = details.representation(); FieldIndex index = FieldIndex::ForDescriptor(*map, i); prop_value = JSObject::FastPropertyAt(from, representation, index); } } else { ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, prop_value, JSReceiver::GetProperty(from, next_key), Nothing()); stable = from->map() == *map; } } else { // If the map did change, do a slower lookup. We are still guaranteed that // the object has a simple shape, and that the key is a name. LookupIterator it(from, next_key, from, LookupIterator::OWN_SKIP_INTERCEPTOR); if (!it.IsFound()) continue; DCHECK(it.state() == LookupIterator::DATA || it.state() == LookupIterator::ACCESSOR); if (!it.IsEnumerable()) continue; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, prop_value, Object::GetProperty(&it), Nothing()); } if (use_set) { LookupIterator it(target, next_key, target); bool call_to_js = it.IsFound() && it.state() != LookupIterator::DATA; Maybe result = Object::SetProperty( &it, prop_value, STRICT, Object::CERTAINLY_NOT_STORE_FROM_KEYED); if (result.IsNothing()) return result; if (stable && call_to_js) stable = from->map() == *map; } else { if (excluded_properties != nullptr && HasExcludedProperty(excluded_properties, next_key)) { continue; } // 4a ii 2. Perform ? CreateDataProperty(target, nextKey, propValue). bool success; LookupIterator it = LookupIterator::PropertyOrElement( isolate, target, next_key, &success, LookupIterator::OWN); CHECK(success); CHECK( JSObject::CreateDataProperty(&it, prop_value, Object::THROW_ON_ERROR) .FromJust()); } } return Just(true); } } // namespace // static Maybe JSReceiver::SetOrCopyDataProperties( Isolate* isolate, Handle target, Handle source, const ScopedVector>* excluded_properties, bool use_set) { Maybe fast_assign = FastAssign(target, source, excluded_properties, use_set); if (fast_assign.IsNothing()) return Nothing(); if (fast_assign.FromJust()) return Just(true); Handle from = Object::ToObject(isolate, source).ToHandleChecked(); // 3b. Let keys be ? from.[[OwnPropertyKeys]](). Handle keys; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, keys, KeyAccumulator::GetKeys(from, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES, GetKeysConversion::kKeepNumbers), Nothing()); // 4. Repeat for each element nextKey of keys in List order, for (int j = 0; j < keys->length(); ++j) { Handle next_key(keys->get(j), isolate); // 4a i. Let desc be ? from.[[GetOwnProperty]](nextKey). PropertyDescriptor desc; Maybe found = JSReceiver::GetOwnPropertyDescriptor(isolate, from, next_key, &desc); if (found.IsNothing()) return Nothing(); // 4a ii. If desc is not undefined and desc.[[Enumerable]] is true, then if (found.FromJust() && desc.enumerable()) { // 4a ii 1. Let propValue be ? Get(from, nextKey). Handle prop_value; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, prop_value, Runtime::GetObjectProperty(isolate, from, next_key), Nothing()); if (use_set) { // 4c ii 2. Let status be ? Set(to, nextKey, propValue, true). Handle status; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, status, Runtime::SetObjectProperty( isolate, target, next_key, prop_value, STRICT), Nothing()); } else { if (excluded_properties != nullptr && HasExcludedProperty(excluded_properties, next_key)) { continue; } // 4a ii 2. Perform ! CreateDataProperty(target, nextKey, propValue). bool success; LookupIterator it = LookupIterator::PropertyOrElement( isolate, target, next_key, &success, LookupIterator::OWN); CHECK(success); CHECK(JSObject::CreateDataProperty(&it, prop_value, Object::THROW_ON_ERROR) .FromJust()); } } } return Just(true); } Map* Object::GetPrototypeChainRootMap(Isolate* isolate) { DisallowHeapAllocation no_alloc; if (IsSmi()) { Context* native_context = isolate->context()->native_context(); return native_context->number_function()->initial_map(); } // The object is either a number, a string, a symbol, a boolean, a real JS // object, or a Harmony proxy. HeapObject* heap_object = HeapObject::cast(this); return heap_object->map()->GetPrototypeChainRootMap(isolate); } Map* Map::GetPrototypeChainRootMap(Isolate* isolate) { DisallowHeapAllocation no_alloc; if (IsJSReceiverMap()) { return this; } int constructor_function_index = GetConstructorFunctionIndex(); if (constructor_function_index != Map::kNoConstructorFunctionIndex) { Context* native_context = isolate->context()->native_context(); JSFunction* constructor_function = JSFunction::cast(native_context->get(constructor_function_index)); return constructor_function->initial_map(); } return isolate->heap()->null_value()->map(); } namespace { // Returns a non-SMI for JSObjects, but returns the hash code for simple // objects. This avoids a double lookup in the cases where we know we will // add the hash to the JSObject if it does not already exist. Object* GetSimpleHash(Object* object) { // The object is either a Smi, a HeapNumber, a name, an odd-ball, a real JS // object, or a Harmony proxy. if (object->IsSmi()) { uint32_t hash = ComputeIntegerHash(Smi::cast(object)->value(), kZeroHashSeed); return Smi::FromInt(hash & Smi::kMaxValue); } if (object->IsHeapNumber()) { double num = HeapNumber::cast(object)->value(); if (std::isnan(num)) return Smi::FromInt(Smi::kMaxValue); if (i::IsMinusZero(num)) num = 0; if (IsSmiDouble(num)) { return Smi::FromInt(FastD2I(num))->GetHash(); } uint32_t hash = ComputeLongHash(double_to_uint64(num)); return Smi::FromInt(hash & Smi::kMaxValue); } if (object->IsName()) { uint32_t hash = Name::cast(object)->Hash(); return Smi::FromInt(hash); } if (object->IsOddball()) { uint32_t hash = Oddball::cast(object)->to_string()->Hash(); return Smi::FromInt(hash); } DCHECK(object->IsJSReceiver()); // Simply return the receiver as it is guaranteed to not be a SMI. return object; } } // namespace Object* Object::GetHash() { Object* hash = GetSimpleHash(this); if (hash->IsSmi()) return hash; DisallowHeapAllocation no_gc; DCHECK(IsJSReceiver()); JSReceiver* receiver = JSReceiver::cast(this); Isolate* isolate = receiver->GetIsolate(); return JSReceiver::GetIdentityHash(isolate, handle(receiver, isolate)); } Smi* Object::GetOrCreateHash(Isolate* isolate, Handle object) { Object* hash = GetSimpleHash(*object); if (hash->IsSmi()) return Smi::cast(hash); DCHECK(object->IsJSReceiver()); return JSReceiver::GetOrCreateIdentityHash(isolate, Handle::cast(object)); } bool Object::SameValue(Object* other) { if (other == this) return true; // The object is either a number, a name, an odd-ball, // a real JS object, or a Harmony proxy. if (IsNumber() && other->IsNumber()) { double this_value = Number(); double other_value = other->Number(); // SameValue(NaN, NaN) is true. if (this_value != other_value) { return std::isnan(this_value) && std::isnan(other_value); } // SameValue(0.0, -0.0) is false. return (std::signbit(this_value) == std::signbit(other_value)); } if (IsString() && other->IsString()) { return String::cast(this)->Equals(String::cast(other)); } return false; } bool Object::SameValueZero(Object* other) { if (other == this) return true; // The object is either a number, a name, an odd-ball, // a real JS object, or a Harmony proxy. if (IsNumber() && other->IsNumber()) { double this_value = Number(); double other_value = other->Number(); // +0 == -0 is true return this_value == other_value || (std::isnan(this_value) && std::isnan(other_value)); } if (IsString() && other->IsString()) { return String::cast(this)->Equals(String::cast(other)); } return false; } MaybeHandle Object::ArraySpeciesConstructor( Isolate* isolate, Handle original_array) { Handle default_species = isolate->array_function(); if (original_array->IsJSArray() && Handle::cast(original_array)->HasArrayPrototype(isolate) && isolate->IsArraySpeciesLookupChainIntact()) { return default_species; } Handle constructor = isolate->factory()->undefined_value(); Maybe is_array = Object::IsArray(original_array); MAYBE_RETURN_NULL(is_array); if (is_array.FromJust()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, constructor, Object::GetProperty(original_array, isolate->factory()->constructor_string()), Object); if (constructor->IsConstructor()) { Handle constructor_context; ASSIGN_RETURN_ON_EXCEPTION( isolate, constructor_context, JSReceiver::GetFunctionRealm(Handle::cast(constructor)), Object); if (*constructor_context != *isolate->native_context() && *constructor == constructor_context->array_function()) { constructor = isolate->factory()->undefined_value(); } } if (constructor->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, constructor, JSReceiver::GetProperty(Handle::cast(constructor), isolate->factory()->species_symbol()), Object); if (constructor->IsNull(isolate)) { constructor = isolate->factory()->undefined_value(); } } } if (constructor->IsUndefined(isolate)) { return default_species; } else { if (!constructor->IsConstructor()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kSpeciesNotConstructor), Object); } return constructor; } } bool Object::IterationHasObservableEffects() { // Check that this object is an array. if (!IsJSArray()) return true; JSArray* spread_array = JSArray::cast(this); Isolate* isolate = spread_array->GetIsolate(); // Check that we have the original ArrayPrototype. JSObject* array_proto = JSObject::cast(spread_array->map()->prototype()); if (!isolate->is_initial_array_prototype(array_proto)) return true; // Check that the ArrayPrototype hasn't been modified in a way that would // affect iteration. if (!isolate->IsArrayIteratorLookupChainIntact()) return true; // Check that the map of the initial array iterator hasn't changed. Map* iterator_map = isolate->initial_array_iterator_prototype()->map(); if (!isolate->is_initial_array_iterator_prototype_map(iterator_map)) { return true; } // For FastPacked kinds, iteration will have the same effect as simply // accessing each property in order. ElementsKind array_kind = spread_array->GetElementsKind(); if (IsFastPackedElementsKind(array_kind)) return false; // For FastHoley kinds, an element access on a hole would cause a lookup on // the prototype. This could have different results if the prototype has been // changed. if (IsFastHoleyElementsKind(array_kind) && isolate->IsFastArrayConstructorPrototypeChainIntact()) { return false; } return true; } void Object::ShortPrint(FILE* out) { OFStream os(out); os << Brief(this); } void Object::ShortPrint(StringStream* accumulator) { std::ostringstream os; os << Brief(this); accumulator->Add(os.str().c_str()); } void Object::ShortPrint(std::ostream& os) { os << Brief(this); } std::ostream& operator<<(std::ostream& os, const Brief& v) { if (v.value->IsSmi()) { Smi::cast(v.value)->SmiPrint(os); } else { // TODO(svenpanne) Const-correct HeapObjectShortPrint! HeapObject* obj = const_cast(HeapObject::cast(v.value)); obj->HeapObjectShortPrint(os); } return os; } void Smi::SmiPrint(std::ostream& os) const { // NOLINT os << value(); } // Should a word be prefixed by 'a' or 'an' in order to read naturally in // English? Returns false for non-ASCII or words that don't start with // a capital letter. The a/an rule follows pronunciation in English. // We don't use the BBC's overcorrect "an historic occasion" though if // you speak a dialect you may well say "an 'istoric occasion". static bool AnWord(String* str) { if (str->length() == 0) return false; // A nothing. int c0 = str->Get(0); int c1 = str->length() > 1 ? str->Get(1) : 0; if (c0 == 'U') { if (c1 > 'Z') { return true; // An Umpire, but a UTF8String, a U. } } else if (c0 == 'A' || c0 == 'E' || c0 == 'I' || c0 == 'O') { return true; // An Ape, an ABCBook. } else if ((c1 == 0 || (c1 >= 'A' && c1 <= 'Z')) && (c0 == 'F' || c0 == 'H' || c0 == 'M' || c0 == 'N' || c0 == 'R' || c0 == 'S' || c0 == 'X')) { return true; // An MP3File, an M. } return false; } Handle String::SlowFlatten(Handle cons, PretenureFlag pretenure) { DCHECK(cons->second()->length() != 0); // TurboFan can create cons strings with empty first parts. while (cons->first()->length() == 0) { // We do not want to call this function recursively. Therefore we call // String::Flatten only in those cases where String::SlowFlatten is not // called again. if (cons->second()->IsConsString() && !cons->second()->IsFlat()) { cons = handle(ConsString::cast(cons->second())); } else { return String::Flatten(handle(cons->second())); } } DCHECK(AllowHeapAllocation::IsAllowed()); Isolate* isolate = cons->GetIsolate(); int length = cons->length(); PretenureFlag tenure = isolate->heap()->InNewSpace(*cons) ? pretenure : TENURED; Handle result; if (cons->IsOneByteRepresentation()) { Handle flat = isolate->factory()->NewRawOneByteString( length, tenure).ToHandleChecked(); DisallowHeapAllocation no_gc; WriteToFlat(*cons, flat->GetChars(), 0, length); result = flat; } else { Handle flat = isolate->factory()->NewRawTwoByteString( length, tenure).ToHandleChecked(); DisallowHeapAllocation no_gc; WriteToFlat(*cons, flat->GetChars(), 0, length); result = flat; } cons->set_first(*result); cons->set_second(isolate->heap()->empty_string()); DCHECK(result->IsFlat()); return result; } bool String::MakeExternal(v8::String::ExternalStringResource* resource) { // Externalizing twice leaks the external resource, so it's // prohibited by the API. DCHECK(!this->IsExternalString()); DCHECK(!resource->IsCompressible()); #ifdef ENABLE_SLOW_DCHECKS if (FLAG_enable_slow_asserts) { // Assert that the resource and the string are equivalent. DCHECK(static_cast(this->length()) == resource->length()); ScopedVector smart_chars(this->length()); String::WriteToFlat(this, smart_chars.start(), 0, this->length()); DCHECK(memcmp(smart_chars.start(), resource->data(), resource->length() * sizeof(smart_chars[0])) == 0); } #endif // DEBUG int size = this->Size(); // Byte size of the original string. // Abort if size does not allow in-place conversion. if (size < ExternalString::kShortSize) return false; Heap* heap = GetHeap(); bool is_one_byte = this->IsOneByteRepresentation(); bool is_internalized = this->IsInternalizedString(); bool has_pointers = StringShape(this).IsIndirect(); // Morph the string to an external string by replacing the map and // reinitializing the fields. This won't work if the space the existing // string occupies is too small for a regular external string. // Instead, we resort to a short external string instead, omitting // the field caching the address of the backing store. When we encounter // short external strings in generated code, we need to bailout to runtime. Map* new_map; if (size < ExternalString::kSize) { new_map = is_internalized ? (is_one_byte ? heap->short_external_internalized_string_with_one_byte_data_map() : heap->short_external_internalized_string_map()) : (is_one_byte ? heap->short_external_string_with_one_byte_data_map() : heap->short_external_string_map()); } else { new_map = is_internalized ? (is_one_byte ? heap->external_internalized_string_with_one_byte_data_map() : heap->external_internalized_string_map()) : (is_one_byte ? heap->external_string_with_one_byte_data_map() : heap->external_string_map()); } // Byte size of the external String object. int new_size = this->SizeFromMap(new_map); heap->CreateFillerObjectAt(this->address() + new_size, size - new_size, ClearRecordedSlots::kNo); if (has_pointers) { heap->ClearRecordedSlotRange(this->address(), this->address() + new_size); } // We are storing the new map using release store after creating a filler for // the left-over space to avoid races with the sweeper thread. this->synchronized_set_map(new_map); ExternalTwoByteString* self = ExternalTwoByteString::cast(this); self->set_resource(resource); if (is_internalized) self->Hash(); // Force regeneration of the hash value. heap->AdjustLiveBytes(this, new_size - size); return true; } bool String::MakeExternal(v8::String::ExternalOneByteStringResource* resource) { // Externalizing twice leaks the external resource, so it's // prohibited by the API. DCHECK(!this->IsExternalString()); DCHECK(!resource->IsCompressible()); #ifdef ENABLE_SLOW_DCHECKS if (FLAG_enable_slow_asserts) { // Assert that the resource and the string are equivalent. DCHECK(static_cast(this->length()) == resource->length()); if (this->IsTwoByteRepresentation()) { ScopedVector smart_chars(this->length()); String::WriteToFlat(this, smart_chars.start(), 0, this->length()); DCHECK(String::IsOneByte(smart_chars.start(), this->length())); } ScopedVector smart_chars(this->length()); String::WriteToFlat(this, smart_chars.start(), 0, this->length()); DCHECK(memcmp(smart_chars.start(), resource->data(), resource->length() * sizeof(smart_chars[0])) == 0); } #endif // DEBUG int size = this->Size(); // Byte size of the original string. // Abort if size does not allow in-place conversion. if (size < ExternalString::kShortSize) return false; Heap* heap = GetHeap(); bool is_internalized = this->IsInternalizedString(); bool has_pointers = StringShape(this).IsIndirect(); // Morph the string to an external string by replacing the map and // reinitializing the fields. This won't work if the space the existing // string occupies is too small for a regular external string. // Instead, we resort to a short external string instead, omitting // the field caching the address of the backing store. When we encounter // short external strings in generated code, we need to bailout to runtime. Map* new_map; if (size < ExternalString::kSize) { new_map = is_internalized ? heap->short_external_one_byte_internalized_string_map() : heap->short_external_one_byte_string_map(); } else { new_map = is_internalized ? heap->external_one_byte_internalized_string_map() : heap->external_one_byte_string_map(); } // Byte size of the external String object. int new_size = this->SizeFromMap(new_map); heap->CreateFillerObjectAt(this->address() + new_size, size - new_size, ClearRecordedSlots::kNo); if (has_pointers) { heap->ClearRecordedSlotRange(this->address(), this->address() + new_size); } // We are storing the new map using release store after creating a filler for // the left-over space to avoid races with the sweeper thread. this->synchronized_set_map(new_map); ExternalOneByteString* self = ExternalOneByteString::cast(this); self->set_resource(resource); if (is_internalized) self->Hash(); // Force regeneration of the hash value. heap->AdjustLiveBytes(this, new_size - size); return true; } void String::StringShortPrint(StringStream* accumulator, bool show_details) { int len = length(); if (len > kMaxShortPrintLength) { accumulator->Add("", len); return; } if (!LooksValid()) { accumulator->Add(""); return; } StringCharacterStream stream(this); bool truncated = false; if (len > kMaxShortPrintLength) { len = kMaxShortPrintLength; truncated = true; } bool one_byte = true; for (int i = 0; i < len; i++) { uint16_t c = stream.GetNext(); if (c < 32 || c >= 127) { one_byte = false; } } stream.Reset(this); if (one_byte) { if (show_details) accumulator->Add("Put(static_cast(stream.GetNext())); } if (show_details) accumulator->Put('>'); } else { // Backslash indicates that the string contains control // characters and that backslashes are therefore escaped. if (show_details) accumulator->Add("Add("\\n"); } else if (c == '\r') { accumulator->Add("\\r"); } else if (c == '\\') { accumulator->Add("\\\\"); } else if (c < 32 || c > 126) { accumulator->Add("\\x%02x", c); } else { accumulator->Put(static_cast(c)); } } if (truncated) { accumulator->Put('.'); accumulator->Put('.'); accumulator->Put('.'); } if (show_details) accumulator->Put('>'); } return; } void String::PrintUC16(std::ostream& os, int start, int end) { // NOLINT if (end < 0) end = length(); StringCharacterStream stream(this, start); for (int i = start; i < end && stream.HasMore(); i++) { os << AsUC16(stream.GetNext()); } } void JSObject::JSObjectShortPrint(StringStream* accumulator) { switch (map()->instance_type()) { case JS_ARRAY_TYPE: { double length = JSArray::cast(this)->length()->IsUndefined(GetIsolate()) ? 0 : JSArray::cast(this)->length()->Number(); accumulator->Add("", static_cast(length)); break; } case JS_BOUND_FUNCTION_TYPE: { JSBoundFunction* bound_function = JSBoundFunction::cast(this); accumulator->Add("Add( " (BoundTargetFunction %p)>", reinterpret_cast(bound_function->bound_target_function())); break; } case JS_WEAK_MAP_TYPE: { accumulator->Add(""); break; } case JS_WEAK_SET_TYPE: { accumulator->Add(""); break; } case JS_REGEXP_TYPE: { accumulator->Add(""); break; } case JS_FUNCTION_TYPE: { JSFunction* function = JSFunction::cast(this); Object* fun_name = function->shared()->DebugName(); bool printed = false; if (fun_name->IsString()) { String* str = String::cast(fun_name); if (str->length() > 0) { accumulator->Add("Put(str); printed = true; } } if (!printed) { accumulator->Add("shared()->script())->name(); if (source_name->IsString()) { String* str = String::cast(source_name); if (str->length() > 0) { accumulator->Add(" <"); accumulator->Put(str); accumulator->Add(">"); } } } accumulator->Add(" (SharedFunctionInfo %p)", reinterpret_cast(function->shared())); accumulator->Put('>'); break; } case JS_GENERATOR_OBJECT_TYPE: { accumulator->Add(""); break; } // All other JSObjects are rather similar to each other (JSObject, // JSGlobalProxy, JSGlobalObject, JSUndetectable, JSValue). default: { Map* map_of_this = map(); Heap* heap = GetHeap(); Object* constructor = map_of_this->GetConstructor(); bool printed = false; if (constructor->IsHeapObject() && !heap->Contains(HeapObject::cast(constructor))) { accumulator->Add("!!!INVALID CONSTRUCTOR!!!"); } else { bool global_object = IsJSGlobalProxy(); if (constructor->IsJSFunction()) { if (!heap->Contains(JSFunction::cast(constructor)->shared())) { accumulator->Add("!!!INVALID SHARED ON CONSTRUCTOR!!!"); } else { Object* constructor_name = JSFunction::cast(constructor)->shared()->name(); if (constructor_name->IsString()) { String* str = String::cast(constructor_name); if (str->length() > 0) { bool vowel = AnWord(str); accumulator->Add("<%sa%s ", global_object ? "Global Object: " : "", vowel ? "n" : ""); accumulator->Put(str); accumulator->Add(" with %smap %p", map_of_this->is_deprecated() ? "deprecated " : "", map_of_this); printed = true; } } } } if (!printed) { accumulator->Add("Add(" value = "); JSValue::cast(this)->value()->ShortPrint(accumulator); } accumulator->Put('>'); break; } } } void JSObject::PrintElementsTransition( FILE* file, Handle object, ElementsKind from_kind, Handle from_elements, ElementsKind to_kind, Handle to_elements) { if (from_kind != to_kind) { OFStream os(file); os << "elements transition [" << ElementsKindToString(from_kind) << " -> " << ElementsKindToString(to_kind) << "] in "; JavaScriptFrame::PrintTop(object->GetIsolate(), file, false, true); PrintF(file, " for "); object->ShortPrint(file); PrintF(file, " from "); from_elements->ShortPrint(file); PrintF(file, " to "); to_elements->ShortPrint(file); PrintF(file, "\n"); } } // static MaybeHandle Map::GetConstructorFunction( Handle map, Handle native_context) { if (map->IsPrimitiveMap()) { int const constructor_function_index = map->GetConstructorFunctionIndex(); if (constructor_function_index != kNoConstructorFunctionIndex) { return handle( JSFunction::cast(native_context->get(constructor_function_index))); } } return MaybeHandle(); } void Map::PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind, PropertyAttributes attributes) { OFStream os(file); os << "[reconfiguring]"; Name* name = instance_descriptors()->GetKey(modify_index); if (name->IsString()) { String::cast(name)->PrintOn(file); } else { os << "{symbol " << static_cast(name) << "}"; } os << ": " << (kind == kData ? "kData" : "ACCESSORS") << ", attrs: "; os << attributes << " ["; JavaScriptFrame::PrintTop(GetIsolate(), file, false, true); os << "]\n"; } void Map::PrintGeneralization( FILE* file, const char* reason, int modify_index, int split, int descriptors, bool descriptor_to_field, Representation old_representation, Representation new_representation, MaybeHandle old_field_type, MaybeHandle old_value, MaybeHandle new_field_type, MaybeHandle new_value) { OFStream os(file); os << "[generalizing]"; Name* name = instance_descriptors()->GetKey(modify_index); if (name->IsString()) { String::cast(name)->PrintOn(file); } else { os << "{symbol " << static_cast(name) << "}"; } os << ":"; if (descriptor_to_field) { os << "c"; } else { os << old_representation.Mnemonic() << "{"; if (old_field_type.is_null()) { os << Brief(*(old_value.ToHandleChecked())); } else { old_field_type.ToHandleChecked()->PrintTo(os); } os << "}"; } os << "->" << new_representation.Mnemonic() << "{"; if (new_field_type.is_null()) { os << Brief(*(new_value.ToHandleChecked())); } else { new_field_type.ToHandleChecked()->PrintTo(os); } os << "} ("; if (strlen(reason) > 0) { os << reason; } else { os << "+" << (descriptors - split) << " maps"; } os << ") ["; JavaScriptFrame::PrintTop(GetIsolate(), file, false, true); os << "]\n"; } void JSObject::PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map) { PrintF(file, "[migrating]"); DescriptorArray* o = original_map->instance_descriptors(); DescriptorArray* n = new_map->instance_descriptors(); for (int i = 0; i < original_map->NumberOfOwnDescriptors(); i++) { Representation o_r = o->GetDetails(i).representation(); Representation n_r = n->GetDetails(i).representation(); if (!o_r.Equals(n_r)) { String::cast(o->GetKey(i))->PrintOn(file); PrintF(file, ":%s->%s ", o_r.Mnemonic(), n_r.Mnemonic()); } else if (o->GetDetails(i).location() == kDescriptor && n->GetDetails(i).location() == kField) { Name* name = o->GetKey(i); if (name->IsString()) { String::cast(name)->PrintOn(file); } else { PrintF(file, "{symbol %p}", static_cast(name)); } PrintF(file, " "); } } PrintF(file, "\n"); } void HeapObject::HeapObjectShortPrint(std::ostream& os) { // NOLINT Heap* heap = GetHeap(); Isolate* isolate = heap->isolate(); if (!heap->Contains(this)) { os << "!!!INVALID POINTER!!!"; return; } if (!heap->Contains(map())) { os << "!!!INVALID MAP!!!"; return; } os << this << " "; if (IsString()) { HeapStringAllocator allocator; StringStream accumulator(&allocator); String::cast(this)->StringShortPrint(&accumulator); os << accumulator.ToCString().get(); return; } if (IsJSObject()) { HeapStringAllocator allocator; StringStream accumulator(&allocator); JSObject::cast(this)->JSObjectShortPrint(&accumulator); os << accumulator.ToCString().get(); return; } switch (map()->instance_type()) { case MAP_TYPE: os << "elements_kind()) << ")>"; break; case FIXED_ARRAY_TYPE: os << "length() << "]>"; break; case FIXED_DOUBLE_ARRAY_TYPE: os << "length() << "]>"; break; case BYTE_ARRAY_TYPE: os << "length() << "]>"; break; case BYTECODE_ARRAY_TYPE: os << "length() << "]>"; break; case TRANSITION_ARRAY_TYPE: os << "length() << "]>"; break; case FREE_SPACE_TYPE: os << "size() << "]>"; break; #define TYPED_ARRAY_SHORT_PRINT(Type, type, TYPE, ctype, size) \ case FIXED_##TYPE##_ARRAY_TYPE: \ os << "length() \ << "]>"; \ break; TYPED_ARRAYS(TYPED_ARRAY_SHORT_PRINT) #undef TYPED_ARRAY_SHORT_PRINT case SHARED_FUNCTION_INFO_TYPE: { SharedFunctionInfo* shared = SharedFunctionInfo::cast(this); std::unique_ptr debug_name = shared->DebugName()->ToCString(); if (debug_name[0] != 0) { os << ""; } else { os << ""; } break; } case JS_MESSAGE_OBJECT_TYPE: os << ""; break; #define MAKE_STRUCT_CASE(NAME, Name, name) \ case NAME##_TYPE: \ os << "<" #Name ">"; \ break; STRUCT_LIST(MAKE_STRUCT_CASE) #undef MAKE_STRUCT_CASE case CODE_TYPE: { Code* code = Code::cast(this); os << "kind()) << ">"; break; } case ODDBALL_TYPE: { if (IsUndefined(isolate)) { os << ""; } else if (IsTheHole(isolate)) { os << ""; } else if (IsNull(isolate)) { os << ""; } else if (IsTrue(isolate)) { os << ""; } else if (IsFalse(isolate)) { os << ""; } else { os << "to_string()->ToCString().get(); os << ">"; } break; } case SYMBOL_TYPE: { Symbol* symbol = Symbol::cast(this); symbol->SymbolShortPrint(os); break; } case HEAP_NUMBER_TYPE: { os << "HeapNumberPrint(os); os << ">"; break; } case MUTABLE_HEAP_NUMBER_TYPE: { os << "HeapNumberPrint(os); os << '>'; break; } case JS_PROXY_TYPE: os << ""; break; case FOREIGN_TYPE: os << ""; break; case CELL_TYPE: { os << "Cell for "; HeapStringAllocator allocator; StringStream accumulator(&allocator); Cell::cast(this)->value()->ShortPrint(&accumulator); os << accumulator.ToCString().get(); break; } case PROPERTY_CELL_TYPE: { os << "PropertyCell for "; HeapStringAllocator allocator; StringStream accumulator(&allocator); PropertyCell* cell = PropertyCell::cast(this); cell->value()->ShortPrint(&accumulator); os << accumulator.ToCString().get(); break; } case WEAK_CELL_TYPE: { os << "WeakCell for "; HeapStringAllocator allocator; StringStream accumulator(&allocator); WeakCell::cast(this)->value()->ShortPrint(&accumulator); os << accumulator.ToCString().get(); break; } default: os << "instance_type() << ")>"; break; } } void HeapObject::Iterate(ObjectVisitor* v) { IterateFast(v); } void HeapObject::IterateBody(ObjectVisitor* v) { Map* m = map(); IterateBodyFast(m->instance_type(), SizeFromMap(m), v); } void HeapObject::IterateBody(InstanceType type, int object_size, ObjectVisitor* v) { IterateBodyFast(type, object_size, v); } struct CallIsValidSlot { template static bool apply(HeapObject* obj, int offset, int) { return BodyDescriptor::IsValidSlot(obj, offset); } }; bool HeapObject::IsValidSlot(int offset) { DCHECK_NE(0, offset); return BodyDescriptorApply(map()->instance_type(), this, offset, 0); } bool HeapNumber::HeapNumberBooleanValue() { return DoubleToBoolean(value()); } void HeapNumber::HeapNumberPrint(std::ostream& os) { // NOLINT os << value(); } #define FIELD_ADDR_CONST(p, offset) \ (reinterpret_cast(p) + offset - kHeapObjectTag) #define READ_INT32_FIELD(p, offset) \ (*reinterpret_cast(FIELD_ADDR_CONST(p, offset))) #define READ_INT64_FIELD(p, offset) \ (*reinterpret_cast(FIELD_ADDR_CONST(p, offset))) #define READ_BYTE_FIELD(p, offset) \ (*reinterpret_cast(FIELD_ADDR_CONST(p, offset))) String* JSReceiver::class_name() { if (IsFunction()) { return GetHeap()->Function_string(); } Object* maybe_constructor = map()->GetConstructor(); if (maybe_constructor->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(maybe_constructor); return String::cast(constructor->shared()->instance_class_name()); } // If the constructor is not present, return "Object". return GetHeap()->Object_string(); } // static Handle JSReceiver::GetConstructorName(Handle receiver) { Isolate* isolate = receiver->GetIsolate(); // If the object was instantiated simply with base == new.target, the // constructor on the map provides the most accurate name. // Don't provide the info for prototypes, since their constructors are // reclaimed and replaced by Object in OptimizeAsPrototype. if (!receiver->IsJSProxy() && receiver->map()->new_target_is_base() && !receiver->map()->is_prototype_map()) { Object* maybe_constructor = receiver->map()->GetConstructor(); if (maybe_constructor->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(maybe_constructor); String* name = String::cast(constructor->shared()->name()); if (name->length() == 0) name = constructor->shared()->inferred_name(); if (name->length() != 0 && !name->Equals(isolate->heap()->Object_string())) { return handle(name, isolate); } } } Handle maybe_tag = JSReceiver::GetDataProperty( receiver, isolate->factory()->to_string_tag_symbol()); if (maybe_tag->IsString()) return Handle::cast(maybe_tag); PrototypeIterator iter(isolate, receiver); if (iter.IsAtEnd()) return handle(receiver->class_name()); Handle start = PrototypeIterator::GetCurrent(iter); LookupIterator it(receiver, isolate->factory()->constructor_string(), start, LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR); Handle maybe_constructor = JSReceiver::GetDataProperty(&it); Handle result = isolate->factory()->Object_string(); if (maybe_constructor->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(*maybe_constructor); String* name = String::cast(constructor->shared()->name()); if (name->length() == 0) name = constructor->shared()->inferred_name(); if (name->length() > 0) result = handle(name, isolate); } return result.is_identical_to(isolate->factory()->Object_string()) ? handle(receiver->class_name()) : result; } Handle JSReceiver::GetCreationContext() { JSReceiver* receiver = this; while (receiver->IsJSBoundFunction()) { receiver = JSBoundFunction::cast(receiver)->bound_target_function(); } Object* constructor = receiver->map()->GetConstructor(); JSFunction* function; if (constructor->IsJSFunction()) { function = JSFunction::cast(constructor); } else { // Functions have null as a constructor, // but any JSFunction knows its context immediately. CHECK(receiver->IsJSFunction()); function = JSFunction::cast(receiver); } return function->has_context() ? Handle(function->context()->native_context()) : Handle::null(); } Handle Map::WrapFieldType(Handle type) { if (type->IsClass()) return Map::WeakCellForMap(type->AsClass()); return type; } FieldType* Map::UnwrapFieldType(Object* wrapped_type) { Object* value = wrapped_type; if (value->IsWeakCell()) { if (WeakCell::cast(value)->cleared()) return FieldType::None(); value = WeakCell::cast(value)->value(); } return FieldType::cast(value); } MaybeHandle Map::CopyWithField(Handle map, Handle name, Handle type, PropertyAttributes attributes, PropertyConstness constness, Representation representation, TransitionFlag flag) { DCHECK(DescriptorArray::kNotFound == map->instance_descriptors()->Search( *name, map->NumberOfOwnDescriptors())); // Ensure the descriptor array does not get too big. if (map->NumberOfOwnDescriptors() >= kMaxNumberOfDescriptors) { return MaybeHandle(); } Isolate* isolate = map->GetIsolate(); // Compute the new index for new field. int index = map->NextFreePropertyIndex(); if (map->instance_type() == JS_CONTEXT_EXTENSION_OBJECT_TYPE) { representation = Representation::Tagged(); type = FieldType::Any(isolate); } Handle wrapped_type(WrapFieldType(type)); DCHECK_IMPLIES(!FLAG_track_constant_fields, constness == kMutable); Descriptor d = Descriptor::DataField(name, index, attributes, constness, representation, wrapped_type); Handle new_map = Map::CopyAddDescriptor(map, &d, flag); int unused_property_fields = new_map->unused_property_fields() - 1; if (unused_property_fields < 0) { unused_property_fields += JSObject::kFieldsAdded; } new_map->set_unused_property_fields(unused_property_fields); return new_map; } MaybeHandle Map::CopyWithConstant(Handle map, Handle name, Handle constant, PropertyAttributes attributes, TransitionFlag flag) { // Ensure the descriptor array does not get too big. if (map->NumberOfOwnDescriptors() >= kMaxNumberOfDescriptors) { return MaybeHandle(); } if (FLAG_track_constant_fields) { Isolate* isolate = map->GetIsolate(); Representation representation = constant->OptimalRepresentation(); Handle type = constant->OptimalType(isolate, representation); return CopyWithField(map, name, type, attributes, kConst, representation, flag); } else { // Allocate new instance descriptors with (name, constant) added. Descriptor d = Descriptor::DataConstant(name, 0, constant, attributes); Handle new_map = Map::CopyAddDescriptor(map, &d, flag); return new_map; } } const char* Representation::Mnemonic() const { switch (kind_) { case kNone: return "v"; case kTagged: return "t"; case kSmi: return "s"; case kDouble: return "d"; case kInteger32: return "i"; case kHeapObject: return "h"; case kExternal: return "x"; default: UNREACHABLE(); return NULL; } } bool Map::TransitionRemovesTaggedField(Map* target) { int inobject = GetInObjectProperties(); int target_inobject = target->GetInObjectProperties(); for (int i = target_inobject; i < inobject; i++) { FieldIndex index = FieldIndex::ForPropertyIndex(this, i); if (!IsUnboxedDoubleField(index)) return true; } return false; } bool Map::TransitionChangesTaggedFieldToUntaggedField(Map* target) { int inobject = GetInObjectProperties(); int target_inobject = target->GetInObjectProperties(); int limit = Min(inobject, target_inobject); for (int i = 0; i < limit; i++) { FieldIndex index = FieldIndex::ForPropertyIndex(target, i); if (!IsUnboxedDoubleField(index) && target->IsUnboxedDoubleField(index)) { return true; } } return false; } bool Map::TransitionRequiresSynchronizationWithGC(Map* target) { return TransitionRemovesTaggedField(target) || TransitionChangesTaggedFieldToUntaggedField(target); } bool Map::InstancesNeedRewriting(Map* target) { int target_number_of_fields = target->NumberOfFields(); int target_inobject = target->GetInObjectProperties(); int target_unused = target->unused_property_fields(); int old_number_of_fields; return InstancesNeedRewriting(target, target_number_of_fields, target_inobject, target_unused, &old_number_of_fields); } bool Map::InstancesNeedRewriting(Map* target, int target_number_of_fields, int target_inobject, int target_unused, int* old_number_of_fields) { // If fields were added (or removed), rewrite the instance. *old_number_of_fields = NumberOfFields(); DCHECK(target_number_of_fields >= *old_number_of_fields); if (target_number_of_fields != *old_number_of_fields) return true; // If smi descriptors were replaced by double descriptors, rewrite. DescriptorArray* old_desc = instance_descriptors(); DescriptorArray* new_desc = target->instance_descriptors(); int limit = NumberOfOwnDescriptors(); for (int i = 0; i < limit; i++) { if (new_desc->GetDetails(i).representation().IsDouble() != old_desc->GetDetails(i).representation().IsDouble()) { return true; } } // If no fields were added, and no inobject properties were removed, setting // the map is sufficient. if (target_inobject == GetInObjectProperties()) return false; // In-object slack tracking may have reduced the object size of the new map. // In that case, succeed if all existing fields were inobject, and they still // fit within the new inobject size. DCHECK(target_inobject < GetInObjectProperties()); if (target_number_of_fields <= target_inobject) { DCHECK(target_number_of_fields + target_unused == target_inobject); return false; } // Otherwise, properties will need to be moved to the backing store. return true; } // static void JSObject::UpdatePrototypeUserRegistration(Handle old_map, Handle new_map, Isolate* isolate) { DCHECK(old_map->is_prototype_map()); DCHECK(new_map->is_prototype_map()); bool was_registered = JSObject::UnregisterPrototypeUser(old_map, isolate); new_map->set_prototype_info(old_map->prototype_info()); old_map->set_prototype_info(Smi::kZero); if (FLAG_trace_prototype_users) { PrintF("Moving prototype_info %p from map %p to map %p.\n", reinterpret_cast(new_map->prototype_info()), reinterpret_cast(*old_map), reinterpret_cast(*new_map)); } if (was_registered) { if (new_map->prototype_info()->IsPrototypeInfo()) { // The new map isn't registered with its prototype yet; reflect this fact // in the PrototypeInfo it just inherited from the old map. PrototypeInfo::cast(new_map->prototype_info()) ->set_registry_slot(PrototypeInfo::UNREGISTERED); } JSObject::LazyRegisterPrototypeUser(new_map, isolate); } } namespace { // To migrate a fast instance to a fast map: // - First check whether the instance needs to be rewritten. If not, simply // change the map. // - Otherwise, allocate a fixed array large enough to hold all fields, in // addition to unused space. // - Copy all existing properties in, in the following order: backing store // properties, unused fields, inobject properties. // - If all allocation succeeded, commit the state atomically: // * Copy inobject properties from the backing store back into the object. // * Trim the difference in instance size of the object. This also cleanly // frees inobject properties that moved to the backing store. // * If there are properties left in the backing store, trim of the space used // to temporarily store the inobject properties. // * If there are properties left in the backing store, install the backing // store. void MigrateFastToFast(Handle object, Handle new_map) { Isolate* isolate = object->GetIsolate(); Handle old_map(object->map()); // In case of a regular transition. if (new_map->GetBackPointer() == *old_map) { // If the map does not add named properties, simply set the map. if (old_map->NumberOfOwnDescriptors() == new_map->NumberOfOwnDescriptors()) { object->synchronized_set_map(*new_map); return; } PropertyDetails details = new_map->GetLastDescriptorDetails(); // Either new_map adds an kDescriptor property, or a kField property for // which there is still space, and which does not require a mutable double // box (an out-of-object double). if (details.location() == kDescriptor || (old_map->unused_property_fields() > 0 && ((FLAG_unbox_double_fields && object->properties()->length() == 0) || !details.representation().IsDouble()))) { object->synchronized_set_map(*new_map); return; } // If there is still space in the object, we need to allocate a mutable // double box. if (old_map->unused_property_fields() > 0) { FieldIndex index = FieldIndex::ForDescriptor(*new_map, new_map->LastAdded()); DCHECK(details.representation().IsDouble()); DCHECK(!new_map->IsUnboxedDoubleField(index)); Handle value = isolate->factory()->NewMutableHeapNumber(); object->RawFastPropertyAtPut(index, *value); object->synchronized_set_map(*new_map); return; } // This migration is a transition from a map that has run out of property // space. Extend the backing store. int grow_by = new_map->unused_property_fields() + 1; Handle old_storage = handle(object->properties(), isolate); Handle new_storage = isolate->factory()->CopyFixedArrayAndGrow(old_storage, grow_by); // Properly initialize newly added property. Handle value; if (details.representation().IsDouble()) { value = isolate->factory()->NewMutableHeapNumber(); } else { value = isolate->factory()->uninitialized_value(); } DCHECK_EQ(kField, details.location()); DCHECK_EQ(kData, details.kind()); int target_index = details.field_index() - new_map->GetInObjectProperties(); DCHECK(target_index >= 0); // Must be a backing store index. new_storage->set(target_index, *value); // From here on we cannot fail and we shouldn't GC anymore. DisallowHeapAllocation no_allocation; // Set the new property value and do the map transition. object->set_properties(*new_storage); object->synchronized_set_map(*new_map); return; } int old_number_of_fields; int number_of_fields = new_map->NumberOfFields(); int inobject = new_map->GetInObjectProperties(); int unused = new_map->unused_property_fields(); // Nothing to do if no functions were converted to fields and no smis were // converted to doubles. if (!old_map->InstancesNeedRewriting(*new_map, number_of_fields, inobject, unused, &old_number_of_fields)) { object->synchronized_set_map(*new_map); return; } int total_size = number_of_fields + unused; int external = total_size - inobject; Handle array = isolate->factory()->NewFixedArray(total_size); Handle old_descriptors(old_map->instance_descriptors()); Handle new_descriptors(new_map->instance_descriptors()); int old_nof = old_map->NumberOfOwnDescriptors(); int new_nof = new_map->NumberOfOwnDescriptors(); // This method only supports generalizing instances to at least the same // number of properties. DCHECK(old_nof <= new_nof); for (int i = 0; i < old_nof; i++) { PropertyDetails details = new_descriptors->GetDetails(i); if (details.location() != kField) continue; DCHECK_EQ(kData, details.kind()); PropertyDetails old_details = old_descriptors->GetDetails(i); Representation old_representation = old_details.representation(); Representation representation = details.representation(); Handle value; if (old_details.location() == kDescriptor) { if (old_details.kind() == kAccessor) { // In case of kAccessor -> kData property reconfiguration, the property // must already be prepared for data of certain type. DCHECK(!details.representation().IsNone()); if (details.representation().IsDouble()) { value = isolate->factory()->NewMutableHeapNumber(); } else { value = isolate->factory()->uninitialized_value(); } } else { DCHECK_EQ(kData, old_details.kind()); value = handle(old_descriptors->GetValue(i), isolate); DCHECK(!old_representation.IsDouble() && !representation.IsDouble()); } } else { DCHECK_EQ(kField, old_details.location()); FieldIndex index = FieldIndex::ForDescriptor(*old_map, i); if (object->IsUnboxedDoubleField(index)) { uint64_t old_bits = object->RawFastDoublePropertyAsBitsAt(index); value = isolate->factory()->NewHeapNumberFromBits( old_bits, representation.IsDouble() ? MUTABLE : IMMUTABLE); } else { value = handle(object->RawFastPropertyAt(index), isolate); if (!old_representation.IsDouble() && representation.IsDouble()) { DCHECK_IMPLIES(old_representation.IsNone(), value->IsUninitialized(isolate)); value = Object::NewStorageFor(isolate, value, representation); } else if (old_representation.IsDouble() && !representation.IsDouble()) { value = Object::WrapForRead(isolate, value, old_representation); } } } DCHECK(!(representation.IsDouble() && value->IsSmi())); int target_index = new_descriptors->GetFieldIndex(i) - inobject; if (target_index < 0) target_index += total_size; array->set(target_index, *value); } for (int i = old_nof; i < new_nof; i++) { PropertyDetails details = new_descriptors->GetDetails(i); if (details.location() != kField) continue; DCHECK_EQ(kData, details.kind()); Handle value; if (details.representation().IsDouble()) { value = isolate->factory()->NewMutableHeapNumber(); } else { value = isolate->factory()->uninitialized_value(); } int target_index = new_descriptors->GetFieldIndex(i) - inobject; if (target_index < 0) target_index += total_size; array->set(target_index, *value); } // From here on we cannot fail and we shouldn't GC anymore. DisallowHeapAllocation no_allocation; Heap* heap = isolate->heap(); heap->NotifyObjectLayoutChange(*object, no_allocation); // Copy (real) inobject properties. If necessary, stop at number_of_fields to // avoid overwriting |one_pointer_filler_map|. int limit = Min(inobject, number_of_fields); for (int i = 0; i < limit; i++) { FieldIndex index = FieldIndex::ForPropertyIndex(*new_map, i); Object* value = array->get(external + i); // Can't use JSObject::FastPropertyAtPut() because proper map was not set // yet. if (new_map->IsUnboxedDoubleField(index)) { DCHECK(value->IsMutableHeapNumber()); // Ensure that all bits of the double value are preserved. object->RawFastDoublePropertyAsBitsAtPut( index, HeapNumber::cast(value)->value_as_bits()); if (i < old_number_of_fields && !old_map->IsUnboxedDoubleField(index)) { // Transition from tagged to untagged slot. heap->ClearRecordedSlot(*object, HeapObject::RawField(*object, index.offset())); } else { DCHECK(!heap->HasRecordedSlot( *object, HeapObject::RawField(*object, index.offset()))); } } else { object->RawFastPropertyAtPut(index, value); } } // If there are properties in the new backing store, trim it to the correct // size and install the backing store into the object. if (external > 0) { heap->RightTrimFixedArray(*array, inobject); object->set_properties(*array); } // Create filler object past the new instance size. int new_instance_size = new_map->instance_size(); int instance_size_delta = old_map->instance_size() - new_instance_size; DCHECK(instance_size_delta >= 0); if (instance_size_delta > 0) { Address address = object->address(); heap->CreateFillerObjectAt(address + new_instance_size, instance_size_delta, ClearRecordedSlots::kYes); heap->AdjustLiveBytes(*object, -instance_size_delta); } // We are storing the new map using release store after creating a filler for // the left-over space to avoid races with the sweeper thread. object->synchronized_set_map(*new_map); } void MigrateFastToSlow(Handle object, Handle new_map, int expected_additional_properties) { // The global object is always normalized. DCHECK(!object->IsJSGlobalObject()); // JSGlobalProxy must never be normalized DCHECK(!object->IsJSGlobalProxy()); Isolate* isolate = object->GetIsolate(); HandleScope scope(isolate); Handle map(object->map()); // Allocate new content. int real_size = map->NumberOfOwnDescriptors(); int property_count = real_size; if (expected_additional_properties > 0) { property_count += expected_additional_properties; } else { // Make space for two more properties. property_count += NameDictionary::kInitialCapacity; } Handle dictionary = NameDictionary::New(isolate, property_count); Handle descs(map->instance_descriptors()); for (int i = 0; i < real_size; i++) { PropertyDetails details = descs->GetDetails(i); Handle key(descs->GetKey(i)); Handle value; if (details.location() == kField) { FieldIndex index = FieldIndex::ForDescriptor(*map, i); if (details.kind() == kData) { if (object->IsUnboxedDoubleField(index)) { double old_value = object->RawFastDoublePropertyAt(index); value = isolate->factory()->NewHeapNumber(old_value); } else { value = handle(object->RawFastPropertyAt(index), isolate); if (details.representation().IsDouble()) { DCHECK(value->IsMutableHeapNumber()); Handle old = Handle::cast(value); value = isolate->factory()->NewHeapNumber(old->value()); } } } else { DCHECK_EQ(kAccessor, details.kind()); value = handle(object->RawFastPropertyAt(index), isolate); } } else { DCHECK_EQ(kDescriptor, details.location()); value = handle(descs->GetValue(i), isolate); } DCHECK(!value.is_null()); PropertyDetails d(details.kind(), details.attributes(), i + 1, PropertyCellType::kNoCell); dictionary = NameDictionary::Add(dictionary, key, value, d); } // Copy the next enumeration index from instance descriptor. dictionary->SetNextEnumerationIndex(real_size + 1); // From here on we cannot fail and we shouldn't GC anymore. DisallowHeapAllocation no_allocation; Heap* heap = isolate->heap(); heap->NotifyObjectLayoutChange(*object, no_allocation); // Resize the object in the heap if necessary. int new_instance_size = new_map->instance_size(); int instance_size_delta = map->instance_size() - new_instance_size; DCHECK(instance_size_delta >= 0); if (instance_size_delta > 0) { heap->CreateFillerObjectAt(object->address() + new_instance_size, instance_size_delta, ClearRecordedSlots::kYes); heap->AdjustLiveBytes(*object, -instance_size_delta); } // We are storing the new map using release store after creating a filler for // the left-over space to avoid races with the sweeper thread. object->synchronized_set_map(*new_map); object->set_properties(*dictionary); // Ensure that in-object space of slow-mode object does not contain random // garbage. int inobject_properties = new_map->GetInObjectProperties(); if (inobject_properties) { Heap* heap = isolate->heap(); heap->ClearRecordedSlotRange( object->address() + map->GetInObjectPropertyOffset(0), object->address() + new_instance_size); for (int i = 0; i < inobject_properties; i++) { FieldIndex index = FieldIndex::ForPropertyIndex(*new_map, i); object->RawFastPropertyAtPut(index, Smi::kZero); } } isolate->counters()->props_to_dictionary()->Increment(); #ifdef DEBUG if (FLAG_trace_normalization) { OFStream os(stdout); os << "Object properties have been normalized:\n"; object->Print(os); } #endif } } // namespace // static void JSObject::NotifyMapChange(Handle old_map, Handle new_map, Isolate* isolate) { if (!old_map->is_prototype_map()) return; InvalidatePrototypeChains(*old_map); // If the map was registered with its prototype before, ensure that it // registers with its new prototype now. This preserves the invariant that // when a map on a prototype chain is registered with its prototype, then // all prototypes further up the chain are also registered with their // respective prototypes. UpdatePrototypeUserRegistration(old_map, new_map, isolate); } void JSObject::MigrateToMap(Handle object, Handle new_map, int expected_additional_properties) { if (object->map() == *new_map) return; Handle old_map(object->map()); NotifyMapChange(old_map, new_map, new_map->GetIsolate()); if (old_map->is_dictionary_map()) { // For slow-to-fast migrations JSObject::MigrateSlowToFast() // must be used instead. CHECK(new_map->is_dictionary_map()); // Slow-to-slow migration is trivial. object->set_map(*new_map); } else if (!new_map->is_dictionary_map()) { MigrateFastToFast(object, new_map); if (old_map->is_prototype_map()) { DCHECK(!old_map->is_stable()); DCHECK(new_map->is_stable()); // Clear out the old descriptor array to avoid problems to sharing // the descriptor array without using an explicit. old_map->InitializeDescriptors( old_map->GetHeap()->empty_descriptor_array(), LayoutDescriptor::FastPointerLayout()); // Ensure that no transition was inserted for prototype migrations. DCHECK_EQ( 0, TransitionArray::NumberOfTransitions(old_map->raw_transitions())); DCHECK(new_map->GetBackPointer()->IsUndefined(new_map->GetIsolate())); } } else { MigrateFastToSlow(object, new_map, expected_additional_properties); } // Careful: Don't allocate here! // For some callers of this method, |object| might be in an inconsistent // state now: the new map might have a new elements_kind, but the object's // elements pointer hasn't been updated yet. Callers will fix this, but in // the meantime, (indirectly) calling JSObjectVerify() must be avoided. // When adding code here, add a DisallowHeapAllocation too. } void JSObject::ForceSetPrototype(Handle object, Handle proto) { // object.__proto__ = proto; Handle old_map = Handle(object->map()); Handle new_map = Map::Copy(old_map, "ForceSetPrototype"); Map::SetPrototype(new_map, proto, FAST_PROTOTYPE); JSObject::MigrateToMap(object, new_map); } int Map::NumberOfFields() { DescriptorArray* descriptors = instance_descriptors(); int result = 0; for (int i = 0; i < NumberOfOwnDescriptors(); i++) { if (descriptors->GetDetails(i).location() == kField) result++; } return result; } void DescriptorArray::GeneralizeAllFields() { int length = number_of_descriptors(); for (int i = 0; i < length; i++) { PropertyDetails details = GetDetails(i); details = details.CopyWithRepresentation(Representation::Tagged()); if (details.location() == kField) { DCHECK_EQ(kData, details.kind()); details = details.CopyWithConstness(kMutable); SetValue(i, FieldType::Any()); } set(ToDetailsIndex(i), details.AsSmi()); } } Handle Map::CopyGeneralizeAllFields(Handle map, ElementsKind elements_kind, int modify_index, PropertyKind kind, PropertyAttributes attributes, const char* reason) { Isolate* isolate = map->GetIsolate(); Handle old_descriptors(map->instance_descriptors(), isolate); int number_of_own_descriptors = map->NumberOfOwnDescriptors(); Handle descriptors = DescriptorArray::CopyUpTo(old_descriptors, number_of_own_descriptors); descriptors->GeneralizeAllFields(); Handle new_layout_descriptor( LayoutDescriptor::FastPointerLayout(), isolate); Handle new_map = CopyReplaceDescriptors( map, descriptors, new_layout_descriptor, OMIT_TRANSITION, MaybeHandle(), reason, SPECIAL_TRANSITION); // Unless the instance is being migrated, ensure that modify_index is a field. if (modify_index >= 0) { PropertyDetails details = descriptors->GetDetails(modify_index); if (details.constness() != kMutable || details.location() != kField || details.attributes() != attributes) { int field_index = details.location() == kField ? details.field_index() : new_map->NumberOfFields(); Descriptor d = Descriptor::DataField( handle(descriptors->GetKey(modify_index), isolate), field_index, attributes, Representation::Tagged()); descriptors->Replace(modify_index, &d); if (details.location() != kField) { int unused_property_fields = new_map->unused_property_fields() - 1; if (unused_property_fields < 0) { unused_property_fields += JSObject::kFieldsAdded; } new_map->set_unused_property_fields(unused_property_fields); } } else { DCHECK(details.attributes() == attributes); } if (FLAG_trace_generalization) { MaybeHandle field_type = FieldType::None(isolate); if (details.location() == kField) { field_type = handle( map->instance_descriptors()->GetFieldType(modify_index), isolate); } map->PrintGeneralization( stdout, reason, modify_index, new_map->NumberOfOwnDescriptors(), new_map->NumberOfOwnDescriptors(), details.location() == kDescriptor, details.representation(), Representation::Tagged(), field_type, MaybeHandle(), FieldType::Any(isolate), MaybeHandle()); } } new_map->set_elements_kind(elements_kind); return new_map; } void Map::DeprecateTransitionTree() { if (is_deprecated()) return; Object* transitions = raw_transitions(); int num_transitions = TransitionArray::NumberOfTransitions(transitions); for (int i = 0; i < num_transitions; ++i) { TransitionArray::GetTarget(transitions, i)->DeprecateTransitionTree(); } deprecate(); dependent_code()->DeoptimizeDependentCodeGroup( GetIsolate(), DependentCode::kTransitionGroup); NotifyLeafMapLayoutChange(); } // Installs |new_descriptors| over the current instance_descriptors to ensure // proper sharing of descriptor arrays. void Map::ReplaceDescriptors(DescriptorArray* new_descriptors, LayoutDescriptor* new_layout_descriptor) { Isolate* isolate = GetIsolate(); // Don't overwrite the empty descriptor array or initial map's descriptors. if (NumberOfOwnDescriptors() == 0 || GetBackPointer()->IsUndefined(isolate)) { return; } DescriptorArray* to_replace = instance_descriptors(); isolate->heap()->incremental_marking()->IterateBlackObject(to_replace); Map* current = this; while (current->instance_descriptors() == to_replace) { Object* next = current->GetBackPointer(); if (next->IsUndefined(isolate)) break; // Stop overwriting at initial map. current->SetEnumLength(kInvalidEnumCacheSentinel); current->UpdateDescriptors(new_descriptors, new_layout_descriptor); current = Map::cast(next); } set_owns_descriptors(false); } Map* Map::FindRootMap() { Map* result = this; Isolate* isolate = GetIsolate(); while (true) { Object* back = result->GetBackPointer(); if (back->IsUndefined(isolate)) { // Initial map always owns descriptors and doesn't have unused entries // in the descriptor array. DCHECK(result->owns_descriptors()); DCHECK_EQ(result->NumberOfOwnDescriptors(), result->instance_descriptors()->number_of_descriptors()); return result; } result = Map::cast(back); } } Map* Map::FindFieldOwner(int descriptor) { DisallowHeapAllocation no_allocation; DCHECK_EQ(kField, instance_descriptors()->GetDetails(descriptor).location()); Map* result = this; Isolate* isolate = GetIsolate(); while (true) { Object* back = result->GetBackPointer(); if (back->IsUndefined(isolate)) break; Map* parent = Map::cast(back); if (parent->NumberOfOwnDescriptors() <= descriptor) break; result = parent; } return result; } void Map::UpdateFieldType(int descriptor, Handle name, PropertyConstness new_constness, Representation new_representation, Handle new_wrapped_type) { DCHECK(new_wrapped_type->IsSmi() || new_wrapped_type->IsWeakCell()); // We store raw pointers in the queue, so no allocations are allowed. DisallowHeapAllocation no_allocation; PropertyDetails details = instance_descriptors()->GetDetails(descriptor); if (details.location() != kField) return; DCHECK_EQ(kData, details.kind()); Zone zone(GetIsolate()->allocator(), ZONE_NAME); ZoneQueue backlog(&zone); backlog.push(this); while (!backlog.empty()) { Map* current = backlog.front(); backlog.pop(); Object* transitions = current->raw_transitions(); int num_transitions = TransitionArray::NumberOfTransitions(transitions); for (int i = 0; i < num_transitions; ++i) { Map* target = TransitionArray::GetTarget(transitions, i); backlog.push(target); } DescriptorArray* descriptors = current->instance_descriptors(); PropertyDetails details = descriptors->GetDetails(descriptor); // Currently constness change implies map change. DCHECK_EQ(new_constness, details.constness()); // It is allowed to change representation here only from None to something. DCHECK(details.representation().Equals(new_representation) || details.representation().IsNone()); // Skip if already updated the shared descriptor. if (descriptors->GetValue(descriptor) != *new_wrapped_type) { DCHECK_IMPLIES(!FLAG_track_constant_fields, new_constness == kMutable); Descriptor d = Descriptor::DataField( name, descriptors->GetFieldIndex(descriptor), details.attributes(), new_constness, new_representation, new_wrapped_type); descriptors->Replace(descriptor, &d); } } } bool FieldTypeIsCleared(Representation rep, FieldType* type) { return type->IsNone() && rep.IsHeapObject(); } // static Handle Map::GeneralizeFieldType(Representation rep1, Handle type1, Representation rep2, Handle type2, Isolate* isolate) { // Cleared field types need special treatment. They represent lost knowledge, // so we must be conservative, so their generalization with any other type // is "Any". if (FieldTypeIsCleared(rep1, *type1) || FieldTypeIsCleared(rep2, *type2)) { return FieldType::Any(isolate); } if (type1->NowIs(type2)) return type2; if (type2->NowIs(type1)) return type1; return FieldType::Any(isolate); } // static void Map::GeneralizeField(Handle map, int modify_index, PropertyConstness new_constness, Representation new_representation, Handle new_field_type) { Isolate* isolate = map->GetIsolate(); // Check if we actually need to generalize the field type at all. Handle old_descriptors(map->instance_descriptors(), isolate); PropertyDetails old_details = old_descriptors->GetDetails(modify_index); PropertyConstness old_constness = old_details.constness(); Representation old_representation = old_details.representation(); Handle old_field_type(old_descriptors->GetFieldType(modify_index), isolate); if (old_constness == new_constness && old_representation.Equals(new_representation) && !FieldTypeIsCleared(new_representation, *new_field_type) && // Checking old_field_type for being cleared is not necessary because // the NowIs check below would fail anyway in that case. new_field_type->NowIs(old_field_type)) { DCHECK(GeneralizeFieldType(old_representation, old_field_type, new_representation, new_field_type, isolate) ->NowIs(old_field_type)); return; } // Determine the field owner. Handle field_owner(map->FindFieldOwner(modify_index), isolate); Handle descriptors( field_owner->instance_descriptors(), isolate); DCHECK_EQ(*old_field_type, descriptors->GetFieldType(modify_index)); new_field_type = Map::GeneralizeFieldType(old_representation, old_field_type, new_representation, new_field_type, isolate); PropertyDetails details = descriptors->GetDetails(modify_index); Handle name(descriptors->GetKey(modify_index)); Handle wrapped_type(WrapFieldType(new_field_type)); field_owner->UpdateFieldType(modify_index, name, new_constness, new_representation, wrapped_type); field_owner->dependent_code()->DeoptimizeDependentCodeGroup( isolate, DependentCode::kFieldOwnerGroup); if (FLAG_trace_generalization) { map->PrintGeneralization( stdout, "field type generalization", modify_index, map->NumberOfOwnDescriptors(), map->NumberOfOwnDescriptors(), false, details.representation(), details.representation(), old_field_type, MaybeHandle(), new_field_type, MaybeHandle()); } } // TODO(ishell): remove. // static Handle Map::ReconfigureProperty(Handle map, int modify_index, PropertyKind new_kind, PropertyAttributes new_attributes, Representation new_representation, Handle new_field_type) { DCHECK_EQ(kData, new_kind); // Only kData case is supported. MapUpdater mu(map->GetIsolate(), map); return mu.ReconfigureToDataField(modify_index, new_attributes, kConst, new_representation, new_field_type); } // TODO(ishell): remove. // static Handle Map::ReconfigureElementsKind(Handle map, ElementsKind new_elements_kind) { MapUpdater mu(map->GetIsolate(), map); return mu.ReconfigureElementsKind(new_elements_kind); } // Generalize all fields and update the transition tree. Handle Map::GeneralizeAllFields(Handle map) { Isolate* isolate = map->GetIsolate(); Handle any_type = FieldType::Any(isolate); Handle descriptors(map->instance_descriptors()); for (int i = 0; i < map->NumberOfOwnDescriptors(); ++i) { PropertyDetails details = descriptors->GetDetails(i); if (details.location() == kField) { DCHECK_EQ(kData, details.kind()); MapUpdater mu(isolate, map); map = mu.ReconfigureToDataField(i, details.attributes(), kMutable, Representation::Tagged(), any_type); } } return map; } // static MaybeHandle Map::TryUpdate(Handle old_map) { DisallowHeapAllocation no_allocation; DisallowDeoptimization no_deoptimization(old_map->GetIsolate()); if (!old_map->is_deprecated()) return old_map; // Check the state of the root map. Map* root_map = old_map->FindRootMap(); if (!old_map->EquivalentToForTransition(root_map)) return MaybeHandle(); ElementsKind from_kind = root_map->elements_kind(); ElementsKind to_kind = old_map->elements_kind(); if (from_kind != to_kind) { // Try to follow existing elements kind transitions. root_map = root_map->LookupElementsTransitionMap(to_kind); if (root_map == NULL) return MaybeHandle(); // From here on, use the map with correct elements kind as root map. } Map* new_map = root_map->TryReplayPropertyTransitions(*old_map); if (new_map == nullptr) return MaybeHandle(); return handle(new_map); } Map* Map::TryReplayPropertyTransitions(Map* old_map) { DisallowHeapAllocation no_allocation; DisallowDeoptimization no_deoptimization(GetIsolate()); int root_nof = NumberOfOwnDescriptors(); int old_nof = old_map->NumberOfOwnDescriptors(); DescriptorArray* old_descriptors = old_map->instance_descriptors(); Map* new_map = this; for (int i = root_nof; i < old_nof; ++i) { PropertyDetails old_details = old_descriptors->GetDetails(i); Map* transition = TransitionArray::SearchTransition( new_map, old_details.kind(), old_descriptors->GetKey(i), old_details.attributes()); if (transition == NULL) return nullptr; new_map = transition; DescriptorArray* new_descriptors = new_map->instance_descriptors(); PropertyDetails new_details = new_descriptors->GetDetails(i); DCHECK_EQ(old_details.kind(), new_details.kind()); DCHECK_EQ(old_details.attributes(), new_details.attributes()); if (!IsGeneralizableTo(old_details.constness(), new_details.constness())) { return nullptr; } DCHECK(IsGeneralizableTo(old_details.location(), new_details.location())); if (!old_details.representation().fits_into(new_details.representation())) { return nullptr; } if (new_details.location() == kField) { if (new_details.kind() == kData) { FieldType* new_type = new_descriptors->GetFieldType(i); // Cleared field types need special treatment. They represent lost // knowledge, so we must first generalize the new_type to "Any". if (FieldTypeIsCleared(new_details.representation(), new_type)) { return nullptr; } DCHECK_EQ(kData, old_details.kind()); if (old_details.location() == kField) { FieldType* old_type = old_descriptors->GetFieldType(i); if (FieldTypeIsCleared(old_details.representation(), old_type) || !old_type->NowIs(new_type)) { return nullptr; } } else { DCHECK_EQ(kDescriptor, old_details.location()); DCHECK(!FLAG_track_constant_fields); Object* old_value = old_descriptors->GetValue(i); if (!new_type->NowContains(old_value)) { return nullptr; } } } else { DCHECK_EQ(kAccessor, new_details.kind()); #ifdef DEBUG FieldType* new_type = new_descriptors->GetFieldType(i); DCHECK(new_type->IsAny()); #endif UNREACHABLE(); } } else { DCHECK_EQ(kDescriptor, new_details.location()); Object* old_value = old_descriptors->GetValue(i); Object* new_value = new_descriptors->GetValue(i); if (old_details.location() == kField || old_value != new_value) { return nullptr; } } } if (new_map->NumberOfOwnDescriptors() != old_nof) return nullptr; return new_map; } // static Handle Map::Update(Handle map) { if (!map->is_deprecated()) return map; MapUpdater mu(map->GetIsolate(), map); return mu.Update(); } Maybe JSObject::SetPropertyWithInterceptor(LookupIterator* it, ShouldThrow should_throw, Handle value) { DCHECK_EQ(LookupIterator::INTERCEPTOR, it->state()); return SetPropertyWithInterceptorInternal(it, it->GetInterceptor(), should_throw, value); } MaybeHandle Object::SetProperty(Handle object, Handle name, Handle value, LanguageMode language_mode, StoreFromKeyed store_mode) { LookupIterator it(object, name); MAYBE_RETURN_NULL(SetProperty(&it, value, language_mode, store_mode)); return value; } Maybe Object::SetPropertyInternal(LookupIterator* it, Handle value, LanguageMode language_mode, StoreFromKeyed store_mode, bool* found) { it->UpdateProtector(); DCHECK(it->IsFound()); ShouldThrow should_throw = is_sloppy(language_mode) ? DONT_THROW : THROW_ON_ERROR; // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(it->isolate()); do { switch (it->state()) { case LookupIterator::NOT_FOUND: UNREACHABLE(); case LookupIterator::ACCESS_CHECK: if (it->HasAccess()) break; // Check whether it makes sense to reuse the lookup iterator. Here it // might still call into setters up the prototype chain. return JSObject::SetPropertyWithFailedAccessCheck(it, value, should_throw); case LookupIterator::JSPROXY: return JSProxy::SetProperty(it->GetHolder(), it->GetName(), value, it->GetReceiver(), language_mode); case LookupIterator::INTERCEPTOR: { if (it->HolderIsReceiverOrHiddenPrototype()) { Maybe result = JSObject::SetPropertyWithInterceptor(it, should_throw, value); if (result.IsNothing() || result.FromJust()) return result; } else { Maybe maybe_attributes = JSObject::GetPropertyAttributesWithInterceptor(it); if (!maybe_attributes.IsJust()) return Nothing(); if ((maybe_attributes.FromJust() & READ_ONLY) != 0) { return WriteToReadOnlyProperty(it, value, should_throw); } if (maybe_attributes.FromJust() == ABSENT) break; *found = false; return Nothing(); } break; } case LookupIterator::ACCESSOR: { if (it->IsReadOnly()) { return WriteToReadOnlyProperty(it, value, should_throw); } Handle accessors = it->GetAccessors(); if (accessors->IsAccessorInfo() && !it->HolderIsReceiverOrHiddenPrototype() && AccessorInfo::cast(*accessors)->is_special_data_property()) { *found = false; return Nothing(); } return SetPropertyWithAccessor(it, value, should_throw); } case LookupIterator::INTEGER_INDEXED_EXOTIC: // TODO(verwaest): We should throw an exception if holder is receiver. return Just(true); case LookupIterator::DATA: if (it->IsReadOnly()) { return WriteToReadOnlyProperty(it, value, should_throw); } if (it->HolderIsReceiverOrHiddenPrototype()) { return SetDataProperty(it, value); } // Fall through. case LookupIterator::TRANSITION: *found = false; return Nothing(); } it->Next(); } while (it->IsFound()); *found = false; return Nothing(); } Maybe Object::SetProperty(LookupIterator* it, Handle value, LanguageMode language_mode, StoreFromKeyed store_mode) { if (it->IsFound()) { bool found = true; Maybe result = SetPropertyInternal(it, value, language_mode, store_mode, &found); if (found) return result; } // If the receiver is the JSGlobalObject, the store was contextual. In case // the property did not exist yet on the global object itself, we have to // throw a reference error in strict mode. In sloppy mode, we continue. if (is_strict(language_mode) && it->GetReceiver()->IsJSGlobalObject()) { it->isolate()->Throw(*it->isolate()->factory()->NewReferenceError( MessageTemplate::kNotDefined, it->name())); return Nothing(); } ShouldThrow should_throw = is_sloppy(language_mode) ? DONT_THROW : THROW_ON_ERROR; return AddDataProperty(it, value, NONE, should_throw, store_mode); } Maybe Object::SetSuperProperty(LookupIterator* it, Handle value, LanguageMode language_mode, StoreFromKeyed store_mode) { Isolate* isolate = it->isolate(); if (it->IsFound()) { bool found = true; Maybe result = SetPropertyInternal(it, value, language_mode, store_mode, &found); if (found) return result; } it->UpdateProtector(); // The property either doesn't exist on the holder or exists there as a data // property. ShouldThrow should_throw = is_sloppy(language_mode) ? DONT_THROW : THROW_ON_ERROR; if (!it->GetReceiver()->IsJSReceiver()) { return WriteToReadOnlyProperty(it, value, should_throw); } Handle receiver = Handle::cast(it->GetReceiver()); LookupIterator::Configuration c = LookupIterator::OWN; LookupIterator own_lookup = it->IsElement() ? LookupIterator(isolate, receiver, it->index(), c) : LookupIterator(receiver, it->name(), c); for (; own_lookup.IsFound(); own_lookup.Next()) { switch (own_lookup.state()) { case LookupIterator::ACCESS_CHECK: if (!own_lookup.HasAccess()) { return JSObject::SetPropertyWithFailedAccessCheck(&own_lookup, value, should_throw); } break; case LookupIterator::ACCESSOR: if (own_lookup.GetAccessors()->IsAccessorInfo()) { if (own_lookup.IsReadOnly()) { return WriteToReadOnlyProperty(&own_lookup, value, should_throw); } return JSObject::SetPropertyWithAccessor(&own_lookup, value, should_throw); } // Fall through. case LookupIterator::INTEGER_INDEXED_EXOTIC: return RedefineIncompatibleProperty(isolate, it->GetName(), value, should_throw); case LookupIterator::DATA: { if (own_lookup.IsReadOnly()) { return WriteToReadOnlyProperty(&own_lookup, value, should_throw); } return SetDataProperty(&own_lookup, value); } case LookupIterator::INTERCEPTOR: case LookupIterator::JSPROXY: { PropertyDescriptor desc; Maybe owned = JSReceiver::GetOwnPropertyDescriptor(&own_lookup, &desc); MAYBE_RETURN(owned, Nothing()); if (!owned.FromJust()) { return JSReceiver::CreateDataProperty(&own_lookup, value, should_throw); } if (PropertyDescriptor::IsAccessorDescriptor(&desc) || !desc.writable()) { return RedefineIncompatibleProperty(isolate, it->GetName(), value, should_throw); } PropertyDescriptor value_desc; value_desc.set_value(value); return JSReceiver::DefineOwnProperty(isolate, receiver, it->GetName(), &value_desc, should_throw); } case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); } } return AddDataProperty(&own_lookup, value, NONE, should_throw, store_mode); } Maybe Object::CannotCreateProperty(Isolate* isolate, Handle receiver, Handle name, Handle value, ShouldThrow should_throw) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kStrictCannotCreateProperty, name, Object::TypeOf(isolate, receiver), receiver)); } Maybe Object::WriteToReadOnlyProperty(LookupIterator* it, Handle value, ShouldThrow should_throw) { return WriteToReadOnlyProperty(it->isolate(), it->GetReceiver(), it->GetName(), value, should_throw); } Maybe Object::WriteToReadOnlyProperty(Isolate* isolate, Handle receiver, Handle name, Handle value, ShouldThrow should_throw) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kStrictReadOnlyProperty, name, Object::TypeOf(isolate, receiver), receiver)); } Maybe Object::RedefineIncompatibleProperty(Isolate* isolate, Handle name, Handle value, ShouldThrow should_throw) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, name)); } Maybe Object::SetDataProperty(LookupIterator* it, Handle value) { // Proxies are handled elsewhere. Other non-JSObjects cannot have own // properties. Handle receiver = Handle::cast(it->GetReceiver()); // Store on the holder which may be hidden behind the receiver. DCHECK(it->HolderIsReceiverOrHiddenPrototype()); Handle to_assign = value; // Convert the incoming value to a number for storing into typed arrays. if (it->IsElement() && receiver->HasFixedTypedArrayElements()) { if (!value->IsNumber() && !value->IsUndefined(it->isolate())) { ASSIGN_RETURN_ON_EXCEPTION_VALUE( it->isolate(), to_assign, Object::ToNumber(value), Nothing()); // We have to recheck the length. However, it can only change if the // underlying buffer was neutered, so just check that. if (Handle::cast(receiver)->WasNeutered()) { return Just(true); // TODO(neis): According to the spec, this should throw a TypeError. } } } // Possibly migrate to the most up-to-date map that will be able to store // |value| under it->name(). it->PrepareForDataProperty(to_assign); // Write the property value. it->WriteDataValue(to_assign, false); #if VERIFY_HEAP if (FLAG_verify_heap) { receiver->JSObjectVerify(); } #endif return Just(true); } Maybe Object::AddDataProperty(LookupIterator* it, Handle value, PropertyAttributes attributes, ShouldThrow should_throw, StoreFromKeyed store_mode) { if (!it->GetReceiver()->IsJSObject()) { if (it->GetReceiver()->IsJSProxy() && it->GetName()->IsPrivate()) { RETURN_FAILURE(it->isolate(), should_throw, NewTypeError(MessageTemplate::kProxyPrivate)); } return CannotCreateProperty(it->isolate(), it->GetReceiver(), it->GetName(), value, should_throw); } DCHECK_NE(LookupIterator::INTEGER_INDEXED_EXOTIC, it->state()); Handle receiver = it->GetStoreTarget(); // If the receiver is a JSGlobalProxy, store on the prototype (JSGlobalObject) // instead. If the prototype is Null, the proxy is detached. if (receiver->IsJSGlobalProxy()) return Just(true); Isolate* isolate = it->isolate(); if (it->ExtendingNonExtensible(receiver)) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kObjectNotExtensible, it->GetName())); } if (it->IsElement()) { if (receiver->IsJSArray()) { Handle array = Handle::cast(receiver); if (JSArray::WouldChangeReadOnlyLength(array, it->index())) { RETURN_FAILURE(array->GetIsolate(), should_throw, NewTypeError(MessageTemplate::kStrictReadOnlyProperty, isolate->factory()->length_string(), Object::TypeOf(isolate, array), array)); } if (FLAG_trace_external_array_abuse && array->HasFixedTypedArrayElements()) { CheckArrayAbuse(array, "typed elements write", it->index(), true); } if (FLAG_trace_js_array_abuse && !array->HasFixedTypedArrayElements()) { CheckArrayAbuse(array, "elements write", it->index(), false); } } Maybe result = JSObject::AddDataElement(receiver, it->index(), value, attributes, should_throw); JSObject::ValidateElements(receiver); return result; } else { it->UpdateProtector(); // Migrate to the most up-to-date map that will be able to store |value| // under it->name() with |attributes|. it->PrepareTransitionToDataProperty(receiver, value, attributes, store_mode); DCHECK_EQ(LookupIterator::TRANSITION, it->state()); it->ApplyTransitionToDataProperty(receiver); // Write the property value. it->WriteDataValue(value, true); #if VERIFY_HEAP if (FLAG_verify_heap) { receiver->JSObjectVerify(); } #endif } return Just(true); } void Map::EnsureDescriptorSlack(Handle map, int slack) { // Only supports adding slack to owned descriptors. DCHECK(map->owns_descriptors()); Handle descriptors(map->instance_descriptors()); int old_size = map->NumberOfOwnDescriptors(); if (slack <= descriptors->NumberOfSlackDescriptors()) return; Handle new_descriptors = DescriptorArray::CopyUpTo( descriptors, old_size, slack); DisallowHeapAllocation no_allocation; // The descriptors are still the same, so keep the layout descriptor. LayoutDescriptor* layout_descriptor = map->GetLayoutDescriptor(); if (old_size == 0) { map->UpdateDescriptors(*new_descriptors, layout_descriptor); return; } // If the source descriptors had an enum cache we copy it. This ensures // that the maps to which we push the new descriptor array back can rely // on a cache always being available once it is set. If the map has more // enumerated descriptors than available in the original cache, the cache // will be lazily replaced by the extended cache when needed. if (descriptors->HasEnumCache()) { new_descriptors->CopyEnumCacheFrom(*descriptors); } Isolate* isolate = map->GetIsolate(); // Replace descriptors by new_descriptors in all maps that share it. isolate->heap()->incremental_marking()->IterateBlackObject(*descriptors); Map* current = *map; while (current->instance_descriptors() == *descriptors) { Object* next = current->GetBackPointer(); if (next->IsUndefined(isolate)) break; // Stop overwriting at initial map. current->UpdateDescriptors(*new_descriptors, layout_descriptor); current = Map::cast(next); } map->UpdateDescriptors(*new_descriptors, layout_descriptor); } // static Handle Map::GetObjectCreateMap(Handle prototype) { Isolate* isolate = prototype->GetIsolate(); Handle map(isolate->native_context()->object_function()->initial_map(), isolate); if (map->prototype() == *prototype) return map; if (prototype->IsNull(isolate)) { return isolate->slow_object_with_null_prototype_map(); } if (prototype->IsJSObject()) { Handle js_prototype = Handle::cast(prototype); if (!js_prototype->map()->is_prototype_map()) { JSObject::OptimizeAsPrototype(js_prototype, FAST_PROTOTYPE); } Handle info = Map::GetOrCreatePrototypeInfo(js_prototype, isolate); // TODO(verwaest): Use inobject slack tracking for this map. if (info->HasObjectCreateMap()) { map = handle(info->ObjectCreateMap(), isolate); } else { map = Map::CopyInitialMap(map); Map::SetPrototype(map, prototype, FAST_PROTOTYPE); PrototypeInfo::SetObjectCreateMap(info, map); } return map; } return Map::TransitionToPrototype(map, prototype, REGULAR_PROTOTYPE); } template static int AppendUniqueCallbacks(Handle callbacks, Handle array, int valid_descriptors) { int nof_callbacks = callbacks->length(); Isolate* isolate = array->GetIsolate(); // Ensure the keys are unique names before writing them into the // instance descriptor. Since it may cause a GC, it has to be done before we // temporarily put the heap in an invalid state while appending descriptors. for (int i = 0; i < nof_callbacks; ++i) { Handle entry(AccessorInfo::cast(callbacks->get(i))); if (entry->name()->IsUniqueName()) continue; Handle key = isolate->factory()->InternalizeString( Handle(String::cast(entry->name()))); entry->set_name(*key); } // Fill in new callback descriptors. Process the callbacks from // back to front so that the last callback with a given name takes // precedence over previously added callbacks with that name. for (int i = nof_callbacks - 1; i >= 0; i--) { Handle entry(AccessorInfo::cast(callbacks->get(i))); Handle key(Name::cast(entry->name())); // Check if a descriptor with this name already exists before writing. if (!T::Contains(key, entry, valid_descriptors, array)) { T::Insert(key, entry, valid_descriptors, array); valid_descriptors++; } } return valid_descriptors; } struct DescriptorArrayAppender { typedef DescriptorArray Array; static bool Contains(Handle key, Handle entry, int valid_descriptors, Handle array) { DisallowHeapAllocation no_gc; return array->Search(*key, valid_descriptors) != DescriptorArray::kNotFound; } static void Insert(Handle key, Handle entry, int valid_descriptors, Handle array) { DisallowHeapAllocation no_gc; Descriptor d = Descriptor::AccessorConstant(key, entry, entry->property_attributes()); array->Append(&d); } }; struct FixedArrayAppender { typedef FixedArray Array; static bool Contains(Handle key, Handle entry, int valid_descriptors, Handle array) { for (int i = 0; i < valid_descriptors; i++) { if (*key == AccessorInfo::cast(array->get(i))->name()) return true; } return false; } static void Insert(Handle key, Handle entry, int valid_descriptors, Handle array) { DisallowHeapAllocation no_gc; array->set(valid_descriptors, *entry); } }; void Map::AppendCallbackDescriptors(Handle map, Handle descriptors) { int nof = map->NumberOfOwnDescriptors(); Handle array(map->instance_descriptors()); Handle callbacks = Handle::cast(descriptors); DCHECK_GE(array->NumberOfSlackDescriptors(), callbacks->length()); nof = AppendUniqueCallbacks(callbacks, array, nof); map->SetNumberOfOwnDescriptors(nof); } int AccessorInfo::AppendUnique(Handle descriptors, Handle array, int valid_descriptors) { Handle callbacks = Handle::cast(descriptors); DCHECK_GE(array->length(), callbacks->length() + valid_descriptors); return AppendUniqueCallbacks(callbacks, array, valid_descriptors); } static bool ContainsMap(MapHandleList* maps, Map* map) { DCHECK_NOT_NULL(map); for (int i = 0; i < maps->length(); ++i) { if (!maps->at(i).is_null() && *maps->at(i) == map) return true; } return false; } Map* Map::FindElementsKindTransitionedMap(MapHandleList* candidates) { DisallowHeapAllocation no_allocation; DisallowDeoptimization no_deoptimization(GetIsolate()); ElementsKind kind = elements_kind(); bool packed = IsFastPackedElementsKind(kind); Map* transition = nullptr; if (IsTransitionableFastElementsKind(kind)) { // Check the state of the root map. Map* root_map = FindRootMap(); if (!EquivalentToForTransition(root_map)) return nullptr; root_map = root_map->LookupElementsTransitionMap(kind); DCHECK_NOT_NULL(root_map); // Starting from the next existing elements kind transition try to // replay the property transitions that does not involve instance rewriting // (ElementsTransitionAndStoreStub does not support that). for (root_map = root_map->ElementsTransitionMap(); root_map != nullptr && root_map->has_fast_elements(); root_map = root_map->ElementsTransitionMap()) { Map* current = root_map->TryReplayPropertyTransitions(this); if (current == nullptr) continue; if (InstancesNeedRewriting(current)) continue; if (ContainsMap(candidates, current) && (packed || !IsFastPackedElementsKind(current->elements_kind()))) { transition = current; packed = packed && IsFastPackedElementsKind(current->elements_kind()); } } } return transition; } static Map* FindClosestElementsTransition(Map* map, ElementsKind to_kind) { // Ensure we are requested to search elements kind transition "near the root". DCHECK_EQ(map->FindRootMap()->NumberOfOwnDescriptors(), map->NumberOfOwnDescriptors()); Map* current_map = map; ElementsKind kind = map->elements_kind(); while (kind != to_kind) { Map* next_map = current_map->ElementsTransitionMap(); if (next_map == nullptr) return current_map; kind = next_map->elements_kind(); current_map = next_map; } DCHECK_EQ(to_kind, current_map->elements_kind()); return current_map; } Map* Map::LookupElementsTransitionMap(ElementsKind to_kind) { Map* to_map = FindClosestElementsTransition(this, to_kind); if (to_map->elements_kind() == to_kind) return to_map; return nullptr; } bool Map::IsMapInArrayPrototypeChain() { Isolate* isolate = GetIsolate(); if (isolate->initial_array_prototype()->map() == this) { return true; } if (isolate->initial_object_prototype()->map() == this) { return true; } return false; } Handle Map::WeakCellForMap(Handle map) { Isolate* isolate = map->GetIsolate(); if (map->weak_cell_cache()->IsWeakCell()) { return Handle(WeakCell::cast(map->weak_cell_cache())); } Handle weak_cell = isolate->factory()->NewWeakCell(map); map->set_weak_cell_cache(*weak_cell); return weak_cell; } static Handle AddMissingElementsTransitions(Handle map, ElementsKind to_kind) { DCHECK(IsTransitionElementsKind(map->elements_kind())); Handle current_map = map; ElementsKind kind = map->elements_kind(); TransitionFlag flag; if (map->is_prototype_map()) { flag = OMIT_TRANSITION; } else { flag = INSERT_TRANSITION; if (IsFastElementsKind(kind)) { while (kind != to_kind && !IsTerminalElementsKind(kind)) { kind = GetNextTransitionElementsKind(kind); current_map = Map::CopyAsElementsKind(current_map, kind, flag); } } } // In case we are exiting the fast elements kind system, just add the map in // the end. if (kind != to_kind) { current_map = Map::CopyAsElementsKind(current_map, to_kind, flag); } DCHECK(current_map->elements_kind() == to_kind); return current_map; } Handle Map::TransitionElementsTo(Handle map, ElementsKind to_kind) { ElementsKind from_kind = map->elements_kind(); if (from_kind == to_kind) return map; Isolate* isolate = map->GetIsolate(); Context* native_context = isolate->context()->native_context(); if (from_kind == FAST_SLOPPY_ARGUMENTS_ELEMENTS) { if (*map == native_context->fast_aliased_arguments_map()) { DCHECK_EQ(SLOW_SLOPPY_ARGUMENTS_ELEMENTS, to_kind); return handle(native_context->slow_aliased_arguments_map()); } } else if (from_kind == SLOW_SLOPPY_ARGUMENTS_ELEMENTS) { if (*map == native_context->slow_aliased_arguments_map()) { DCHECK_EQ(FAST_SLOPPY_ARGUMENTS_ELEMENTS, to_kind); return handle(native_context->fast_aliased_arguments_map()); } } else if (IsFastElementsKind(from_kind) && IsFastElementsKind(to_kind)) { // Reuse map transitions for JSArrays. DisallowHeapAllocation no_gc; if (native_context->get(Context::ArrayMapIndex(from_kind)) == *map) { Object* maybe_transitioned_map = native_context->get(Context::ArrayMapIndex(to_kind)); if (maybe_transitioned_map->IsMap()) { return handle(Map::cast(maybe_transitioned_map), isolate); } } } DCHECK(!map->IsUndefined(isolate)); // Check if we can go back in the elements kind transition chain. if (IsHoleyElementsKind(from_kind) && to_kind == GetPackedElementsKind(from_kind) && map->GetBackPointer()->IsMap() && Map::cast(map->GetBackPointer())->elements_kind() == to_kind) { return handle(Map::cast(map->GetBackPointer())); } bool allow_store_transition = IsTransitionElementsKind(from_kind); // Only store fast element maps in ascending generality. if (IsFastElementsKind(to_kind)) { allow_store_transition = allow_store_transition && IsTransitionableFastElementsKind(from_kind) && IsMoreGeneralElementsKindTransition(from_kind, to_kind); } if (!allow_store_transition) { return Map::CopyAsElementsKind(map, to_kind, OMIT_TRANSITION); } return Map::ReconfigureElementsKind(map, to_kind); } // static Handle Map::AsElementsKind(Handle map, ElementsKind kind) { Handle closest_map(FindClosestElementsTransition(*map, kind)); if (closest_map->elements_kind() == kind) { return closest_map; } return AddMissingElementsTransitions(closest_map, kind); } Handle JSObject::GetElementsTransitionMap(Handle object, ElementsKind to_kind) { Handle map(object->map()); return Map::TransitionElementsTo(map, to_kind); } void JSProxy::Revoke(Handle proxy) { Isolate* isolate = proxy->GetIsolate(); if (!proxy->IsRevoked()) proxy->set_handler(isolate->heap()->null_value()); DCHECK(proxy->IsRevoked()); } Maybe JSProxy::HasProperty(Isolate* isolate, Handle proxy, Handle name) { DCHECK(!name->IsPrivate()); STACK_CHECK(isolate, Nothing()); // 1. (Assert) // 2. Let handler be the value of the [[ProxyHandler]] internal slot of O. Handle handler(proxy->handler(), isolate); // 3. If handler is null, throw a TypeError exception. // 4. Assert: Type(handler) is Object. if (proxy->IsRevoked()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyRevoked, isolate->factory()->has_string())); return Nothing(); } // 5. Let target be the value of the [[ProxyTarget]] internal slot of O. Handle target(proxy->target(), isolate); // 6. Let trap be ? GetMethod(handler, "has"). Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(Handle::cast(handler), isolate->factory()->has_string()), Nothing()); // 7. If trap is undefined, then if (trap->IsUndefined(isolate)) { // 7a. Return target.[[HasProperty]](P). return JSReceiver::HasProperty(target, name); } // 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, «target, P»)). Handle trap_result_obj; Handle args[] = {target, name}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result_obj, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); bool boolean_trap_result = trap_result_obj->BooleanValue(); // 9. If booleanTrapResult is false, then: if (!boolean_trap_result) { // 9a. Let targetDesc be ? target.[[GetOwnProperty]](P). PropertyDescriptor target_desc; Maybe target_found = JSReceiver::GetOwnPropertyDescriptor( isolate, target, name, &target_desc); MAYBE_RETURN(target_found, Nothing()); // 9b. If targetDesc is not undefined, then: if (target_found.FromJust()) { // 9b i. If targetDesc.[[Configurable]] is false, throw a TypeError // exception. if (!target_desc.configurable()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyHasNonConfigurable, name)); return Nothing(); } // 9b ii. Let extensibleTarget be ? IsExtensible(target). Maybe extensible_target = JSReceiver::IsExtensible(target); MAYBE_RETURN(extensible_target, Nothing()); // 9b iii. If extensibleTarget is false, throw a TypeError exception. if (!extensible_target.FromJust()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyHasNonExtensible, name)); return Nothing(); } } } // 10. Return booleanTrapResult. return Just(boolean_trap_result); } Maybe JSProxy::SetProperty(Handle proxy, Handle name, Handle value, Handle receiver, LanguageMode language_mode) { DCHECK(!name->IsPrivate()); Isolate* isolate = proxy->GetIsolate(); STACK_CHECK(isolate, Nothing()); Factory* factory = isolate->factory(); Handle trap_name = factory->set_string(); ShouldThrow should_throw = is_sloppy(language_mode) ? DONT_THROW : THROW_ON_ERROR; if (proxy->IsRevoked()) { isolate->Throw( *factory->NewTypeError(MessageTemplate::kProxyRevoked, trap_name)); return Nothing(); } Handle target(proxy->target(), isolate); Handle handler(JSReceiver::cast(proxy->handler()), isolate); Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(handler, trap_name), Nothing()); if (trap->IsUndefined(isolate)) { LookupIterator it = LookupIterator::PropertyOrElement(isolate, receiver, name, target); return Object::SetSuperProperty(&it, value, language_mode, Object::MAY_BE_STORE_FROM_KEYED); } Handle trap_result; Handle args[] = {target, name, value, receiver}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); if (!trap_result->BooleanValue()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kProxyTrapReturnedFalsishFor, trap_name, name)); } // Enforce the invariant. PropertyDescriptor target_desc; Maybe owned = JSReceiver::GetOwnPropertyDescriptor(isolate, target, name, &target_desc); MAYBE_RETURN(owned, Nothing()); if (owned.FromJust()) { bool inconsistent = PropertyDescriptor::IsDataDescriptor(&target_desc) && !target_desc.configurable() && !target_desc.writable() && !value->SameValue(*target_desc.value()); if (inconsistent) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxySetFrozenData, name)); return Nothing(); } inconsistent = PropertyDescriptor::IsAccessorDescriptor(&target_desc) && !target_desc.configurable() && target_desc.set()->IsUndefined(isolate); if (inconsistent) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxySetFrozenAccessor, name)); return Nothing(); } } return Just(true); } Maybe JSProxy::DeletePropertyOrElement(Handle proxy, Handle name, LanguageMode language_mode) { DCHECK(!name->IsPrivate()); ShouldThrow should_throw = is_sloppy(language_mode) ? DONT_THROW : THROW_ON_ERROR; Isolate* isolate = proxy->GetIsolate(); STACK_CHECK(isolate, Nothing()); Factory* factory = isolate->factory(); Handle trap_name = factory->deleteProperty_string(); if (proxy->IsRevoked()) { isolate->Throw( *factory->NewTypeError(MessageTemplate::kProxyRevoked, trap_name)); return Nothing(); } Handle target(proxy->target(), isolate); Handle handler(JSReceiver::cast(proxy->handler()), isolate); Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(handler, trap_name), Nothing()); if (trap->IsUndefined(isolate)) { return JSReceiver::DeletePropertyOrElement(target, name, language_mode); } Handle trap_result; Handle args[] = {target, name}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); if (!trap_result->BooleanValue()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kProxyTrapReturnedFalsishFor, trap_name, name)); } // Enforce the invariant. PropertyDescriptor target_desc; Maybe owned = JSReceiver::GetOwnPropertyDescriptor(isolate, target, name, &target_desc); MAYBE_RETURN(owned, Nothing()); if (owned.FromJust() && !target_desc.configurable()) { isolate->Throw(*factory->NewTypeError( MessageTemplate::kProxyDeletePropertyNonConfigurable, name)); return Nothing(); } return Just(true); } // static MaybeHandle JSProxy::New(Isolate* isolate, Handle target, Handle handler) { if (!target->IsJSReceiver()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyNonObject), JSProxy); } if (target->IsJSProxy() && JSProxy::cast(*target)->IsRevoked()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyHandlerOrTargetRevoked), JSProxy); } if (!handler->IsJSReceiver()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyNonObject), JSProxy); } if (handler->IsJSProxy() && JSProxy::cast(*handler)->IsRevoked()) { THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kProxyHandlerOrTargetRevoked), JSProxy); } return isolate->factory()->NewJSProxy(Handle::cast(target), Handle::cast(handler)); } // static MaybeHandle JSProxy::GetFunctionRealm(Handle proxy) { DCHECK(proxy->map()->is_constructor()); if (proxy->IsRevoked()) { THROW_NEW_ERROR(proxy->GetIsolate(), NewTypeError(MessageTemplate::kProxyRevoked), Context); } Handle target(JSReceiver::cast(proxy->target())); return JSReceiver::GetFunctionRealm(target); } // static MaybeHandle JSBoundFunction::GetFunctionRealm( Handle function) { DCHECK(function->map()->is_constructor()); return JSReceiver::GetFunctionRealm( handle(function->bound_target_function())); } // static MaybeHandle JSBoundFunction::GetName(Isolate* isolate, Handle function) { Handle prefix = isolate->factory()->bound__string(); if (!function->bound_target_function()->IsJSFunction()) return prefix; Handle target(JSFunction::cast(function->bound_target_function()), isolate); Handle target_name = JSFunction::GetName(isolate, target); if (!target_name->IsString()) return prefix; Factory* factory = isolate->factory(); return factory->NewConsString(prefix, Handle::cast(target_name)); } // static Handle JSFunction::GetName(Isolate* isolate, Handle function) { if (function->shared()->name_should_print_as_anonymous()) { return isolate->factory()->anonymous_string(); } return handle(function->shared()->name(), isolate); } // static MaybeHandle JSFunction::GetLength(Isolate* isolate, Handle function) { int length = 0; if (function->shared()->is_compiled()) { length = function->shared()->length(); } else { // If the function isn't compiled yet, the length is not computed // correctly yet. Compile it now and return the right length. if (Compiler::Compile(function, Compiler::KEEP_EXCEPTION)) { length = function->shared()->length(); } if (isolate->has_pending_exception()) return MaybeHandle(); } return handle(Smi::FromInt(length), isolate); } // static Handle JSFunction::GetFunctionRealm(Handle function) { DCHECK(function->map()->is_constructor()); return handle(function->context()->native_context()); } // static MaybeHandle JSObject::GetFunctionRealm(Handle object) { DCHECK(object->map()->is_constructor()); DCHECK(!object->IsJSFunction()); return object->GetCreationContext(); } // static MaybeHandle JSReceiver::GetFunctionRealm(Handle receiver) { if (receiver->IsJSProxy()) { return JSProxy::GetFunctionRealm(Handle::cast(receiver)); } if (receiver->IsJSFunction()) { return JSFunction::GetFunctionRealm(Handle::cast(receiver)); } if (receiver->IsJSBoundFunction()) { return JSBoundFunction::GetFunctionRealm( Handle::cast(receiver)); } return JSObject::GetFunctionRealm(Handle::cast(receiver)); } Maybe JSProxy::GetPropertyAttributes(LookupIterator* it) { PropertyDescriptor desc; Maybe found = JSProxy::GetOwnPropertyDescriptor( it->isolate(), it->GetHolder(), it->GetName(), &desc); MAYBE_RETURN(found, Nothing()); if (!found.FromJust()) return Just(ABSENT); return Just(desc.ToAttributes()); } void JSObject::AllocateStorageForMap(Handle object, Handle map) { DCHECK(object->map()->GetInObjectProperties() == map->GetInObjectProperties()); ElementsKind obj_kind = object->map()->elements_kind(); ElementsKind map_kind = map->elements_kind(); if (map_kind != obj_kind) { ElementsKind to_kind = GetMoreGeneralElementsKind(map_kind, obj_kind); if (IsDictionaryElementsKind(obj_kind)) { to_kind = obj_kind; } if (IsDictionaryElementsKind(to_kind)) { NormalizeElements(object); } else { TransitionElementsKind(object, to_kind); } map = Map::ReconfigureElementsKind(map, to_kind); } JSObject::MigrateToMap(object, map); } void JSObject::MigrateInstance(Handle object) { Handle original_map(object->map()); Handle map = Map::Update(original_map); map->set_migration_target(true); MigrateToMap(object, map); if (FLAG_trace_migration) { object->PrintInstanceMigration(stdout, *original_map, *map); } #if VERIFY_HEAP if (FLAG_verify_heap) { object->JSObjectVerify(); } #endif } // static bool JSObject::TryMigrateInstance(Handle object) { Isolate* isolate = object->GetIsolate(); DisallowDeoptimization no_deoptimization(isolate); Handle original_map(object->map(), isolate); Handle new_map; if (!Map::TryUpdate(original_map).ToHandle(&new_map)) { return false; } JSObject::MigrateToMap(object, new_map); if (FLAG_trace_migration) { object->PrintInstanceMigration(stdout, *original_map, object->map()); } #if VERIFY_HEAP if (FLAG_verify_heap) { object->JSObjectVerify(); } #endif return true; } void JSObject::AddProperty(Handle object, Handle name, Handle value, PropertyAttributes attributes) { LookupIterator it(object, name, object, LookupIterator::OWN_SKIP_INTERCEPTOR); CHECK_NE(LookupIterator::ACCESS_CHECK, it.state()); #ifdef DEBUG uint32_t index; DCHECK(!object->IsJSProxy()); DCHECK(!name->AsArrayIndex(&index)); Maybe maybe = GetPropertyAttributes(&it); DCHECK(maybe.IsJust()); DCHECK(!it.IsFound()); DCHECK(object->map()->is_extensible() || name->IsPrivate()); #endif CHECK(AddDataProperty(&it, value, attributes, THROW_ON_ERROR, CERTAINLY_NOT_STORE_FROM_KEYED) .IsJust()); } // Reconfigures a property to a data property with attributes, even if it is not // reconfigurable. // Requires a LookupIterator that does not look at the prototype chain beyond // hidden prototypes. MaybeHandle JSObject::DefineOwnPropertyIgnoreAttributes( LookupIterator* it, Handle value, PropertyAttributes attributes, AccessorInfoHandling handling) { MAYBE_RETURN_NULL(DefineOwnPropertyIgnoreAttributes( it, value, attributes, THROW_ON_ERROR, handling)); return value; } Maybe JSObject::DefineOwnPropertyIgnoreAttributes( LookupIterator* it, Handle value, PropertyAttributes attributes, ShouldThrow should_throw, AccessorInfoHandling handling) { it->UpdateProtector(); Handle object = Handle::cast(it->GetReceiver()); for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::JSPROXY: case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::ACCESS_CHECK: if (!it->HasAccess()) { it->isolate()->ReportFailedAccessCheck(it->GetHolder()); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(it->isolate(), Nothing()); return Just(true); } break; // If there's an interceptor, try to store the property with the // interceptor. // In case of success, the attributes will have been reset to the default // attributes of the interceptor, rather than the incoming attributes. // // TODO(verwaest): JSProxy afterwards verify the attributes that the // JSProxy claims it has, and verifies that they are compatible. If not, // they throw. Here we should do the same. case LookupIterator::INTERCEPTOR: if (handling == DONT_FORCE_FIELD) { Maybe result = JSObject::SetPropertyWithInterceptor(it, should_throw, value); if (result.IsNothing() || result.FromJust()) return result; } break; case LookupIterator::ACCESSOR: { Handle accessors = it->GetAccessors(); // Special handling for AccessorInfo, which behaves like a data // property. if (accessors->IsAccessorInfo() && handling == DONT_FORCE_FIELD) { PropertyAttributes current_attributes = it->property_attributes(); // Ensure the context isn't changed after calling into accessors. AssertNoContextChange ncc(it->isolate()); // Update the attributes before calling the setter. The setter may // later change the shape of the property. if (current_attributes != attributes) { it->TransitionToAccessorPair(accessors, attributes); } return JSObject::SetPropertyWithAccessor(it, value, should_throw); } it->ReconfigureDataProperty(value, attributes); return Just(true); } case LookupIterator::INTEGER_INDEXED_EXOTIC: return RedefineIncompatibleProperty(it->isolate(), it->GetName(), value, should_throw); case LookupIterator::DATA: { // Regular property update if the attributes match. if (it->property_attributes() == attributes) { return SetDataProperty(it, value); } // Special case: properties of typed arrays cannot be reconfigured to // non-writable nor to non-enumerable. if (it->IsElement() && object->HasFixedTypedArrayElements()) { return RedefineIncompatibleProperty(it->isolate(), it->GetName(), value, should_throw); } // Reconfigure the data property if the attributes mismatch. it->ReconfigureDataProperty(value, attributes); return Just(true); } } } return AddDataProperty(it, value, attributes, should_throw, CERTAINLY_NOT_STORE_FROM_KEYED); } MaybeHandle JSObject::SetOwnPropertyIgnoreAttributes( Handle object, Handle name, Handle value, PropertyAttributes attributes) { DCHECK(!value->IsTheHole(object->GetIsolate())); LookupIterator it(object, name, object, LookupIterator::OWN); return DefineOwnPropertyIgnoreAttributes(&it, value, attributes); } MaybeHandle JSObject::SetOwnElementIgnoreAttributes( Handle object, uint32_t index, Handle value, PropertyAttributes attributes) { Isolate* isolate = object->GetIsolate(); LookupIterator it(isolate, object, index, object, LookupIterator::OWN); return DefineOwnPropertyIgnoreAttributes(&it, value, attributes); } MaybeHandle JSObject::DefinePropertyOrElementIgnoreAttributes( Handle object, Handle name, Handle value, PropertyAttributes attributes) { Isolate* isolate = object->GetIsolate(); LookupIterator it = LookupIterator::PropertyOrElement( isolate, object, name, object, LookupIterator::OWN); return DefineOwnPropertyIgnoreAttributes(&it, value, attributes); } Maybe JSObject::GetPropertyAttributesWithInterceptor( LookupIterator* it) { return GetPropertyAttributesWithInterceptorInternal(it, it->GetInterceptor()); } Maybe JSReceiver::GetPropertyAttributes( LookupIterator* it) { for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::JSPROXY: return JSProxy::GetPropertyAttributes(it); case LookupIterator::INTERCEPTOR: { Maybe result = JSObject::GetPropertyAttributesWithInterceptor(it); if (!result.IsJust()) return result; if (result.FromJust() != ABSENT) return result; break; } case LookupIterator::ACCESS_CHECK: if (it->HasAccess()) break; return JSObject::GetPropertyAttributesWithFailedAccessCheck(it); case LookupIterator::INTEGER_INDEXED_EXOTIC: return Just(ABSENT); case LookupIterator::ACCESSOR: case LookupIterator::DATA: return Just(it->property_attributes()); } } return Just(ABSENT); } Handle NormalizedMapCache::New(Isolate* isolate) { Handle array( isolate->factory()->NewFixedArray(kEntries, TENURED)); return Handle::cast(array); } MaybeHandle NormalizedMapCache::Get(Handle fast_map, PropertyNormalizationMode mode) { DisallowHeapAllocation no_gc; Object* value = FixedArray::get(GetIndex(fast_map)); if (!value->IsMap() || !Map::cast(value)->EquivalentToForNormalization(*fast_map, mode)) { return MaybeHandle(); } return handle(Map::cast(value)); } void NormalizedMapCache::Set(Handle fast_map, Handle normalized_map) { DisallowHeapAllocation no_gc; DCHECK(normalized_map->is_dictionary_map()); FixedArray::set(GetIndex(fast_map), *normalized_map); } void NormalizedMapCache::Clear() { int entries = length(); for (int i = 0; i != entries; i++) { set_undefined(i); } } void HeapObject::UpdateMapCodeCache(Handle object, Handle name, Handle code) { Handle map(object->map()); Map::UpdateCodeCache(map, name, code); } void JSObject::NormalizeProperties(Handle object, PropertyNormalizationMode mode, int expected_additional_properties, const char* reason) { if (!object->HasFastProperties()) return; Handle map(object->map()); Handle new_map = Map::Normalize(map, mode, reason); MigrateToMap(object, new_map, expected_additional_properties); } void JSObject::MigrateSlowToFast(Handle object, int unused_property_fields, const char* reason) { if (object->HasFastProperties()) return; DCHECK(!object->IsJSGlobalObject()); Isolate* isolate = object->GetIsolate(); Factory* factory = isolate->factory(); Handle dictionary(object->property_dictionary()); // Make sure we preserve dictionary representation if there are too many // descriptors. int number_of_elements = dictionary->NumberOfElements(); if (number_of_elements > kMaxNumberOfDescriptors) return; Handle iteration_order; if (number_of_elements != dictionary->NextEnumerationIndex()) { iteration_order = NameDictionary::DoGenerateNewEnumerationIndices(dictionary); } else { iteration_order = NameDictionary::IterationIndices(dictionary); } int instance_descriptor_length = iteration_order->length(); int number_of_fields = 0; // Compute the length of the instance descriptor. for (int i = 0; i < instance_descriptor_length; i++) { int index = Smi::cast(iteration_order->get(i))->value(); DCHECK(dictionary->IsKey(isolate, dictionary->KeyAt(index))); PropertyKind kind = dictionary->DetailsAt(index).kind(); if (kind == kData) { if (FLAG_track_constant_fields) { number_of_fields += 1; } else { Object* value = dictionary->ValueAt(index); if (!value->IsJSFunction()) { number_of_fields += 1; } } } } Handle old_map(object->map(), isolate); int inobject_props = old_map->GetInObjectProperties(); // Allocate new map. Handle new_map = Map::CopyDropDescriptors(old_map); new_map->set_dictionary_map(false); NotifyMapChange(old_map, new_map, isolate); #if TRACE_MAPS if (FLAG_trace_maps) { PrintF("[TraceMaps: SlowToFast from= %p to= %p reason= %s ]\n", reinterpret_cast(*old_map), reinterpret_cast(*new_map), reason); } #endif if (instance_descriptor_length == 0) { DisallowHeapAllocation no_gc; DCHECK_LE(unused_property_fields, inobject_props); // Transform the object. new_map->set_unused_property_fields(inobject_props); object->synchronized_set_map(*new_map); object->set_properties(isolate->heap()->empty_fixed_array()); // Check that it really works. DCHECK(object->HasFastProperties()); return; } // Allocate the instance descriptor. Handle descriptors = DescriptorArray::Allocate( isolate, instance_descriptor_length, 0, TENURED); int number_of_allocated_fields = number_of_fields + unused_property_fields - inobject_props; if (number_of_allocated_fields < 0) { // There is enough inobject space for all fields (including unused). number_of_allocated_fields = 0; unused_property_fields = inobject_props - number_of_fields; } // Allocate the fixed array for the fields. Handle fields = factory->NewFixedArray( number_of_allocated_fields); // Fill in the instance descriptor and the fields. int current_offset = 0; for (int i = 0; i < instance_descriptor_length; i++) { int index = Smi::cast(iteration_order->get(i))->value(); Object* k = dictionary->KeyAt(index); DCHECK(dictionary->IsKey(k)); // Dictionary keys are internalized upon insertion. // TODO(jkummerow): Turn this into a DCHECK if it's not hit in the wild. CHECK(k->IsUniqueName()); Handle key(Name::cast(k), isolate); Object* value = dictionary->ValueAt(index); PropertyDetails details = dictionary->DetailsAt(index); DCHECK_EQ(kField, details.location()); DCHECK_EQ(kMutable, details.constness()); int enumeration_index = details.dictionary_index(); Descriptor d; if (details.kind() == kData) { if (!FLAG_track_constant_fields && value->IsJSFunction()) { d = Descriptor::DataConstant(key, handle(value, isolate), details.attributes()); } else { d = Descriptor::DataField( key, current_offset, details.attributes(), kDefaultFieldConstness, // TODO(verwaest): value->OptimalRepresentation(); Representation::Tagged(), FieldType::Any(isolate)); } } else { DCHECK_EQ(kAccessor, details.kind()); d = Descriptor::AccessorConstant(key, handle(value, isolate), details.attributes()); } details = d.GetDetails(); if (details.location() == kField) { if (current_offset < inobject_props) { object->InObjectPropertyAtPut(current_offset, value, UPDATE_WRITE_BARRIER); } else { int offset = current_offset - inobject_props; fields->set(offset, value); } current_offset += details.field_width_in_words(); } descriptors->Set(enumeration_index - 1, &d); } DCHECK(current_offset == number_of_fields); descriptors->Sort(); Handle layout_descriptor = LayoutDescriptor::New( new_map, descriptors, descriptors->number_of_descriptors()); DisallowHeapAllocation no_gc; new_map->InitializeDescriptors(*descriptors, *layout_descriptor); new_map->set_unused_property_fields(unused_property_fields); // Transform the object. object->synchronized_set_map(*new_map); object->set_properties(*fields); DCHECK(object->IsJSObject()); // Check that it really works. DCHECK(object->HasFastProperties()); } void JSObject::ResetElements(Handle object) { Isolate* isolate = object->GetIsolate(); CHECK(object->map() != isolate->heap()->sloppy_arguments_elements_map()); if (object->map()->has_dictionary_elements()) { Handle new_elements = SeededNumberDictionary::New(isolate, 0); object->set_elements(*new_elements); } else { object->set_elements(object->map()->GetInitialElements()); } } void JSObject::RequireSlowElements(SeededNumberDictionary* dictionary) { if (dictionary->requires_slow_elements()) return; dictionary->set_requires_slow_elements(); if (map()->is_prototype_map()) { // If this object is a prototype (the callee will check), invalidate any // prototype chains involving it. InvalidatePrototypeChains(map()); } } Handle JSObject::NormalizeElements( Handle object) { DCHECK(!object->HasFixedTypedArrayElements()); Isolate* isolate = object->GetIsolate(); bool is_arguments = object->HasSloppyArgumentsElements(); { DisallowHeapAllocation no_gc; FixedArrayBase* elements = object->elements(); if (is_arguments) { FixedArray* parameter_map = FixedArray::cast(elements); elements = FixedArrayBase::cast(parameter_map->get(1)); } if (elements->IsDictionary()) { return handle(SeededNumberDictionary::cast(elements), isolate); } } DCHECK(object->HasFastSmiOrObjectElements() || object->HasFastDoubleElements() || object->HasFastArgumentsElements() || object->HasFastStringWrapperElements()); Handle dictionary = object->GetElementsAccessor()->Normalize(object); // Switch to using the dictionary as the backing storage for elements. ElementsKind target_kind = is_arguments ? SLOW_SLOPPY_ARGUMENTS_ELEMENTS : object->HasFastStringWrapperElements() ? SLOW_STRING_WRAPPER_ELEMENTS : DICTIONARY_ELEMENTS; Handle new_map = JSObject::GetElementsTransitionMap(object, target_kind); // Set the new map first to satify the elements type assert in set_elements(). JSObject::MigrateToMap(object, new_map); if (is_arguments) { FixedArray::cast(object->elements())->set(1, *dictionary); } else { object->set_elements(*dictionary); } isolate->counters()->elements_to_dictionary()->Increment(); #ifdef DEBUG if (FLAG_trace_normalization) { OFStream os(stdout); os << "Object elements have been normalized:\n"; object->Print(os); } #endif DCHECK(object->HasDictionaryElements() || object->HasSlowArgumentsElements() || object->HasSlowStringWrapperElements()); return dictionary; } template static Smi* GetOrCreateIdentityHashHelper(Isolate* isolate, Handle proxy) { Object* maybe_hash = proxy->hash(); if (maybe_hash->IsSmi()) return Smi::cast(maybe_hash); Smi* hash = Smi::FromInt(isolate->GenerateIdentityHash(Smi::kMaxValue)); proxy->set_hash(hash); return hash; } // static Object* JSObject::GetIdentityHash(Isolate* isolate, Handle object) { if (object->IsJSGlobalProxy()) { return JSGlobalProxy::cast(*object)->hash(); } Handle hash_code_symbol = isolate->factory()->hash_code_symbol(); return *JSReceiver::GetDataProperty(object, hash_code_symbol); } // static Smi* JSObject::GetOrCreateIdentityHash(Isolate* isolate, Handle object) { if (object->IsJSGlobalProxy()) { return GetOrCreateIdentityHashHelper(isolate, Handle::cast(object)); } Handle hash_code_symbol = isolate->factory()->hash_code_symbol(); LookupIterator it(object, hash_code_symbol, object, LookupIterator::OWN); if (it.IsFound()) { DCHECK_EQ(LookupIterator::DATA, it.state()); Object* maybe_hash = *it.GetDataValue(); if (maybe_hash->IsSmi()) return Smi::cast(maybe_hash); } Smi* hash = Smi::FromInt(isolate->GenerateIdentityHash(Smi::kMaxValue)); CHECK(AddDataProperty(&it, handle(hash, isolate), NONE, THROW_ON_ERROR, CERTAINLY_NOT_STORE_FROM_KEYED) .IsJust()); return hash; } // static Object* JSProxy::GetIdentityHash(Handle proxy) { return proxy->hash(); } Smi* JSProxy::GetOrCreateIdentityHash(Isolate* isolate, Handle proxy) { return GetOrCreateIdentityHashHelper(isolate, proxy); } Maybe JSObject::DeletePropertyWithInterceptor(LookupIterator* it, ShouldThrow should_throw) { Isolate* isolate = it->isolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); DCHECK_EQ(LookupIterator::INTERCEPTOR, it->state()); Handle interceptor(it->GetInterceptor()); if (interceptor->deleter()->IsUndefined(isolate)) return Nothing(); Handle holder = it->GetHolder(); Handle receiver = it->GetReceiver(); if (!receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, receiver, Object::ConvertReceiver(isolate, receiver), Nothing()); } PropertyCallbackArguments args(isolate, interceptor->data(), *receiver, *holder, should_throw); Handle result; if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertyDeleterCallback deleter = v8::ToCData(interceptor->deleter()); result = args.Call(deleter, index); } else if (it->name()->IsSymbol() && !interceptor->can_intercept_symbols()) { return Nothing(); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); v8::GenericNamedPropertyDeleterCallback deleter = v8::ToCData( interceptor->deleter()); result = args.Call(deleter, name); } RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); if (result.is_null()) return Nothing(); DCHECK(result->IsBoolean()); // Rebox CustomArguments::kReturnValueOffset before returning. return Just(result->IsTrue(isolate)); } void JSReceiver::DeleteNormalizedProperty(Handle object, Handle name, int entry) { DCHECK(!object->HasFastProperties()); Isolate* isolate = object->GetIsolate(); if (object->IsJSGlobalObject()) { // If we have a global object, invalidate the cell and swap in a new one. Handle dictionary( JSObject::cast(*object)->global_dictionary()); DCHECK_NE(GlobalDictionary::kNotFound, entry); auto cell = PropertyCell::InvalidateEntry(dictionary, entry); cell->set_value(isolate->heap()->the_hole_value()); cell->set_property_details( PropertyDetails::Empty(PropertyCellType::kUninitialized)); } else { Handle dictionary(object->property_dictionary()); DCHECK_NE(NameDictionary::kNotFound, entry); NameDictionary::DeleteProperty(dictionary, entry); Handle new_properties = NameDictionary::Shrink(dictionary, name); object->set_properties(*new_properties); } } Maybe JSReceiver::DeleteProperty(LookupIterator* it, LanguageMode language_mode) { it->UpdateProtector(); Isolate* isolate = it->isolate(); if (it->state() == LookupIterator::JSPROXY) { return JSProxy::DeletePropertyOrElement(it->GetHolder(), it->GetName(), language_mode); } if (it->GetReceiver()->IsJSProxy()) { if (it->state() != LookupIterator::NOT_FOUND) { DCHECK_EQ(LookupIterator::DATA, it->state()); DCHECK(it->name()->IsPrivate()); it->Delete(); } return Just(true); } Handle receiver = Handle::cast(it->GetReceiver()); for (; it->IsFound(); it->Next()) { switch (it->state()) { case LookupIterator::JSPROXY: case LookupIterator::NOT_FOUND: case LookupIterator::TRANSITION: UNREACHABLE(); case LookupIterator::ACCESS_CHECK: if (it->HasAccess()) break; isolate->ReportFailedAccessCheck(it->GetHolder()); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); return Just(false); case LookupIterator::INTERCEPTOR: { ShouldThrow should_throw = is_sloppy(language_mode) ? DONT_THROW : THROW_ON_ERROR; Maybe result = JSObject::DeletePropertyWithInterceptor(it, should_throw); // An exception was thrown in the interceptor. Propagate. if (isolate->has_pending_exception()) return Nothing(); // Delete with interceptor succeeded. Return result. // TODO(neis): In strict mode, we should probably throw if the // interceptor returns false. if (result.IsJust()) return result; break; } case LookupIterator::INTEGER_INDEXED_EXOTIC: return Just(true); case LookupIterator::DATA: case LookupIterator::ACCESSOR: { if (!it->IsConfigurable()) { // Fail if the property is not configurable. if (is_strict(language_mode)) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kStrictDeleteProperty, it->GetName(), receiver)); return Nothing(); } return Just(false); } it->Delete(); return Just(true); } } } return Just(true); } Maybe JSReceiver::DeleteElement(Handle object, uint32_t index, LanguageMode language_mode) { LookupIterator it(object->GetIsolate(), object, index, object, LookupIterator::OWN); return DeleteProperty(&it, language_mode); } Maybe JSReceiver::DeleteProperty(Handle object, Handle name, LanguageMode language_mode) { LookupIterator it(object, name, object, LookupIterator::OWN); return DeleteProperty(&it, language_mode); } Maybe JSReceiver::DeletePropertyOrElement(Handle object, Handle name, LanguageMode language_mode) { LookupIterator it = LookupIterator::PropertyOrElement( name->GetIsolate(), object, name, object, LookupIterator::OWN); return DeleteProperty(&it, language_mode); } // ES6 19.1.2.4 // static Object* JSReceiver::DefineProperty(Isolate* isolate, Handle object, Handle key, Handle attributes) { // 1. If Type(O) is not Object, throw a TypeError exception. if (!object->IsJSReceiver()) { Handle fun_name = isolate->factory()->InternalizeUtf8String("Object.defineProperty"); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError(MessageTemplate::kCalledOnNonObject, fun_name)); } // 2. Let key be ToPropertyKey(P). // 3. ReturnIfAbrupt(key). ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, key, ToPropertyKey(isolate, key)); // 4. Let desc be ToPropertyDescriptor(Attributes). // 5. ReturnIfAbrupt(desc). PropertyDescriptor desc; if (!PropertyDescriptor::ToPropertyDescriptor(isolate, attributes, &desc)) { return isolate->heap()->exception(); } // 6. Let success be DefinePropertyOrThrow(O,key, desc). Maybe success = DefineOwnProperty( isolate, Handle::cast(object), key, &desc, THROW_ON_ERROR); // 7. ReturnIfAbrupt(success). MAYBE_RETURN(success, isolate->heap()->exception()); CHECK(success.FromJust()); // 8. Return O. return *object; } // ES6 19.1.2.3.1 // static MaybeHandle JSReceiver::DefineProperties(Isolate* isolate, Handle object, Handle properties) { // 1. If Type(O) is not Object, throw a TypeError exception. if (!object->IsJSReceiver()) { Handle fun_name = isolate->factory()->InternalizeUtf8String("Object.defineProperties"); THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kCalledOnNonObject, fun_name), Object); } // 2. Let props be ToObject(Properties). // 3. ReturnIfAbrupt(props). Handle props; ASSIGN_RETURN_ON_EXCEPTION(isolate, props, Object::ToObject(isolate, properties), Object); // 4. Let keys be props.[[OwnPropertyKeys]](). // 5. ReturnIfAbrupt(keys). Handle keys; ASSIGN_RETURN_ON_EXCEPTION( isolate, keys, KeyAccumulator::GetKeys(props, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES), Object); // 6. Let descriptors be an empty List. int capacity = keys->length(); std::vector descriptors(capacity); size_t descriptors_index = 0; // 7. Repeat for each element nextKey of keys in List order, for (int i = 0; i < keys->length(); ++i) { Handle next_key(keys->get(i), isolate); // 7a. Let propDesc be props.[[GetOwnProperty]](nextKey). // 7b. ReturnIfAbrupt(propDesc). bool success = false; LookupIterator it = LookupIterator::PropertyOrElement( isolate, props, next_key, &success, LookupIterator::OWN); DCHECK(success); Maybe maybe = JSReceiver::GetPropertyAttributes(&it); if (!maybe.IsJust()) return MaybeHandle(); PropertyAttributes attrs = maybe.FromJust(); // 7c. If propDesc is not undefined and propDesc.[[Enumerable]] is true: if (attrs == ABSENT) continue; if (attrs & DONT_ENUM) continue; // 7c i. Let descObj be Get(props, nextKey). // 7c ii. ReturnIfAbrupt(descObj). Handle desc_obj; ASSIGN_RETURN_ON_EXCEPTION(isolate, desc_obj, Object::GetProperty(&it), Object); // 7c iii. Let desc be ToPropertyDescriptor(descObj). success = PropertyDescriptor::ToPropertyDescriptor( isolate, desc_obj, &descriptors[descriptors_index]); // 7c iv. ReturnIfAbrupt(desc). if (!success) return MaybeHandle(); // 7c v. Append the pair (a two element List) consisting of nextKey and // desc to the end of descriptors. descriptors[descriptors_index].set_name(next_key); descriptors_index++; } // 8. For each pair from descriptors in list order, for (size_t i = 0; i < descriptors_index; ++i) { PropertyDescriptor* desc = &descriptors[i]; // 8a. Let P be the first element of pair. // 8b. Let desc be the second element of pair. // 8c. Let status be DefinePropertyOrThrow(O, P, desc). Maybe status = DefineOwnProperty(isolate, Handle::cast(object), desc->name(), desc, THROW_ON_ERROR); // 8d. ReturnIfAbrupt(status). if (!status.IsJust()) return MaybeHandle(); CHECK(status.FromJust()); } // 9. Return o. return object; } // static Maybe JSReceiver::DefineOwnProperty(Isolate* isolate, Handle object, Handle key, PropertyDescriptor* desc, ShouldThrow should_throw) { if (object->IsJSArray()) { return JSArray::DefineOwnProperty(isolate, Handle::cast(object), key, desc, should_throw); } if (object->IsJSProxy()) { return JSProxy::DefineOwnProperty(isolate, Handle::cast(object), key, desc, should_throw); } if (object->IsJSTypedArray()) { return JSTypedArray::DefineOwnProperty( isolate, Handle::cast(object), key, desc, should_throw); } // TODO(neis): Special case for JSModuleNamespace? // OrdinaryDefineOwnProperty, by virtue of calling // DefineOwnPropertyIgnoreAttributes, can handle arguments // (ES#sec-arguments-exotic-objects-defineownproperty-p-desc). return OrdinaryDefineOwnProperty(isolate, Handle::cast(object), key, desc, should_throw); } // static Maybe JSReceiver::OrdinaryDefineOwnProperty(Isolate* isolate, Handle object, Handle key, PropertyDescriptor* desc, ShouldThrow should_throw) { bool success = false; DCHECK(key->IsName() || key->IsNumber()); // |key| is a PropertyKey... LookupIterator it = LookupIterator::PropertyOrElement( isolate, object, key, &success, LookupIterator::OWN); DCHECK(success); // ...so creating a LookupIterator can't fail. // Deal with access checks first. if (it.state() == LookupIterator::ACCESS_CHECK) { if (!it.HasAccess()) { isolate->ReportFailedAccessCheck(it.GetHolder()); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); return Just(true); } it.Next(); } // Handle interceptor if (it.state() == LookupIterator::INTERCEPTOR) { if (it.HolderIsReceiverOrHiddenPrototype()) { Maybe result = DefinePropertyWithInterceptorInternal( &it, it.GetInterceptor(), should_throw, *desc); if (result.IsNothing() || result.FromJust()) { return result; } } } return OrdinaryDefineOwnProperty(&it, desc, should_throw); } // ES6 9.1.6.1 // static Maybe JSReceiver::OrdinaryDefineOwnProperty(LookupIterator* it, PropertyDescriptor* desc, ShouldThrow should_throw) { Isolate* isolate = it->isolate(); // 1. Let current be O.[[GetOwnProperty]](P). // 2. ReturnIfAbrupt(current). PropertyDescriptor current; MAYBE_RETURN(GetOwnPropertyDescriptor(it, ¤t), Nothing()); // TODO(jkummerow/verwaest): It would be nice if we didn't have to reset // the iterator every time. Currently, the reasons why we need it are: // - handle interceptors correctly // - handle accessors correctly (which might change the holder's map) it->Restart(); // 3. Let extensible be the value of the [[Extensible]] internal slot of O. Handle object = Handle::cast(it->GetReceiver()); bool extensible = JSObject::IsExtensible(object); return ValidateAndApplyPropertyDescriptor(isolate, it, extensible, desc, ¤t, should_throw); } // ES6 9.1.6.2 // static Maybe JSReceiver::IsCompatiblePropertyDescriptor( Isolate* isolate, bool extensible, PropertyDescriptor* desc, PropertyDescriptor* current, Handle property_name, ShouldThrow should_throw) { // 1. Return ValidateAndApplyPropertyDescriptor(undefined, undefined, // Extensible, Desc, Current). return ValidateAndApplyPropertyDescriptor( isolate, NULL, extensible, desc, current, should_throw, property_name); } // ES6 9.1.6.3 // static Maybe JSReceiver::ValidateAndApplyPropertyDescriptor( Isolate* isolate, LookupIterator* it, bool extensible, PropertyDescriptor* desc, PropertyDescriptor* current, ShouldThrow should_throw, Handle property_name) { // We either need a LookupIterator, or a property name. DCHECK((it == NULL) != property_name.is_null()); Handle object; if (it != NULL) object = Handle::cast(it->GetReceiver()); bool desc_is_data_descriptor = PropertyDescriptor::IsDataDescriptor(desc); bool desc_is_accessor_descriptor = PropertyDescriptor::IsAccessorDescriptor(desc); bool desc_is_generic_descriptor = PropertyDescriptor::IsGenericDescriptor(desc); // 1. (Assert) // 2. If current is undefined, then if (current->is_empty()) { // 2a. If extensible is false, return false. if (!extensible) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kDefineDisallowed, it != NULL ? it->GetName() : property_name)); } // 2c. If IsGenericDescriptor(Desc) or IsDataDescriptor(Desc) is true, then: // (This is equivalent to !IsAccessorDescriptor(desc).) DCHECK((desc_is_generic_descriptor || desc_is_data_descriptor) == !desc_is_accessor_descriptor); if (!desc_is_accessor_descriptor) { // 2c i. If O is not undefined, create an own data property named P of // object O whose [[Value]], [[Writable]], [[Enumerable]] and // [[Configurable]] attribute values are described by Desc. If the value // of an attribute field of Desc is absent, the attribute of the newly // created property is set to its default value. if (it != NULL) { if (!desc->has_writable()) desc->set_writable(false); if (!desc->has_enumerable()) desc->set_enumerable(false); if (!desc->has_configurable()) desc->set_configurable(false); Handle value( desc->has_value() ? desc->value() : Handle::cast(isolate->factory()->undefined_value())); MaybeHandle result = JSObject::DefineOwnPropertyIgnoreAttributes(it, value, desc->ToAttributes()); if (result.is_null()) return Nothing(); } } else { // 2d. Else Desc must be an accessor Property Descriptor, DCHECK(desc_is_accessor_descriptor); // 2d i. If O is not undefined, create an own accessor property named P // of object O whose [[Get]], [[Set]], [[Enumerable]] and // [[Configurable]] attribute values are described by Desc. If the value // of an attribute field of Desc is absent, the attribute of the newly // created property is set to its default value. if (it != NULL) { if (!desc->has_enumerable()) desc->set_enumerable(false); if (!desc->has_configurable()) desc->set_configurable(false); Handle getter( desc->has_get() ? desc->get() : Handle::cast(isolate->factory()->null_value())); Handle setter( desc->has_set() ? desc->set() : Handle::cast(isolate->factory()->null_value())); MaybeHandle result = JSObject::DefineAccessor(it, getter, setter, desc->ToAttributes()); if (result.is_null()) return Nothing(); } } // 2e. Return true. return Just(true); } // 3. Return true, if every field in Desc is absent. // 4. Return true, if every field in Desc also occurs in current and the // value of every field in Desc is the same value as the corresponding field // in current when compared using the SameValue algorithm. if ((!desc->has_enumerable() || desc->enumerable() == current->enumerable()) && (!desc->has_configurable() || desc->configurable() == current->configurable()) && (!desc->has_value() || (current->has_value() && current->value()->SameValue(*desc->value()))) && (!desc->has_writable() || (current->has_writable() && current->writable() == desc->writable())) && (!desc->has_get() || (current->has_get() && current->get()->SameValue(*desc->get()))) && (!desc->has_set() || (current->has_set() && current->set()->SameValue(*desc->set())))) { return Just(true); } // 5. If the [[Configurable]] field of current is false, then if (!current->configurable()) { // 5a. Return false, if the [[Configurable]] field of Desc is true. if (desc->has_configurable() && desc->configurable()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } // 5b. Return false, if the [[Enumerable]] field of Desc is present and the // [[Enumerable]] fields of current and Desc are the Boolean negation of // each other. if (desc->has_enumerable() && desc->enumerable() != current->enumerable()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } } bool current_is_data_descriptor = PropertyDescriptor::IsDataDescriptor(current); // 6. If IsGenericDescriptor(Desc) is true, no further validation is required. if (desc_is_generic_descriptor) { // Nothing to see here. // 7. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) have // different results, then: } else if (current_is_data_descriptor != desc_is_data_descriptor) { // 7a. Return false, if the [[Configurable]] field of current is false. if (!current->configurable()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } // 7b. If IsDataDescriptor(current) is true, then: if (current_is_data_descriptor) { // 7b i. If O is not undefined, convert the property named P of object O // from a data property to an accessor property. Preserve the existing // values of the converted property's [[Configurable]] and [[Enumerable]] // attributes and set the rest of the property's attributes to their // default values. // --> Folded into step 10. } else { // 7c i. If O is not undefined, convert the property named P of object O // from an accessor property to a data property. Preserve the existing // values of the converted property’s [[Configurable]] and [[Enumerable]] // attributes and set the rest of the property’s attributes to their // default values. // --> Folded into step 10. } // 8. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both // true, then: } else if (current_is_data_descriptor && desc_is_data_descriptor) { // 8a. If the [[Configurable]] field of current is false, then: if (!current->configurable()) { // 8a i. Return false, if the [[Writable]] field of current is false and // the [[Writable]] field of Desc is true. if (!current->writable() && desc->has_writable() && desc->writable()) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } // 8a ii. If the [[Writable]] field of current is false, then: if (!current->writable()) { // 8a ii 1. Return false, if the [[Value]] field of Desc is present and // SameValue(Desc.[[Value]], current.[[Value]]) is false. if (desc->has_value() && !desc->value()->SameValue(*current->value())) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } } } } else { // 9. Else IsAccessorDescriptor(current) and IsAccessorDescriptor(Desc) // are both true, DCHECK(PropertyDescriptor::IsAccessorDescriptor(current) && desc_is_accessor_descriptor); // 9a. If the [[Configurable]] field of current is false, then: if (!current->configurable()) { // 9a i. Return false, if the [[Set]] field of Desc is present and // SameValue(Desc.[[Set]], current.[[Set]]) is false. if (desc->has_set() && !desc->set()->SameValue(*current->set())) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } // 9a ii. Return false, if the [[Get]] field of Desc is present and // SameValue(Desc.[[Get]], current.[[Get]]) is false. if (desc->has_get() && !desc->get()->SameValue(*current->get())) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it != NULL ? it->GetName() : property_name)); } } } // 10. If O is not undefined, then: if (it != NULL) { // 10a. For each field of Desc that is present, set the corresponding // attribute of the property named P of object O to the value of the field. PropertyAttributes attrs = NONE; if (desc->has_enumerable()) { attrs = static_cast( attrs | (desc->enumerable() ? NONE : DONT_ENUM)); } else { attrs = static_cast( attrs | (current->enumerable() ? NONE : DONT_ENUM)); } if (desc->has_configurable()) { attrs = static_cast( attrs | (desc->configurable() ? NONE : DONT_DELETE)); } else { attrs = static_cast( attrs | (current->configurable() ? NONE : DONT_DELETE)); } if (desc_is_data_descriptor || (desc_is_generic_descriptor && current_is_data_descriptor)) { if (desc->has_writable()) { attrs = static_cast( attrs | (desc->writable() ? NONE : READ_ONLY)); } else { attrs = static_cast( attrs | (current->writable() ? NONE : READ_ONLY)); } Handle value( desc->has_value() ? desc->value() : current->has_value() ? current->value() : Handle::cast( isolate->factory()->undefined_value())); MaybeHandle result = JSObject::DefineOwnPropertyIgnoreAttributes(it, value, attrs); if (result.is_null()) return Nothing(); } else { DCHECK(desc_is_accessor_descriptor || (desc_is_generic_descriptor && PropertyDescriptor::IsAccessorDescriptor(current))); Handle getter( desc->has_get() ? desc->get() : current->has_get() ? current->get() : Handle::cast(isolate->factory()->null_value())); Handle setter( desc->has_set() ? desc->set() : current->has_set() ? current->set() : Handle::cast(isolate->factory()->null_value())); MaybeHandle result = JSObject::DefineAccessor(it, getter, setter, attrs); if (result.is_null()) return Nothing(); } } // 11. Return true. return Just(true); } // static Maybe JSReceiver::CreateDataProperty(LookupIterator* it, Handle value, ShouldThrow should_throw) { DCHECK(!it->check_prototype_chain()); Handle receiver = Handle::cast(it->GetReceiver()); Isolate* isolate = receiver->GetIsolate(); if (receiver->IsJSObject()) { return JSObject::CreateDataProperty(it, value, should_throw); // Shortcut. } PropertyDescriptor new_desc; new_desc.set_value(value); new_desc.set_writable(true); new_desc.set_enumerable(true); new_desc.set_configurable(true); return JSReceiver::DefineOwnProperty(isolate, receiver, it->GetName(), &new_desc, should_throw); } Maybe JSObject::CreateDataProperty(LookupIterator* it, Handle value, ShouldThrow should_throw) { DCHECK(it->GetReceiver()->IsJSObject()); MAYBE_RETURN(JSReceiver::GetPropertyAttributes(it), Nothing()); Handle receiver = Handle::cast(it->GetReceiver()); Isolate* isolate = receiver->GetIsolate(); if (it->IsFound()) { Maybe attributes = GetPropertyAttributes(it); MAYBE_RETURN(attributes, Nothing()); if ((attributes.FromJust() & DONT_DELETE) != 0) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, it->GetName())); } } else { if (!JSObject::IsExtensible(Handle::cast(it->GetReceiver()))) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kDefineDisallowed, it->GetName())); } } RETURN_ON_EXCEPTION_VALUE(it->isolate(), DefineOwnPropertyIgnoreAttributes(it, value, NONE), Nothing()); return Just(true); } // TODO(jkummerow): Consider unification with FastAsArrayLength() in // accessors.cc. bool PropertyKeyToArrayLength(Handle value, uint32_t* length) { DCHECK(value->IsNumber() || value->IsName()); if (value->ToArrayLength(length)) return true; if (value->IsString()) return String::cast(*value)->AsArrayIndex(length); return false; } bool PropertyKeyToArrayIndex(Handle index_obj, uint32_t* output) { return PropertyKeyToArrayLength(index_obj, output) && *output != kMaxUInt32; } // ES6 9.4.2.1 // static Maybe JSArray::DefineOwnProperty(Isolate* isolate, Handle o, Handle name, PropertyDescriptor* desc, ShouldThrow should_throw) { // 1. Assert: IsPropertyKey(P) is true. ("P" is |name|.) // 2. If P is "length", then: // TODO(jkummerow): Check if we need slow string comparison. if (*name == isolate->heap()->length_string()) { // 2a. Return ArraySetLength(A, Desc). return ArraySetLength(isolate, o, desc, should_throw); } // 3. Else if P is an array index, then: uint32_t index = 0; if (PropertyKeyToArrayIndex(name, &index)) { // 3a. Let oldLenDesc be OrdinaryGetOwnProperty(A, "length"). PropertyDescriptor old_len_desc; Maybe success = GetOwnPropertyDescriptor( isolate, o, isolate->factory()->length_string(), &old_len_desc); // 3b. (Assert) DCHECK(success.FromJust()); USE(success); // 3c. Let oldLen be oldLenDesc.[[Value]]. uint32_t old_len = 0; CHECK(old_len_desc.value()->ToArrayLength(&old_len)); // 3d. Let index be ToUint32(P). // (Already done above.) // 3e. (Assert) // 3f. If index >= oldLen and oldLenDesc.[[Writable]] is false, // return false. if (index >= old_len && old_len_desc.has_writable() && !old_len_desc.writable()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kDefineDisallowed, name)); } // 3g. Let succeeded be OrdinaryDefineOwnProperty(A, P, Desc). Maybe succeeded = OrdinaryDefineOwnProperty(isolate, o, name, desc, should_throw); // 3h. Assert: succeeded is not an abrupt completion. // In our case, if should_throw == THROW_ON_ERROR, it can be! // 3i. If succeeded is false, return false. if (succeeded.IsNothing() || !succeeded.FromJust()) return succeeded; // 3j. If index >= oldLen, then: if (index >= old_len) { // 3j i. Set oldLenDesc.[[Value]] to index + 1. old_len_desc.set_value(isolate->factory()->NewNumberFromUint(index + 1)); // 3j ii. Let succeeded be // OrdinaryDefineOwnProperty(A, "length", oldLenDesc). succeeded = OrdinaryDefineOwnProperty(isolate, o, isolate->factory()->length_string(), &old_len_desc, should_throw); // 3j iii. Assert: succeeded is true. DCHECK(succeeded.FromJust()); USE(succeeded); } // 3k. Return true. return Just(true); } // 4. Return OrdinaryDefineOwnProperty(A, P, Desc). return OrdinaryDefineOwnProperty(isolate, o, name, desc, should_throw); } // Part of ES6 9.4.2.4 ArraySetLength. // static bool JSArray::AnythingToArrayLength(Isolate* isolate, Handle length_object, uint32_t* output) { // Fast path: check numbers and strings that can be converted directly // and unobservably. if (length_object->ToArrayLength(output)) return true; if (length_object->IsString() && Handle::cast(length_object)->AsArrayIndex(output)) { return true; } // Slow path: follow steps in ES6 9.4.2.4 "ArraySetLength". // 3. Let newLen be ToUint32(Desc.[[Value]]). Handle uint32_v; if (!Object::ToUint32(isolate, length_object).ToHandle(&uint32_v)) { // 4. ReturnIfAbrupt(newLen). return false; } // 5. Let numberLen be ToNumber(Desc.[[Value]]). Handle number_v; if (!Object::ToNumber(length_object).ToHandle(&number_v)) { // 6. ReturnIfAbrupt(newLen). return false; } // 7. If newLen != numberLen, throw a RangeError exception. if (uint32_v->Number() != number_v->Number()) { Handle exception = isolate->factory()->NewRangeError(MessageTemplate::kInvalidArrayLength); isolate->Throw(*exception); return false; } CHECK(uint32_v->ToArrayLength(output)); return true; } // ES6 9.4.2.4 // static Maybe JSArray::ArraySetLength(Isolate* isolate, Handle a, PropertyDescriptor* desc, ShouldThrow should_throw) { // 1. If the [[Value]] field of Desc is absent, then if (!desc->has_value()) { // 1a. Return OrdinaryDefineOwnProperty(A, "length", Desc). return OrdinaryDefineOwnProperty( isolate, a, isolate->factory()->length_string(), desc, should_throw); } // 2. Let newLenDesc be a copy of Desc. // (Actual copying is not necessary.) PropertyDescriptor* new_len_desc = desc; // 3. - 7. Convert Desc.[[Value]] to newLen. uint32_t new_len = 0; if (!AnythingToArrayLength(isolate, desc->value(), &new_len)) { DCHECK(isolate->has_pending_exception()); return Nothing(); } // 8. Set newLenDesc.[[Value]] to newLen. // (Done below, if needed.) // 9. Let oldLenDesc be OrdinaryGetOwnProperty(A, "length"). PropertyDescriptor old_len_desc; Maybe success = GetOwnPropertyDescriptor( isolate, a, isolate->factory()->length_string(), &old_len_desc); // 10. (Assert) DCHECK(success.FromJust()); USE(success); // 11. Let oldLen be oldLenDesc.[[Value]]. uint32_t old_len = 0; CHECK(old_len_desc.value()->ToArrayLength(&old_len)); // 12. If newLen >= oldLen, then if (new_len >= old_len) { // 8. Set newLenDesc.[[Value]] to newLen. // 12a. Return OrdinaryDefineOwnProperty(A, "length", newLenDesc). new_len_desc->set_value(isolate->factory()->NewNumberFromUint(new_len)); return OrdinaryDefineOwnProperty(isolate, a, isolate->factory()->length_string(), new_len_desc, should_throw); } // 13. If oldLenDesc.[[Writable]] is false, return false. if (!old_len_desc.writable()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kRedefineDisallowed, isolate->factory()->length_string())); } // 14. If newLenDesc.[[Writable]] is absent or has the value true, // let newWritable be true. bool new_writable = false; if (!new_len_desc->has_writable() || new_len_desc->writable()) { new_writable = true; } else { // 15. Else, // 15a. Need to defer setting the [[Writable]] attribute to false in case // any elements cannot be deleted. // 15b. Let newWritable be false. (It's initialized as "false" anyway.) // 15c. Set newLenDesc.[[Writable]] to true. // (Not needed.) } // Most of steps 16 through 19 is implemented by JSArray::SetLength. JSArray::SetLength(a, new_len); // Steps 19d-ii, 20. if (!new_writable) { PropertyDescriptor readonly; readonly.set_writable(false); Maybe success = OrdinaryDefineOwnProperty( isolate, a, isolate->factory()->length_string(), &readonly, should_throw); DCHECK(success.FromJust()); USE(success); } uint32_t actual_new_len = 0; CHECK(a->length()->ToArrayLength(&actual_new_len)); // Steps 19d-v, 21. Return false if there were non-deletable elements. bool result = actual_new_len == new_len; if (!result) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kStrictDeleteProperty, isolate->factory()->NewNumberFromUint(actual_new_len - 1), a)); } return Just(result); } // ES6 9.5.6 // static Maybe JSProxy::DefineOwnProperty(Isolate* isolate, Handle proxy, Handle key, PropertyDescriptor* desc, ShouldThrow should_throw) { STACK_CHECK(isolate, Nothing()); if (key->IsSymbol() && Handle::cast(key)->IsPrivate()) { return SetPrivateProperty(isolate, proxy, Handle::cast(key), desc, should_throw); } Handle trap_name = isolate->factory()->defineProperty_string(); // 1. Assert: IsPropertyKey(P) is true. DCHECK(key->IsName() || key->IsNumber()); // 2. Let handler be the value of the [[ProxyHandler]] internal slot of O. Handle handler(proxy->handler(), isolate); // 3. If handler is null, throw a TypeError exception. // 4. Assert: Type(handler) is Object. if (proxy->IsRevoked()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyRevoked, trap_name)); return Nothing(); } // 5. Let target be the value of the [[ProxyTarget]] internal slot of O. Handle target(proxy->target(), isolate); // 6. Let trap be ? GetMethod(handler, "defineProperty"). Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(Handle::cast(handler), trap_name), Nothing()); // 7. If trap is undefined, then: if (trap->IsUndefined(isolate)) { // 7a. Return target.[[DefineOwnProperty]](P, Desc). return JSReceiver::DefineOwnProperty(isolate, target, key, desc, should_throw); } // 8. Let descObj be FromPropertyDescriptor(Desc). Handle desc_obj = desc->ToObject(isolate); // 9. Let booleanTrapResult be // ToBoolean(? Call(trap, handler, «target, P, descObj»)). Handle property_name = key->IsName() ? Handle::cast(key) : Handle::cast(isolate->factory()->NumberToString(key)); // Do not leak private property names. DCHECK(!property_name->IsPrivate()); Handle trap_result_obj; Handle args[] = {target, property_name, desc_obj}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result_obj, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); // 10. If booleanTrapResult is false, return false. if (!trap_result_obj->BooleanValue()) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kProxyTrapReturnedFalsishFor, trap_name, property_name)); } // 11. Let targetDesc be ? target.[[GetOwnProperty]](P). PropertyDescriptor target_desc; Maybe target_found = JSReceiver::GetOwnPropertyDescriptor(isolate, target, key, &target_desc); MAYBE_RETURN(target_found, Nothing()); // 12. Let extensibleTarget be ? IsExtensible(target). Maybe maybe_extensible = JSReceiver::IsExtensible(target); MAYBE_RETURN(maybe_extensible, Nothing()); bool extensible_target = maybe_extensible.FromJust(); // 13. If Desc has a [[Configurable]] field and if Desc.[[Configurable]] // is false, then: // 13a. Let settingConfigFalse be true. // 14. Else let settingConfigFalse be false. bool setting_config_false = desc->has_configurable() && !desc->configurable(); // 15. If targetDesc is undefined, then if (!target_found.FromJust()) { // 15a. If extensibleTarget is false, throw a TypeError exception. if (!extensible_target) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyDefinePropertyNonExtensible, property_name)); return Nothing(); } // 15b. If settingConfigFalse is true, throw a TypeError exception. if (setting_config_false) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyDefinePropertyNonConfigurable, property_name)); return Nothing(); } } else { // 16. Else targetDesc is not undefined, // 16a. If IsCompatiblePropertyDescriptor(extensibleTarget, Desc, // targetDesc) is false, throw a TypeError exception. Maybe valid = IsCompatiblePropertyDescriptor(isolate, extensible_target, desc, &target_desc, property_name, DONT_THROW); MAYBE_RETURN(valid, Nothing()); if (!valid.FromJust()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyDefinePropertyIncompatible, property_name)); return Nothing(); } // 16b. If settingConfigFalse is true and targetDesc.[[Configurable]] is // true, throw a TypeError exception. if (setting_config_false && target_desc.configurable()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyDefinePropertyNonConfigurable, property_name)); return Nothing(); } } // 17. Return true. return Just(true); } // static Maybe JSProxy::SetPrivateProperty(Isolate* isolate, Handle proxy, Handle private_name, PropertyDescriptor* desc, ShouldThrow should_throw) { // Despite the generic name, this can only add private data properties. if (!PropertyDescriptor::IsDataDescriptor(desc) || desc->ToAttributes() != DONT_ENUM) { RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kProxyPrivate)); } DCHECK(proxy->map()->is_dictionary_map()); Handle value = desc->has_value() ? desc->value() : Handle::cast(isolate->factory()->undefined_value()); LookupIterator it(proxy, private_name, proxy); if (it.IsFound()) { DCHECK_EQ(LookupIterator::DATA, it.state()); DCHECK_EQ(DONT_ENUM, it.property_attributes()); it.WriteDataValue(value, false); return Just(true); } Handle dict(proxy->property_dictionary()); PropertyDetails details(kData, DONT_ENUM, 0, PropertyCellType::kNoCell); Handle result = NameDictionary::Add(dict, private_name, value, details); if (!dict.is_identical_to(result)) proxy->set_properties(*result); return Just(true); } // static Maybe JSReceiver::GetOwnPropertyDescriptor(Isolate* isolate, Handle object, Handle key, PropertyDescriptor* desc) { bool success = false; DCHECK(key->IsName() || key->IsNumber()); // |key| is a PropertyKey... LookupIterator it = LookupIterator::PropertyOrElement( isolate, object, key, &success, LookupIterator::OWN); DCHECK(success); // ...so creating a LookupIterator can't fail. return GetOwnPropertyDescriptor(&it, desc); } namespace { Maybe GetPropertyDescriptorWithInterceptor(LookupIterator* it, PropertyDescriptor* desc) { bool has_access = true; if (it->state() == LookupIterator::ACCESS_CHECK) { has_access = it->HasAccess() || JSObject::AllCanRead(it); it->Next(); } if (has_access && it->state() == LookupIterator::INTERCEPTOR) { Isolate* isolate = it->isolate(); Handle interceptor = it->GetInterceptor(); if (!interceptor->descriptor()->IsUndefined(isolate)) { Handle result; Handle holder = it->GetHolder(); Handle receiver = it->GetReceiver(); if (!receiver->IsJSReceiver()) { ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, receiver, Object::ConvertReceiver(isolate, receiver), Nothing()); } PropertyCallbackArguments args(isolate, interceptor->data(), *receiver, *holder, Object::DONT_THROW); if (it->IsElement()) { uint32_t index = it->index(); v8::IndexedPropertyDescriptorCallback descriptorCallback = v8::ToCData( interceptor->descriptor()); result = args.Call(descriptorCallback, index); } else { Handle name = it->name(); DCHECK(!name->IsPrivate()); v8::GenericNamedPropertyDescriptorCallback descriptorCallback = v8::ToCData( interceptor->descriptor()); result = args.Call(descriptorCallback, name); } if (!result.is_null()) { // Request successfully intercepted, try to set the property // descriptor. Utils::ApiCheck( PropertyDescriptor::ToPropertyDescriptor(isolate, result, desc), it->IsElement() ? "v8::IndexedPropertyDescriptorCallback" : "v8::NamedPropertyDescriptorCallback", "Invalid property descriptor."); return Just(true); } } } it->Restart(); return Just(false); } } // namespace // ES6 9.1.5.1 // Returns true on success, false if the property didn't exist, nothing if // an exception was thrown. // static Maybe JSReceiver::GetOwnPropertyDescriptor(LookupIterator* it, PropertyDescriptor* desc) { Isolate* isolate = it->isolate(); // "Virtual" dispatch. if (it->IsFound() && it->GetHolder()->IsJSProxy()) { return JSProxy::GetOwnPropertyDescriptor(isolate, it->GetHolder(), it->GetName(), desc); } Maybe intercepted = GetPropertyDescriptorWithInterceptor(it, desc); MAYBE_RETURN(intercepted, Nothing()); if (intercepted.FromJust()) { return Just(true); } // Request was not intercepted, continue as normal. // 1. (Assert) // 2. If O does not have an own property with key P, return undefined. Maybe maybe = JSObject::GetPropertyAttributes(it); MAYBE_RETURN(maybe, Nothing()); PropertyAttributes attrs = maybe.FromJust(); if (attrs == ABSENT) return Just(false); DCHECK(!isolate->has_pending_exception()); // 3. Let D be a newly created Property Descriptor with no fields. DCHECK(desc->is_empty()); // 4. Let X be O's own property whose key is P. // 5. If X is a data property, then bool is_accessor_pair = it->state() == LookupIterator::ACCESSOR && it->GetAccessors()->IsAccessorPair(); if (!is_accessor_pair) { // 5a. Set D.[[Value]] to the value of X's [[Value]] attribute. Handle value; if (!Object::GetProperty(it).ToHandle(&value)) { DCHECK(isolate->has_pending_exception()); return Nothing(); } desc->set_value(value); // 5b. Set D.[[Writable]] to the value of X's [[Writable]] attribute desc->set_writable((attrs & READ_ONLY) == 0); } else { // 6. Else X is an accessor property, so Handle accessors = Handle::cast(it->GetAccessors()); // 6a. Set D.[[Get]] to the value of X's [[Get]] attribute. desc->set_get(AccessorPair::GetComponent(accessors, ACCESSOR_GETTER)); // 6b. Set D.[[Set]] to the value of X's [[Set]] attribute. desc->set_set(AccessorPair::GetComponent(accessors, ACCESSOR_SETTER)); } // 7. Set D.[[Enumerable]] to the value of X's [[Enumerable]] attribute. desc->set_enumerable((attrs & DONT_ENUM) == 0); // 8. Set D.[[Configurable]] to the value of X's [[Configurable]] attribute. desc->set_configurable((attrs & DONT_DELETE) == 0); // 9. Return D. DCHECK(PropertyDescriptor::IsAccessorDescriptor(desc) != PropertyDescriptor::IsDataDescriptor(desc)); return Just(true); } // ES6 9.5.5 // static Maybe JSProxy::GetOwnPropertyDescriptor(Isolate* isolate, Handle proxy, Handle name, PropertyDescriptor* desc) { DCHECK(!name->IsPrivate()); STACK_CHECK(isolate, Nothing()); Handle trap_name = isolate->factory()->getOwnPropertyDescriptor_string(); // 1. (Assert) // 2. Let handler be the value of the [[ProxyHandler]] internal slot of O. Handle handler(proxy->handler(), isolate); // 3. If handler is null, throw a TypeError exception. // 4. Assert: Type(handler) is Object. if (proxy->IsRevoked()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyRevoked, trap_name)); return Nothing(); } // 5. Let target be the value of the [[ProxyTarget]] internal slot of O. Handle target(proxy->target(), isolate); // 6. Let trap be ? GetMethod(handler, "getOwnPropertyDescriptor"). Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(Handle::cast(handler), trap_name), Nothing()); // 7. If trap is undefined, then if (trap->IsUndefined(isolate)) { // 7a. Return target.[[GetOwnProperty]](P). return JSReceiver::GetOwnPropertyDescriptor(isolate, target, name, desc); } // 8. Let trapResultObj be ? Call(trap, handler, «target, P»). Handle trap_result_obj; Handle args[] = {target, name}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result_obj, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); // 9. If Type(trapResultObj) is neither Object nor Undefined, throw a // TypeError exception. if (!trap_result_obj->IsJSReceiver() && !trap_result_obj->IsUndefined(isolate)) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyGetOwnPropertyDescriptorInvalid, name)); return Nothing(); } // 10. Let targetDesc be ? target.[[GetOwnProperty]](P). PropertyDescriptor target_desc; Maybe found = JSReceiver::GetOwnPropertyDescriptor(isolate, target, name, &target_desc); MAYBE_RETURN(found, Nothing()); // 11. If trapResultObj is undefined, then if (trap_result_obj->IsUndefined(isolate)) { // 11a. If targetDesc is undefined, return undefined. if (!found.FromJust()) return Just(false); // 11b. If targetDesc.[[Configurable]] is false, throw a TypeError // exception. if (!target_desc.configurable()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyGetOwnPropertyDescriptorUndefined, name)); return Nothing(); } // 11c. Let extensibleTarget be ? IsExtensible(target). Maybe extensible_target = JSReceiver::IsExtensible(target); MAYBE_RETURN(extensible_target, Nothing()); // 11d. (Assert) // 11e. If extensibleTarget is false, throw a TypeError exception. if (!extensible_target.FromJust()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyGetOwnPropertyDescriptorNonExtensible, name)); return Nothing(); } // 11f. Return undefined. return Just(false); } // 12. Let extensibleTarget be ? IsExtensible(target). Maybe extensible_target = JSReceiver::IsExtensible(target); MAYBE_RETURN(extensible_target, Nothing()); // 13. Let resultDesc be ? ToPropertyDescriptor(trapResultObj). if (!PropertyDescriptor::ToPropertyDescriptor(isolate, trap_result_obj, desc)) { DCHECK(isolate->has_pending_exception()); return Nothing(); } // 14. Call CompletePropertyDescriptor(resultDesc). PropertyDescriptor::CompletePropertyDescriptor(isolate, desc); // 15. Let valid be IsCompatiblePropertyDescriptor (extensibleTarget, // resultDesc, targetDesc). Maybe valid = IsCompatiblePropertyDescriptor(isolate, extensible_target.FromJust(), desc, &target_desc, name, DONT_THROW); MAYBE_RETURN(valid, Nothing()); // 16. If valid is false, throw a TypeError exception. if (!valid.FromJust()) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyGetOwnPropertyDescriptorIncompatible, name)); return Nothing(); } // 17. If resultDesc.[[Configurable]] is false, then if (!desc->configurable()) { // 17a. If targetDesc is undefined or targetDesc.[[Configurable]] is true: if (target_desc.is_empty() || target_desc.configurable()) { // 17a i. Throw a TypeError exception. isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kProxyGetOwnPropertyDescriptorNonConfigurable, name)); return Nothing(); } } // 18. Return resultDesc. return Just(true); } bool JSObject::ReferencesObjectFromElements(FixedArray* elements, ElementsKind kind, Object* object) { Isolate* isolate = elements->GetIsolate(); if (IsFastObjectElementsKind(kind) || kind == FAST_STRING_WRAPPER_ELEMENTS) { int length = IsJSArray() ? Smi::cast(JSArray::cast(this)->length())->value() : elements->length(); for (int i = 0; i < length; ++i) { Object* element = elements->get(i); if (!element->IsTheHole(isolate) && element == object) return true; } } else { DCHECK(kind == DICTIONARY_ELEMENTS || kind == SLOW_STRING_WRAPPER_ELEMENTS); Object* key = SeededNumberDictionary::cast(elements)->SlowReverseLookup(object); if (!key->IsUndefined(isolate)) return true; } return false; } // Check whether this object references another object. bool JSObject::ReferencesObject(Object* obj) { Map* map_of_this = map(); Heap* heap = GetHeap(); DisallowHeapAllocation no_allocation; // Is the object the constructor for this object? if (map_of_this->GetConstructor() == obj) { return true; } // Is the object the prototype for this object? if (map_of_this->prototype() == obj) { return true; } // Check if the object is among the named properties. Object* key = SlowReverseLookup(obj); if (!key->IsUndefined(heap->isolate())) { return true; } // Check if the object is among the indexed properties. ElementsKind kind = GetElementsKind(); switch (kind) { // Raw pixels and external arrays do not reference other // objects. #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case TYPE##_ELEMENTS: \ break; TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: break; case FAST_SMI_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: break; case FAST_ELEMENTS: case FAST_HOLEY_ELEMENTS: case DICTIONARY_ELEMENTS: case FAST_STRING_WRAPPER_ELEMENTS: case SLOW_STRING_WRAPPER_ELEMENTS: { FixedArray* elements = FixedArray::cast(this->elements()); if (ReferencesObjectFromElements(elements, kind, obj)) return true; break; } case FAST_SLOPPY_ARGUMENTS_ELEMENTS: case SLOW_SLOPPY_ARGUMENTS_ELEMENTS: { FixedArray* parameter_map = FixedArray::cast(elements()); // Check the mapped parameters. int length = parameter_map->length(); for (int i = 2; i < length; ++i) { Object* value = parameter_map->get(i); if (!value->IsTheHole(heap->isolate()) && value == obj) return true; } // Check the arguments. FixedArray* arguments = FixedArray::cast(parameter_map->get(1)); kind = arguments->IsDictionary() ? DICTIONARY_ELEMENTS : FAST_HOLEY_ELEMENTS; if (ReferencesObjectFromElements(arguments, kind, obj)) return true; break; } case NO_ELEMENTS: break; } // For functions check the context. if (IsJSFunction()) { // Get the constructor function for arguments array. Map* arguments_map = heap->isolate()->context()->native_context()->sloppy_arguments_map(); JSFunction* arguments_function = JSFunction::cast(arguments_map->GetConstructor()); // Get the context and don't check if it is the native context. JSFunction* f = JSFunction::cast(this); Context* context = f->context(); if (context->IsNativeContext()) { return false; } // Check the non-special context slots. for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) { // Only check JS objects. if (context->get(i)->IsJSObject()) { JSObject* ctxobj = JSObject::cast(context->get(i)); // If it is an arguments array check the content. if (ctxobj->map()->GetConstructor() == arguments_function) { if (ctxobj->ReferencesObject(obj)) { return true; } } else if (ctxobj == obj) { return true; } } } // Check the context extension (if any) if it can have references. if (context->has_extension() && !context->IsCatchContext()) { // With harmony scoping, a JSFunction may have a script context. // TODO(mvstanton): walk into the ScopeInfo. if (context->IsScriptContext()) { return false; } return context->extension_object()->ReferencesObject(obj); } } // No references to object. return false; } Maybe JSReceiver::SetIntegrityLevel(Handle receiver, IntegrityLevel level, ShouldThrow should_throw) { DCHECK(level == SEALED || level == FROZEN); if (receiver->IsJSObject()) { Handle object = Handle::cast(receiver); if (!object->HasSloppyArgumentsElements()) { // Fast path. if (level == SEALED) { return JSObject::PreventExtensionsWithTransition(object, should_throw); } else { return JSObject::PreventExtensionsWithTransition(object, should_throw); } } } Isolate* isolate = receiver->GetIsolate(); MAYBE_RETURN(JSReceiver::PreventExtensions(receiver, should_throw), Nothing()); Handle keys; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, keys, JSReceiver::OwnPropertyKeys(receiver), Nothing()); PropertyDescriptor no_conf; no_conf.set_configurable(false); PropertyDescriptor no_conf_no_write; no_conf_no_write.set_configurable(false); no_conf_no_write.set_writable(false); if (level == SEALED) { for (int i = 0; i < keys->length(); ++i) { Handle key(keys->get(i), isolate); MAYBE_RETURN( DefineOwnProperty(isolate, receiver, key, &no_conf, THROW_ON_ERROR), Nothing()); } return Just(true); } for (int i = 0; i < keys->length(); ++i) { Handle key(keys->get(i), isolate); PropertyDescriptor current_desc; Maybe owned = JSReceiver::GetOwnPropertyDescriptor( isolate, receiver, key, ¤t_desc); MAYBE_RETURN(owned, Nothing()); if (owned.FromJust()) { PropertyDescriptor desc = PropertyDescriptor::IsAccessorDescriptor(¤t_desc) ? no_conf : no_conf_no_write; MAYBE_RETURN( DefineOwnProperty(isolate, receiver, key, &desc, THROW_ON_ERROR), Nothing()); } } return Just(true); } Maybe JSReceiver::TestIntegrityLevel(Handle object, IntegrityLevel level) { DCHECK(level == SEALED || level == FROZEN); Isolate* isolate = object->GetIsolate(); Maybe extensible = JSReceiver::IsExtensible(object); MAYBE_RETURN(extensible, Nothing()); if (extensible.FromJust()) return Just(false); Handle keys; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, keys, JSReceiver::OwnPropertyKeys(object), Nothing()); for (int i = 0; i < keys->length(); ++i) { Handle key(keys->get(i), isolate); PropertyDescriptor current_desc; Maybe owned = JSReceiver::GetOwnPropertyDescriptor( isolate, object, key, ¤t_desc); MAYBE_RETURN(owned, Nothing()); if (owned.FromJust()) { if (current_desc.configurable()) return Just(false); if (level == FROZEN && PropertyDescriptor::IsDataDescriptor(¤t_desc) && current_desc.writable()) { return Just(false); } } } return Just(true); } Maybe JSReceiver::PreventExtensions(Handle object, ShouldThrow should_throw) { if (object->IsJSProxy()) { return JSProxy::PreventExtensions(Handle::cast(object), should_throw); } DCHECK(object->IsJSObject()); return JSObject::PreventExtensions(Handle::cast(object), should_throw); } Maybe JSProxy::PreventExtensions(Handle proxy, ShouldThrow should_throw) { Isolate* isolate = proxy->GetIsolate(); STACK_CHECK(isolate, Nothing()); Factory* factory = isolate->factory(); Handle trap_name = factory->preventExtensions_string(); if (proxy->IsRevoked()) { isolate->Throw( *factory->NewTypeError(MessageTemplate::kProxyRevoked, trap_name)); return Nothing(); } Handle target(proxy->target(), isolate); Handle handler(JSReceiver::cast(proxy->handler()), isolate); Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(handler, trap_name), Nothing()); if (trap->IsUndefined(isolate)) { return JSReceiver::PreventExtensions(target, should_throw); } Handle trap_result; Handle args[] = {target}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); if (!trap_result->BooleanValue()) { RETURN_FAILURE( isolate, should_throw, NewTypeError(MessageTemplate::kProxyTrapReturnedFalsish, trap_name)); } // Enforce the invariant. Maybe target_result = JSReceiver::IsExtensible(target); MAYBE_RETURN(target_result, Nothing()); if (target_result.FromJust()) { isolate->Throw(*factory->NewTypeError( MessageTemplate::kProxyPreventExtensionsExtensible)); return Nothing(); } return Just(true); } Maybe JSObject::PreventExtensions(Handle object, ShouldThrow should_throw) { Isolate* isolate = object->GetIsolate(); if (!object->HasSloppyArgumentsElements()) { return PreventExtensionsWithTransition(object, should_throw); } if (object->IsAccessCheckNeeded() && !isolate->MayAccess(handle(isolate->context()), object)) { isolate->ReportFailedAccessCheck(object); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kNoAccess)); } if (!object->map()->is_extensible()) return Just(true); if (object->IsJSGlobalProxy()) { PrototypeIterator iter(isolate, object); if (iter.IsAtEnd()) return Just(true); DCHECK(PrototypeIterator::GetCurrent(iter)->IsJSGlobalObject()); return PreventExtensions(PrototypeIterator::GetCurrent(iter), should_throw); } if (!object->HasFixedTypedArrayElements()) { // If there are fast elements we normalize. Handle dictionary = NormalizeElements(object); DCHECK(object->HasDictionaryElements() || object->HasSlowArgumentsElements()); // Make sure that we never go back to fast case. object->RequireSlowElements(*dictionary); } // Do a map transition, other objects with this map may still // be extensible. // TODO(adamk): Extend the NormalizedMapCache to handle non-extensible maps. Handle new_map = Map::Copy(handle(object->map()), "PreventExtensions"); new_map->set_is_extensible(false); JSObject::MigrateToMap(object, new_map); DCHECK(!object->map()->is_extensible()); return Just(true); } Maybe JSReceiver::IsExtensible(Handle object) { if (object->IsJSProxy()) { return JSProxy::IsExtensible(Handle::cast(object)); } return Just(JSObject::IsExtensible(Handle::cast(object))); } Maybe JSProxy::IsExtensible(Handle proxy) { Isolate* isolate = proxy->GetIsolate(); STACK_CHECK(isolate, Nothing()); Factory* factory = isolate->factory(); Handle trap_name = factory->isExtensible_string(); if (proxy->IsRevoked()) { isolate->Throw( *factory->NewTypeError(MessageTemplate::kProxyRevoked, trap_name)); return Nothing(); } Handle target(proxy->target(), isolate); Handle handler(JSReceiver::cast(proxy->handler()), isolate); Handle trap; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap, Object::GetMethod(handler, trap_name), Nothing()); if (trap->IsUndefined(isolate)) { return JSReceiver::IsExtensible(target); } Handle trap_result; Handle args[] = {target}; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, trap_result, Execution::Call(isolate, trap, handler, arraysize(args), args), Nothing()); // Enforce the invariant. Maybe target_result = JSReceiver::IsExtensible(target); MAYBE_RETURN(target_result, Nothing()); if (target_result.FromJust() != trap_result->BooleanValue()) { isolate->Throw( *factory->NewTypeError(MessageTemplate::kProxyIsExtensibleInconsistent, factory->ToBoolean(target_result.FromJust()))); return Nothing(); } return target_result; } bool JSObject::IsExtensible(Handle object) { Isolate* isolate = object->GetIsolate(); if (object->IsAccessCheckNeeded() && !isolate->MayAccess(handle(isolate->context()), object)) { return true; } if (object->IsJSGlobalProxy()) { PrototypeIterator iter(isolate, *object); if (iter.IsAtEnd()) return false; DCHECK(iter.GetCurrent()->IsJSGlobalObject()); return iter.GetCurrent()->map()->is_extensible(); } return object->map()->is_extensible(); } namespace { template void DictionaryDetailsAtPut(Isolate* isolate, Handle dictionary, int entry, PropertyDetails details) { dictionary->DetailsAtPut(entry, details); } template <> void DictionaryDetailsAtPut( Isolate* isolate, Handle dictionary, int entry, PropertyDetails details) { Object* value = dictionary->ValueAt(entry); DCHECK(value->IsPropertyCell()); value = PropertyCell::cast(value)->value(); if (value->IsTheHole(isolate)) return; PropertyCell::PrepareForValue(dictionary, entry, handle(value, isolate), details); } template void ApplyAttributesToDictionary(Isolate* isolate, Handle dictionary, const PropertyAttributes attributes) { int capacity = dictionary->Capacity(); for (int i = 0; i < capacity; i++) { Object* k = dictionary->KeyAt(i); if (dictionary->IsKey(isolate, k) && !(k->IsSymbol() && Symbol::cast(k)->is_private())) { PropertyDetails details = dictionary->DetailsAt(i); int attrs = attributes; // READ_ONLY is an invalid attribute for JS setters/getters. if ((attributes & READ_ONLY) && details.kind() == kAccessor) { Object* v = dictionary->ValueAt(i); if (v->IsPropertyCell()) v = PropertyCell::cast(v)->value(); if (v->IsAccessorPair()) attrs &= ~READ_ONLY; } details = details.CopyAddAttributes( static_cast(attrs)); DictionaryDetailsAtPut(isolate, dictionary, i, details); } } } } // namespace template Maybe JSObject::PreventExtensionsWithTransition( Handle object, ShouldThrow should_throw) { STATIC_ASSERT(attrs == NONE || attrs == SEALED || attrs == FROZEN); // Sealing/freezing sloppy arguments should be handled elsewhere. DCHECK(!object->HasSloppyArgumentsElements()); Isolate* isolate = object->GetIsolate(); if (object->IsAccessCheckNeeded() && !isolate->MayAccess(handle(isolate->context()), object)) { isolate->ReportFailedAccessCheck(object); RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing()); RETURN_FAILURE(isolate, should_throw, NewTypeError(MessageTemplate::kNoAccess)); } if (attrs == NONE && !object->map()->is_extensible()) return Just(true); if (object->IsJSGlobalProxy()) { PrototypeIterator iter(isolate, object); if (iter.IsAtEnd()) return Just(true); DCHECK(PrototypeIterator::GetCurrent(iter)->IsJSGlobalObject()); return PreventExtensionsWithTransition( PrototypeIterator::GetCurrent(iter), should_throw); } Handle new_element_dictionary; if (!object->HasFixedTypedArrayElements() && !object->HasDictionaryElements() && !object->HasSlowStringWrapperElements()) { int length = object->IsJSArray() ? Smi::cast(Handle::cast(object)->length())->value() : object->elements()->length(); new_element_dictionary = length == 0 ? isolate->factory()->empty_slow_element_dictionary() : object->GetElementsAccessor()->Normalize(object); } Handle transition_marker; if (attrs == NONE) { transition_marker = isolate->factory()->nonextensible_symbol(); } else if (attrs == SEALED) { transition_marker = isolate->factory()->sealed_symbol(); } else { DCHECK(attrs == FROZEN); transition_marker = isolate->factory()->frozen_symbol(); } Handle old_map(object->map(), isolate); Map* transition = TransitionArray::SearchSpecial(*old_map, *transition_marker); if (transition != NULL) { Handle transition_map(transition, isolate); DCHECK(transition_map->has_dictionary_elements() || transition_map->has_fixed_typed_array_elements() || transition_map->elements_kind() == SLOW_STRING_WRAPPER_ELEMENTS); DCHECK(!transition_map->is_extensible()); JSObject::MigrateToMap(object, transition_map); } else if (TransitionArray::CanHaveMoreTransitions(old_map)) { // Create a new descriptor array with the appropriate property attributes Handle new_map = Map::CopyForPreventExtensions( old_map, attrs, transition_marker, "CopyForPreventExtensions"); JSObject::MigrateToMap(object, new_map); } else { DCHECK(old_map->is_dictionary_map() || !old_map->is_prototype_map()); // Slow path: need to normalize properties for safety NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0, "SlowPreventExtensions"); // Create a new map, since other objects with this map may be extensible. // TODO(adamk): Extend the NormalizedMapCache to handle non-extensible maps. Handle new_map = Map::Copy(handle(object->map()), "SlowCopyForPreventExtensions"); new_map->set_is_extensible(false); if (!new_element_dictionary.is_null()) { ElementsKind new_kind = IsStringWrapperElementsKind(old_map->elements_kind()) ? SLOW_STRING_WRAPPER_ELEMENTS : DICTIONARY_ELEMENTS; new_map->set_elements_kind(new_kind); } JSObject::MigrateToMap(object, new_map); if (attrs != NONE) { if (object->IsJSGlobalObject()) { Handle dictionary(object->global_dictionary(), isolate); ApplyAttributesToDictionary(isolate, dictionary, attrs); } else { Handle dictionary(object->property_dictionary(), isolate); ApplyAttributesToDictionary(isolate, dictionary, attrs); } } } // Both seal and preventExtensions always go through without modifications to // typed array elements. Freeze works only if there are no actual elements. if (object->HasFixedTypedArrayElements()) { if (attrs == FROZEN && JSArrayBufferView::cast(*object)->byte_length()->Number() > 0) { isolate->Throw(*isolate->factory()->NewTypeError( MessageTemplate::kCannotFreezeArrayBufferView)); return Nothing(); } return Just(true); } DCHECK(object->map()->has_dictionary_elements() || object->map()->elements_kind() == SLOW_STRING_WRAPPER_ELEMENTS); if (!new_element_dictionary.is_null()) { object->set_elements(*new_element_dictionary); } if (object->elements() != isolate->heap()->empty_slow_element_dictionary()) { Handle dictionary(object->element_dictionary(), isolate); // Make sure we never go back to the fast case object->RequireSlowElements(*dictionary); if (attrs != NONE) { ApplyAttributesToDictionary(isolate, dictionary, attrs); } } return Just(true); } Handle JSObject::FastPropertyAt(Handle object, Representation representation, FieldIndex index) { Isolate* isolate = object->GetIsolate(); if (object->IsUnboxedDoubleField(index)) { double value = object->RawFastDoublePropertyAt(index); return isolate->factory()->NewHeapNumber(value); } Handle raw_value(object->RawFastPropertyAt(index), isolate); return Object::WrapForRead(isolate, raw_value, representation); } template class JSObjectWalkVisitor { public: JSObjectWalkVisitor(ContextObject* site_context, bool copying, JSObject::DeepCopyHints hints) : site_context_(site_context), copying_(copying), hints_(hints) {} MUST_USE_RESULT MaybeHandle StructureWalk(Handle object); protected: MUST_USE_RESULT inline MaybeHandle VisitElementOrProperty( Handle object, Handle value) { Handle current_site = site_context()->EnterNewScope(); MaybeHandle copy_of_value = StructureWalk(value); site_context()->ExitScope(current_site, value); return copy_of_value; } inline ContextObject* site_context() { return site_context_; } inline Isolate* isolate() { return site_context()->isolate(); } inline bool copying() const { return copying_; } private: ContextObject* site_context_; const bool copying_; const JSObject::DeepCopyHints hints_; }; template MaybeHandle JSObjectWalkVisitor::StructureWalk( Handle object) { Isolate* isolate = this->isolate(); bool copying = this->copying(); bool shallow = hints_ == JSObject::kObjectIsShallow; if (!shallow) { StackLimitCheck check(isolate); if (check.HasOverflowed()) { isolate->StackOverflow(); return MaybeHandle(); } } if (object->map()->is_deprecated()) { JSObject::MigrateInstance(object); } Handle copy; if (copying) { // JSFunction objects are not allowed to be in normal boilerplates at all. DCHECK(!object->IsJSFunction()); Handle site_to_pass; if (site_context()->ShouldCreateMemento(object)) { site_to_pass = site_context()->current(); } copy = isolate->factory()->CopyJSObjectWithAllocationSite( object, site_to_pass); } else { copy = object; } DCHECK(copying || copy.is_identical_to(object)); ElementsKind kind = copy->GetElementsKind(); if (copying && IsFastSmiOrObjectElementsKind(kind) && FixedArray::cast(copy->elements())->map() == isolate->heap()->fixed_cow_array_map()) { isolate->counters()->cow_arrays_created_runtime()->Increment(); } if (!shallow) { HandleScope scope(isolate); // Deep copy own properties. if (copy->HasFastProperties()) { Handle descriptors(copy->map()->instance_descriptors()); int limit = copy->map()->NumberOfOwnDescriptors(); for (int i = 0; i < limit; i++) { PropertyDetails details = descriptors->GetDetails(i); if (details.location() != kField) continue; DCHECK_EQ(kData, details.kind()); FieldIndex index = FieldIndex::ForDescriptor(copy->map(), i); if (object->IsUnboxedDoubleField(index)) { if (copying) { // Ensure that all bits of the double value are preserved. uint64_t value = object->RawFastDoublePropertyAsBitsAt(index); copy->RawFastDoublePropertyAsBitsAtPut(index, value); } } else { Handle value(object->RawFastPropertyAt(index), isolate); if (value->IsJSObject()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, value, VisitElementOrProperty(copy, Handle::cast(value)), JSObject); if (copying) { copy->FastPropertyAtPut(index, *value); } } else { if (copying) { Representation representation = details.representation(); value = Object::NewStorageFor(isolate, value, representation); copy->FastPropertyAtPut(index, *value); } } } } } else { // Only deep copy fields from the object literal expression. // In particular, don't try to copy the length attribute of // an array. PropertyFilter filter = static_cast( ONLY_WRITABLE | ONLY_ENUMERABLE | ONLY_CONFIGURABLE); KeyAccumulator accumulator(isolate, KeyCollectionMode::kOwnOnly, filter); accumulator.CollectOwnPropertyNames(copy, copy); Handle names = accumulator.GetKeys(); for (int i = 0; i < names->length(); i++) { DCHECK(names->get(i)->IsName()); Handle name(Name::cast(names->get(i))); Handle value = JSObject::GetProperty(copy, name).ToHandleChecked(); if (value->IsJSObject()) { Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, VisitElementOrProperty(copy, Handle::cast(value)), JSObject); if (copying) { // Creating object copy for literals. No strict mode needed. JSObject::SetProperty(copy, name, result, SLOPPY).Assert(); } } } } // Deep copy own elements. switch (kind) { case FAST_ELEMENTS: case FAST_HOLEY_ELEMENTS: { Handle elements(FixedArray::cast(copy->elements())); if (elements->map() == isolate->heap()->fixed_cow_array_map()) { #ifdef DEBUG for (int i = 0; i < elements->length(); i++) { DCHECK(!elements->get(i)->IsJSObject()); } #endif } else { for (int i = 0; i < elements->length(); i++) { Handle value(elements->get(i), isolate); if (value->IsJSObject()) { Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, VisitElementOrProperty(copy, Handle::cast(value)), JSObject); if (copying) { elements->set(i, *result); } } } } break; } case DICTIONARY_ELEMENTS: { Handle element_dictionary( copy->element_dictionary()); int capacity = element_dictionary->Capacity(); for (int i = 0; i < capacity; i++) { Object* k = element_dictionary->KeyAt(i); if (element_dictionary->IsKey(isolate, k)) { Handle value(element_dictionary->ValueAt(i), isolate); if (value->IsJSObject()) { Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, VisitElementOrProperty(copy, Handle::cast(value)), JSObject); if (copying) { element_dictionary->ValueAtPut(i, *result); } } } } break; } case FAST_SLOPPY_ARGUMENTS_ELEMENTS: case SLOW_SLOPPY_ARGUMENTS_ELEMENTS: UNIMPLEMENTED(); break; case FAST_STRING_WRAPPER_ELEMENTS: case SLOW_STRING_WRAPPER_ELEMENTS: UNREACHABLE(); break; #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case TYPE##_ELEMENTS: \ TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE // Typed elements cannot be created using an object literal. UNREACHABLE(); break; case FAST_SMI_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: case NO_ELEMENTS: // No contained objects, nothing to do. break; } } return copy; } MaybeHandle JSObject::DeepWalk( Handle object, AllocationSiteCreationContext* site_context) { JSObjectWalkVisitor v(site_context, false, kNoHints); MaybeHandle result = v.StructureWalk(object); Handle for_assert; DCHECK(!result.ToHandle(&for_assert) || for_assert.is_identical_to(object)); return result; } MaybeHandle JSObject::DeepCopy( Handle object, AllocationSiteUsageContext* site_context, DeepCopyHints hints) { JSObjectWalkVisitor v(site_context, true, hints); MaybeHandle copy = v.StructureWalk(object); Handle for_assert; DCHECK(!copy.ToHandle(&for_assert) || !for_assert.is_identical_to(object)); return copy; } // static MaybeHandle JSReceiver::ToPrimitive(Handle receiver, ToPrimitiveHint hint) { Isolate* const isolate = receiver->GetIsolate(); Handle exotic_to_prim; ASSIGN_RETURN_ON_EXCEPTION( isolate, exotic_to_prim, GetMethod(receiver, isolate->factory()->to_primitive_symbol()), Object); if (!exotic_to_prim->IsUndefined(isolate)) { Handle hint_string = isolate->factory()->ToPrimitiveHintString(hint); Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, Execution::Call(isolate, exotic_to_prim, receiver, 1, &hint_string), Object); if (result->IsPrimitive()) return result; THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kCannotConvertToPrimitive), Object); } return OrdinaryToPrimitive(receiver, (hint == ToPrimitiveHint::kString) ? OrdinaryToPrimitiveHint::kString : OrdinaryToPrimitiveHint::kNumber); } // static MaybeHandle JSReceiver::OrdinaryToPrimitive( Handle receiver, OrdinaryToPrimitiveHint hint) { Isolate* const isolate = receiver->GetIsolate(); Handle method_names[2]; switch (hint) { case OrdinaryToPrimitiveHint::kNumber: method_names[0] = isolate->factory()->valueOf_string(); method_names[1] = isolate->factory()->toString_string(); break; case OrdinaryToPrimitiveHint::kString: method_names[0] = isolate->factory()->toString_string(); method_names[1] = isolate->factory()->valueOf_string(); break; } for (Handle name : method_names) { Handle method; ASSIGN_RETURN_ON_EXCEPTION(isolate, method, JSReceiver::GetProperty(receiver, name), Object); if (method->IsCallable()) { Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, Execution::Call(isolate, method, receiver, 0, NULL), Object); if (result->IsPrimitive()) return result; } } THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kCannotConvertToPrimitive), Object); } // TODO(cbruni/jkummerow): Consider moving this into elements.cc. bool JSObject::HasEnumerableElements() { // TODO(cbruni): cleanup JSObject* object = this; switch (object->GetElementsKind()) { case FAST_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_DOUBLE_ELEMENTS: { int length = object->IsJSArray() ? Smi::cast(JSArray::cast(object)->length())->value() : object->elements()->length(); return length > 0; } case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_ELEMENTS: { FixedArray* elements = FixedArray::cast(object->elements()); int length = object->IsJSArray() ? Smi::cast(JSArray::cast(object)->length())->value() : elements->length(); Isolate* isolate = GetIsolate(); for (int i = 0; i < length; i++) { if (!elements->is_the_hole(isolate, i)) return true; } return false; } case FAST_HOLEY_DOUBLE_ELEMENTS: { int length = object->IsJSArray() ? Smi::cast(JSArray::cast(object)->length())->value() : object->elements()->length(); // Zero-length arrays would use the empty FixedArray... if (length == 0) return false; // ...so only cast to FixedDoubleArray otherwise. FixedDoubleArray* elements = FixedDoubleArray::cast(object->elements()); for (int i = 0; i < length; i++) { if (!elements->is_the_hole(i)) return true; } return false; } #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case TYPE##_ELEMENTS: TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE { int length = object->elements()->length(); return length > 0; } case DICTIONARY_ELEMENTS: { SeededNumberDictionary* elements = SeededNumberDictionary::cast(object->elements()); return elements->NumberOfElementsFilterAttributes(ONLY_ENUMERABLE) > 0; } case FAST_SLOPPY_ARGUMENTS_ELEMENTS: case SLOW_SLOPPY_ARGUMENTS_ELEMENTS: // We're approximating non-empty arguments objects here. return true; case FAST_STRING_WRAPPER_ELEMENTS: case SLOW_STRING_WRAPPER_ELEMENTS: if (String::cast(JSValue::cast(object)->value())->length() > 0) { return true; } return object->elements()->length() > 0; case NO_ELEMENTS: return false; } UNREACHABLE(); return true; } int Map::NumberOfDescribedProperties(DescriptorFlag which, PropertyFilter filter) { int result = 0; DescriptorArray* descs = instance_descriptors(); int limit = which == ALL_DESCRIPTORS ? descs->number_of_descriptors() : NumberOfOwnDescriptors(); for (int i = 0; i < limit; i++) { if ((descs->GetDetails(i).attributes() & filter) == 0 && !descs->GetKey(i)->FilterKey(filter)) { result++; } } return result; } int Map::NextFreePropertyIndex() { int free_index = 0; int number_of_own_descriptors = NumberOfOwnDescriptors(); DescriptorArray* descs = instance_descriptors(); for (int i = 0; i < number_of_own_descriptors; i++) { PropertyDetails details = descs->GetDetails(i); if (details.location() == kField) { int candidate = details.field_index() + details.field_width_in_words(); if (candidate > free_index) free_index = candidate; } } return free_index; } bool Map::OnlyHasSimpleProperties() { // Wrapped string elements aren't explicitly stored in the elements backing // store, but are loaded indirectly from the underlying string. return !IsStringWrapperElementsKind(elements_kind()) && !IsSpecialReceiverMap() && !has_hidden_prototype() && !is_dictionary_map(); } MUST_USE_RESULT Maybe FastGetOwnValuesOrEntries( Isolate* isolate, Handle receiver, bool get_entries, Handle* result) { Handle map(JSReceiver::cast(*receiver)->map(), isolate); if (!map->IsJSObjectMap()) return Just(false); if (!map->OnlyHasSimpleProperties()) return Just(false); Handle object(JSObject::cast(*receiver)); Handle descriptors(map->instance_descriptors(), isolate); int number_of_own_descriptors = map->NumberOfOwnDescriptors(); int number_of_own_elements = object->GetElementsAccessor()->GetCapacity(*object, object->elements()); Handle values_or_entries = isolate->factory()->NewFixedArray( number_of_own_descriptors + number_of_own_elements); int count = 0; if (object->elements() != isolate->heap()->empty_fixed_array()) { MAYBE_RETURN(object->GetElementsAccessor()->CollectValuesOrEntries( isolate, object, values_or_entries, get_entries, &count, ENUMERABLE_STRINGS), Nothing()); } bool stable = object->map() == *map; for (int index = 0; index < number_of_own_descriptors; index++) { Handle next_key(descriptors->GetKey(index), isolate); if (!next_key->IsString()) continue; Handle prop_value; // Directly decode from the descriptor array if |from| did not change shape. if (stable) { PropertyDetails details = descriptors->GetDetails(index); if (!details.IsEnumerable()) continue; if (details.kind() == kData) { if (details.location() == kDescriptor) { prop_value = handle(descriptors->GetValue(index), isolate); } else { Representation representation = details.representation(); FieldIndex field_index = FieldIndex::ForDescriptor(*map, index); prop_value = JSObject::FastPropertyAt(object, representation, field_index); } } else { ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, prop_value, JSReceiver::GetProperty(object, next_key), Nothing()); stable = object->map() == *map; } } else { // If the map did change, do a slower lookup. We are still guaranteed that // the object has a simple shape, and that the key is a name. LookupIterator it(object, next_key, LookupIterator::OWN_SKIP_INTERCEPTOR); if (!it.IsFound()) continue; DCHECK(it.state() == LookupIterator::DATA || it.state() == LookupIterator::ACCESSOR); if (!it.IsEnumerable()) continue; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, prop_value, Object::GetProperty(&it), Nothing()); } if (get_entries) { prop_value = MakeEntryPair(isolate, next_key, prop_value); } values_or_entries->set(count, *prop_value); count++; } if (count < values_or_entries->length()) values_or_entries->Shrink(count); *result = values_or_entries; return Just(true); } MaybeHandle GetOwnValuesOrEntries(Isolate* isolate, Handle object, PropertyFilter filter, bool get_entries) { Handle values_or_entries; if (filter == ENUMERABLE_STRINGS) { Maybe fast_values_or_entries = FastGetOwnValuesOrEntries( isolate, object, get_entries, &values_or_entries); if (fast_values_or_entries.IsNothing()) return MaybeHandle(); if (fast_values_or_entries.FromJust()) return values_or_entries; } PropertyFilter key_filter = static_cast(filter & ~ONLY_ENUMERABLE); Handle keys; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, keys, KeyAccumulator::GetKeys(object, KeyCollectionMode::kOwnOnly, key_filter, GetKeysConversion::kConvertToString), MaybeHandle()); values_or_entries = isolate->factory()->NewFixedArray(keys->length()); int length = 0; for (int i = 0; i < keys->length(); ++i) { Handle key = Handle::cast(handle(keys->get(i), isolate)); if (filter & ONLY_ENUMERABLE) { PropertyDescriptor descriptor; Maybe did_get_descriptor = JSReceiver::GetOwnPropertyDescriptor( isolate, object, key, &descriptor); MAYBE_RETURN(did_get_descriptor, MaybeHandle()); if (!did_get_descriptor.FromJust() || !descriptor.enumerable()) continue; } Handle value; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, value, JSReceiver::GetPropertyOrElement(object, key), MaybeHandle()); if (get_entries) { Handle entry_storage = isolate->factory()->NewUninitializedFixedArray(2); entry_storage->set(0, *key); entry_storage->set(1, *value); value = isolate->factory()->NewJSArrayWithElements(entry_storage, FAST_ELEMENTS, 2); } values_or_entries->set(length, *value); length++; } if (length < values_or_entries->length()) values_or_entries->Shrink(length); return values_or_entries; } MaybeHandle JSReceiver::GetOwnValues(Handle object, PropertyFilter filter) { return GetOwnValuesOrEntries(object->GetIsolate(), object, filter, false); } MaybeHandle JSReceiver::GetOwnEntries(Handle object, PropertyFilter filter) { return GetOwnValuesOrEntries(object->GetIsolate(), object, filter, true); } bool Map::DictionaryElementsInPrototypeChainOnly() { if (IsDictionaryElementsKind(elements_kind())) { return false; } for (PrototypeIterator iter(this); !iter.IsAtEnd(); iter.Advance()) { // Be conservative, don't walk into proxies. if (iter.GetCurrent()->IsJSProxy()) return true; // String wrappers have non-configurable, non-writable elements. if (iter.GetCurrent()->IsStringWrapper()) return true; JSObject* current = iter.GetCurrent(); if (current->HasDictionaryElements() && current->element_dictionary()->requires_slow_elements()) { return true; } if (current->HasSlowArgumentsElements()) { FixedArray* parameter_map = FixedArray::cast(current->elements()); Object* arguments = parameter_map->get(1); if (SeededNumberDictionary::cast(arguments)->requires_slow_elements()) { return true; } } } return false; } MaybeHandle JSObject::DefineAccessor(Handle object, Handle name, Handle getter, Handle setter, PropertyAttributes attributes) { Isolate* isolate = object->GetIsolate(); LookupIterator it = LookupIterator::PropertyOrElement( isolate, object, name, LookupIterator::OWN_SKIP_INTERCEPTOR); return DefineAccessor(&it, getter, setter, attributes); } MaybeHandle JSObject::DefineAccessor(LookupIterator* it, Handle getter, Handle setter, PropertyAttributes attributes) { Isolate* isolate = it->isolate(); it->UpdateProtector(); if (it->state() == LookupIterator::ACCESS_CHECK) { if (!it->HasAccess()) { isolate->ReportFailedAccessCheck(it->GetHolder()); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->undefined_value(); } it->Next(); } Handle object = Handle::cast(it->GetReceiver()); // Ignore accessors on typed arrays. if (it->IsElement() && object->HasFixedTypedArrayElements()) { return it->factory()->undefined_value(); } DCHECK(getter->IsCallable() || getter->IsUndefined(isolate) || getter->IsNull(isolate) || getter->IsFunctionTemplateInfo()); DCHECK(setter->IsCallable() || setter->IsUndefined(isolate) || setter->IsNull(isolate) || setter->IsFunctionTemplateInfo()); it->TransitionToAccessorProperty(getter, setter, attributes); return isolate->factory()->undefined_value(); } MaybeHandle JSObject::SetAccessor(Handle object, Handle info) { Isolate* isolate = object->GetIsolate(); Handle name(Name::cast(info->name()), isolate); LookupIterator it = LookupIterator::PropertyOrElement( isolate, object, name, LookupIterator::OWN_SKIP_INTERCEPTOR); // Duplicate ACCESS_CHECK outside of GetPropertyAttributes for the case that // the FailedAccessCheckCallbackFunction doesn't throw an exception. // // TODO(verwaest): Force throw an exception if the callback doesn't, so we can // remove reliance on default return values. if (it.state() == LookupIterator::ACCESS_CHECK) { if (!it.HasAccess()) { isolate->ReportFailedAccessCheck(object); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return it.factory()->undefined_value(); } it.Next(); } // Ignore accessors on typed arrays. if (it.IsElement() && object->HasFixedTypedArrayElements()) { return it.factory()->undefined_value(); } CHECK(GetPropertyAttributes(&it).IsJust()); // ES5 forbids turning a property into an accessor if it's not // configurable. See 8.6.1 (Table 5). if (it.IsFound() && !it.IsConfigurable()) { return it.factory()->undefined_value(); } it.TransitionToAccessorPair(info, info->property_attributes()); return object; } Object* JSObject::SlowReverseLookup(Object* value) { if (HasFastProperties()) { int number_of_own_descriptors = map()->NumberOfOwnDescriptors(); DescriptorArray* descs = map()->instance_descriptors(); bool value_is_number = value->IsNumber(); for (int i = 0; i < number_of_own_descriptors; i++) { PropertyDetails details = descs->GetDetails(i); if (details.location() == kField) { DCHECK_EQ(kData, details.kind()); FieldIndex field_index = FieldIndex::ForDescriptor(map(), i); if (IsUnboxedDoubleField(field_index)) { if (value_is_number) { double property = RawFastDoublePropertyAt(field_index); if (property == value->Number()) { return descs->GetKey(i); } } } else { Object* property = RawFastPropertyAt(field_index); if (field_index.is_double()) { DCHECK(property->IsMutableHeapNumber()); if (value_is_number && property->Number() == value->Number()) { return descs->GetKey(i); } } else if (property == value) { return descs->GetKey(i); } } } else { DCHECK_EQ(kDescriptor, details.location()); if (details.kind() == kData) { if (descs->GetValue(i) == value) { return descs->GetKey(i); } } } } return GetHeap()->undefined_value(); } else if (IsJSGlobalObject()) { return global_dictionary()->SlowReverseLookup(value); } else { return property_dictionary()->SlowReverseLookup(value); } } Handle Map::RawCopy(Handle map, int instance_size) { Isolate* isolate = map->GetIsolate(); Handle result = isolate->factory()->NewMap(map->instance_type(), instance_size); Handle prototype(map->prototype(), isolate); Map::SetPrototype(result, prototype); result->set_constructor_or_backpointer(map->GetConstructor()); result->set_bit_field(map->bit_field()); result->set_bit_field2(map->bit_field2()); int new_bit_field3 = map->bit_field3(); new_bit_field3 = OwnsDescriptors::update(new_bit_field3, true); new_bit_field3 = NumberOfOwnDescriptorsBits::update(new_bit_field3, 0); new_bit_field3 = EnumLengthBits::update(new_bit_field3, kInvalidEnumCacheSentinel); new_bit_field3 = Deprecated::update(new_bit_field3, false); if (!map->is_dictionary_map()) { new_bit_field3 = IsUnstable::update(new_bit_field3, false); } result->set_bit_field3(new_bit_field3); return result; } Handle Map::Normalize(Handle fast_map, PropertyNormalizationMode mode, const char* reason) { DCHECK(!fast_map->is_dictionary_map()); Isolate* isolate = fast_map->GetIsolate(); Handle maybe_cache(isolate->native_context()->normalized_map_cache(), isolate); bool use_cache = !fast_map->is_prototype_map() && !maybe_cache->IsUndefined(isolate); Handle cache; if (use_cache) cache = Handle::cast(maybe_cache); Handle new_map; if (use_cache && cache->Get(fast_map, mode).ToHandle(&new_map)) { #ifdef VERIFY_HEAP if (FLAG_verify_heap) new_map->DictionaryMapVerify(); #endif #ifdef ENABLE_SLOW_DCHECKS if (FLAG_enable_slow_asserts) { // The cached map should match newly created normalized map bit-by-bit, // except for the code cache, which can contain some ics which can be // applied to the shared map, dependent code and weak cell cache. Handle fresh = Map::CopyNormalized(fast_map, mode); if (new_map->is_prototype_map()) { // For prototype maps, the PrototypeInfo is not copied. DCHECK(memcmp(fresh->address(), new_map->address(), kTransitionsOrPrototypeInfoOffset) == 0); DCHECK(fresh->raw_transitions() == Smi::kZero); STATIC_ASSERT(kDescriptorsOffset == kTransitionsOrPrototypeInfoOffset + kPointerSize); DCHECK(memcmp(HeapObject::RawField(*fresh, kDescriptorsOffset), HeapObject::RawField(*new_map, kDescriptorsOffset), kCodeCacheOffset - kDescriptorsOffset) == 0); } else { DCHECK(memcmp(fresh->address(), new_map->address(), Map::kCodeCacheOffset) == 0); } STATIC_ASSERT(Map::kDependentCodeOffset == Map::kCodeCacheOffset + kPointerSize); STATIC_ASSERT(Map::kWeakCellCacheOffset == Map::kDependentCodeOffset + kPointerSize); int offset = Map::kWeakCellCacheOffset + kPointerSize; DCHECK(memcmp(fresh->address() + offset, new_map->address() + offset, Map::kSize - offset) == 0); } #endif } else { new_map = Map::CopyNormalized(fast_map, mode); if (use_cache) { cache->Set(fast_map, new_map); isolate->counters()->maps_normalized()->Increment(); } #if TRACE_MAPS if (FLAG_trace_maps) { PrintF("[TraceMaps: Normalize from= %p to= %p reason= %s ]\n", reinterpret_cast(*fast_map), reinterpret_cast(*new_map), reason); } #endif } fast_map->NotifyLeafMapLayoutChange(); return new_map; } Handle Map::CopyNormalized(Handle map, PropertyNormalizationMode mode) { int new_instance_size = map->instance_size(); if (mode == CLEAR_INOBJECT_PROPERTIES) { new_instance_size -= map->GetInObjectProperties() * kPointerSize; } Handle result = RawCopy(map, new_instance_size); if (mode != CLEAR_INOBJECT_PROPERTIES) { result->SetInObjectProperties(map->GetInObjectProperties()); } result->set_dictionary_map(true); result->set_migration_target(false); result->set_construction_counter(kNoSlackTracking); #ifdef VERIFY_HEAP if (FLAG_verify_heap) result->DictionaryMapVerify(); #endif return result; } // Return an immutable prototype exotic object version of the input map. // Never even try to cache it in the transition tree, as it is intended // for the global object and its prototype chain, and excluding it saves // memory on the map transition tree. // static Handle Map::TransitionToImmutableProto(Handle map) { Handle new_map = Map::Copy(map, "ImmutablePrototype"); new_map->set_immutable_proto(true); return new_map; } Handle Map::CopyInitialMap(Handle map, int instance_size, int in_object_properties, int unused_property_fields) { #ifdef DEBUG Isolate* isolate = map->GetIsolate(); // Strict function maps have Function as a constructor but the // Function's initial map is a sloppy function map. Same holds for // GeneratorFunction / AsyncFunction and its initial map. Object* constructor = map->GetConstructor(); DCHECK(constructor->IsJSFunction()); DCHECK(*map == JSFunction::cast(constructor)->initial_map() || *map == *isolate->strict_function_map() || *map == *isolate->generator_function_map() || *map == *isolate->async_function_map()); #endif // Initial maps must always own their descriptors and it's descriptor array // does not contain descriptors that do not belong to the map. DCHECK(map->owns_descriptors()); DCHECK_EQ(map->NumberOfOwnDescriptors(), map->instance_descriptors()->number_of_descriptors()); Handle result = RawCopy(map, instance_size); // Please note instance_type and instance_size are set when allocated. result->SetInObjectProperties(in_object_properties); result->set_unused_property_fields(unused_property_fields); int number_of_own_descriptors = map->NumberOfOwnDescriptors(); if (number_of_own_descriptors > 0) { // The copy will use the same descriptors array. result->UpdateDescriptors(map->instance_descriptors(), map->GetLayoutDescriptor()); result->SetNumberOfOwnDescriptors(number_of_own_descriptors); DCHECK_EQ(result->NumberOfFields(), in_object_properties - unused_property_fields); } return result; } Handle Map::CopyDropDescriptors(Handle map) { Handle result = RawCopy(map, map->instance_size()); // Please note instance_type and instance_size are set when allocated. if (map->IsJSObjectMap()) { result->SetInObjectProperties(map->GetInObjectProperties()); result->set_unused_property_fields(map->unused_property_fields()); } result->ClearCodeCache(map->GetHeap()); map->NotifyLeafMapLayoutChange(); return result; } Handle Map::ShareDescriptor(Handle map, Handle descriptors, Descriptor* descriptor) { // Sanity check. This path is only to be taken if the map owns its descriptor // array, implying that its NumberOfOwnDescriptors equals the number of // descriptors in the descriptor array. DCHECK_EQ(map->NumberOfOwnDescriptors(), map->instance_descriptors()->number_of_descriptors()); Handle result = CopyDropDescriptors(map); Handle name = descriptor->GetKey(); // Ensure there's space for the new descriptor in the shared descriptor array. if (descriptors->NumberOfSlackDescriptors() == 0) { int old_size = descriptors->number_of_descriptors(); if (old_size == 0) { descriptors = DescriptorArray::Allocate(map->GetIsolate(), 0, 1); } else { int slack = SlackForArraySize(old_size, kMaxNumberOfDescriptors); EnsureDescriptorSlack(map, slack); descriptors = handle(map->instance_descriptors()); } } Handle layout_descriptor = FLAG_unbox_double_fields ? LayoutDescriptor::ShareAppend(map, descriptor->GetDetails()) : handle(LayoutDescriptor::FastPointerLayout(), map->GetIsolate()); { DisallowHeapAllocation no_gc; descriptors->Append(descriptor); result->InitializeDescriptors(*descriptors, *layout_descriptor); } DCHECK(result->NumberOfOwnDescriptors() == map->NumberOfOwnDescriptors() + 1); ConnectTransition(map, result, name, SIMPLE_PROPERTY_TRANSITION); return result; } #if TRACE_MAPS // static void Map::TraceTransition(const char* what, Map* from, Map* to, Name* name) { if (FLAG_trace_maps) { PrintF("[TraceMaps: %s from= %p to= %p name= ", what, reinterpret_cast(from), reinterpret_cast(to)); name->NameShortPrint(); PrintF(" ]\n"); } } // static void Map::TraceAllTransitions(Map* map) { Object* transitions = map->raw_transitions(); int num_transitions = TransitionArray::NumberOfTransitions(transitions); for (int i = -0; i < num_transitions; ++i) { Map* target = TransitionArray::GetTarget(transitions, i); Name* key = TransitionArray::GetKey(transitions, i); Map::TraceTransition("Transition", map, target, key); Map::TraceAllTransitions(target); } } #endif // TRACE_MAPS void Map::ConnectTransition(Handle parent, Handle child, Handle name, SimpleTransitionFlag flag) { if (!parent->GetBackPointer()->IsUndefined(parent->GetIsolate())) { parent->set_owns_descriptors(false); } else { // |parent| is initial map and it must keep the ownership, there must be no // descriptors in the descriptors array that do not belong to the map. DCHECK(parent->owns_descriptors()); DCHECK_EQ(parent->NumberOfOwnDescriptors(), parent->instance_descriptors()->number_of_descriptors()); } if (parent->is_prototype_map()) { DCHECK(child->is_prototype_map()); #if TRACE_MAPS Map::TraceTransition("NoTransition", *parent, *child, *name); #endif } else { TransitionArray::Insert(parent, name, child, flag); #if TRACE_MAPS Map::TraceTransition("Transition", *parent, *child, *name); #endif } } Handle Map::CopyReplaceDescriptors( Handle map, Handle descriptors, Handle layout_descriptor, TransitionFlag flag, MaybeHandle maybe_name, const char* reason, SimpleTransitionFlag simple_flag) { DCHECK(descriptors->IsSortedNoDuplicates()); Handle result = CopyDropDescriptors(map); if (!map->is_prototype_map()) { if (flag == INSERT_TRANSITION && TransitionArray::CanHaveMoreTransitions(map)) { result->InitializeDescriptors(*descriptors, *layout_descriptor); Handle name; CHECK(maybe_name.ToHandle(&name)); ConnectTransition(map, result, name, simple_flag); } else { descriptors->GeneralizeAllFields(); result->InitializeDescriptors(*descriptors, LayoutDescriptor::FastPointerLayout()); } } else { result->InitializeDescriptors(*descriptors, *layout_descriptor); } #if TRACE_MAPS if (FLAG_trace_maps && // Mirror conditions above that did not call ConnectTransition(). (map->is_prototype_map() || !(flag == INSERT_TRANSITION && TransitionArray::CanHaveMoreTransitions(map)))) { PrintF("[TraceMaps: ReplaceDescriptors from= %p to= %p reason= %s ]\n", reinterpret_cast(*map), reinterpret_cast(*result), reason); } #endif return result; } // Creates transition tree starting from |split_map| and adding all descriptors // starting from descriptor with index |split_map|.NumberOfOwnDescriptors(). // The way how it is done is tricky because of GC and special descriptors // marking logic. Handle Map::AddMissingTransitions( Handle split_map, Handle descriptors, Handle full_layout_descriptor) { DCHECK(descriptors->IsSortedNoDuplicates()); int split_nof = split_map->NumberOfOwnDescriptors(); int nof_descriptors = descriptors->number_of_descriptors(); DCHECK_LT(split_nof, nof_descriptors); // Start with creating last map which will own full descriptors array. // This is necessary to guarantee that GC will mark the whole descriptor // array if any of the allocations happening below fail. // Number of unused properties is temporarily incorrect and the layout // descriptor could unnecessarily be in slow mode but we will fix after // all the other intermediate maps are created. Handle last_map = CopyDropDescriptors(split_map); last_map->InitializeDescriptors(*descriptors, *full_layout_descriptor); last_map->set_unused_property_fields(0); // During creation of intermediate maps we violate descriptors sharing // invariant since the last map is not yet connected to the transition tree // we create here. But it is safe because GC never trims map's descriptors // if there are no dead transitions from that map and this is exactly the // case for all the intermediate maps we create here. Handle map = split_map; for (int i = split_nof; i < nof_descriptors - 1; ++i) { Handle new_map = CopyDropDescriptors(map); InstallDescriptors(map, new_map, i, descriptors, full_layout_descriptor); map = new_map; } map->NotifyLeafMapLayoutChange(); InstallDescriptors(map, last_map, nof_descriptors - 1, descriptors, full_layout_descriptor); return last_map; } // Since this method is used to rewrite an existing transition tree, it can // always insert transitions without checking. void Map::InstallDescriptors(Handle parent, Handle child, int new_descriptor, Handle descriptors, Handle full_layout_descriptor) { DCHECK(descriptors->IsSortedNoDuplicates()); child->set_instance_descriptors(*descriptors); child->SetNumberOfOwnDescriptors(new_descriptor + 1); int unused_property_fields = parent->unused_property_fields(); PropertyDetails details = descriptors->GetDetails(new_descriptor); if (details.location() == kField) { unused_property_fields = parent->unused_property_fields() - 1; if (unused_property_fields < 0) { unused_property_fields += JSObject::kFieldsAdded; } } child->set_unused_property_fields(unused_property_fields); if (FLAG_unbox_double_fields) { Handle layout_descriptor = LayoutDescriptor::AppendIfFastOrUseFull(parent, details, full_layout_descriptor); child->set_layout_descriptor(*layout_descriptor); #ifdef VERIFY_HEAP // TODO(ishell): remove these checks from VERIFY_HEAP mode. if (FLAG_verify_heap) { CHECK(child->layout_descriptor()->IsConsistentWithMap(*child)); } #else SLOW_DCHECK(child->layout_descriptor()->IsConsistentWithMap(*child)); #endif child->set_visitor_id(Heap::GetStaticVisitorIdForMap(*child)); } Handle name = handle(descriptors->GetKey(new_descriptor)); ConnectTransition(parent, child, name, SIMPLE_PROPERTY_TRANSITION); } Handle Map::CopyAsElementsKind(Handle map, ElementsKind kind, TransitionFlag flag) { Map* maybe_elements_transition_map = NULL; if (flag == INSERT_TRANSITION) { // Ensure we are requested to add elements kind transition "near the root". DCHECK_EQ(map->FindRootMap()->NumberOfOwnDescriptors(), map->NumberOfOwnDescriptors()); maybe_elements_transition_map = map->ElementsTransitionMap(); DCHECK(maybe_elements_transition_map == NULL || (maybe_elements_transition_map->elements_kind() == DICTIONARY_ELEMENTS && kind == DICTIONARY_ELEMENTS)); DCHECK(!IsFastElementsKind(kind) || IsMoreGeneralElementsKindTransition(map->elements_kind(), kind)); DCHECK(kind != map->elements_kind()); } bool insert_transition = flag == INSERT_TRANSITION && TransitionArray::CanHaveMoreTransitions(map) && maybe_elements_transition_map == NULL; if (insert_transition) { Handle new_map = CopyForTransition(map, "CopyAsElementsKind"); new_map->set_elements_kind(kind); Isolate* isolate = map->GetIsolate(); Handle name = isolate->factory()->elements_transition_symbol(); ConnectTransition(map, new_map, name, SPECIAL_TRANSITION); return new_map; } // Create a new free-floating map only if we are not allowed to store it. Handle new_map = Copy(map, "CopyAsElementsKind"); new_map->set_elements_kind(kind); return new_map; } Handle Map::AsLanguageMode(Handle initial_map, LanguageMode language_mode, FunctionKind kind) { DCHECK_EQ(JS_FUNCTION_TYPE, initial_map->instance_type()); // Initial map for sloppy mode function is stored in the function // constructor. Initial maps for strict mode are cached as special transitions // using |strict_function_transition_symbol| as a key. if (language_mode == SLOPPY) return initial_map; Isolate* isolate = initial_map->GetIsolate(); int map_index = Context::FunctionMapIndex(language_mode, kind); Handle function_map( Map::cast(isolate->native_context()->get(map_index))); STATIC_ASSERT(LANGUAGE_END == 2); DCHECK_EQ(STRICT, language_mode); Handle transition_symbol = isolate->factory()->strict_function_transition_symbol(); Map* maybe_transition = TransitionArray::SearchSpecial(*initial_map, *transition_symbol); if (maybe_transition != NULL) { return handle(maybe_transition, isolate); } initial_map->NotifyLeafMapLayoutChange(); // Create new map taking descriptors from the |function_map| and all // the other details from the |initial_map|. Handle map = Map::CopyInitialMap(function_map, initial_map->instance_size(), initial_map->GetInObjectProperties(), initial_map->unused_property_fields()); map->SetConstructor(initial_map->GetConstructor()); map->set_prototype(initial_map->prototype()); if (TransitionArray::CanHaveMoreTransitions(initial_map)) { Map::ConnectTransition(initial_map, map, transition_symbol, SPECIAL_TRANSITION); } return map; } Handle Map::CopyForTransition(Handle map, const char* reason) { DCHECK(!map->is_prototype_map()); Handle new_map = CopyDropDescriptors(map); if (map->owns_descriptors()) { // In case the map owned its own descriptors, share the descriptors and // transfer ownership to the new map. // The properties did not change, so reuse descriptors. new_map->InitializeDescriptors(map->instance_descriptors(), map->GetLayoutDescriptor()); } else { // In case the map did not own its own descriptors, a split is forced by // copying the map; creating a new descriptor array cell. Handle descriptors(map->instance_descriptors()); int number_of_own_descriptors = map->NumberOfOwnDescriptors(); Handle new_descriptors = DescriptorArray::CopyUpTo(descriptors, number_of_own_descriptors); Handle new_layout_descriptor(map->GetLayoutDescriptor(), map->GetIsolate()); new_map->InitializeDescriptors(*new_descriptors, *new_layout_descriptor); } #if TRACE_MAPS if (FLAG_trace_maps) { PrintF("[TraceMaps: CopyForTransition from= %p to= %p reason= %s ]\n", reinterpret_cast(*map), reinterpret_cast(*new_map), reason); } #endif return new_map; } Handle Map::Copy(Handle map, const char* reason) { Handle descriptors(map->instance_descriptors()); int number_of_own_descriptors = map->NumberOfOwnDescriptors(); Handle new_descriptors = DescriptorArray::CopyUpTo(descriptors, number_of_own_descriptors); Handle new_layout_descriptor(map->GetLayoutDescriptor(), map->GetIsolate()); return CopyReplaceDescriptors(map, new_descriptors, new_layout_descriptor, OMIT_TRANSITION, MaybeHandle(), reason, SPECIAL_TRANSITION); } Handle Map::Create(Isolate* isolate, int inobject_properties) { Handle copy = Copy(handle(isolate->object_function()->initial_map()), "MapCreate"); // Check that we do not overflow the instance size when adding the extra // inobject properties. If the instance size overflows, we allocate as many // properties as we can as inobject properties. int max_extra_properties = (JSObject::kMaxInstanceSize - JSObject::kHeaderSize) >> kPointerSizeLog2; if (inobject_properties > max_extra_properties) { inobject_properties = max_extra_properties; } int new_instance_size = JSObject::kHeaderSize + kPointerSize * inobject_properties; // Adjust the map with the extra inobject properties. copy->SetInObjectProperties(inobject_properties); copy->set_unused_property_fields(inobject_properties); copy->set_instance_size(new_instance_size); copy->set_visitor_id(Heap::GetStaticVisitorIdForMap(*copy)); return copy; } Handle Map::CopyForPreventExtensions(Handle map, PropertyAttributes attrs_to_add, Handle transition_marker, const char* reason) { int num_descriptors = map->NumberOfOwnDescriptors(); Isolate* isolate = map->GetIsolate(); Handle new_desc = DescriptorArray::CopyUpToAddAttributes( handle(map->instance_descriptors(), isolate), num_descriptors, attrs_to_add); Handle new_layout_descriptor(map->GetLayoutDescriptor(), isolate); Handle new_map = CopyReplaceDescriptors( map, new_desc, new_layout_descriptor, INSERT_TRANSITION, transition_marker, reason, SPECIAL_TRANSITION); new_map->set_is_extensible(false); if (!IsFixedTypedArrayElementsKind(map->elements_kind())) { ElementsKind new_kind = IsStringWrapperElementsKind(map->elements_kind()) ? SLOW_STRING_WRAPPER_ELEMENTS : DICTIONARY_ELEMENTS; new_map->set_elements_kind(new_kind); } return new_map; } namespace { bool CanHoldValue(DescriptorArray* descriptors, int descriptor, PropertyConstness constness, Object* value) { PropertyDetails details = descriptors->GetDetails(descriptor); if (details.location() == kField) { if (details.kind() == kData) { return IsGeneralizableTo(constness, details.constness()) && value->FitsRepresentation(details.representation()) && descriptors->GetFieldType(descriptor)->NowContains(value); } else { DCHECK_EQ(kAccessor, details.kind()); return false; } } else { DCHECK_EQ(kDescriptor, details.location()); DCHECK_EQ(kConst, details.constness()); if (details.kind() == kData) { DCHECK(!FLAG_track_constant_fields); DCHECK(descriptors->GetValue(descriptor) != value || value->FitsRepresentation(details.representation())); return descriptors->GetValue(descriptor) == value; } else { DCHECK_EQ(kAccessor, details.kind()); return false; } } UNREACHABLE(); return false; } Handle UpdateDescriptorForValue(Handle map, int descriptor, PropertyConstness constness, Handle value) { if (CanHoldValue(map->instance_descriptors(), descriptor, constness, *value)) { return map; } Isolate* isolate = map->GetIsolate(); PropertyAttributes attributes = map->instance_descriptors()->GetDetails(descriptor).attributes(); Representation representation = value->OptimalRepresentation(); Handle type = value->OptimalType(isolate, representation); MapUpdater mu(isolate, map); return mu.ReconfigureToDataField(descriptor, attributes, constness, representation, type); } } // namespace // static Handle Map::PrepareForDataProperty(Handle map, int descriptor, PropertyConstness constness, Handle value) { // Dictionaries can store any property value. DCHECK(!map->is_dictionary_map()); // Update to the newest map before storing the property. return UpdateDescriptorForValue(Update(map), descriptor, constness, value); } Handle Map::TransitionToDataProperty(Handle map, Handle name, Handle value, PropertyAttributes attributes, PropertyConstness constness, StoreFromKeyed store_mode) { RuntimeCallTimerScope stats_scope( *map, map->is_prototype_map() ? &RuntimeCallStats::PrototypeMap_TransitionToDataProperty : &RuntimeCallStats::Map_TransitionToDataProperty); DCHECK(name->IsUniqueName()); DCHECK(!map->is_dictionary_map()); // Migrate to the newest map before storing the property. map = Update(map); Map* maybe_transition = TransitionArray::SearchTransition(*map, kData, *name, attributes); if (maybe_transition != NULL) { Handle transition(maybe_transition); int descriptor = transition->LastAdded(); DCHECK_EQ(attributes, transition->instance_descriptors() ->GetDetails(descriptor) .attributes()); return UpdateDescriptorForValue(transition, descriptor, constness, value); } TransitionFlag flag = INSERT_TRANSITION; MaybeHandle maybe_map; if (!FLAG_track_constant_fields && value->IsJSFunction()) { maybe_map = Map::CopyWithConstant(map, name, value, attributes, flag); } else if (!map->TooManyFastProperties(store_mode)) { Isolate* isolate = name->GetIsolate(); Representation representation = value->OptimalRepresentation(); Handle type = value->OptimalType(isolate, representation); maybe_map = Map::CopyWithField(map, name, type, attributes, constness, representation, flag); } Handle result; if (!maybe_map.ToHandle(&result)) { #if TRACE_MAPS if (FLAG_trace_maps) { Vector name_buffer = Vector::New(100); name->NameShortPrint(name_buffer); Vector buffer = Vector::New(128); SNPrintF(buffer, "TooManyFastProperties %s", name_buffer.start()); return Map::Normalize(map, CLEAR_INOBJECT_PROPERTIES, buffer.start()); } #endif return Map::Normalize(map, CLEAR_INOBJECT_PROPERTIES, "TooManyFastProperties"); } return result; } Handle Map::ReconfigureExistingProperty(Handle map, int descriptor, PropertyKind kind, PropertyAttributes attributes) { // Dictionaries have to be reconfigured in-place. DCHECK(!map->is_dictionary_map()); if (!map->GetBackPointer()->IsMap()) { // There is no benefit from reconstructing transition tree for maps without // back pointers. return CopyGeneralizeAllFields(map, map->elements_kind(), descriptor, kind, attributes, "GenAll_AttributesMismatchProtoMap"); } if (FLAG_trace_generalization) { map->PrintReconfiguration(stdout, descriptor, kind, attributes); } Isolate* isolate = map->GetIsolate(); MapUpdater mu(isolate, map); DCHECK_EQ(kData, kind); // Only kData case is supported so far. Handle new_map = mu.ReconfigureToDataField( descriptor, attributes, kDefaultFieldConstness, Representation::None(), FieldType::None(isolate)); return new_map; } Handle Map::TransitionToAccessorProperty(Isolate* isolate, Handle map, Handle name, int descriptor, Handle getter, Handle setter, PropertyAttributes attributes) { RuntimeCallTimerScope stats_scope( isolate, map->is_prototype_map() ? &RuntimeCallStats::PrototypeMap_TransitionToAccessorProperty : &RuntimeCallStats::Map_TransitionToAccessorProperty); // At least one of the accessors needs to be a new value. DCHECK(!getter->IsNull(isolate) || !setter->IsNull(isolate)); DCHECK(name->IsUniqueName()); // Dictionary maps can always have additional data properties. if (map->is_dictionary_map()) return map; // Migrate to the newest map before transitioning to the new property. map = Update(map); PropertyNormalizationMode mode = map->is_prototype_map() ? KEEP_INOBJECT_PROPERTIES : CLEAR_INOBJECT_PROPERTIES; Map* maybe_transition = TransitionArray::SearchTransition(*map, kAccessor, *name, attributes); if (maybe_transition != NULL) { Handle transition(maybe_transition, isolate); DescriptorArray* descriptors = transition->instance_descriptors(); int descriptor = transition->LastAdded(); DCHECK(descriptors->GetKey(descriptor)->Equals(*name)); DCHECK_EQ(kAccessor, descriptors->GetDetails(descriptor).kind()); DCHECK_EQ(attributes, descriptors->GetDetails(descriptor).attributes()); Handle maybe_pair(descriptors->GetValue(descriptor), isolate); if (!maybe_pair->IsAccessorPair()) { return Map::Normalize(map, mode, "TransitionToAccessorFromNonPair"); } Handle pair = Handle::cast(maybe_pair); if (!pair->Equals(*getter, *setter)) { return Map::Normalize(map, mode, "TransitionToDifferentAccessor"); } return transition; } Handle pair; DescriptorArray* old_descriptors = map->instance_descriptors(); if (descriptor != DescriptorArray::kNotFound) { if (descriptor != map->LastAdded()) { return Map::Normalize(map, mode, "AccessorsOverwritingNonLast"); } PropertyDetails old_details = old_descriptors->GetDetails(descriptor); if (old_details.kind() != kAccessor) { return Map::Normalize(map, mode, "AccessorsOverwritingNonAccessors"); } if (old_details.attributes() != attributes) { return Map::Normalize(map, mode, "AccessorsWithAttributes"); } Handle maybe_pair(old_descriptors->GetValue(descriptor), isolate); if (!maybe_pair->IsAccessorPair()) { return Map::Normalize(map, mode, "AccessorsOverwritingNonPair"); } Handle current_pair = Handle::cast(maybe_pair); if (current_pair->Equals(*getter, *setter)) return map; bool overwriting_accessor = false; if (!getter->IsNull(isolate) && !current_pair->get(ACCESSOR_GETTER)->IsNull(isolate) && current_pair->get(ACCESSOR_GETTER) != *getter) { overwriting_accessor = true; } if (!setter->IsNull(isolate) && !current_pair->get(ACCESSOR_SETTER)->IsNull(isolate) && current_pair->get(ACCESSOR_SETTER) != *setter) { overwriting_accessor = true; } if (overwriting_accessor) { return Map::Normalize(map, mode, "AccessorsOverwritingAccessors"); } pair = AccessorPair::Copy(Handle::cast(maybe_pair)); } else if (map->NumberOfOwnDescriptors() >= kMaxNumberOfDescriptors || map->TooManyFastProperties(CERTAINLY_NOT_STORE_FROM_KEYED)) { return Map::Normalize(map, CLEAR_INOBJECT_PROPERTIES, "TooManyAccessors"); } else { pair = isolate->factory()->NewAccessorPair(); } pair->SetComponents(*getter, *setter); TransitionFlag flag = INSERT_TRANSITION; Descriptor d = Descriptor::AccessorConstant(name, pair, attributes); return Map::CopyInsertDescriptor(map, &d, flag); } Handle Map::CopyAddDescriptor(Handle map, Descriptor* descriptor, TransitionFlag flag) { Handle descriptors(map->instance_descriptors()); // Share descriptors only if map owns descriptors and it not an initial map. if (flag == INSERT_TRANSITION && map->owns_descriptors() && !map->GetBackPointer()->IsUndefined(map->GetIsolate()) && TransitionArray::CanHaveMoreTransitions(map)) { return ShareDescriptor(map, descriptors, descriptor); } int nof = map->NumberOfOwnDescriptors(); Handle new_descriptors = DescriptorArray::CopyUpTo(descriptors, nof, 1); new_descriptors->Append(descriptor); Handle new_layout_descriptor = FLAG_unbox_double_fields ? LayoutDescriptor::New(map, new_descriptors, nof + 1) : handle(LayoutDescriptor::FastPointerLayout(), map->GetIsolate()); return CopyReplaceDescriptors(map, new_descriptors, new_layout_descriptor, flag, descriptor->GetKey(), "CopyAddDescriptor", SIMPLE_PROPERTY_TRANSITION); } Handle Map::CopyInsertDescriptor(Handle map, Descriptor* descriptor, TransitionFlag flag) { Handle old_descriptors(map->instance_descriptors()); // We replace the key if it is already present. int index = old_descriptors->SearchWithCache(map->GetIsolate(), *descriptor->GetKey(), *map); if (index != DescriptorArray::kNotFound) { return CopyReplaceDescriptor(map, old_descriptors, descriptor, index, flag); } return CopyAddDescriptor(map, descriptor, flag); } Handle DescriptorArray::CopyUpTo( Handle desc, int enumeration_index, int slack) { return DescriptorArray::CopyUpToAddAttributes( desc, enumeration_index, NONE, slack); } Handle DescriptorArray::CopyUpToAddAttributes( Handle desc, int enumeration_index, PropertyAttributes attributes, int slack) { if (enumeration_index + slack == 0) { return desc->GetIsolate()->factory()->empty_descriptor_array(); } int size = enumeration_index; Handle descriptors = DescriptorArray::Allocate(desc->GetIsolate(), size, slack); if (attributes != NONE) { for (int i = 0; i < size; ++i) { Object* value = desc->GetValue(i); Name* key = desc->GetKey(i); PropertyDetails details = desc->GetDetails(i); // Bulk attribute changes never affect private properties. if (!key->IsPrivate()) { int mask = DONT_DELETE | DONT_ENUM; // READ_ONLY is an invalid attribute for JS setters/getters. if (details.kind() != kAccessor || !value->IsAccessorPair()) { mask |= READ_ONLY; } details = details.CopyAddAttributes( static_cast(attributes & mask)); } descriptors->Set(i, key, value, details); } } else { for (int i = 0; i < size; ++i) { descriptors->CopyFrom(i, *desc); } } if (desc->number_of_descriptors() != enumeration_index) descriptors->Sort(); return descriptors; } bool DescriptorArray::IsEqualUpTo(DescriptorArray* desc, int nof_descriptors) { for (int i = 0; i < nof_descriptors; i++) { if (GetKey(i) != desc->GetKey(i) || GetValue(i) != desc->GetValue(i)) { return false; } PropertyDetails details = GetDetails(i); PropertyDetails other_details = desc->GetDetails(i); if (details.kind() != other_details.kind() || details.location() != other_details.location() || !details.representation().Equals(other_details.representation())) { return false; } } return true; } Handle Map::CopyReplaceDescriptor(Handle map, Handle descriptors, Descriptor* descriptor, int insertion_index, TransitionFlag flag) { Handle key = descriptor->GetKey(); DCHECK(*key == descriptors->GetKey(insertion_index)); Handle new_descriptors = DescriptorArray::CopyUpTo( descriptors, map->NumberOfOwnDescriptors()); new_descriptors->Replace(insertion_index, descriptor); Handle new_layout_descriptor = LayoutDescriptor::New( map, new_descriptors, new_descriptors->number_of_descriptors()); SimpleTransitionFlag simple_flag = (insertion_index == descriptors->number_of_descriptors() - 1) ? SIMPLE_PROPERTY_TRANSITION : PROPERTY_TRANSITION; return CopyReplaceDescriptors(map, new_descriptors, new_layout_descriptor, flag, key, "CopyReplaceDescriptor", simple_flag); } // Helper class to manage a Map's code cache. The layout depends on the number // of entries; this is worthwhile because most code caches are very small, // but some are huge (thousands of entries). // For zero entries, the EmptyFixedArray is used. // For one entry, we use a 2-element FixedArray containing [name, code]. // For 2..100 entries, we use a FixedArray with linear lookups, the layout is: // [0] - number of slots that are currently in use // [1] - first name // [2] - first code // [3] - second name // [4] - second code // etc. // For more than 128 entries, we use a CodeCacheHashTable. class CodeCache : public AllStatic { public: // Returns the new cache, to be stored on the map. static Handle Put(Isolate* isolate, Handle cache, Handle name, Handle code) { int length = cache->length(); if (length == 0) return PutFirstElement(isolate, name, code); if (length == kEntrySize) { return PutSecondElement(isolate, cache, name, code); } if (length <= kLinearMaxSize) { Handle result = PutLinearElement(isolate, cache, name, code); if (!result.is_null()) return result; // Fall through if linear storage is getting too large. } return PutHashTableElement(isolate, cache, name, code); } static Code* Lookup(FixedArray* cache, Name* name, Code::Flags flags) { int length = cache->length(); if (length == 0) return nullptr; if (length == kEntrySize) return OneElementLookup(cache, name, flags); if (!cache->IsCodeCacheHashTable()) { return LinearLookup(cache, name, flags); } else { return CodeCacheHashTable::cast(cache)->Lookup(name, flags); } } private: static const int kNameIndex = 0; static const int kCodeIndex = 1; static const int kEntrySize = 2; static const int kLinearUsageIndex = 0; static const int kLinearReservedSlots = 1; static const int kLinearInitialCapacity = 2; static const int kLinearMaxSize = 257; // == LinearSizeFor(128); static const int kHashTableInitialCapacity = 200; // Number of entries. static int LinearSizeFor(int entries) { return kLinearReservedSlots + kEntrySize * entries; } static int LinearNewSize(int old_size) { int old_entries = (old_size - kLinearReservedSlots) / kEntrySize; return LinearSizeFor(old_entries * 2); } static Code* OneElementLookup(FixedArray* cache, Name* name, Code::Flags flags) { DCHECK_EQ(cache->length(), kEntrySize); if (cache->get(kNameIndex) != name) return nullptr; Code* maybe_code = Code::cast(cache->get(kCodeIndex)); if (maybe_code->flags() != flags) return nullptr; return maybe_code; } static Code* LinearLookup(FixedArray* cache, Name* name, Code::Flags flags) { DCHECK_GE(cache->length(), kEntrySize); DCHECK(!cache->IsCodeCacheHashTable()); int usage = GetLinearUsage(cache); for (int i = kLinearReservedSlots; i < usage; i += kEntrySize) { if (cache->get(i + kNameIndex) != name) continue; Code* code = Code::cast(cache->get(i + kCodeIndex)); if (code->flags() == flags) return code; } return nullptr; } static Handle PutFirstElement(Isolate* isolate, Handle name, Handle code) { Handle cache = isolate->factory()->NewFixedArray(kEntrySize); cache->set(kNameIndex, *name); cache->set(kCodeIndex, *code); return cache; } static Handle PutSecondElement(Isolate* isolate, Handle cache, Handle name, Handle code) { DCHECK_EQ(cache->length(), kEntrySize); Handle new_cache = isolate->factory()->NewFixedArray( LinearSizeFor(kLinearInitialCapacity)); new_cache->set(kLinearReservedSlots + kNameIndex, cache->get(kNameIndex)); new_cache->set(kLinearReservedSlots + kCodeIndex, cache->get(kCodeIndex)); new_cache->set(LinearSizeFor(1) + kNameIndex, *name); new_cache->set(LinearSizeFor(1) + kCodeIndex, *code); new_cache->set(kLinearUsageIndex, Smi::FromInt(LinearSizeFor(2))); return new_cache; } static Handle PutLinearElement(Isolate* isolate, Handle cache, Handle name, Handle code) { int length = cache->length(); int usage = GetLinearUsage(*cache); DCHECK_LE(usage, length); // Check if we need to grow. if (usage == length) { int new_length = LinearNewSize(length); if (new_length > kLinearMaxSize) return Handle::null(); Handle new_cache = isolate->factory()->NewFixedArray(new_length); for (int i = kLinearReservedSlots; i < length; i++) { new_cache->set(i, cache->get(i)); } cache = new_cache; } // Store new entry. DCHECK_GE(cache->length(), usage + kEntrySize); cache->set(usage + kNameIndex, *name); cache->set(usage + kCodeIndex, *code); cache->set(kLinearUsageIndex, Smi::FromInt(usage + kEntrySize)); return cache; } static Handle PutHashTableElement(Isolate* isolate, Handle cache, Handle name, Handle code) { // Check if we need to transition from linear to hash table storage. if (!cache->IsCodeCacheHashTable()) { // Check that the initial hash table capacity is large enough. DCHECK_EQ(kLinearMaxSize, LinearSizeFor(128)); STATIC_ASSERT(kHashTableInitialCapacity > 128); int length = cache->length(); // Only migrate from linear storage when it's full. DCHECK_EQ(length, GetLinearUsage(*cache)); DCHECK_EQ(length, kLinearMaxSize); Handle table = CodeCacheHashTable::New(isolate, kHashTableInitialCapacity); HandleScope scope(isolate); for (int i = kLinearReservedSlots; i < length; i += kEntrySize) { Handle old_name(Name::cast(cache->get(i + kNameIndex)), isolate); Handle old_code(Code::cast(cache->get(i + kCodeIndex)), isolate); CodeCacheHashTable::Put(table, old_name, old_code); } cache = table; } // Store new entry. DCHECK(cache->IsCodeCacheHashTable()); return CodeCacheHashTable::Put(Handle::cast(cache), name, code); } static inline int GetLinearUsage(FixedArray* linear_cache) { DCHECK_GT(linear_cache->length(), kEntrySize); return Smi::cast(linear_cache->get(kLinearUsageIndex))->value(); } }; void Map::UpdateCodeCache(Handle map, Handle name, Handle code) { Isolate* isolate = map->GetIsolate(); Handle cache(map->code_cache(), isolate); Handle new_cache = CodeCache::Put(isolate, cache, name, code); map->set_code_cache(*new_cache); } Code* Map::LookupInCodeCache(Name* name, Code::Flags flags) { return CodeCache::Lookup(code_cache(), name, flags); } // The key in the code cache hash table consists of the property name and the // code object. The actual match is on the name and the code flags. If a key // is created using the flags and not a code object it can only be used for // lookup not to create a new entry. class CodeCacheHashTableKey : public HashTableKey { public: CodeCacheHashTableKey(Handle name, Code::Flags flags) : name_(name), flags_(flags), code_() { DCHECK(name_->IsUniqueName()); } CodeCacheHashTableKey(Handle name, Handle code) : name_(name), flags_(code->flags()), code_(code) { DCHECK(name_->IsUniqueName()); } bool IsMatch(Object* other) override { DCHECK(other->IsFixedArray()); FixedArray* pair = FixedArray::cast(other); Name* name = Name::cast(pair->get(0)); Code::Flags flags = Code::cast(pair->get(1))->flags(); if (flags != flags_) return false; DCHECK(name->IsUniqueName()); return *name_ == name; } static uint32_t NameFlagsHashHelper(Name* name, Code::Flags flags) { return name->Hash() ^ flags; } uint32_t Hash() override { return NameFlagsHashHelper(*name_, flags_); } uint32_t HashForObject(Object* obj) override { FixedArray* pair = FixedArray::cast(obj); Name* name = Name::cast(pair->get(0)); Code* code = Code::cast(pair->get(1)); return NameFlagsHashHelper(name, code->flags()); } MUST_USE_RESULT Handle AsHandle(Isolate* isolate) override { Handle code = code_.ToHandleChecked(); Handle pair = isolate->factory()->NewFixedArray(2); pair->set(0, *name_); pair->set(1, *code); return pair; } private: Handle name_; Code::Flags flags_; // TODO(jkummerow): We should be able to get by without this. MaybeHandle code_; }; Handle CodeCacheHashTable::Put( Handle cache, Handle name, Handle code) { CodeCacheHashTableKey key(name, code); Handle new_cache = EnsureCapacity(cache, 1, &key); int entry = new_cache->FindInsertionEntry(key.Hash()); Handle k = key.AsHandle(cache->GetIsolate()); new_cache->set(EntryToIndex(entry), *k); new_cache->ElementAdded(); return new_cache; } Code* CodeCacheHashTable::Lookup(Name* name, Code::Flags flags) { DisallowHeapAllocation no_alloc; CodeCacheHashTableKey key(handle(name), flags); int entry = FindEntry(&key); if (entry == kNotFound) return nullptr; return Code::cast(FixedArray::cast(get(EntryToIndex(entry)))->get(1)); } Handle FixedArray::SetAndGrow(Handle array, int index, Handle value) { if (index < array->length()) { array->set(index, *value); return array; } int capacity = array->length(); do { capacity = JSObject::NewElementsCapacity(capacity); } while (capacity <= index); Handle new_array = array->GetIsolate()->factory()->NewUninitializedFixedArray(capacity); array->CopyTo(0, *new_array, 0, array->length()); new_array->FillWithHoles(array->length(), new_array->length()); new_array->set(index, *value); return new_array; } void FixedArray::Shrink(int new_length) { DCHECK(0 <= new_length && new_length <= length()); if (new_length < length()) { GetHeap()->RightTrimFixedArray(this, length() - new_length); } } void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) { DisallowHeapAllocation no_gc; WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc); for (int index = 0; index < len; index++) { dest->set(dest_pos+index, get(pos+index), mode); } } #ifdef DEBUG bool FixedArray::IsEqualTo(FixedArray* other) { if (length() != other->length()) return false; for (int i = 0 ; i < length(); ++i) { if (get(i) != other->get(i)) return false; } return true; } #endif // static void WeakFixedArray::Set(Handle array, int index, Handle value) { DCHECK(array->IsEmptySlot(index)); // Don't overwrite anything. Handle cell = value->IsMap() ? Map::WeakCellForMap(Handle::cast(value)) : array->GetIsolate()->factory()->NewWeakCell(value); Handle::cast(array)->set(index + kFirstIndex, *cell); if (FLAG_trace_weak_arrays) { PrintF("[WeakFixedArray: storing at index %d ]\n", index); } array->set_last_used_index(index); } // static Handle WeakFixedArray::Add(Handle maybe_array, Handle value, int* assigned_index) { Handle array = (maybe_array.is_null() || !maybe_array->IsWeakFixedArray()) ? Allocate(value->GetIsolate(), 1, Handle::null()) : Handle::cast(maybe_array); // Try to store the new entry if there's room. Optimize for consecutive // accesses. int first_index = array->last_used_index(); int length = array->Length(); if (length > 0) { for (int i = first_index;;) { if (array->IsEmptySlot((i))) { WeakFixedArray::Set(array, i, value); if (assigned_index != NULL) *assigned_index = i; return array; } if (FLAG_trace_weak_arrays) { PrintF("[WeakFixedArray: searching for free slot]\n"); } i = (i + 1) % length; if (i == first_index) break; } } // No usable slot found, grow the array. int new_length = length == 0 ? 1 : length + (length >> 1) + 4; Handle new_array = Allocate(array->GetIsolate(), new_length, array); if (FLAG_trace_weak_arrays) { PrintF("[WeakFixedArray: growing to size %d ]\n", new_length); } WeakFixedArray::Set(new_array, length, value); if (assigned_index != NULL) *assigned_index = length; return new_array; } template void WeakFixedArray::Compact() { FixedArray* array = FixedArray::cast(this); int new_length = kFirstIndex; for (int i = kFirstIndex; i < array->length(); i++) { Object* element = array->get(i); if (element->IsSmi()) continue; if (WeakCell::cast(element)->cleared()) continue; Object* value = WeakCell::cast(element)->value(); CompactionCallback::Callback(value, i - kFirstIndex, new_length - kFirstIndex); array->set(new_length++, element); } array->Shrink(new_length); set_last_used_index(0); } void WeakFixedArray::Iterator::Reset(Object* maybe_array) { if (maybe_array->IsWeakFixedArray()) { list_ = WeakFixedArray::cast(maybe_array); index_ = 0; #ifdef DEBUG last_used_index_ = list_->last_used_index(); #endif // DEBUG } } void JSObject::PrototypeRegistryCompactionCallback::Callback(Object* value, int old_index, int new_index) { DCHECK(value->IsMap() && Map::cast(value)->is_prototype_map()); Map* map = Map::cast(value); DCHECK(map->prototype_info()->IsPrototypeInfo()); PrototypeInfo* proto_info = PrototypeInfo::cast(map->prototype_info()); DCHECK_EQ(old_index, proto_info->registry_slot()); proto_info->set_registry_slot(new_index); } template void WeakFixedArray::Compact(); template void WeakFixedArray::Compact(); bool WeakFixedArray::Remove(Handle value) { if (Length() == 0) return false; // Optimize for the most recently added element to be removed again. int first_index = last_used_index(); for (int i = first_index;;) { if (Get(i) == *value) { Clear(i); // Users of WeakFixedArray should make sure that there are no duplicates. return true; } i = (i + 1) % Length(); if (i == first_index) return false; } UNREACHABLE(); } // static Handle WeakFixedArray::Allocate( Isolate* isolate, int size, Handle initialize_from) { DCHECK(0 <= size); Handle result = isolate->factory()->NewUninitializedFixedArray(size + kFirstIndex); int index = 0; if (!initialize_from.is_null()) { DCHECK(initialize_from->Length() <= size); Handle raw_source = Handle::cast(initialize_from); // Copy the entries without compacting, since the PrototypeInfo relies on // the index of the entries not to change. while (index < raw_source->length()) { result->set(index, raw_source->get(index)); index++; } } while (index < result->length()) { result->set(index, Smi::kZero); index++; } return Handle::cast(result); } Handle ArrayList::Add(Handle array, Handle obj, AddMode mode) { int length = array->Length(); array = EnsureSpace(array, length + 1); if (mode == kReloadLengthAfterAllocation) { DCHECK(array->Length() <= length); length = array->Length(); } array->Set(length, *obj); array->SetLength(length + 1); return array; } Handle ArrayList::Add(Handle array, Handle obj1, Handle obj2, AddMode mode) { int length = array->Length(); array = EnsureSpace(array, length + 2); if (mode == kReloadLengthAfterAllocation) { length = array->Length(); } array->Set(length, *obj1); array->Set(length + 1, *obj2); array->SetLength(length + 2); return array; } Handle ArrayList::New(Isolate* isolate, int size) { Handle result = Handle::cast( isolate->factory()->NewFixedArray(size + kFirstIndex)); result->SetLength(0); return result; } bool ArrayList::IsFull() { int capacity = length(); return kFirstIndex + Length() == capacity; } namespace { Handle EnsureSpaceInFixedArray(Handle array, int length) { int capacity = array->length(); if (capacity < length) { Isolate* isolate = array->GetIsolate(); int new_capacity = length; new_capacity = new_capacity + Max(new_capacity / 2, 2); int grow_by = new_capacity - capacity; array = Handle::cast( isolate->factory()->CopyFixedArrayAndGrow(array, grow_by)); } return array; } } // namespace Handle ArrayList::EnsureSpace(Handle array, int length) { const bool empty = (array->length() == 0); auto ret = Handle::cast( EnsureSpaceInFixedArray(array, kFirstIndex + length)); if (empty) ret->SetLength(0); return ret; } Handle RegExpMatchInfo::ReserveCaptures( Handle match_info, int capture_count) { DCHECK_GE(match_info->length(), kLastMatchOverhead); const int required_length = kFirstCaptureIndex + capture_count; Handle result = EnsureSpaceInFixedArray(match_info, required_length); return Handle::cast(result); } // static Handle FrameArray::AppendJSFrame(Handle in, Handle receiver, Handle function, Handle code, int offset, int flags) { const int frame_count = in->FrameCount(); const int new_length = LengthFor(frame_count + 1); Handle array = EnsureSpace(in, new_length); array->SetReceiver(frame_count, *receiver); array->SetFunction(frame_count, *function); array->SetCode(frame_count, *code); array->SetOffset(frame_count, Smi::FromInt(offset)); array->SetFlags(frame_count, Smi::FromInt(flags)); array->set(kFrameCountIndex, Smi::FromInt(frame_count + 1)); return array; } // static Handle FrameArray::AppendWasmFrame(Handle in, Handle wasm_instance, int wasm_function_index, Handle code, int offset, int flags) { const int frame_count = in->FrameCount(); const int new_length = LengthFor(frame_count + 1); Handle array = EnsureSpace(in, new_length); array->SetWasmInstance(frame_count, *wasm_instance); array->SetWasmFunctionIndex(frame_count, Smi::FromInt(wasm_function_index)); array->SetCode(frame_count, *code); array->SetOffset(frame_count, Smi::FromInt(offset)); array->SetFlags(frame_count, Smi::FromInt(flags)); array->set(kFrameCountIndex, Smi::FromInt(frame_count + 1)); return array; } void FrameArray::ShrinkToFit() { Shrink(LengthFor(FrameCount())); } // static Handle FrameArray::EnsureSpace(Handle array, int length) { return Handle::cast(EnsureSpaceInFixedArray(array, length)); } Handle DescriptorArray::Allocate(Isolate* isolate, int number_of_descriptors, int slack, PretenureFlag pretenure) { DCHECK(0 <= number_of_descriptors); Factory* factory = isolate->factory(); // Do not use DescriptorArray::cast on incomplete object. int size = number_of_descriptors + slack; if (size == 0) return factory->empty_descriptor_array(); // Allocate the array of keys. Handle result = factory->NewFixedArray(LengthFor(size), pretenure); result->set(kDescriptorLengthIndex, Smi::FromInt(number_of_descriptors)); result->set(kEnumCacheIndex, Smi::kZero); return Handle::cast(result); } void DescriptorArray::ClearEnumCache() { set(kEnumCacheIndex, Smi::kZero); } void DescriptorArray::Replace(int index, Descriptor* descriptor) { descriptor->SetSortedKeyIndex(GetSortedKeyIndex(index)); Set(index, descriptor); } // static void DescriptorArray::SetEnumCache(Handle descriptors, Isolate* isolate, Handle new_cache, Handle new_index_cache) { DCHECK(!descriptors->IsEmpty()); FixedArray* bridge_storage; bool needs_new_enum_cache = !descriptors->HasEnumCache(); if (needs_new_enum_cache) { bridge_storage = *isolate->factory()->NewFixedArray( DescriptorArray::kEnumCacheBridgeLength); } else { bridge_storage = FixedArray::cast(descriptors->get(kEnumCacheIndex)); } bridge_storage->set(kEnumCacheBridgeCacheIndex, *new_cache); bridge_storage->set( kEnumCacheBridgeIndicesCacheIndex, new_index_cache.is_null() ? Object::cast(Smi::kZero) : *new_index_cache); if (needs_new_enum_cache) { descriptors->set(kEnumCacheIndex, bridge_storage); } } void DescriptorArray::CopyFrom(int index, DescriptorArray* src) { PropertyDetails details = src->GetDetails(index); Set(index, src->GetKey(index), src->GetValue(index), details); } void DescriptorArray::Sort() { // In-place heap sort. int len = number_of_descriptors(); // Reset sorting since the descriptor array might contain invalid pointers. for (int i = 0; i < len; ++i) SetSortedKey(i, i); // Bottom-up max-heap construction. // Index of the last node with children const int max_parent_index = (len / 2) - 1; for (int i = max_parent_index; i >= 0; --i) { int parent_index = i; const uint32_t parent_hash = GetSortedKey(i)->Hash(); while (parent_index <= max_parent_index) { int child_index = 2 * parent_index + 1; uint32_t child_hash = GetSortedKey(child_index)->Hash(); if (child_index + 1 < len) { uint32_t right_child_hash = GetSortedKey(child_index + 1)->Hash(); if (right_child_hash > child_hash) { child_index++; child_hash = right_child_hash; } } if (child_hash <= parent_hash) break; SwapSortedKeys(parent_index, child_index); // Now element at child_index could be < its children. parent_index = child_index; // parent_hash remains correct. } } // Extract elements and create sorted array. for (int i = len - 1; i > 0; --i) { // Put max element at the back of the array. SwapSortedKeys(0, i); // Shift down the new top element. int parent_index = 0; const uint32_t parent_hash = GetSortedKey(parent_index)->Hash(); const int max_parent_index = (i / 2) - 1; while (parent_index <= max_parent_index) { int child_index = parent_index * 2 + 1; uint32_t child_hash = GetSortedKey(child_index)->Hash(); if (child_index + 1 < i) { uint32_t right_child_hash = GetSortedKey(child_index + 1)->Hash(); if (right_child_hash > child_hash) { child_index++; child_hash = right_child_hash; } } if (child_hash <= parent_hash) break; SwapSortedKeys(parent_index, child_index); parent_index = child_index; } } DCHECK(IsSortedNoDuplicates()); } Handle AccessorPair::Copy(Handle pair) { Handle copy = pair->GetIsolate()->factory()->NewAccessorPair(); copy->set_getter(pair->getter()); copy->set_setter(pair->setter()); return copy; } Handle AccessorPair::GetComponent(Handle accessor_pair, AccessorComponent component) { Object* accessor = accessor_pair->get(component); if (accessor->IsFunctionTemplateInfo()) { return ApiNatives::InstantiateFunction( handle(FunctionTemplateInfo::cast(accessor))) .ToHandleChecked(); } Isolate* isolate = accessor_pair->GetIsolate(); if (accessor->IsNull(isolate)) { return isolate->factory()->undefined_value(); } return handle(accessor, isolate); } Handle DeoptimizationInputData::New( Isolate* isolate, int deopt_entry_count, PretenureFlag pretenure) { return Handle::cast( isolate->factory()->NewFixedArray(LengthFor(deopt_entry_count), pretenure)); } Handle DeoptimizationOutputData::New( Isolate* isolate, int number_of_deopt_points, PretenureFlag pretenure) { Handle result; if (number_of_deopt_points == 0) { result = isolate->factory()->empty_fixed_array(); } else { result = isolate->factory()->NewFixedArray( LengthOfFixedArray(number_of_deopt_points), pretenure); } return Handle::cast(result); } SharedFunctionInfo* DeoptimizationInputData::GetInlinedFunction(int index) { if (index == -1) { return SharedFunctionInfo::cast(SharedFunctionInfo()); } else { return SharedFunctionInfo::cast(LiteralArray()->get(index)); } } int HandlerTable::LookupRange(int pc_offset, int* data_out, CatchPrediction* prediction_out) { int innermost_handler = -1; #ifdef DEBUG // Assuming that ranges are well nested, we don't need to track the innermost // offsets. This is just to verify that the table is actually well nested. int innermost_start = std::numeric_limits::min(); int innermost_end = std::numeric_limits::max(); #endif for (int i = 0; i < length(); i += kRangeEntrySize) { int start_offset = Smi::cast(get(i + kRangeStartIndex))->value(); int end_offset = Smi::cast(get(i + kRangeEndIndex))->value(); int handler_field = Smi::cast(get(i + kRangeHandlerIndex))->value(); int handler_offset = HandlerOffsetField::decode(handler_field); CatchPrediction prediction = HandlerPredictionField::decode(handler_field); int handler_data = Smi::cast(get(i + kRangeDataIndex))->value(); if (pc_offset >= start_offset && pc_offset < end_offset) { DCHECK_GE(start_offset, innermost_start); DCHECK_LT(end_offset, innermost_end); innermost_handler = handler_offset; #ifdef DEBUG innermost_start = start_offset; innermost_end = end_offset; #endif if (data_out) *data_out = handler_data; if (prediction_out) *prediction_out = prediction; } } return innermost_handler; } // TODO(turbofan): Make sure table is sorted and use binary search. int HandlerTable::LookupReturn(int pc_offset) { for (int i = 0; i < length(); i += kReturnEntrySize) { int return_offset = Smi::cast(get(i + kReturnOffsetIndex))->value(); int handler_field = Smi::cast(get(i + kReturnHandlerIndex))->value(); if (pc_offset == return_offset) { return HandlerOffsetField::decode(handler_field); } } return -1; } #ifdef DEBUG bool DescriptorArray::IsEqualTo(DescriptorArray* other) { if (IsEmpty()) return other->IsEmpty(); if (other->IsEmpty()) return false; if (length() != other->length()) return false; for (int i = 0; i < length(); ++i) { if (get(i) != other->get(i)) return false; } return true; } #endif // static Handle String::Trim(Handle string, TrimMode mode) { Isolate* const isolate = string->GetIsolate(); string = String::Flatten(string); int const length = string->length(); // Perform left trimming if requested. int left = 0; UnicodeCache* unicode_cache = isolate->unicode_cache(); if (mode == kTrim || mode == kTrimLeft) { while (left < length && unicode_cache->IsWhiteSpaceOrLineTerminator(string->Get(left))) { left++; } } // Perform right trimming if requested. int right = length; if (mode == kTrim || mode == kTrimRight) { while ( right > left && unicode_cache->IsWhiteSpaceOrLineTerminator(string->Get(right - 1))) { right--; } } return isolate->factory()->NewSubString(string, left, right); } bool String::LooksValid() { return GetIsolate()->heap()->Contains(this); } // static MaybeHandle Name::ToFunctionName(Handle name) { if (name->IsString()) return Handle::cast(name); // ES6 section 9.2.11 SetFunctionName, step 4. Isolate* const isolate = name->GetIsolate(); Handle description(Handle::cast(name)->name(), isolate); if (description->IsUndefined(isolate)) { return isolate->factory()->empty_string(); } IncrementalStringBuilder builder(isolate); builder.AppendCharacter('['); builder.AppendString(Handle::cast(description)); builder.AppendCharacter(']'); return builder.Finish(); } // static MaybeHandle Name::ToFunctionName(Handle name, Handle prefix) { Handle name_string; Isolate* const isolate = name->GetIsolate(); ASSIGN_RETURN_ON_EXCEPTION(isolate, name_string, ToFunctionName(name), String); IncrementalStringBuilder builder(isolate); builder.AppendString(prefix); builder.AppendCharacter(' '); builder.AppendString(name_string); return builder.Finish(); } namespace { bool AreDigits(const uint8_t* s, int from, int to) { for (int i = from; i < to; i++) { if (s[i] < '0' || s[i] > '9') return false; } return true; } int ParseDecimalInteger(const uint8_t* s, int from, int to) { DCHECK(to - from < 10); // Overflow is not possible. DCHECK(from < to); int d = s[from] - '0'; for (int i = from + 1; i < to; i++) { d = 10 * d + (s[i] - '0'); } return d; } } // namespace // static Handle String::ToNumber(Handle subject) { Isolate* const isolate = subject->GetIsolate(); // Flatten {subject} string first. subject = String::Flatten(subject); // Fast array index case. uint32_t index; if (subject->AsArrayIndex(&index)) { return isolate->factory()->NewNumberFromUint(index); } // Fast case: short integer or some sorts of junk values. if (subject->IsSeqOneByteString()) { int len = subject->length(); if (len == 0) return handle(Smi::kZero, isolate); DisallowHeapAllocation no_gc; uint8_t const* data = Handle::cast(subject)->GetChars(); bool minus = (data[0] == '-'); int start_pos = (minus ? 1 : 0); if (start_pos == len) { return isolate->factory()->nan_value(); } else if (data[start_pos] > '9') { // Fast check for a junk value. A valid string may start from a // whitespace, a sign ('+' or '-'), the decimal point, a decimal digit // or the 'I' character ('Infinity'). All of that have codes not greater // than '9' except 'I' and  . if (data[start_pos] != 'I' && data[start_pos] != 0xa0) { return isolate->factory()->nan_value(); } } else if (len - start_pos < 10 && AreDigits(data, start_pos, len)) { // The maximal/minimal smi has 10 digits. If the string has less digits // we know it will fit into the smi-data type. int d = ParseDecimalInteger(data, start_pos, len); if (minus) { if (d == 0) return isolate->factory()->minus_zero_value(); d = -d; } else if (!subject->HasHashCode() && len <= String::kMaxArrayIndexSize && (len == 1 || data[0] != '0')) { // String hash is not calculated yet but all the data are present. // Update the hash field to speed up sequential convertions. uint32_t hash = StringHasher::MakeArrayIndexHash(d, len); #ifdef DEBUG subject->Hash(); // Force hash calculation. DCHECK_EQ(static_cast(subject->hash_field()), static_cast(hash)); #endif subject->set_hash_field(hash); } return handle(Smi::FromInt(d), isolate); } } // Slower case. int flags = ALLOW_HEX | ALLOW_OCTAL | ALLOW_BINARY; return isolate->factory()->NewNumber( StringToDouble(isolate->unicode_cache(), subject, flags)); } String::FlatContent String::GetFlatContent() { DCHECK(!AllowHeapAllocation::IsAllowed()); int length = this->length(); StringShape shape(this); String* string = this; int offset = 0; if (shape.representation_tag() == kConsStringTag) { ConsString* cons = ConsString::cast(string); if (cons->second()->length() != 0) { return FlatContent(); } string = cons->first(); shape = StringShape(string); } else if (shape.representation_tag() == kSlicedStringTag) { SlicedString* slice = SlicedString::cast(string); offset = slice->offset(); string = slice->parent(); shape = StringShape(string); DCHECK(shape.representation_tag() != kConsStringTag && shape.representation_tag() != kSlicedStringTag); } if (shape.representation_tag() == kThinStringTag) { ThinString* thin = ThinString::cast(string); string = thin->actual(); shape = StringShape(string); DCHECK(!shape.IsCons()); DCHECK(!shape.IsSliced()); } if (shape.encoding_tag() == kOneByteStringTag) { const uint8_t* start; if (shape.representation_tag() == kSeqStringTag) { start = SeqOneByteString::cast(string)->GetChars(); } else { start = ExternalOneByteString::cast(string)->GetChars(); } return FlatContent(start + offset, length); } else { DCHECK(shape.encoding_tag() == kTwoByteStringTag); const uc16* start; if (shape.representation_tag() == kSeqStringTag) { start = SeqTwoByteString::cast(string)->GetChars(); } else { start = ExternalTwoByteString::cast(string)->GetChars(); } return FlatContent(start + offset, length); } } std::unique_ptr String::ToCString(AllowNullsFlag allow_nulls, RobustnessFlag robust_flag, int offset, int length, int* length_return) { if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) { return std::unique_ptr(); } // Negative length means the to the end of the string. if (length < 0) length = kMaxInt - offset; // Compute the size of the UTF-8 string. Start at the specified offset. StringCharacterStream stream(this, offset); int character_position = offset; int utf8_bytes = 0; int last = unibrow::Utf16::kNoPreviousCharacter; while (stream.HasMore() && character_position++ < offset + length) { uint16_t character = stream.GetNext(); utf8_bytes += unibrow::Utf8::Length(character, last); last = character; } if (length_return) { *length_return = utf8_bytes; } char* result = NewArray(utf8_bytes + 1); // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset. stream.Reset(this, offset); character_position = offset; int utf8_byte_position = 0; last = unibrow::Utf16::kNoPreviousCharacter; while (stream.HasMore() && character_position++ < offset + length) { uint16_t character = stream.GetNext(); if (allow_nulls == DISALLOW_NULLS && character == 0) { character = ' '; } utf8_byte_position += unibrow::Utf8::Encode(result + utf8_byte_position, character, last); last = character; } result[utf8_byte_position] = 0; return std::unique_ptr(result); } std::unique_ptr String::ToCString(AllowNullsFlag allow_nulls, RobustnessFlag robust_flag, int* length_return) { return ToCString(allow_nulls, robust_flag, 0, -1, length_return); } const uc16* String::GetTwoByteData(unsigned start) { DCHECK(!IsOneByteRepresentationUnderneath()); switch (StringShape(this).representation_tag()) { case kSeqStringTag: return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start); case kExternalStringTag: return ExternalTwoByteString::cast(this)-> ExternalTwoByteStringGetData(start); case kSlicedStringTag: { SlicedString* slice = SlicedString::cast(this); return slice->parent()->GetTwoByteData(start + slice->offset()); } case kConsStringTag: case kThinStringTag: UNREACHABLE(); return NULL; } UNREACHABLE(); return NULL; } const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) { return reinterpret_cast( reinterpret_cast(this) - kHeapObjectTag + kHeaderSize) + start; } void Relocatable::PostGarbageCollectionProcessing(Isolate* isolate) { Relocatable* current = isolate->relocatable_top(); while (current != NULL) { current->PostGarbageCollection(); current = current->prev_; } } // Reserve space for statics needing saving and restoring. int Relocatable::ArchiveSpacePerThread() { return sizeof(Relocatable*); // NOLINT } // Archive statics that are thread-local. char* Relocatable::ArchiveState(Isolate* isolate, char* to) { *reinterpret_cast(to) = isolate->relocatable_top(); isolate->set_relocatable_top(NULL); return to + ArchiveSpacePerThread(); } // Restore statics that are thread-local. char* Relocatable::RestoreState(Isolate* isolate, char* from) { isolate->set_relocatable_top(*reinterpret_cast(from)); return from + ArchiveSpacePerThread(); } char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) { Relocatable* top = *reinterpret_cast(thread_storage); Iterate(v, top); return thread_storage + ArchiveSpacePerThread(); } void Relocatable::Iterate(Isolate* isolate, ObjectVisitor* v) { Iterate(v, isolate->relocatable_top()); } void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) { Relocatable* current = top; while (current != NULL) { current->IterateInstance(v); current = current->prev_; } } FlatStringReader::FlatStringReader(Isolate* isolate, Handle str) : Relocatable(isolate), str_(str.location()), length_(str->length()) { PostGarbageCollection(); } FlatStringReader::FlatStringReader(Isolate* isolate, Vector input) : Relocatable(isolate), str_(0), is_one_byte_(true), length_(input.length()), start_(input.start()) {} void FlatStringReader::PostGarbageCollection() { if (str_ == NULL) return; Handle str(str_); DCHECK(str->IsFlat()); DisallowHeapAllocation no_gc; // This does not actually prevent the vector from being relocated later. String::FlatContent content = str->GetFlatContent(); DCHECK(content.IsFlat()); is_one_byte_ = content.IsOneByte(); if (is_one_byte_) { start_ = content.ToOneByteVector().start(); } else { start_ = content.ToUC16Vector().start(); } } void ConsStringIterator::Initialize(ConsString* cons_string, int offset) { DCHECK(cons_string != NULL); root_ = cons_string; consumed_ = offset; // Force stack blown condition to trigger restart. depth_ = 1; maximum_depth_ = kStackSize + depth_; DCHECK(StackBlown()); } String* ConsStringIterator::Continue(int* offset_out) { DCHECK(depth_ != 0); DCHECK_EQ(0, *offset_out); bool blew_stack = StackBlown(); String* string = NULL; // Get the next leaf if there is one. if (!blew_stack) string = NextLeaf(&blew_stack); // Restart search from root. if (blew_stack) { DCHECK(string == NULL); string = Search(offset_out); } // Ensure future calls return null immediately. if (string == NULL) Reset(NULL); return string; } String* ConsStringIterator::Search(int* offset_out) { ConsString* cons_string = root_; // Reset the stack, pushing the root string. depth_ = 1; maximum_depth_ = 1; frames_[0] = cons_string; const int consumed = consumed_; int offset = 0; while (true) { // Loop until the string is found which contains the target offset. String* string = cons_string->first(); int length = string->length(); int32_t type; if (consumed < offset + length) { // Target offset is in the left branch. // Keep going if we're still in a ConString. type = string->map()->instance_type(); if ((type & kStringRepresentationMask) == kConsStringTag) { cons_string = ConsString::cast(string); PushLeft(cons_string); continue; } // Tell the stack we're done descending. AdjustMaximumDepth(); } else { // Descend right. // Update progress through the string. offset += length; // Keep going if we're still in a ConString. string = cons_string->second(); type = string->map()->instance_type(); if ((type & kStringRepresentationMask) == kConsStringTag) { cons_string = ConsString::cast(string); PushRight(cons_string); continue; } // Need this to be updated for the current string. length = string->length(); // Account for the possibility of an empty right leaf. // This happens only if we have asked for an offset outside the string. if (length == 0) { // Reset so future operations will return null immediately. Reset(NULL); return NULL; } // Tell the stack we're done descending. AdjustMaximumDepth(); // Pop stack so next iteration is in correct place. Pop(); } DCHECK(length != 0); // Adjust return values and exit. consumed_ = offset + length; *offset_out = consumed - offset; return string; } UNREACHABLE(); return NULL; } String* ConsStringIterator::NextLeaf(bool* blew_stack) { while (true) { // Tree traversal complete. if (depth_ == 0) { *blew_stack = false; return NULL; } // We've lost track of higher nodes. if (StackBlown()) { *blew_stack = true; return NULL; } // Go right. ConsString* cons_string = frames_[OffsetForDepth(depth_ - 1)]; String* string = cons_string->second(); int32_t type = string->map()->instance_type(); if ((type & kStringRepresentationMask) != kConsStringTag) { // Pop stack so next iteration is in correct place. Pop(); int length = string->length(); // Could be a flattened ConsString. if (length == 0) continue; consumed_ += length; return string; } cons_string = ConsString::cast(string); PushRight(cons_string); // Need to traverse all the way left. while (true) { // Continue left. string = cons_string->first(); type = string->map()->instance_type(); if ((type & kStringRepresentationMask) != kConsStringTag) { AdjustMaximumDepth(); int length = string->length(); if (length == 0) break; // Skip empty left-hand sides of ConsStrings. consumed_ += length; return string; } cons_string = ConsString::cast(string); PushLeft(cons_string); } } UNREACHABLE(); return NULL; } uint16_t ConsString::ConsStringGet(int index) { DCHECK(index >= 0 && index < this->length()); // Check for a flattened cons string if (second()->length() == 0) { String* left = first(); return left->Get(index); } String* string = String::cast(this); while (true) { if (StringShape(string).IsCons()) { ConsString* cons_string = ConsString::cast(string); String* left = cons_string->first(); if (left->length() > index) { string = left; } else { index -= left->length(); string = cons_string->second(); } } else { return string->Get(index); } } UNREACHABLE(); return 0; } uint16_t ThinString::ThinStringGet(int index) { return actual()->Get(index); } uint16_t SlicedString::SlicedStringGet(int index) { return parent()->Get(offset() + index); } template void String::WriteToFlat(String* src, sinkchar* sink, int f, int t) { String* source = src; int from = f; int to = t; while (true) { DCHECK(0 <= from && from <= to && to <= source->length()); switch (StringShape(source).full_representation_tag()) { case kOneByteStringTag | kExternalStringTag: { CopyChars(sink, ExternalOneByteString::cast(source)->GetChars() + from, to - from); return; } case kTwoByteStringTag | kExternalStringTag: { const uc16* data = ExternalTwoByteString::cast(source)->GetChars(); CopyChars(sink, data + from, to - from); return; } case kOneByteStringTag | kSeqStringTag: { CopyChars(sink, SeqOneByteString::cast(source)->GetChars() + from, to - from); return; } case kTwoByteStringTag | kSeqStringTag: { CopyChars(sink, SeqTwoByteString::cast(source)->GetChars() + from, to - from); return; } case kOneByteStringTag | kConsStringTag: case kTwoByteStringTag | kConsStringTag: { ConsString* cons_string = ConsString::cast(source); String* first = cons_string->first(); int boundary = first->length(); if (to - boundary >= boundary - from) { // Right hand side is longer. Recurse over left. if (from < boundary) { WriteToFlat(first, sink, from, boundary); if (from == 0 && cons_string->second() == first) { CopyChars(sink + boundary, sink, boundary); return; } sink += boundary - from; from = 0; } else { from -= boundary; } to -= boundary; source = cons_string->second(); } else { // Left hand side is longer. Recurse over right. if (to > boundary) { String* second = cons_string->second(); // When repeatedly appending to a string, we get a cons string that // is unbalanced to the left, a list, essentially. We inline the // common case of sequential one-byte right child. if (to - boundary == 1) { sink[boundary - from] = static_cast(second->Get(0)); } else if (second->IsSeqOneByteString()) { CopyChars(sink + boundary - from, SeqOneByteString::cast(second)->GetChars(), to - boundary); } else { WriteToFlat(second, sink + boundary - from, 0, to - boundary); } to = boundary; } source = first; } break; } case kOneByteStringTag | kSlicedStringTag: case kTwoByteStringTag | kSlicedStringTag: { SlicedString* slice = SlicedString::cast(source); unsigned offset = slice->offset(); WriteToFlat(slice->parent(), sink, from + offset, to + offset); return; } case kOneByteStringTag | kThinStringTag: case kTwoByteStringTag | kThinStringTag: source = ThinString::cast(source)->actual(); break; } } } template static void CalculateLineEndsImpl(Isolate* isolate, List* line_ends, Vector src, bool include_ending_line) { const int src_len = src.length(); UnicodeCache* cache = isolate->unicode_cache(); for (int i = 0; i < src_len - 1; i++) { SourceChar current = src[i]; SourceChar next = src[i + 1]; if (cache->IsLineTerminatorSequence(current, next)) line_ends->Add(i); } if (src_len > 0 && cache->IsLineTerminatorSequence(src[src_len - 1], 0)) { line_ends->Add(src_len - 1); } if (include_ending_line) { // Include one character beyond the end of script. The rewriter uses that // position for the implicit return statement. line_ends->Add(src_len); } } Handle String::CalculateLineEnds(Handle src, bool include_ending_line) { src = Flatten(src); // Rough estimate of line count based on a roughly estimated average // length of (unpacked) code. int line_count_estimate = src->length() >> 4; List line_ends(line_count_estimate); Isolate* isolate = src->GetIsolate(); { DisallowHeapAllocation no_allocation; // ensure vectors stay valid. // Dispatch on type of strings. String::FlatContent content = src->GetFlatContent(); DCHECK(content.IsFlat()); if (content.IsOneByte()) { CalculateLineEndsImpl(isolate, &line_ends, content.ToOneByteVector(), include_ending_line); } else { CalculateLineEndsImpl(isolate, &line_ends, content.ToUC16Vector(), include_ending_line); } } int line_count = line_ends.length(); Handle array = isolate->factory()->NewFixedArray(line_count); for (int i = 0; i < line_count; i++) { array->set(i, Smi::FromInt(line_ends[i])); } return array; } // Compares the contents of two strings by reading and comparing // int-sized blocks of characters. template static inline bool CompareRawStringContents(const Char* const a, const Char* const b, int length) { return CompareChars(a, b, length) == 0; } template class RawStringComparator : public AllStatic { public: static inline bool compare(const Chars1* a, const Chars2* b, int len) { DCHECK(sizeof(Chars1) != sizeof(Chars2)); for (int i = 0; i < len; i++) { if (a[i] != b[i]) { return false; } } return true; } }; template<> class RawStringComparator { public: static inline bool compare(const uint16_t* a, const uint16_t* b, int len) { return CompareRawStringContents(a, b, len); } }; template<> class RawStringComparator { public: static inline bool compare(const uint8_t* a, const uint8_t* b, int len) { return CompareRawStringContents(a, b, len); } }; class StringComparator { class State { public: State() : is_one_byte_(true), length_(0), buffer8_(NULL) {} void Init(String* string) { ConsString* cons_string = String::VisitFlat(this, string); iter_.Reset(cons_string); if (cons_string != NULL) { int offset; string = iter_.Next(&offset); String::VisitFlat(this, string, offset); } } inline void VisitOneByteString(const uint8_t* chars, int length) { is_one_byte_ = true; buffer8_ = chars; length_ = length; } inline void VisitTwoByteString(const uint16_t* chars, int length) { is_one_byte_ = false; buffer16_ = chars; length_ = length; } void Advance(int consumed) { DCHECK(consumed <= length_); // Still in buffer. if (length_ != consumed) { if (is_one_byte_) { buffer8_ += consumed; } else { buffer16_ += consumed; } length_ -= consumed; return; } // Advance state. int offset; String* next = iter_.Next(&offset); DCHECK_EQ(0, offset); DCHECK(next != NULL); String::VisitFlat(this, next); } ConsStringIterator iter_; bool is_one_byte_; int length_; union { const uint8_t* buffer8_; const uint16_t* buffer16_; }; private: DISALLOW_COPY_AND_ASSIGN(State); }; public: inline StringComparator() {} template static inline bool Equals(State* state_1, State* state_2, int to_check) { const Chars1* a = reinterpret_cast(state_1->buffer8_); const Chars2* b = reinterpret_cast(state_2->buffer8_); return RawStringComparator::compare(a, b, to_check); } bool Equals(String* string_1, String* string_2) { int length = string_1->length(); state_1_.Init(string_1); state_2_.Init(string_2); while (true) { int to_check = Min(state_1_.length_, state_2_.length_); DCHECK(to_check > 0 && to_check <= length); bool is_equal; if (state_1_.is_one_byte_) { if (state_2_.is_one_byte_) { is_equal = Equals(&state_1_, &state_2_, to_check); } else { is_equal = Equals(&state_1_, &state_2_, to_check); } } else { if (state_2_.is_one_byte_) { is_equal = Equals(&state_1_, &state_2_, to_check); } else { is_equal = Equals(&state_1_, &state_2_, to_check); } } // Looping done. if (!is_equal) return false; length -= to_check; // Exit condition. Strings are equal. if (length == 0) return true; state_1_.Advance(to_check); state_2_.Advance(to_check); } } private: State state_1_; State state_2_; DISALLOW_COPY_AND_ASSIGN(StringComparator); }; bool String::SlowEquals(String* other) { DisallowHeapAllocation no_gc; // Fast check: negative check with lengths. int len = length(); if (len != other->length()) return false; if (len == 0) return true; // Fast check: if at least one ThinString is involved, dereference it/them // and restart. if (this->IsThinString() || other->IsThinString()) { if (other->IsThinString()) other = ThinString::cast(other)->actual(); if (this->IsThinString()) { return ThinString::cast(this)->actual()->Equals(other); } else { return this->Equals(other); } } // Fast check: if hash code is computed for both strings // a fast negative check can be performed. if (HasHashCode() && other->HasHashCode()) { #ifdef ENABLE_SLOW_DCHECKS if (FLAG_enable_slow_asserts) { if (Hash() != other->Hash()) { bool found_difference = false; for (int i = 0; i < len; i++) { if (Get(i) != other->Get(i)) { found_difference = true; break; } } DCHECK(found_difference); } } #endif if (Hash() != other->Hash()) return false; } // We know the strings are both non-empty. Compare the first chars // before we try to flatten the strings. if (this->Get(0) != other->Get(0)) return false; if (IsSeqOneByteString() && other->IsSeqOneByteString()) { const uint8_t* str1 = SeqOneByteString::cast(this)->GetChars(); const uint8_t* str2 = SeqOneByteString::cast(other)->GetChars(); return CompareRawStringContents(str1, str2, len); } StringComparator comparator; return comparator.Equals(this, other); } bool String::SlowEquals(Handle one, Handle two) { // Fast check: negative check with lengths. int one_length = one->length(); if (one_length != two->length()) return false; if (one_length == 0) return true; // Fast check: if at least one ThinString is involved, dereference it/them // and restart. if (one->IsThinString() || two->IsThinString()) { if (one->IsThinString()) one = handle(ThinString::cast(*one)->actual()); if (two->IsThinString()) two = handle(ThinString::cast(*two)->actual()); return String::Equals(one, two); } // Fast check: if hash code is computed for both strings // a fast negative check can be performed. if (one->HasHashCode() && two->HasHashCode()) { #ifdef ENABLE_SLOW_DCHECKS if (FLAG_enable_slow_asserts) { if (one->Hash() != two->Hash()) { bool found_difference = false; for (int i = 0; i < one_length; i++) { if (one->Get(i) != two->Get(i)) { found_difference = true; break; } } DCHECK(found_difference); } } #endif if (one->Hash() != two->Hash()) return false; } // We know the strings are both non-empty. Compare the first chars // before we try to flatten the strings. if (one->Get(0) != two->Get(0)) return false; one = String::Flatten(one); two = String::Flatten(two); DisallowHeapAllocation no_gc; String::FlatContent flat1 = one->GetFlatContent(); String::FlatContent flat2 = two->GetFlatContent(); if (flat1.IsOneByte() && flat2.IsOneByte()) { return CompareRawStringContents(flat1.ToOneByteVector().start(), flat2.ToOneByteVector().start(), one_length); } else { for (int i = 0; i < one_length; i++) { if (flat1.Get(i) != flat2.Get(i)) return false; } return true; } } // static ComparisonResult String::Compare(Handle x, Handle y) { // A few fast case tests before we flatten. if (x.is_identical_to(y)) { return ComparisonResult::kEqual; } else if (y->length() == 0) { return x->length() == 0 ? ComparisonResult::kEqual : ComparisonResult::kGreaterThan; } else if (x->length() == 0) { return ComparisonResult::kLessThan; } int const d = x->Get(0) - y->Get(0); if (d < 0) { return ComparisonResult::kLessThan; } else if (d > 0) { return ComparisonResult::kGreaterThan; } // Slow case. x = String::Flatten(x); y = String::Flatten(y); DisallowHeapAllocation no_gc; ComparisonResult result = ComparisonResult::kEqual; int prefix_length = x->length(); if (y->length() < prefix_length) { prefix_length = y->length(); result = ComparisonResult::kGreaterThan; } else if (y->length() > prefix_length) { result = ComparisonResult::kLessThan; } int r; String::FlatContent x_content = x->GetFlatContent(); String::FlatContent y_content = y->GetFlatContent(); if (x_content.IsOneByte()) { Vector x_chars = x_content.ToOneByteVector(); if (y_content.IsOneByte()) { Vector y_chars = y_content.ToOneByteVector(); r = CompareChars(x_chars.start(), y_chars.start(), prefix_length); } else { Vector y_chars = y_content.ToUC16Vector(); r = CompareChars(x_chars.start(), y_chars.start(), prefix_length); } } else { Vector x_chars = x_content.ToUC16Vector(); if (y_content.IsOneByte()) { Vector y_chars = y_content.ToOneByteVector(); r = CompareChars(x_chars.start(), y_chars.start(), prefix_length); } else { Vector y_chars = y_content.ToUC16Vector(); r = CompareChars(x_chars.start(), y_chars.start(), prefix_length); } } if (r < 0) { result = ComparisonResult::kLessThan; } else if (r > 0) { result = ComparisonResult::kGreaterThan; } return result; } Object* String::IndexOf(Isolate* isolate, Handle receiver, Handle search, Handle position) { if (receiver->IsNullOrUndefined(isolate)) { THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError(MessageTemplate::kCalledOnNullOrUndefined, isolate->factory()->NewStringFromAsciiChecked( "String.prototype.indexOf"))); } Handle receiver_string; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver_string, Object::ToString(isolate, receiver)); Handle search_string; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, search_string, Object::ToString(isolate, search)); ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position, Object::ToInteger(isolate, position)); uint32_t index = receiver_string->ToValidIndex(*position); return Smi::FromInt( String::IndexOf(isolate, receiver_string, search_string, index)); } namespace { template int SearchString(Isolate* isolate, String::FlatContent receiver_content, Vector pat_vector, int start_index) { if (receiver_content.IsOneByte()) { return SearchString(isolate, receiver_content.ToOneByteVector(), pat_vector, start_index); } return SearchString(isolate, receiver_content.ToUC16Vector(), pat_vector, start_index); } } // namespace int String::IndexOf(Isolate* isolate, Handle receiver, Handle search, int start_index) { DCHECK(0 <= start_index); DCHECK(start_index <= receiver->length()); uint32_t search_length = search->length(); if (search_length == 0) return start_index; uint32_t receiver_length = receiver->length(); if (start_index + search_length > receiver_length) return -1; receiver = String::Flatten(receiver); search = String::Flatten(search); DisallowHeapAllocation no_gc; // ensure vectors stay valid // Extract flattened substrings of cons strings before getting encoding. String::FlatContent receiver_content = receiver->GetFlatContent(); String::FlatContent search_content = search->GetFlatContent(); // dispatch on type of strings if (search_content.IsOneByte()) { Vector pat_vector = search_content.ToOneByteVector(); return SearchString(isolate, receiver_content, pat_vector, start_index); } Vector pat_vector = search_content.ToUC16Vector(); return SearchString(isolate, receiver_content, pat_vector, start_index); } MaybeHandle String::GetSubstitution(Isolate* isolate, Match* match, Handle replacement) { Factory* factory = isolate->factory(); const int replacement_length = replacement->length(); const int captures_length = match->CaptureCount(); replacement = String::Flatten(replacement); Handle dollar_string = factory->LookupSingleCharacterStringFromCode('$'); int next = String::IndexOf(isolate, replacement, dollar_string, 0); if (next < 0) { return replacement; } IncrementalStringBuilder builder(isolate); if (next > 0) { builder.AppendString(factory->NewSubString(replacement, 0, next)); } while (true) { int pos = next + 1; if (pos < replacement_length) { const uint16_t peek = replacement->Get(pos); if (peek == '$') { // $$ pos++; builder.AppendCharacter('$'); } else if (peek == '&') { // $& - match pos++; builder.AppendString(match->GetMatch()); } else if (peek == '`') { // $` - prefix pos++; builder.AppendString(match->GetPrefix()); } else if (peek == '\'') { // $' - suffix pos++; builder.AppendString(match->GetSuffix()); } else if (peek >= '0' && peek <= '9') { // Valid indices are $1 .. $9, $01 .. $09 and $10 .. $99 int scaled_index = (peek - '0'); int advance = 1; if (pos + 1 < replacement_length) { const uint16_t next_peek = replacement->Get(pos + 1); if (next_peek >= '0' && next_peek <= '9') { const int new_scaled_index = scaled_index * 10 + (next_peek - '0'); if (new_scaled_index < captures_length) { scaled_index = new_scaled_index; advance = 2; } } } if (scaled_index != 0 && scaled_index < captures_length) { bool capture_exists; Handle capture; ASSIGN_RETURN_ON_EXCEPTION( isolate, capture, match->GetCapture(scaled_index, &capture_exists), String); if (capture_exists) builder.AppendString(capture); pos += advance; } else { builder.AppendCharacter('$'); } } else { builder.AppendCharacter('$'); } } else { builder.AppendCharacter('$'); } // Go the the next $ in the replacement. next = String::IndexOf(isolate, replacement, dollar_string, pos); // Return if there are no more $ characters in the replacement. If we // haven't reached the end, we need to append the suffix. if (next < 0) { if (pos < replacement_length) { builder.AppendString( factory->NewSubString(replacement, pos, replacement_length)); } return builder.Finish(); } // Append substring between the previous and the next $ character. if (next > pos) { builder.AppendString(factory->NewSubString(replacement, pos, next)); } } UNREACHABLE(); return MaybeHandle(); } namespace { // for String.Prototype.lastIndexOf template int StringMatchBackwards(Vector subject, Vector pattern, int idx) { int pattern_length = pattern.length(); DCHECK(pattern_length >= 1); DCHECK(idx + pattern_length <= subject.length()); if (sizeof(schar) == 1 && sizeof(pchar) > 1) { for (int i = 0; i < pattern_length; i++) { uc16 c = pattern[i]; if (c > String::kMaxOneByteCharCode) { return -1; } } } pchar pattern_first_char = pattern[0]; for (int i = idx; i >= 0; i--) { if (subject[i] != pattern_first_char) continue; int j = 1; while (j < pattern_length) { if (pattern[j] != subject[i + j]) { break; } j++; } if (j == pattern_length) { return i; } } return -1; } } // namespace Object* String::LastIndexOf(Isolate* isolate, Handle receiver, Handle search, Handle position) { if (receiver->IsNullOrUndefined(isolate)) { THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewTypeError(MessageTemplate::kCalledOnNullOrUndefined, isolate->factory()->NewStringFromAsciiChecked( "String.prototype.lastIndexOf"))); } Handle receiver_string; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver_string, Object::ToString(isolate, receiver)); Handle search_string; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, search_string, Object::ToString(isolate, search)); ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position, Object::ToNumber(position)); uint32_t start_index; if (position->IsNaN()) { start_index = receiver_string->length(); } else { ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position, Object::ToInteger(isolate, position)); start_index = receiver_string->ToValidIndex(*position); } uint32_t pattern_length = search_string->length(); uint32_t receiver_length = receiver_string->length(); if (start_index + pattern_length > receiver_length) { start_index = receiver_length - pattern_length; } if (pattern_length == 0) { return Smi::FromInt(start_index); } receiver_string = String::Flatten(receiver_string); search_string = String::Flatten(search_string); int last_index = -1; DisallowHeapAllocation no_gc; // ensure vectors stay valid String::FlatContent receiver_content = receiver_string->GetFlatContent(); String::FlatContent search_content = search_string->GetFlatContent(); if (search_content.IsOneByte()) { Vector pat_vector = search_content.ToOneByteVector(); if (receiver_content.IsOneByte()) { last_index = StringMatchBackwards(receiver_content.ToOneByteVector(), pat_vector, start_index); } else { last_index = StringMatchBackwards(receiver_content.ToUC16Vector(), pat_vector, start_index); } } else { Vector pat_vector = search_content.ToUC16Vector(); if (receiver_content.IsOneByte()) { last_index = StringMatchBackwards(receiver_content.ToOneByteVector(), pat_vector, start_index); } else { last_index = StringMatchBackwards(receiver_content.ToUC16Vector(), pat_vector, start_index); } } return Smi::FromInt(last_index); } bool String::IsUtf8EqualTo(Vector str, bool allow_prefix_match) { int slen = length(); // Can't check exact length equality, but we can check bounds. int str_len = str.length(); if (!allow_prefix_match && (str_len < slen || str_len > slen*static_cast(unibrow::Utf8::kMaxEncodedSize))) { return false; } int i; size_t remaining_in_str = static_cast(str_len); const uint8_t* utf8_data = reinterpret_cast(str.start()); for (i = 0; i < slen && remaining_in_str > 0; i++) { size_t cursor = 0; uint32_t r = unibrow::Utf8::ValueOf(utf8_data, remaining_in_str, &cursor); DCHECK(cursor > 0 && cursor <= remaining_in_str); if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) { if (i > slen - 1) return false; if (Get(i++) != unibrow::Utf16::LeadSurrogate(r)) return false; if (Get(i) != unibrow::Utf16::TrailSurrogate(r)) return false; } else { if (Get(i) != r) return false; } utf8_data += cursor; remaining_in_str -= cursor; } return (allow_prefix_match || i == slen) && remaining_in_str == 0; } bool String::IsOneByteEqualTo(Vector str) { int slen = length(); if (str.length() != slen) return false; DisallowHeapAllocation no_gc; FlatContent content = GetFlatContent(); if (content.IsOneByte()) { return CompareChars(content.ToOneByteVector().start(), str.start(), slen) == 0; } for (int i = 0; i < slen; i++) { if (Get(i) != static_cast(str[i])) return false; } return true; } bool String::IsTwoByteEqualTo(Vector str) { int slen = length(); if (str.length() != slen) return false; DisallowHeapAllocation no_gc; FlatContent content = GetFlatContent(); if (content.IsTwoByte()) { return CompareChars(content.ToUC16Vector().start(), str.start(), slen) == 0; } for (int i = 0; i < slen; i++) { if (Get(i) != str[i]) return false; } return true; } uint32_t String::ComputeAndSetHash() { // Should only be called if hash code has not yet been computed. DCHECK(!HasHashCode()); // Store the hash code in the object. uint32_t field = IteratingStringHasher::Hash(this, GetHeap()->HashSeed()); set_hash_field(field); // Check the hash code is there. DCHECK(HasHashCode()); uint32_t result = field >> kHashShift; DCHECK(result != 0); // Ensure that the hash value of 0 is never computed. return result; } bool String::ComputeArrayIndex(uint32_t* index) { int length = this->length(); if (length == 0 || length > kMaxArrayIndexSize) return false; StringCharacterStream stream(this); return StringToArrayIndex(&stream, index); } bool String::SlowAsArrayIndex(uint32_t* index) { if (length() <= kMaxCachedArrayIndexLength) { Hash(); // force computation of hash code uint32_t field = hash_field(); if ((field & kIsNotArrayIndexMask) != 0) return false; // Isolate the array index form the full hash field. *index = ArrayIndexValueBits::decode(field); return true; } else { return ComputeArrayIndex(index); } } Handle SeqString::Truncate(Handle string, int new_length) { Heap* heap = string->GetHeap(); if (new_length == 0) return heap->isolate()->factory()->empty_string(); int new_size, old_size; int old_length = string->length(); if (old_length <= new_length) return string; if (string->IsSeqOneByteString()) { old_size = SeqOneByteString::SizeFor(old_length); new_size = SeqOneByteString::SizeFor(new_length); } else { DCHECK(string->IsSeqTwoByteString()); old_size = SeqTwoByteString::SizeFor(old_length); new_size = SeqTwoByteString::SizeFor(new_length); } int delta = old_size - new_size; Address start_of_string = string->address(); DCHECK_OBJECT_ALIGNED(start_of_string); DCHECK_OBJECT_ALIGNED(start_of_string + new_size); // Sizes are pointer size aligned, so that we can use filler objects // that are a multiple of pointer size. heap->CreateFillerObjectAt(start_of_string + new_size, delta, ClearRecordedSlots::kNo); heap->AdjustLiveBytes(*string, -delta); // We are storing the new length using release store after creating a filler // for the left-over space to avoid races with the sweeper thread. string->synchronized_set_length(new_length); return string; } uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, int length) { // For array indexes mix the length into the hash as an array index could // be zero. DCHECK(length > 0); DCHECK(length <= String::kMaxArrayIndexSize); DCHECK(TenToThe(String::kMaxCachedArrayIndexLength) < (1 << String::kArrayIndexValueBits)); value <<= String::ArrayIndexValueBits::kShift; value |= length << String::ArrayIndexLengthBits::kShift; DCHECK((value & String::kIsNotArrayIndexMask) == 0); DCHECK_EQ(length <= String::kMaxCachedArrayIndexLength, (value & String::kContainsCachedArrayIndexMask) == 0); return value; } uint32_t StringHasher::GetHashField() { if (length_ <= String::kMaxHashCalcLength) { if (is_array_index_) { return MakeArrayIndexHash(array_index_, length_); } return (GetHashCore(raw_running_hash_) << String::kHashShift) | String::kIsNotArrayIndexMask; } else { return (length_ << String::kHashShift) | String::kIsNotArrayIndexMask; } } uint32_t StringHasher::ComputeUtf8Hash(Vector chars, uint32_t seed, int* utf16_length_out) { int vector_length = chars.length(); // Handle some edge cases if (vector_length <= 1) { DCHECK(vector_length == 0 || static_cast(chars.start()[0]) <= unibrow::Utf8::kMaxOneByteChar); *utf16_length_out = vector_length; return HashSequentialString(chars.start(), vector_length, seed); } // Start with a fake length which won't affect computation. // It will be updated later. StringHasher hasher(String::kMaxArrayIndexSize, seed); size_t remaining = static_cast(vector_length); const uint8_t* stream = reinterpret_cast(chars.start()); int utf16_length = 0; bool is_index = true; DCHECK(hasher.is_array_index_); while (remaining > 0) { size_t consumed = 0; uint32_t c = unibrow::Utf8::ValueOf(stream, remaining, &consumed); DCHECK(consumed > 0 && consumed <= remaining); stream += consumed; remaining -= consumed; bool is_two_characters = c > unibrow::Utf16::kMaxNonSurrogateCharCode; utf16_length += is_two_characters ? 2 : 1; // No need to keep hashing. But we do need to calculate utf16_length. if (utf16_length > String::kMaxHashCalcLength) continue; if (is_two_characters) { uint16_t c1 = unibrow::Utf16::LeadSurrogate(c); uint16_t c2 = unibrow::Utf16::TrailSurrogate(c); hasher.AddCharacter(c1); hasher.AddCharacter(c2); if (is_index) is_index = hasher.UpdateIndex(c1); if (is_index) is_index = hasher.UpdateIndex(c2); } else { hasher.AddCharacter(c); if (is_index) is_index = hasher.UpdateIndex(c); } } *utf16_length_out = static_cast(utf16_length); // Must set length here so that hash computation is correct. hasher.length_ = utf16_length; return hasher.GetHashField(); } void IteratingStringHasher::VisitConsString(ConsString* cons_string) { // Run small ConsStrings through ConsStringIterator. if (cons_string->length() < 64) { ConsStringIterator iter(cons_string); int offset; String* string; while (nullptr != (string = iter.Next(&offset))) { DCHECK_EQ(0, offset); String::VisitFlat(this, string, 0); } return; } // Slow case. const int max_length = String::kMaxHashCalcLength; int length = std::min(cons_string->length(), max_length); if (cons_string->HasOnlyOneByteChars()) { uint8_t* buffer = new uint8_t[length]; String::WriteToFlat(cons_string, buffer, 0, length); AddCharacters(buffer, length); delete[] buffer; } else { uint16_t* buffer = new uint16_t[length]; String::WriteToFlat(cons_string, buffer, 0, length); AddCharacters(buffer, length); delete[] buffer; } } void String::PrintOn(FILE* file) { int length = this->length(); for (int i = 0; i < length; i++) { PrintF(file, "%c", Get(i)); } } int Map::Hash() { // For performance reasons we only hash the 3 most variable fields of a map: // constructor, prototype and bit_field2. For predictability reasons we // use objects' offsets in respective pages for hashing instead of raw // addresses. // Shift away the tag. int hash = ObjectAddressForHashing(GetConstructor()) >> 2; // XOR-ing the prototype and constructor directly yields too many zero bits // when the two pointers are close (which is fairly common). // To avoid this we shift the prototype bits relatively to the constructor. hash ^= ObjectAddressForHashing(prototype()) << (32 - kPageSizeBits); return hash ^ (hash >> 16) ^ bit_field2(); } namespace { bool CheckEquivalent(Map* first, Map* second) { return first->GetConstructor() == second->GetConstructor() && first->prototype() == second->prototype() && first->instance_type() == second->instance_type() && first->bit_field() == second->bit_field() && first->is_extensible() == second->is_extensible() && first->new_target_is_base() == second->new_target_is_base() && first->has_hidden_prototype() == second->has_hidden_prototype(); } } // namespace bool Map::EquivalentToForTransition(Map* other) { if (!CheckEquivalent(this, other)) return false; if (instance_type() == JS_FUNCTION_TYPE) { // JSFunctions require more checks to ensure that sloppy function is // not equvalent to strict function. int nof = Min(NumberOfOwnDescriptors(), other->NumberOfOwnDescriptors()); return instance_descriptors()->IsEqualUpTo(other->instance_descriptors(), nof); } return true; } bool Map::EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode) { int properties = mode == CLEAR_INOBJECT_PROPERTIES ? 0 : other->GetInObjectProperties(); return CheckEquivalent(this, other) && bit_field2() == other->bit_field2() && GetInObjectProperties() == properties && JSObject::GetInternalFieldCount(this) == JSObject::GetInternalFieldCount(other); } bool JSFunction::Inlines(SharedFunctionInfo* candidate) { DisallowHeapAllocation no_gc; if (shared() == candidate) return true; if (code()->kind() != Code::OPTIMIZED_FUNCTION) return false; DeoptimizationInputData* const data = DeoptimizationInputData::cast(code()->deoptimization_data()); if (data->length() == 0) return false; FixedArray* const literals = data->LiteralArray(); int const inlined_count = data->InlinedFunctionCount()->value(); for (int i = 0; i < inlined_count; ++i) { if (SharedFunctionInfo::cast(literals->get(i)) == candidate) { return true; } } return false; } void JSFunction::MarkForBaseline() { Isolate* isolate = GetIsolate(); set_code_no_write_barrier( isolate->builtins()->builtin(Builtins::kCompileBaseline)); // No write barrier required, since the builtin is part of the root set. if (FLAG_mark_shared_functions_for_tier_up) { shared()->set_marked_for_tier_up(true); } } void JSFunction::MarkForOptimization() { Isolate* isolate = GetIsolate(); DCHECK(!IsOptimized()); DCHECK(shared()->allows_lazy_compilation() || !shared()->optimization_disabled()); set_code_no_write_barrier( isolate->builtins()->builtin(Builtins::kCompileOptimized)); // No write barrier required, since the builtin is part of the root set. if (FLAG_mark_shared_functions_for_tier_up) { shared()->set_marked_for_tier_up(true); } } void JSFunction::AttemptConcurrentOptimization() { Isolate* isolate = GetIsolate(); if (!isolate->concurrent_recompilation_enabled() || isolate->bootstrapper()->IsActive()) { MarkForOptimization(); return; } DCHECK(!IsInOptimizationQueue()); DCHECK(!IsOptimized()); DCHECK(shared()->allows_lazy_compilation() || !shared()->optimization_disabled()); DCHECK(isolate->concurrent_recompilation_enabled()); if (FLAG_trace_concurrent_recompilation) { PrintF(" ** Marking "); ShortPrint(); PrintF(" for concurrent recompilation.\n"); } set_code_no_write_barrier( isolate->builtins()->builtin(Builtins::kCompileOptimizedConcurrent)); // No write barrier required, since the builtin is part of the root set. if (FLAG_mark_shared_functions_for_tier_up) { // TODO(leszeks): The compilation isn't concurrent if we trigger it using // this bit. shared()->set_marked_for_tier_up(true); } } // static void SharedFunctionInfo::AddToOptimizedCodeMap( Handle shared, Handle native_context, Handle code, BailoutId osr_ast_id) { Isolate* isolate = shared->GetIsolate(); if (isolate->serializer_enabled()) return; DCHECK(code->kind() == Code::OPTIMIZED_FUNCTION); DCHECK(native_context->IsNativeContext()); STATIC_ASSERT(kEntryLength == 2); Handle new_code_map; int entry; if (!osr_ast_id.IsNone()) { Context::AddToOptimizedCodeMap(native_context, shared, code, osr_ast_id); return; } DCHECK(osr_ast_id.IsNone()); if (shared->OptimizedCodeMapIsCleared()) { new_code_map = isolate->factory()->NewFixedArray(kInitialLength, TENURED); entry = kEntriesStart; } else { Handle old_code_map(shared->optimized_code_map(), isolate); entry = shared->SearchOptimizedCodeMapEntry(*native_context); if (entry >= kEntriesStart) { // Just set the code of the entry. Handle code_cell = isolate->factory()->NewWeakCell(code); old_code_map->set(entry + kCachedCodeOffset, *code_cell); return; } // Can we reuse an entry? DCHECK(entry < kEntriesStart); int length = old_code_map->length(); for (int i = kEntriesStart; i < length; i += kEntryLength) { if (WeakCell::cast(old_code_map->get(i + kContextOffset))->cleared()) { new_code_map = old_code_map; entry = i; break; } } if (entry < kEntriesStart) { // Copy old optimized code map and append one new entry. new_code_map = isolate->factory()->CopyFixedArrayAndGrow( old_code_map, kEntryLength, TENURED); // TODO(mstarzinger): Temporary workaround. The allocation above might // have flushed the optimized code map and the copy we created is full of // holes. For now we just give up on adding the entry and pretend it got // flushed. if (shared->OptimizedCodeMapIsCleared()) return; entry = old_code_map->length(); } } Handle code_cell = isolate->factory()->NewWeakCell(code); WeakCell* context_cell = native_context->self_weak_cell(); new_code_map->set(entry + kContextOffset, context_cell); new_code_map->set(entry + kCachedCodeOffset, *code_cell); #ifdef DEBUG for (int i = kEntriesStart; i < new_code_map->length(); i += kEntryLength) { WeakCell* cell = WeakCell::cast(new_code_map->get(i + kContextOffset)); DCHECK(cell->cleared() || cell->value()->IsNativeContext()); cell = WeakCell::cast(new_code_map->get(i + kCachedCodeOffset)); DCHECK(cell->cleared() || (cell->value()->IsCode() && Code::cast(cell->value())->kind() == Code::OPTIMIZED_FUNCTION)); } #endif FixedArray* old_code_map = shared->optimized_code_map(); if (old_code_map != *new_code_map) { shared->set_optimized_code_map(*new_code_map); } } void SharedFunctionInfo::ClearOptimizedCodeMap() { FixedArray* empty_fixed_array = GetHeap()->empty_fixed_array(); set_optimized_code_map(empty_fixed_array, SKIP_WRITE_BARRIER); } void SharedFunctionInfo::EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason) { DisallowHeapAllocation no_gc; Isolate* isolate = GetIsolate(); bool found = false; if (!OptimizedCodeMapIsCleared()) { Heap* heap = isolate->heap(); FixedArray* code_map = optimized_code_map(); int length = code_map->length(); for (int src = kEntriesStart; src < length; src += kEntryLength) { DCHECK(WeakCell::cast(code_map->get(src))->cleared() || WeakCell::cast(code_map->get(src))->value()->IsNativeContext()); found = WeakCell::cast(code_map->get(src + kCachedCodeOffset))->value() == optimized_code; if (found) { if (FLAG_trace_opt) { PrintF("[evicting entry from optimizing code map (%s) for ", reason); ShortPrint(); PrintF("]\n"); } // Just clear the code. code_map->set(src + kCachedCodeOffset, heap->empty_weak_cell(), SKIP_WRITE_BARRIER); } } } if (!found) { // We didn't find the code in here. It must be osr'd code. isolate->EvictOSROptimizedCode(optimized_code, reason); } } // static void JSFunction::EnsureLiterals(Handle function) { Handle shared(function->shared()); Isolate* isolate = shared->GetIsolate(); FeedbackVectorState state = function->GetFeedbackVectorState(isolate); switch (state) { case TOP_LEVEL_SCRIPT_NEEDS_VECTOR: { // A top level script didn't get it's literals installed. Handle feedback_vector = FeedbackVector::New(isolate, shared); Handle new_cell = isolate->factory()->NewOneClosureCell(feedback_vector); function->set_feedback_vector_cell(*new_cell); break; } case NEEDS_VECTOR: { Handle feedback_vector = FeedbackVector::New(isolate, shared); function->feedback_vector_cell()->set_value(*feedback_vector); break; } case HAS_VECTOR: // Nothing to do. break; } } static void GetMinInobjectSlack(Map* map, void* data) { int slack = map->unused_property_fields(); if (*reinterpret_cast(data) > slack) { *reinterpret_cast(data) = slack; } } static void ShrinkInstanceSize(Map* map, void* data) { int slack = *reinterpret_cast(data); map->SetInObjectProperties(map->GetInObjectProperties() - slack); map->set_unused_property_fields(map->unused_property_fields() - slack); map->set_instance_size(map->instance_size() - slack * kPointerSize); map->set_construction_counter(Map::kNoSlackTracking); // Visitor id might depend on the instance size, recalculate it. map->set_visitor_id(Heap::GetStaticVisitorIdForMap(map)); } static void StopSlackTracking(Map* map, void* data) { map->set_construction_counter(Map::kNoSlackTracking); } void Map::CompleteInobjectSlackTracking() { // Has to be an initial map. DCHECK(GetBackPointer()->IsUndefined(GetIsolate())); int slack = unused_property_fields(); TransitionArray::TraverseTransitionTree(this, &GetMinInobjectSlack, &slack); if (slack != 0) { // Resize the initial map and all maps in its transition tree. TransitionArray::TraverseTransitionTree(this, &ShrinkInstanceSize, &slack); } else { TransitionArray::TraverseTransitionTree(this, &StopSlackTracking, nullptr); } } static bool PrototypeBenefitsFromNormalization(Handle object) { DisallowHeapAllocation no_gc; if (!object->HasFastProperties()) return false; if (object->IsJSGlobalProxy()) return false; if (object->GetIsolate()->bootstrapper()->IsActive()) return false; return !object->map()->is_prototype_map() || !object->map()->should_be_fast_prototype_map(); } // static void JSObject::MakePrototypesFast(Handle receiver, WhereToStart where_to_start, Isolate* isolate) { if (!receiver->IsJSReceiver()) return; for (PrototypeIterator iter(isolate, Handle::cast(receiver), where_to_start); !iter.IsAtEnd(); iter.Advance()) { Handle current = PrototypeIterator::GetCurrent(iter); if (!current->IsJSObject()) return; Handle current_obj = Handle::cast(current); Map* current_map = current_obj->map(); if (current_map->is_prototype_map()) { // If the map is already marked as should be fast, we're done. Its // prototypes will have been marked already as well. if (current_map->should_be_fast_prototype_map()) return; Handle map(current_map); Map::SetShouldBeFastPrototypeMap(map, true, isolate); JSObject::OptimizeAsPrototype(current_obj, FAST_PROTOTYPE); } } } // static void JSObject::OptimizeAsPrototype(Handle object, PrototypeOptimizationMode mode) { if (object->IsJSGlobalObject()) return; if (mode == FAST_PROTOTYPE && PrototypeBenefitsFromNormalization(object)) { // First normalize to ensure all JSFunctions are DATA_CONSTANT. JSObject::NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, 0, "NormalizeAsPrototype"); } Handle previous_map(object->map()); if (object->map()->is_prototype_map()) { if (object->map()->should_be_fast_prototype_map() && !object->HasFastProperties()) { JSObject::MigrateSlowToFast(object, 0, "OptimizeAsPrototype"); } } else { if (object->map() == *previous_map) { Handle new_map = Map::Copy(handle(object->map()), "CopyAsPrototype"); JSObject::MigrateToMap(object, new_map); } object->map()->set_is_prototype_map(true); // Replace the pointer to the exact constructor with the Object function // from the same context if undetectable from JS. This is to avoid keeping // memory alive unnecessarily. Object* maybe_constructor = object->map()->GetConstructor(); if (maybe_constructor->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(maybe_constructor); Isolate* isolate = object->GetIsolate(); if (!constructor->shared()->IsApiFunction() && object->class_name() == isolate->heap()->Object_string()) { Context* context = constructor->context()->native_context(); JSFunction* object_function = context->object_function(); object->map()->SetConstructor(object_function); } } } } // static void JSObject::ReoptimizeIfPrototype(Handle object) { if (!object->map()->is_prototype_map()) return; if (!object->map()->should_be_fast_prototype_map()) return; OptimizeAsPrototype(object, FAST_PROTOTYPE); } // static void JSObject::LazyRegisterPrototypeUser(Handle user, Isolate* isolate) { // Contract: In line with InvalidatePrototypeChains()'s requirements, // leaf maps don't need to register as users, only prototypes do. DCHECK(user->is_prototype_map()); Handle current_user = user; Handle current_user_info = Map::GetOrCreatePrototypeInfo(user, isolate); for (PrototypeIterator iter(user); !iter.IsAtEnd(); iter.Advance()) { // Walk up the prototype chain as far as links haven't been registered yet. if (current_user_info->registry_slot() != PrototypeInfo::UNREGISTERED) { break; } Handle maybe_proto = PrototypeIterator::GetCurrent(iter); // Proxies on the prototype chain are not supported. They make it // impossible to make any assumptions about the prototype chain anyway. if (maybe_proto->IsJSProxy()) return; Handle proto = Handle::cast(maybe_proto); Handle proto_info = Map::GetOrCreatePrototypeInfo(proto, isolate); Handle maybe_registry(proto_info->prototype_users(), isolate); int slot = 0; Handle new_array = WeakFixedArray::Add(maybe_registry, current_user, &slot); current_user_info->set_registry_slot(slot); if (!maybe_registry.is_identical_to(new_array)) { proto_info->set_prototype_users(*new_array); } if (FLAG_trace_prototype_users) { PrintF("Registering %p as a user of prototype %p (map=%p).\n", reinterpret_cast(*current_user), reinterpret_cast(*proto), reinterpret_cast(proto->map())); } current_user = handle(proto->map(), isolate); current_user_info = proto_info; } } // Can be called regardless of whether |user| was actually registered with // |prototype|. Returns true when there was a registration. // static bool JSObject::UnregisterPrototypeUser(Handle user, Isolate* isolate) { DCHECK(user->is_prototype_map()); // If it doesn't have a PrototypeInfo, it was never registered. if (!user->prototype_info()->IsPrototypeInfo()) return false; // If it had no prototype before, see if it had users that might expect // registration. if (!user->prototype()->IsJSObject()) { Object* users = PrototypeInfo::cast(user->prototype_info())->prototype_users(); return users->IsWeakFixedArray(); } Handle prototype(JSObject::cast(user->prototype()), isolate); Handle user_info = Map::GetOrCreatePrototypeInfo(user, isolate); int slot = user_info->registry_slot(); if (slot == PrototypeInfo::UNREGISTERED) return false; DCHECK(prototype->map()->is_prototype_map()); Object* maybe_proto_info = prototype->map()->prototype_info(); // User knows its registry slot, prototype info and user registry must exist. DCHECK(maybe_proto_info->IsPrototypeInfo()); Handle proto_info(PrototypeInfo::cast(maybe_proto_info), isolate); Object* maybe_registry = proto_info->prototype_users(); DCHECK(maybe_registry->IsWeakFixedArray()); DCHECK(WeakFixedArray::cast(maybe_registry)->Get(slot) == *user); WeakFixedArray::cast(maybe_registry)->Clear(slot); if (FLAG_trace_prototype_users) { PrintF("Unregistering %p as a user of prototype %p.\n", reinterpret_cast(*user), reinterpret_cast(*prototype)); } return true; } static void InvalidatePrototypeChainsInternal(Map* map) { DCHECK(map->is_prototype_map()); if (FLAG_trace_prototype_users) { PrintF("Invalidating prototype map %p 's cell\n", reinterpret_cast(map)); } Object* maybe_proto_info = map->prototype_info(); if (!maybe_proto_info->IsPrototypeInfo()) return; PrototypeInfo* proto_info = PrototypeInfo::cast(maybe_proto_info); Object* maybe_cell = proto_info->validity_cell(); if (maybe_cell->IsCell()) { // Just set the value; the cell will be replaced lazily. Cell* cell = Cell::cast(maybe_cell); cell->set_value(Smi::FromInt(Map::kPrototypeChainInvalid)); } WeakFixedArray::Iterator iterator(proto_info->prototype_users()); // For now, only maps register themselves as users. Map* user; while ((user = iterator.Next())) { // Walk the prototype chain (backwards, towards leaf objects) if necessary. InvalidatePrototypeChainsInternal(user); } } // static void JSObject::InvalidatePrototypeChains(Map* map) { DisallowHeapAllocation no_gc; InvalidatePrototypeChainsInternal(map); } // static Handle Map::GetOrCreatePrototypeInfo(Handle prototype, Isolate* isolate) { Object* maybe_proto_info = prototype->map()->prototype_info(); if (maybe_proto_info->IsPrototypeInfo()) { return handle(PrototypeInfo::cast(maybe_proto_info), isolate); } Handle proto_info = isolate->factory()->NewPrototypeInfo(); prototype->map()->set_prototype_info(*proto_info); return proto_info; } // static Handle Map::GetOrCreatePrototypeInfo(Handle prototype_map, Isolate* isolate) { Object* maybe_proto_info = prototype_map->prototype_info(); if (maybe_proto_info->IsPrototypeInfo()) { return handle(PrototypeInfo::cast(maybe_proto_info), isolate); } Handle proto_info = isolate->factory()->NewPrototypeInfo(); prototype_map->set_prototype_info(*proto_info); return proto_info; } // static void Map::SetShouldBeFastPrototypeMap(Handle map, bool value, Isolate* isolate) { if (value == false && !map->prototype_info()->IsPrototypeInfo()) { // "False" is the implicit default value, so there's nothing to do. return; } GetOrCreatePrototypeInfo(map, isolate)->set_should_be_fast_map(value); } // static Handle Map::GetOrCreatePrototypeChainValidityCell(Handle map, Isolate* isolate) { Handle maybe_prototype; if (map->IsJSGlobalObjectMap()) { DCHECK(map->is_prototype_map()); // Global object is prototype of a global proxy and therefore we can // use its validity cell for guarding global object's prototype change. maybe_prototype = isolate->global_object(); } else { maybe_prototype = handle(map->GetPrototypeChainRootMap(isolate)->prototype(), isolate); if (!maybe_prototype->IsJSObject()) return Handle::null(); } Handle prototype = Handle::cast(maybe_prototype); // Ensure the prototype is registered with its own prototypes so its cell // will be invalidated when necessary. JSObject::LazyRegisterPrototypeUser(handle(prototype->map(), isolate), isolate); Handle proto_info = GetOrCreatePrototypeInfo(prototype, isolate); Object* maybe_cell = proto_info->validity_cell(); // Return existing cell if it's still valid. if (maybe_cell->IsCell()) { Handle cell(Cell::cast(maybe_cell), isolate); if (cell->value() == Smi::FromInt(Map::kPrototypeChainValid)) { return cell; } } // Otherwise create a new cell. Handle cell = isolate->factory()->NewCell( handle(Smi::FromInt(Map::kPrototypeChainValid), isolate)); proto_info->set_validity_cell(*cell); return cell; } // static Handle Map::GetOrCreatePrototypeWeakCell(Handle prototype, Isolate* isolate) { DCHECK(!prototype.is_null()); Handle proto_info = GetOrCreatePrototypeInfo(prototype, isolate); Object* maybe_cell = proto_info->weak_cell(); // Return existing cell if it's already created. if (maybe_cell->IsWeakCell()) { Handle cell(WeakCell::cast(maybe_cell), isolate); DCHECK(!cell->cleared()); return cell; } // Otherwise create a new cell. Handle cell = isolate->factory()->NewWeakCell(prototype); proto_info->set_weak_cell(*cell); return cell; } // static void Map::SetPrototype(Handle map, Handle prototype, PrototypeOptimizationMode proto_mode) { RuntimeCallTimerScope stats_scope(*map, &RuntimeCallStats::Map_SetPrototype); bool is_hidden = false; if (prototype->IsJSObject()) { Handle prototype_jsobj = Handle::cast(prototype); JSObject::OptimizeAsPrototype(prototype_jsobj, proto_mode); Object* maybe_constructor = prototype_jsobj->map()->GetConstructor(); if (maybe_constructor->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(maybe_constructor); Object* data = constructor->shared()->function_data(); is_hidden = (data->IsFunctionTemplateInfo() && FunctionTemplateInfo::cast(data)->hidden_prototype()) || prototype->IsJSGlobalObject(); } } map->set_has_hidden_prototype(is_hidden); WriteBarrierMode wb_mode = prototype->IsNull(map->GetIsolate()) ? SKIP_WRITE_BARRIER : UPDATE_WRITE_BARRIER; map->set_prototype(*prototype, wb_mode); } Handle CacheInitialJSArrayMaps( Handle native_context, Handle initial_map) { // Replace all of the cached initial array maps in the native context with // the appropriate transitioned elements kind maps. Handle current_map = initial_map; ElementsKind kind = current_map->elements_kind(); DCHECK_EQ(GetInitialFastElementsKind(), kind); native_context->set(Context::ArrayMapIndex(kind), *current_map); for (int i = GetSequenceIndexFromFastElementsKind(kind) + 1; i < kFastElementsKindCount; ++i) { Handle new_map; ElementsKind next_kind = GetFastElementsKindFromSequenceIndex(i); if (Map* maybe_elements_transition = current_map->ElementsTransitionMap()) { new_map = handle(maybe_elements_transition); } else { new_map = Map::CopyAsElementsKind( current_map, next_kind, INSERT_TRANSITION); } DCHECK_EQ(next_kind, new_map->elements_kind()); native_context->set(Context::ArrayMapIndex(next_kind), *new_map); current_map = new_map; } return initial_map; } void JSFunction::SetInstancePrototype(Handle function, Handle value) { Isolate* isolate = function->GetIsolate(); DCHECK(value->IsJSReceiver()); // Now some logic for the maps of the objects that are created by using this // function as a constructor. if (function->has_initial_map()) { // If the function has allocated the initial map replace it with a // copy containing the new prototype. Also complete any in-object // slack tracking that is in progress at this point because it is // still tracking the old copy. function->CompleteInobjectSlackTrackingIfActive(); Handle initial_map(function->initial_map(), isolate); if (!initial_map->GetIsolate()->bootstrapper()->IsActive() && initial_map->instance_type() == JS_OBJECT_TYPE) { // Put the value in the initial map field until an initial map is needed. // At that point, a new initial map is created and the prototype is put // into the initial map where it belongs. function->set_prototype_or_initial_map(*value); } else { Handle new_map = Map::Copy(initial_map, "SetInstancePrototype"); JSFunction::SetInitialMap(function, new_map, value); // If the function is used as the global Array function, cache the // updated initial maps (and transitioned versions) in the native context. Handle native_context(function->context()->native_context(), isolate); Handle array_function( native_context->get(Context::ARRAY_FUNCTION_INDEX), isolate); if (array_function->IsJSFunction() && *function == JSFunction::cast(*array_function)) { CacheInitialJSArrayMaps(native_context, new_map); } } // Deoptimize all code that embeds the previous initial map. initial_map->dependent_code()->DeoptimizeDependentCodeGroup( isolate, DependentCode::kInitialMapChangedGroup); } else { // Put the value in the initial map field until an initial map is // needed. At that point, a new initial map is created and the // prototype is put into the initial map where it belongs. function->set_prototype_or_initial_map(*value); if (value->IsJSObject()) { // Optimize as prototype to detach it from its transition tree. JSObject::OptimizeAsPrototype(Handle::cast(value), FAST_PROTOTYPE); } } isolate->heap()->ClearInstanceofCache(); } void JSFunction::SetPrototype(Handle function, Handle value) { DCHECK(function->IsConstructor() || IsGeneratorFunction(function->shared()->kind())); Handle construct_prototype = value; // If the value is not a JSReceiver, store the value in the map's // constructor field so it can be accessed. Also, set the prototype // used for constructing objects to the original object prototype. // See ECMA-262 13.2.2. if (!value->IsJSReceiver()) { // Copy the map so this does not affect unrelated functions. // Remove map transitions because they point to maps with a // different prototype. Handle new_map = Map::Copy(handle(function->map()), "SetPrototype"); JSObject::MigrateToMap(function, new_map); new_map->SetConstructor(*value); new_map->set_non_instance_prototype(true); Isolate* isolate = new_map->GetIsolate(); construct_prototype = handle( IsGeneratorFunction(function->shared()->kind()) ? function->context() ->native_context() ->initial_generator_prototype() : function->context()->native_context()->initial_object_prototype(), isolate); } else { function->map()->set_non_instance_prototype(false); } return SetInstancePrototype(function, construct_prototype); } bool JSFunction::RemovePrototype() { Context* native_context = context()->native_context(); Map* no_prototype_map = is_strict(shared()->language_mode()) ? native_context->strict_function_without_prototype_map() : native_context->sloppy_function_without_prototype_map(); if (map() == no_prototype_map) return true; #ifdef DEBUG if (map() != (is_strict(shared()->language_mode()) ? native_context->strict_function_map() : native_context->sloppy_function_map())) { return false; } #endif set_map(no_prototype_map); set_prototype_or_initial_map(no_prototype_map->GetHeap()->the_hole_value()); return true; } void JSFunction::SetInitialMap(Handle function, Handle map, Handle prototype) { if (map->prototype() != *prototype) { Map::SetPrototype(map, prototype, FAST_PROTOTYPE); } function->set_prototype_or_initial_map(*map); map->SetConstructor(*function); #if TRACE_MAPS if (FLAG_trace_maps) { PrintF("[TraceMaps: InitialMap map= %p SFI= %d_%s ]\n", reinterpret_cast(*map), function->shared()->unique_id(), function->shared()->DebugName()->ToCString().get()); } #endif } #ifdef DEBUG namespace { bool CanSubclassHaveInobjectProperties(InstanceType instance_type) { switch (instance_type) { case JS_API_OBJECT_TYPE: case JS_ARRAY_BUFFER_TYPE: case JS_ARRAY_TYPE: case JS_ASYNC_FROM_SYNC_ITERATOR_TYPE: case JS_CONTEXT_EXTENSION_OBJECT_TYPE: case JS_DATA_VIEW_TYPE: case JS_DATE_TYPE: case JS_FUNCTION_TYPE: case JS_GENERATOR_OBJECT_TYPE: case JS_MAP_ITERATOR_TYPE: case JS_MAP_TYPE: case JS_MESSAGE_OBJECT_TYPE: case JS_OBJECT_TYPE: case JS_ERROR_TYPE: case JS_ARGUMENTS_TYPE: case JS_PROMISE_TYPE: case JS_REGEXP_TYPE: case JS_SET_ITERATOR_TYPE: case JS_SET_TYPE: case JS_SPECIAL_API_OBJECT_TYPE: case JS_TYPED_ARRAY_TYPE: case JS_VALUE_TYPE: case JS_WEAK_MAP_TYPE: case JS_WEAK_SET_TYPE: return true; case BYTECODE_ARRAY_TYPE: case BYTE_ARRAY_TYPE: case CELL_TYPE: case CODE_TYPE: case FILLER_TYPE: case FIXED_ARRAY_TYPE: case FIXED_DOUBLE_ARRAY_TYPE: case FOREIGN_TYPE: case FREE_SPACE_TYPE: case HEAP_NUMBER_TYPE: case JS_BOUND_FUNCTION_TYPE: case JS_GLOBAL_OBJECT_TYPE: case JS_GLOBAL_PROXY_TYPE: case JS_PROXY_TYPE: case MAP_TYPE: case MUTABLE_HEAP_NUMBER_TYPE: case ODDBALL_TYPE: case PROPERTY_CELL_TYPE: case SHARED_FUNCTION_INFO_TYPE: case SYMBOL_TYPE: case WEAK_CELL_TYPE: #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case FIXED_##TYPE##_ARRAY_TYPE: #undef TYPED_ARRAY_CASE #define MAKE_STRUCT_CASE(NAME, Name, name) case NAME##_TYPE: STRUCT_LIST(MAKE_STRUCT_CASE) #undef MAKE_STRUCT_CASE // We must not end up here for these instance types at all. UNREACHABLE(); // Fall through. default: return false; } } } // namespace #endif void JSFunction::EnsureHasInitialMap(Handle function) { DCHECK(function->IsConstructor() || IsResumableFunction(function->shared()->kind())); if (function->has_initial_map()) return; Isolate* isolate = function->GetIsolate(); // The constructor should be compiled for the optimization hints to be // available. Compiler::Compile(function, Compiler::CLEAR_EXCEPTION); // First create a new map with the size and number of in-object properties // suggested by the function. InstanceType instance_type; if (IsResumableFunction(function->shared()->kind())) { instance_type = JS_GENERATOR_OBJECT_TYPE; } else { instance_type = JS_OBJECT_TYPE; } int instance_size; int in_object_properties; function->CalculateInstanceSize(instance_type, 0, &instance_size, &in_object_properties); Handle map = isolate->factory()->NewMap(instance_type, instance_size); // Fetch or allocate prototype. Handle prototype; if (function->has_instance_prototype()) { prototype = handle(function->instance_prototype(), isolate); } else { prototype = isolate->factory()->NewFunctionPrototype(function); } map->SetInObjectProperties(in_object_properties); map->set_unused_property_fields(in_object_properties); DCHECK(map->has_fast_object_elements()); // Finally link initial map and constructor function. DCHECK(prototype->IsJSReceiver()); JSFunction::SetInitialMap(function, map, prototype); map->StartInobjectSlackTracking(); } namespace { bool FastInitializeDerivedMap(Isolate* isolate, Handle new_target, Handle constructor, Handle constructor_initial_map) { // Check that |function|'s initial map still in sync with the |constructor|, // otherwise we must create a new initial map for |function|. if (new_target->has_initial_map() && new_target->initial_map()->GetConstructor() == *constructor) { DCHECK(new_target->instance_prototype()->IsJSReceiver()); return true; } // Create a new map with the size and number of in-object properties // suggested by |function|. // Link initial map and constructor function if the new.target is actually a // subclass constructor. if (!IsDerivedConstructor(new_target->shared()->kind())) return false; Handle prototype(new_target->instance_prototype(), isolate); InstanceType instance_type = constructor_initial_map->instance_type(); DCHECK(CanSubclassHaveInobjectProperties(instance_type)); int internal_fields = JSObject::GetInternalFieldCount(*constructor_initial_map); int pre_allocated = constructor_initial_map->GetInObjectProperties() - constructor_initial_map->unused_property_fields(); int instance_size; int in_object_properties; new_target->CalculateInstanceSizeForDerivedClass( instance_type, internal_fields, &instance_size, &in_object_properties); int unused_property_fields = in_object_properties - pre_allocated; Handle map = Map::CopyInitialMap(constructor_initial_map, instance_size, in_object_properties, unused_property_fields); map->set_new_target_is_base(false); JSFunction::SetInitialMap(new_target, map, prototype); map->SetConstructor(*constructor); map->set_construction_counter(Map::kNoSlackTracking); map->StartInobjectSlackTracking(); return true; } } // namespace // static MaybeHandle JSFunction::GetDerivedMap(Isolate* isolate, Handle constructor, Handle new_target) { EnsureHasInitialMap(constructor); Handle constructor_initial_map(constructor->initial_map(), isolate); if (*new_target == *constructor) return constructor_initial_map; // Fast case, new.target is a subclass of constructor. The map is cacheable // (and may already have been cached). new.target.prototype is guaranteed to // be a JSReceiver. if (new_target->IsJSFunction()) { Handle function = Handle::cast(new_target); // Check that |function|'s initial map still in sync with the |constructor|, // otherwise we must create a new initial map for |function|. if (FastInitializeDerivedMap(isolate, function, constructor, constructor_initial_map)) { return handle(function->initial_map(), isolate); } } // Slow path, new.target is either a proxy or can't cache the map. // new.target.prototype is not guaranteed to be a JSReceiver, and may need to // fall back to the intrinsicDefaultProto. Handle prototype; if (new_target->IsJSFunction()) { Handle function = Handle::cast(new_target); // Make sure the new.target.prototype is cached. EnsureHasInitialMap(function); prototype = handle(function->prototype(), isolate); } else { Handle prototype_string = isolate->factory()->prototype_string(); ASSIGN_RETURN_ON_EXCEPTION( isolate, prototype, JSReceiver::GetProperty(new_target, prototype_string), Map); // The above prototype lookup might change the constructor and its // prototype, hence we have to reload the initial map. EnsureHasInitialMap(constructor); constructor_initial_map = handle(constructor->initial_map(), isolate); } // If prototype is not a JSReceiver, fetch the intrinsicDefaultProto from the // correct realm. Rather than directly fetching the .prototype, we fetch the // constructor that points to the .prototype. This relies on // constructor.prototype being FROZEN for those constructors. if (!prototype->IsJSReceiver()) { Handle context; ASSIGN_RETURN_ON_EXCEPTION(isolate, context, JSReceiver::GetFunctionRealm(new_target), Map); DCHECK(context->IsNativeContext()); Handle maybe_index = JSReceiver::GetDataProperty( constructor, isolate->factory()->native_context_index_symbol()); int index = maybe_index->IsSmi() ? Smi::cast(*maybe_index)->value() : Context::OBJECT_FUNCTION_INDEX; Handle realm_constructor(JSFunction::cast(context->get(index))); prototype = handle(realm_constructor->prototype(), isolate); } Handle map = Map::CopyInitialMap(constructor_initial_map); map->set_new_target_is_base(false); DCHECK(prototype->IsJSReceiver()); if (map->prototype() != *prototype) { Map::SetPrototype(map, prototype, FAST_PROTOTYPE); } map->SetConstructor(*constructor); return map; } void JSFunction::PrintName(FILE* out) { std::unique_ptr name = shared()->DebugName()->ToCString(); PrintF(out, "%s", name.get()); } Handle JSFunction::GetName(Handle function) { Isolate* isolate = function->GetIsolate(); Handle name = JSReceiver::GetDataProperty(function, isolate->factory()->name_string()); if (name->IsString()) return Handle::cast(name); return handle(function->shared()->DebugName(), isolate); } Handle JSFunction::GetDebugName(Handle function) { Isolate* isolate = function->GetIsolate(); Handle name = JSReceiver::GetDataProperty( function, isolate->factory()->display_name_string()); if (name->IsString()) return Handle::cast(name); return JSFunction::GetName(function); } void JSFunction::SetName(Handle function, Handle name, Handle prefix) { Isolate* isolate = function->GetIsolate(); Handle function_name = Name::ToFunctionName(name).ToHandleChecked(); if (prefix->length() > 0) { IncrementalStringBuilder builder(isolate); builder.AppendString(prefix); builder.AppendCharacter(' '); builder.AppendString(function_name); function_name = builder.Finish().ToHandleChecked(); } JSObject::DefinePropertyOrElementIgnoreAttributes( function, isolate->factory()->name_string(), function_name, static_cast(DONT_ENUM | READ_ONLY)) .ToHandleChecked(); } namespace { char const kNativeCodeSource[] = "function () { [native code] }"; Handle NativeCodeFunctionSourceString( Handle shared_info) { Isolate* const isolate = shared_info->GetIsolate(); if (shared_info->name()->IsString()) { IncrementalStringBuilder builder(isolate); builder.AppendCString("function "); builder.AppendString(handle(String::cast(shared_info->name()), isolate)); builder.AppendCString("() { [native code] }"); return builder.Finish().ToHandleChecked(); } return isolate->factory()->NewStringFromAsciiChecked(kNativeCodeSource); } } // namespace // static Handle JSBoundFunction::ToString(Handle function) { Isolate* const isolate = function->GetIsolate(); return isolate->factory()->NewStringFromAsciiChecked(kNativeCodeSource); } // static Handle JSFunction::ToString(Handle function) { Isolate* const isolate = function->GetIsolate(); Handle shared_info(function->shared(), isolate); // Check if {function} should hide its source code. if (!shared_info->IsUserJavaScript()) { return NativeCodeFunctionSourceString(shared_info); } // Check if we should print {function} as a class. Handle class_start_position = JSReceiver::GetDataProperty( function, isolate->factory()->class_start_position_symbol()); if (class_start_position->IsSmi()) { Handle class_end_position = JSReceiver::GetDataProperty( function, isolate->factory()->class_end_position_symbol()); Handle script_source( String::cast(Script::cast(shared_info->script())->source()), isolate); return isolate->factory()->NewSubString( script_source, Handle::cast(class_start_position)->value(), Handle::cast(class_end_position)->value()); } // Check if we have source code for the {function}. if (!shared_info->HasSourceCode()) { return NativeCodeFunctionSourceString(shared_info); } if (FLAG_harmony_function_tostring) { return Handle::cast(shared_info->GetSourceCodeHarmony()); } IncrementalStringBuilder builder(isolate); FunctionKind kind = shared_info->kind(); if (!IsArrowFunction(kind)) { if (IsConciseMethod(kind)) { if (IsGeneratorFunction(kind)) { builder.AppendCharacter('*'); } else if (IsAsyncFunction(kind)) { builder.AppendCString("async "); } } else { if (IsGeneratorFunction(kind)) { builder.AppendCString("function* "); } else if (IsAsyncFunction(kind)) { builder.AppendCString("async function "); } else { builder.AppendCString("function "); } } if (shared_info->name_should_print_as_anonymous()) { builder.AppendCString("anonymous"); } else if (!shared_info->is_anonymous_expression()) { builder.AppendString(handle(String::cast(shared_info->name()), isolate)); } } builder.AppendString(Handle::cast(shared_info->GetSourceCode())); return builder.Finish().ToHandleChecked(); } void Oddball::Initialize(Isolate* isolate, Handle oddball, const char* to_string, Handle to_number, const char* type_of, byte kind) { Handle internalized_to_string = isolate->factory()->InternalizeUtf8String(to_string); Handle internalized_type_of = isolate->factory()->InternalizeUtf8String(type_of); oddball->set_to_number_raw(to_number->Number()); oddball->set_to_number(*to_number); oddball->set_to_string(*internalized_to_string); oddball->set_type_of(*internalized_type_of); oddball->set_kind(kind); } void Script::SetEvalOrigin(Handle