// Copyright 2013 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 "v8.h" #include "accessors.h" #include "allocation-site-scopes.h" #include "api.h" #include "arguments.h" #include "bootstrapper.h" #include "codegen.h" #include "code-stubs.h" #include "cpu-profiler.h" #include "debug.h" #include "deoptimizer.h" #include "date.h" #include "elements.h" #include "execution.h" #include "full-codegen.h" #include "hydrogen.h" #include "isolate-inl.h" #include "log.h" #include "objects-inl.h" #include "objects-visiting-inl.h" #include "macro-assembler.h" #include "mark-compact.h" #include "safepoint-table.h" #include "string-search.h" #include "string-stream.h" #include "utils.h" #ifdef ENABLE_DISASSEMBLER #include "disasm.h" #include "disassembler.h" #endif namespace v8 { namespace internal { Handle Object::OptimalType(Isolate* isolate, Representation representation) { if (representation.IsNone()) return HeapType::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->instance_type() >= FIRST_NONCALLABLE_SPEC_OBJECT_TYPE && map->instance_type() <= LAST_NONCALLABLE_SPEC_OBJECT_TYPE) { return HeapType::Class(map, isolate); } } } return HeapType::Any(isolate); } MaybeHandle Object::ToObject(Isolate* isolate, Handle object, Handle native_context) { if (object->IsJSReceiver()) return Handle::cast(object); Handle constructor; if (object->IsNumber()) { constructor = handle(native_context->number_function(), isolate); } else if (object->IsBoolean()) { constructor = handle(native_context->boolean_function(), isolate); } else if (object->IsString()) { constructor = handle(native_context->string_function(), isolate); } else if (object->IsSymbol()) { constructor = handle(native_context->symbol_function(), isolate); } else { return MaybeHandle(); } Handle result = isolate->factory()->NewJSObject(constructor); Handle::cast(result)->set_value(*object); return result; } bool Object::BooleanValue() { if (IsBoolean()) return IsTrue(); if (IsSmi()) return Smi::cast(this)->value() != 0; if (IsUndefined() || IsNull()) return false; if (IsUndetectableObject()) return false; // Undetectable object is false. if (IsString()) return String::cast(this)->length() != 0; if (IsHeapNumber()) return HeapNumber::cast(this)->HeapNumberBooleanValue(); return true; } bool Object::IsCallable() { Object* fun = this; while (fun->IsJSFunctionProxy()) { fun = JSFunctionProxy::cast(fun)->call_trap(); } return fun->IsJSFunction() || (fun->IsHeapObject() && HeapObject::cast(fun)->map()->has_instance_call_handler()); } void Object::Lookup(Handle name, LookupResult* result) { DisallowHeapAllocation no_gc; Object* holder = NULL; if (IsJSReceiver()) { holder = this; } else { Context* native_context = result->isolate()->context()->native_context(); if (IsNumber()) { holder = native_context->number_function()->instance_prototype(); } else if (IsString()) { holder = native_context->string_function()->instance_prototype(); } else if (IsSymbol()) { holder = native_context->symbol_function()->instance_prototype(); } else if (IsBoolean()) { holder = native_context->boolean_function()->instance_prototype(); } else { result->isolate()->PushStackTraceAndDie( 0xDEAD0000, this, JSReceiver::cast(this)->map(), 0xDEAD0001); } } ASSERT(holder != NULL); // Cannot handle null or undefined. JSReceiver::cast(holder)->Lookup(name, result); } MaybeHandle Object::GetPropertyWithReceiver( Handle object, Handle receiver, Handle name, PropertyAttributes* attributes) { LookupResult lookup(name->GetIsolate()); object->Lookup(name, &lookup); MaybeHandle result = GetProperty(object, receiver, &lookup, name, attributes); ASSERT(*attributes <= ABSENT); return result; } 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; } bool Object::ToUint32(uint32_t* value) { if (IsSmi()) { int num = Smi::cast(this)->value(); if (num >= 0) { *value = static_cast(num); return true; } } if (IsHeapNumber()) { double num = HeapNumber::cast(this)->value(); if (num >= 0 && FastUI2D(FastD2UI(num)) == num) { *value = FastD2UI(num); return true; } } return false; } bool FunctionTemplateInfo::IsTemplateFor(Object* object) { if (!object->IsHeapObject()) return false; return IsTemplateFor(HeapObject::cast(object)->map()); } 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->constructor(); 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; } template static inline To* CheckedCast(void *from) { uintptr_t temp = reinterpret_cast(from); ASSERT(temp % sizeof(To) == 0); return reinterpret_cast(temp); } static Handle PerformCompare(const BitmaskCompareDescriptor& descriptor, char* ptr, Isolate* isolate) { uint32_t bitmask = descriptor.bitmask; uint32_t compare_value = descriptor.compare_value; uint32_t value; switch (descriptor.size) { case 1: value = static_cast(*CheckedCast(ptr)); compare_value &= 0xff; bitmask &= 0xff; break; case 2: value = static_cast(*CheckedCast(ptr)); compare_value &= 0xffff; bitmask &= 0xffff; break; case 4: value = *CheckedCast(ptr); break; default: UNREACHABLE(); return isolate->factory()->undefined_value(); } return isolate->factory()->ToBoolean( (bitmask & value) == (bitmask & compare_value)); } static Handle PerformCompare(const PointerCompareDescriptor& descriptor, char* ptr, Isolate* isolate) { uintptr_t compare_value = reinterpret_cast(descriptor.compare_value); uintptr_t value = *CheckedCast(ptr); return isolate->factory()->ToBoolean(compare_value == value); } static Handle GetPrimitiveValue( const PrimitiveValueDescriptor& descriptor, char* ptr, Isolate* isolate) { int32_t int32_value = 0; switch (descriptor.data_type) { case kDescriptorInt8Type: int32_value = *CheckedCast(ptr); break; case kDescriptorUint8Type: int32_value = *CheckedCast(ptr); break; case kDescriptorInt16Type: int32_value = *CheckedCast(ptr); break; case kDescriptorUint16Type: int32_value = *CheckedCast(ptr); break; case kDescriptorInt32Type: int32_value = *CheckedCast(ptr); break; case kDescriptorUint32Type: { uint32_t value = *CheckedCast(ptr); AllowHeapAllocation allow_gc; return isolate->factory()->NewNumberFromUint(value); } case kDescriptorBoolType: { uint8_t byte = *CheckedCast(ptr); return isolate->factory()->ToBoolean( byte & (0x1 << descriptor.bool_offset)); } case kDescriptorFloatType: { float value = *CheckedCast(ptr); AllowHeapAllocation allow_gc; return isolate->factory()->NewNumber(value); } case kDescriptorDoubleType: { double value = *CheckedCast(ptr); AllowHeapAllocation allow_gc; return isolate->factory()->NewNumber(value); } } AllowHeapAllocation allow_gc; return isolate->factory()->NewNumberFromInt(int32_value); } static Handle GetDeclaredAccessorProperty( Handle receiver, Handle info, Isolate* isolate) { DisallowHeapAllocation no_gc; char* current = reinterpret_cast(*receiver); DeclaredAccessorDescriptorIterator iterator(info->descriptor()); while (true) { const DeclaredAccessorDescriptorData* data = iterator.Next(); switch (data->type) { case kDescriptorReturnObject: { ASSERT(iterator.Complete()); current = *CheckedCast(current); return handle(*CheckedCast(current), isolate); } case kDescriptorPointerDereference: ASSERT(!iterator.Complete()); current = *reinterpret_cast(current); break; case kDescriptorPointerShift: ASSERT(!iterator.Complete()); current += data->pointer_shift_descriptor.byte_offset; break; case kDescriptorObjectDereference: { ASSERT(!iterator.Complete()); Object* object = CheckedCast(current); int field = data->object_dereference_descriptor.internal_field; Object* smi = JSObject::cast(object)->GetInternalField(field); ASSERT(smi->IsSmi()); current = reinterpret_cast(smi); break; } case kDescriptorBitmaskCompare: ASSERT(iterator.Complete()); return PerformCompare(data->bitmask_compare_descriptor, current, isolate); case kDescriptorPointerCompare: ASSERT(iterator.Complete()); return PerformCompare(data->pointer_compare_descriptor, current, isolate); case kDescriptorPrimitiveValue: ASSERT(iterator.Complete()); return GetPrimitiveValue(data->primitive_value_descriptor, current, isolate); } } UNREACHABLE(); return isolate->factory()->undefined_value(); } Handle JSObject::EnsureWritableFastElements( Handle object) { ASSERT(object->HasFastSmiOrObjectElements()); Isolate* isolate = object->GetIsolate(); Handle elems(FixedArray::cast(object->elements()), isolate); if (elems->map() != isolate->heap()->fixed_cow_array_map()) return elems; Handle writable_elems = isolate->factory()->CopyFixedArrayWithMap( elems, isolate->factory()->fixed_array_map()); object->set_elements(*writable_elems); isolate->counters()->cow_arrays_converted()->Increment(); return writable_elems; } MaybeHandle JSObject::GetPropertyWithCallback(Handle object, Handle receiver, Handle structure, Handle name) { Isolate* isolate = name->GetIsolate(); ASSERT(!structure->IsForeign()); // api style callbacks. if (structure->IsAccessorInfo()) { Handle accessor_info = Handle::cast(structure); if (!accessor_info->IsCompatibleReceiver(*receiver)) { Handle args[2] = { name, receiver }; Handle error = isolate->factory()->NewTypeError("incompatible_method_receiver", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } // TODO(rossberg): Handling symbols in the API requires changing the API, // so we do not support it for now. if (name->IsSymbol()) return isolate->factory()->undefined_value(); if (structure->IsDeclaredAccessorInfo()) { return GetDeclaredAccessorProperty( receiver, Handle::cast(structure), isolate); } Handle data = Handle::cast(structure); v8::AccessorGetterCallback call_fun = v8::ToCData(data->getter()); if (call_fun == NULL) return isolate->factory()->undefined_value(); Handle key = Handle::cast(name); LOG(isolate, ApiNamedPropertyAccess("load", *object, *name)); PropertyCallbackArguments args(isolate, data->data(), *receiver, *object); v8::Handle result = args.Call(call_fun, v8::Utils::ToLocal(key)); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); if (result.IsEmpty()) { return isolate->factory()->undefined_value(); } Handle return_value = v8::Utils::OpenHandle(*result); return_value->VerifyApiCallResultType(); // Rebox handle before return. return handle(*return_value, isolate); } // __defineGetter__ callback Handle getter(Handle::cast(structure)->getter(), isolate); if (getter->IsSpecFunction()) { // TODO(rossberg): nicer would be to cast to some JSCallable here... return Object::GetPropertyWithDefinedGetter( object, receiver, Handle::cast(getter)); } // Getter is not a function. return isolate->factory()->undefined_value(); } MaybeHandle JSProxy::GetPropertyWithHandler(Handle proxy, Handle receiver, Handle name) { Isolate* isolate = proxy->GetIsolate(); // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (name->IsSymbol()) return isolate->factory()->undefined_value(); Handle args[] = { receiver, name }; return CallTrap( proxy, "get", isolate->derived_get_trap(), ARRAY_SIZE(args), args); } MaybeHandle Object::GetPropertyWithDefinedGetter( Handle object, Handle receiver, Handle getter) { Isolate* isolate = getter->GetIsolate(); Debug* debug = isolate->debug(); // Handle stepping into a getter if step into is active. // TODO(rossberg): should this apply to getters that are function proxies? if (debug->StepInActive() && getter->IsJSFunction()) { debug->HandleStepIn( Handle::cast(getter), Handle::null(), 0, false); } return Execution::Call(isolate, getter, receiver, 0, NULL, true); } // Only deal with CALLBACKS and INTERCEPTOR MaybeHandle JSObject::GetPropertyWithFailedAccessCheck( Handle object, Handle receiver, LookupResult* result, Handle name, PropertyAttributes* attributes) { Isolate* isolate = name->GetIsolate(); if (result->IsProperty()) { switch (result->type()) { case CALLBACKS: { // Only allow API accessors. Handle callback_obj(result->GetCallbackObject(), isolate); if (callback_obj->IsAccessorInfo()) { if (!AccessorInfo::cast(*callback_obj)->all_can_read()) break; *attributes = result->GetAttributes(); // Fall through to GetPropertyWithCallback. } else if (callback_obj->IsAccessorPair()) { if (!AccessorPair::cast(*callback_obj)->all_can_read()) break; // Fall through to GetPropertyWithCallback. } else { break; } Handle holder(result->holder(), isolate); return GetPropertyWithCallback(holder, receiver, callback_obj, name); } case NORMAL: case FIELD: case CONSTANT: { // Search ALL_CAN_READ accessors in prototype chain. LookupResult r(isolate); result->holder()->LookupRealNamedPropertyInPrototypes(name, &r); if (r.IsProperty()) { return GetPropertyWithFailedAccessCheck( object, receiver, &r, name, attributes); } break; } case INTERCEPTOR: { // If the object has an interceptor, try real named properties. // No access check in GetPropertyAttributeWithInterceptor. LookupResult r(isolate); result->holder()->LookupRealNamedProperty(name, &r); if (r.IsProperty()) { return GetPropertyWithFailedAccessCheck( object, receiver, &r, name, attributes); } break; } default: UNREACHABLE(); } } // No accessible property found. *attributes = ABSENT; isolate->ReportFailedAccessCheck(object, v8::ACCESS_GET); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->undefined_value(); } PropertyAttributes JSObject::GetPropertyAttributeWithFailedAccessCheck( Handle object, LookupResult* result, Handle name, bool continue_search) { if (result->IsProperty()) { switch (result->type()) { case CALLBACKS: { // Only allow API accessors. Handle obj(result->GetCallbackObject(), object->GetIsolate()); if (obj->IsAccessorInfo()) { Handle info = Handle::cast(obj); if (info->all_can_read()) { return result->GetAttributes(); } } else if (obj->IsAccessorPair()) { Handle pair = Handle::cast(obj); if (pair->all_can_read()) { return result->GetAttributes(); } } break; } case NORMAL: case FIELD: case CONSTANT: { if (!continue_search) break; // Search ALL_CAN_READ accessors in prototype chain. LookupResult r(object->GetIsolate()); result->holder()->LookupRealNamedPropertyInPrototypes(name, &r); if (r.IsProperty()) { return GetPropertyAttributeWithFailedAccessCheck( object, &r, name, continue_search); } break; } case INTERCEPTOR: { // If the object has an interceptor, try real named properties. // No access check in GetPropertyAttributeWithInterceptor. LookupResult r(object->GetIsolate()); if (continue_search) { result->holder()->LookupRealNamedProperty(name, &r); } else { result->holder()->LookupOwnRealNamedProperty(name, &r); } if (!r.IsFound()) break; return GetPropertyAttributeWithFailedAccessCheck( object, &r, name, continue_search); } case HANDLER: case NONEXISTENT: UNREACHABLE(); } } object->GetIsolate()->ReportFailedAccessCheck(object, v8::ACCESS_HAS); // TODO(yangguo): Issue 3269, check for scheduled exception missing? return ABSENT; } Object* JSObject::GetNormalizedProperty(const LookupResult* result) { ASSERT(!HasFastProperties()); Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry()); if (IsGlobalObject()) { value = PropertyCell::cast(value)->value(); } ASSERT(!value->IsPropertyCell() && !value->IsCell()); return value; } Handle JSObject::GetNormalizedProperty(Handle object, const LookupResult* result) { ASSERT(!object->HasFastProperties()); Isolate* isolate = object->GetIsolate(); Handle value(object->property_dictionary()->ValueAt( result->GetDictionaryEntry()), isolate); if (object->IsGlobalObject()) { value = Handle(Handle::cast(value)->value(), isolate); } ASSERT(!value->IsPropertyCell() && !value->IsCell()); return value; } void JSObject::SetNormalizedProperty(Handle object, const LookupResult* result, Handle value) { ASSERT(!object->HasFastProperties()); NameDictionary* property_dictionary = object->property_dictionary(); if (object->IsGlobalObject()) { Handle cell(PropertyCell::cast( property_dictionary->ValueAt(result->GetDictionaryEntry()))); PropertyCell::SetValueInferType(cell, value); } else { property_dictionary->ValueAtPut(result->GetDictionaryEntry(), *value); } } void JSObject::SetNormalizedProperty(Handle object, Handle name, Handle value, PropertyDetails details) { ASSERT(!object->HasFastProperties()); Handle property_dictionary(object->property_dictionary()); if (!name->IsUniqueName()) { name = object->GetIsolate()->factory()->InternalizeString( Handle::cast(name)); } int entry = property_dictionary->FindEntry(name); if (entry == NameDictionary::kNotFound) { Handle store_value = value; if (object->IsGlobalObject()) { store_value = object->GetIsolate()->factory()->NewPropertyCell(value); } property_dictionary = NameDictionary::Add( property_dictionary, name, store_value, details); object->set_properties(*property_dictionary); return; } PropertyDetails original_details = property_dictionary->DetailsAt(entry); int enumeration_index; // Preserve the enumeration index unless the property was deleted. if (original_details.IsDeleted()) { enumeration_index = property_dictionary->NextEnumerationIndex(); property_dictionary->SetNextEnumerationIndex(enumeration_index + 1); } else { enumeration_index = original_details.dictionary_index(); ASSERT(enumeration_index > 0); } details = PropertyDetails( details.attributes(), details.type(), enumeration_index); if (object->IsGlobalObject()) { Handle cell( PropertyCell::cast(property_dictionary->ValueAt(entry))); PropertyCell::SetValueInferType(cell, value); // Please note we have to update the property details. property_dictionary->DetailsAtPut(entry, details); } else { property_dictionary->SetEntry(entry, name, value, details); } } Handle JSObject::DeleteNormalizedProperty(Handle object, Handle name, DeleteMode mode) { ASSERT(!object->HasFastProperties()); Isolate* isolate = object->GetIsolate(); Handle dictionary(object->property_dictionary()); int entry = dictionary->FindEntry(name); if (entry != NameDictionary::kNotFound) { // If we have a global object set the cell to the hole. if (object->IsGlobalObject()) { PropertyDetails details = dictionary->DetailsAt(entry); if (details.IsDontDelete()) { if (mode != FORCE_DELETION) return isolate->factory()->false_value(); // When forced to delete global properties, we have to make a // map change to invalidate any ICs that think they can load // from the DontDelete cell without checking if it contains // the hole value. Handle new_map = Map::CopyDropDescriptors(handle(object->map())); ASSERT(new_map->is_dictionary_map()); object->set_map(*new_map); } Handle cell(PropertyCell::cast(dictionary->ValueAt(entry))); Handle value = isolate->factory()->the_hole_value(); PropertyCell::SetValueInferType(cell, value); dictionary->DetailsAtPut(entry, details.AsDeleted()); } else { Handle deleted( NameDictionary::DeleteProperty(dictionary, entry, mode)); if (*deleted == isolate->heap()->true_value()) { Handle new_properties = NameDictionary::Shrink(dictionary, name); object->set_properties(*new_properties); } return deleted; } } return isolate->factory()->true_value(); } bool JSObject::IsDirty() { Object* cons_obj = map()->constructor(); if (!cons_obj->IsJSFunction()) return true; JSFunction* fun = JSFunction::cast(cons_obj); if (!fun->shared()->IsApiFunction()) return true; // If the object is fully fast case and has the same map it was // created with then no changes can have been made to it. return map() != fun->initial_map() || !HasFastObjectElements() || !HasFastProperties(); } MaybeHandle Object::GetProperty(Handle object, Handle receiver, LookupResult* result, Handle name, PropertyAttributes* attributes) { Isolate* isolate = name->GetIsolate(); Factory* factory = isolate->factory(); // Make sure that the top context does not change when doing // callbacks or interceptor calls. AssertNoContextChange ncc(isolate); // Traverse the prototype chain from the current object (this) to // the holder and check for access rights. This avoids traversing the // objects more than once in case of interceptors, because the // holder will always be the interceptor holder and the search may // only continue with a current object just after the interceptor // holder in the prototype chain. // Proxy handlers do not use the proxy's prototype, so we can skip this. if (!result->IsHandler()) { ASSERT(*object != object->GetPrototype(isolate)); Handle last = result->IsProperty() ? Handle(result->holder(), isolate) : Handle::cast(factory->null_value()); for (Handle current = object; true; current = Handle(current->GetPrototype(isolate), isolate)) { if (current->IsAccessCheckNeeded()) { // Check if we're allowed to read from the current object. Note // that even though we may not actually end up loading the named // property from the current object, we still check that we have // access to it. Handle checked = Handle::cast(current); if (!isolate->MayNamedAccess(checked, name, v8::ACCESS_GET)) { return JSObject::GetPropertyWithFailedAccessCheck( checked, receiver, result, name, attributes); } } // Stop traversing the chain once we reach the last object in the // chain; either the holder of the result or null in case of an // absent property. if (current.is_identical_to(last)) break; } } if (!result->IsProperty()) { *attributes = ABSENT; return factory->undefined_value(); } *attributes = result->GetAttributes(); Handle value; switch (result->type()) { case NORMAL: { value = JSObject::GetNormalizedProperty( handle(result->holder(), isolate), result); break; } case FIELD: value = JSObject::FastPropertyAt(handle(result->holder(), isolate), result->representation(), result->GetFieldIndex().field_index()); break; case CONSTANT: return handle(result->GetConstant(), isolate); case CALLBACKS: return JSObject::GetPropertyWithCallback( handle(result->holder(), isolate), receiver, handle(result->GetCallbackObject(), isolate), name); case HANDLER: return JSProxy::GetPropertyWithHandler( handle(result->proxy(), isolate), receiver, name); case INTERCEPTOR: return JSObject::GetPropertyWithInterceptor( handle(result->holder(), isolate), receiver, name, attributes); case NONEXISTENT: UNREACHABLE(); break; } ASSERT(!value->IsTheHole() || result->IsReadOnly()); return value->IsTheHole() ? Handle::cast(factory->undefined_value()) : value; } MaybeHandle Object::GetElementWithReceiver(Isolate* isolate, Handle object, Handle receiver, uint32_t index) { Handle holder; // Iterate up the prototype chain until an element is found or the null // prototype is encountered. for (holder = object; !holder->IsNull(); holder = Handle(holder->GetPrototype(isolate), isolate)) { if (!holder->IsJSObject()) { Context* native_context = isolate->context()->native_context(); if (holder->IsNumber()) { holder = Handle( native_context->number_function()->instance_prototype(), isolate); } else if (holder->IsString()) { holder = Handle( native_context->string_function()->instance_prototype(), isolate); } else if (holder->IsSymbol()) { holder = Handle( native_context->symbol_function()->instance_prototype(), isolate); } else if (holder->IsBoolean()) { holder = Handle( native_context->boolean_function()->instance_prototype(), isolate); } else if (holder->IsJSProxy()) { return JSProxy::GetElementWithHandler( Handle::cast(holder), receiver, index); } else { // Undefined and null have no indexed properties. ASSERT(holder->IsUndefined() || holder->IsNull()); return isolate->factory()->undefined_value(); } } // Inline the case for JSObjects. Doing so significantly improves the // performance of fetching elements where checking the prototype chain is // necessary. Handle js_object = Handle::cast(holder); // Check access rights if needed. if (js_object->IsAccessCheckNeeded()) { if (!isolate->MayIndexedAccess(js_object, index, v8::ACCESS_GET)) { isolate->ReportFailedAccessCheck(js_object, v8::ACCESS_GET); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->undefined_value(); } } if (js_object->HasIndexedInterceptor()) { return JSObject::GetElementWithInterceptor(js_object, receiver, index); } if (js_object->elements() != isolate->heap()->empty_fixed_array()) { Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, js_object->GetElementsAccessor()->Get(receiver, js_object, index), Object); if (!result->IsTheHole()) return result; } } return isolate->factory()->undefined_value(); } Object* Object::GetPrototype(Isolate* isolate) { DisallowHeapAllocation no_alloc; if (IsSmi()) { Context* context = isolate->context()->native_context(); return context->number_function()->instance_prototype(); } HeapObject* heap_object = HeapObject::cast(this); // The object is either a number, a string, a boolean, // a real JS object, or a Harmony proxy. if (heap_object->IsJSReceiver()) { return heap_object->map()->prototype(); } Context* context = isolate->context()->native_context(); if (heap_object->IsHeapNumber()) { return context->number_function()->instance_prototype(); } if (heap_object->IsString()) { return context->string_function()->instance_prototype(); } if (heap_object->IsSymbol()) { return context->symbol_function()->instance_prototype(); } if (heap_object->IsBoolean()) { return context->boolean_function()->instance_prototype(); } else { return isolate->heap()->null_value(); } } Handle Object::GetPrototype(Isolate* isolate, Handle object) { return handle(object->GetPrototype(isolate), isolate); } Map* Object::GetMarkerMap(Isolate* isolate) { if (IsSmi()) return isolate->heap()->heap_number_map(); return HeapObject::cast(this)->map(); } Object* Object::GetHash() { // The object is either a number, a name, an odd-ball, // a real JS object, or a Harmony proxy. if (IsNumber()) { uint32_t hash = ComputeLongHash(double_to_uint64(Number())); return Smi::FromInt(hash & Smi::kMaxValue); } if (IsName()) { uint32_t hash = Name::cast(this)->Hash(); return Smi::FromInt(hash); } if (IsOddball()) { uint32_t hash = Oddball::cast(this)->to_string()->Hash(); return Smi::FromInt(hash); } ASSERT(IsJSReceiver()); return JSReceiver::cast(this)->GetIdentityHash(); } Handle Object::GetOrCreateHash(Isolate* isolate, Handle object) { Handle hash(object->GetHash(), isolate); if (hash->IsSmi()) return Handle::cast(hash); ASSERT(object->IsJSReceiver()); return JSReceiver::GetOrCreateIdentityHash(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(); bool equal = this_value == other_value; // SameValue(NaN, NaN) is true. if (!equal) return std::isnan(this_value) && std::isnan(other_value); // SameValue(0.0, -0.0) is false. return (this_value != 0) || ((1 / this_value) == (1 / 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; } void Object::ShortPrint(FILE* out) { HeapStringAllocator allocator; StringStream accumulator(&allocator); ShortPrint(&accumulator); accumulator.OutputToFile(out); } void Object::ShortPrint(StringStream* accumulator) { if (IsSmi()) { Smi::cast(this)->SmiPrint(accumulator); } else { HeapObject::cast(this)->HeapObjectShortPrint(accumulator); } } void Smi::SmiPrint(FILE* out) { PrintF(out, "%d", value()); } void Smi::SmiPrint(StringStream* accumulator) { accumulator->Add("%d", 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) { ASSERT(AllowHeapAllocation::IsAllowed()); ASSERT(cons->second()->length() != 0); 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()); ASSERT(result->IsFlat()); return result; } bool String::MakeExternal(v8::String::ExternalStringResource* resource) { // Externalizing twice leaks the external resource, so it's // prohibited by the API. ASSERT(!this->IsExternalString()); #ifdef ENABLE_SLOW_ASSERTS if (FLAG_enable_slow_asserts) { // Assert that the resource and the string are equivalent. ASSERT(static_cast(this->length()) == resource->length()); ScopedVector smart_chars(this->length()); String::WriteToFlat(this, smart_chars.start(), 0, this->length()); ASSERT(memcmp(smart_chars.start(), resource->data(), resource->length() * sizeof(smart_chars[0])) == 0); } #endif // DEBUG Heap* heap = GetHeap(); int size = this->Size(); // Byte size of the original string. if (size < ExternalString::kShortSize) { return false; } bool is_ascii = this->IsOneByteRepresentation(); bool is_internalized = this->IsInternalizedString(); // 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. // - the existing string is in old pointer space and the backing store of // the external string is not aligned. The GC cannot deal with a field // containing a possibly unaligned address to outside of V8's heap. // In either case 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 || heap->old_pointer_space()->Contains(this)) { new_map = is_internalized ? (is_ascii ? heap-> short_external_internalized_string_with_one_byte_data_map() : heap->short_external_internalized_string_map()) : (is_ascii ? heap->short_external_string_with_one_byte_data_map() : heap->short_external_string_map()); } else { new_map = is_internalized ? (is_ascii ? heap->external_internalized_string_with_one_byte_data_map() : heap->external_internalized_string_map()) : (is_ascii ? 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); // 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->address(), new_size - size, Heap::FROM_MUTATOR); return true; } bool String::MakeExternal(v8::String::ExternalAsciiStringResource* resource) { #ifdef ENABLE_SLOW_ASSERTS if (FLAG_enable_slow_asserts) { // Assert that the resource and the string are equivalent. ASSERT(static_cast(this->length()) == resource->length()); if (this->IsTwoByteRepresentation()) { ScopedVector smart_chars(this->length()); String::WriteToFlat(this, smart_chars.start(), 0, this->length()); ASSERT(String::IsOneByte(smart_chars.start(), this->length())); } ScopedVector smart_chars(this->length()); String::WriteToFlat(this, smart_chars.start(), 0, this->length()); ASSERT(memcmp(smart_chars.start(), resource->data(), resource->length() * sizeof(smart_chars[0])) == 0); } #endif // DEBUG Heap* heap = GetHeap(); int size = this->Size(); // Byte size of the original string. if (size < ExternalString::kShortSize) { return false; } bool is_internalized = this->IsInternalizedString(); // 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. // - the existing string is in old pointer space and the backing store of // the external string is not aligned. The GC cannot deal with a field // containing a possibly unaligned address to outside of V8's heap. // In either case 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 || heap->old_pointer_space()->Contains(this)) { new_map = is_internalized ? heap->short_external_ascii_internalized_string_map() : heap->short_external_ascii_string_map(); } else { new_map = is_internalized ? heap->external_ascii_internalized_string_map() : heap->external_ascii_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); // 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); ExternalAsciiString* self = ExternalAsciiString::cast(this); self->set_resource(resource); if (is_internalized) self->Hash(); // Force regeneration of the hash value. heap->AdjustLiveBytes(this->address(), new_size - size, Heap::FROM_MUTATOR); return true; } void String::StringShortPrint(StringStream* accumulator) { int len = length(); if (len > kMaxShortPrintLength) { accumulator->Add("", len); return; } if (!LooksValid()) { accumulator->Add(""); return; } ConsStringIteratorOp op; StringCharacterStream stream(this, &op); bool truncated = false; if (len > kMaxShortPrintLength) { len = kMaxShortPrintLength; truncated = true; } bool ascii = true; for (int i = 0; i < len; i++) { uint16_t c = stream.GetNext(); if (c < 32 || c >= 127) { ascii = false; } } stream.Reset(this); if (ascii) { accumulator->Add("Put(static_cast(stream.GetNext())); } accumulator->Put('>'); } else { // Backslash indicates that the string contains control // characters and that backslashes are therefore escaped. 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('.'); } accumulator->Put('>'); } return; } void JSObject::JSObjectShortPrint(StringStream* accumulator) { switch (map()->instance_type()) { case JS_ARRAY_TYPE: { double length = JSArray::cast(this)->length()->IsUndefined() ? 0 : JSArray::cast(this)->length()->Number(); accumulator->Add("", static_cast(length)); 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("Add(" (SharedFunctionInfo %p)", reinterpret_cast(function->shared())); accumulator->Put('>'); break; } case JS_GENERATOR_OBJECT_TYPE: { accumulator->Add(""); break; } case JS_MODULE_TYPE: { accumulator->Add(""); break; } // All other JSObjects are rather similar to each other (JSObject, // JSGlobalProxy, JSGlobalObject, JSUndetectableObject, JSValue). default: { Map* map_of_this = map(); Heap* heap = GetHeap(); Object* constructor = map_of_this->constructor(); 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) { PrintF(file, "elements transition ["); PrintElementsKind(file, from_kind); PrintF(file, " -> "); PrintElementsKind(file, to_kind); PrintF(file, "] 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"); } } void Map::PrintGeneralization(FILE* file, const char* reason, int modify_index, int split, int descriptors, bool constant_to_field, Representation old_representation, Representation new_representation, HeapType* old_field_type, HeapType* new_field_type) { PrintF(file, "[generalizing "); constructor_name()->PrintOn(file); PrintF(file, "] "); Name* name = instance_descriptors()->GetKey(modify_index); if (name->IsString()) { String::cast(name)->PrintOn(file); } else { PrintF(file, "{symbol %p}", static_cast(name)); } PrintF(file, ":"); if (constant_to_field) { PrintF(file, "c"); } else { PrintF(file, "%s", old_representation.Mnemonic()); PrintF(file, "{"); old_field_type->TypePrint(file, HeapType::SEMANTIC_DIM); PrintF(file, "}"); } PrintF(file, "->%s", new_representation.Mnemonic()); PrintF(file, "{"); new_field_type->TypePrint(file, HeapType::SEMANTIC_DIM); PrintF(file, "}"); PrintF(file, " ("); if (strlen(reason) > 0) { PrintF(file, "%s", reason); } else { PrintF(file, "+%i maps", descriptors - split); } PrintF(file, ") ["); JavaScriptFrame::PrintTop(GetIsolate(), file, false, true); PrintF(file, "]\n"); } void JSObject::PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map) { PrintF(file, "[migrating "); map()->constructor_name()->PrintOn(file); PrintF(file, "] "); 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).type() == CONSTANT && n->GetDetails(i).type() == FIELD) { 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(StringStream* accumulator) { Heap* heap = GetHeap(); if (!heap->Contains(this)) { accumulator->Add("!!!INVALID POINTER!!!"); return; } if (!heap->Contains(map())) { accumulator->Add("!!!INVALID MAP!!!"); return; } accumulator->Add("%p ", this); if (IsString()) { String::cast(this)->StringShortPrint(accumulator); return; } if (IsJSObject()) { JSObject::cast(this)->JSObjectShortPrint(accumulator); return; } switch (map()->instance_type()) { case MAP_TYPE: accumulator->Add("", Map::cast(this)->elements_kind()); break; case FIXED_ARRAY_TYPE: accumulator->Add("", FixedArray::cast(this)->length()); break; case FIXED_DOUBLE_ARRAY_TYPE: accumulator->Add("", FixedDoubleArray::cast(this)->length()); break; case BYTE_ARRAY_TYPE: accumulator->Add("", ByteArray::cast(this)->length()); break; case FREE_SPACE_TYPE: accumulator->Add("", FreeSpace::cast(this)->Size()); break; #define TYPED_ARRAY_SHORT_PRINT(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ARRAY_TYPE: \ accumulator->Add("", \ External##Type##Array::cast(this)->length()); \ break; \ case FIXED_##TYPE##_ARRAY_TYPE: \ accumulator->Add("", \ Fixed##Type##Array::cast(this)->length()); \ break; TYPED_ARRAYS(TYPED_ARRAY_SHORT_PRINT) #undef TYPED_ARRAY_SHORT_PRINT case SHARED_FUNCTION_INFO_TYPE: { SharedFunctionInfo* shared = SharedFunctionInfo::cast(this); SmartArrayPointer debug_name = shared->DebugName()->ToCString(); if (debug_name[0] != 0) { accumulator->Add("", debug_name.get()); } else { accumulator->Add(""); } break; } case JS_MESSAGE_OBJECT_TYPE: accumulator->Add(""); break; #define MAKE_STRUCT_CASE(NAME, Name, name) \ case NAME##_TYPE: \ accumulator->Put('<'); \ accumulator->Add(#Name); \ accumulator->Put('>'); \ break; STRUCT_LIST(MAKE_STRUCT_CASE) #undef MAKE_STRUCT_CASE case CODE_TYPE: accumulator->Add(""); break; case ODDBALL_TYPE: { if (IsUndefined()) accumulator->Add(""); else if (IsTheHole()) accumulator->Add(""); else if (IsNull()) accumulator->Add(""); else if (IsTrue()) accumulator->Add(""); else if (IsFalse()) accumulator->Add(""); else accumulator->Add(""); break; } case SYMBOL_TYPE: { Symbol* symbol = Symbol::cast(this); accumulator->Add("Hash()); if (!symbol->name()->IsUndefined()) { accumulator->Add(" "); String::cast(symbol->name())->StringShortPrint(accumulator); } accumulator->Add(">"); break; } case HEAP_NUMBER_TYPE: accumulator->Add("HeapNumberPrint(accumulator); accumulator->Put('>'); break; case JS_PROXY_TYPE: accumulator->Add(""); break; case JS_FUNCTION_PROXY_TYPE: accumulator->Add(""); break; case FOREIGN_TYPE: accumulator->Add(""); break; case CELL_TYPE: accumulator->Add("Cell for "); Cell::cast(this)->value()->ShortPrint(accumulator); break; case PROPERTY_CELL_TYPE: accumulator->Add("PropertyCell for "); PropertyCell::cast(this)->value()->ShortPrint(accumulator); break; default: accumulator->Add("", map()->instance_type()); break; } } void HeapObject::Iterate(ObjectVisitor* v) { // Handle header IteratePointer(v, kMapOffset); // Handle object body Map* m = map(); IterateBody(m->instance_type(), SizeFromMap(m), v); } void HeapObject::IterateBody(InstanceType type, int object_size, ObjectVisitor* v) { // Avoiding ::cast(this) because it accesses the map pointer field. // During GC, the map pointer field is encoded. if (type < FIRST_NONSTRING_TYPE) { switch (type & kStringRepresentationMask) { case kSeqStringTag: break; case kConsStringTag: ConsString::BodyDescriptor::IterateBody(this, v); break; case kSlicedStringTag: SlicedString::BodyDescriptor::IterateBody(this, v); break; case kExternalStringTag: if ((type & kStringEncodingMask) == kOneByteStringTag) { reinterpret_cast(this)-> ExternalAsciiStringIterateBody(v); } else { reinterpret_cast(this)-> ExternalTwoByteStringIterateBody(v); } break; } return; } switch (type) { case FIXED_ARRAY_TYPE: FixedArray::BodyDescriptor::IterateBody(this, object_size, v); break; case CONSTANT_POOL_ARRAY_TYPE: reinterpret_cast(this)->ConstantPoolIterateBody(v); break; case FIXED_DOUBLE_ARRAY_TYPE: break; case JS_OBJECT_TYPE: case JS_CONTEXT_EXTENSION_OBJECT_TYPE: case JS_GENERATOR_OBJECT_TYPE: case JS_MODULE_TYPE: case JS_VALUE_TYPE: case JS_DATE_TYPE: case JS_ARRAY_TYPE: case JS_ARRAY_BUFFER_TYPE: case JS_TYPED_ARRAY_TYPE: case JS_DATA_VIEW_TYPE: case JS_SET_TYPE: case JS_MAP_TYPE: case JS_SET_ITERATOR_TYPE: case JS_MAP_ITERATOR_TYPE: case JS_WEAK_MAP_TYPE: case JS_WEAK_SET_TYPE: case JS_REGEXP_TYPE: case JS_GLOBAL_PROXY_TYPE: case JS_GLOBAL_OBJECT_TYPE: case JS_BUILTINS_OBJECT_TYPE: case JS_MESSAGE_OBJECT_TYPE: JSObject::BodyDescriptor::IterateBody(this, object_size, v); break; case JS_FUNCTION_TYPE: reinterpret_cast(this) ->JSFunctionIterateBody(object_size, v); break; case ODDBALL_TYPE: Oddball::BodyDescriptor::IterateBody(this, v); break; case JS_PROXY_TYPE: JSProxy::BodyDescriptor::IterateBody(this, v); break; case JS_FUNCTION_PROXY_TYPE: JSFunctionProxy::BodyDescriptor::IterateBody(this, v); break; case FOREIGN_TYPE: reinterpret_cast(this)->ForeignIterateBody(v); break; case MAP_TYPE: Map::BodyDescriptor::IterateBody(this, v); break; case CODE_TYPE: reinterpret_cast(this)->CodeIterateBody(v); break; case CELL_TYPE: Cell::BodyDescriptor::IterateBody(this, v); break; case PROPERTY_CELL_TYPE: PropertyCell::BodyDescriptor::IterateBody(this, v); break; case SYMBOL_TYPE: Symbol::BodyDescriptor::IterateBody(this, v); break; case HEAP_NUMBER_TYPE: case FILLER_TYPE: case BYTE_ARRAY_TYPE: case FREE_SPACE_TYPE: break; #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ARRAY_TYPE: \ case FIXED_##TYPE##_ARRAY_TYPE: \ break; TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE case SHARED_FUNCTION_INFO_TYPE: { SharedFunctionInfo::BodyDescriptor::IterateBody(this, v); break; } #define MAKE_STRUCT_CASE(NAME, Name, name) \ case NAME##_TYPE: STRUCT_LIST(MAKE_STRUCT_CASE) #undef MAKE_STRUCT_CASE if (type == ALLOCATION_SITE_TYPE) { AllocationSite::BodyDescriptor::IterateBody(this, v); } else { StructBodyDescriptor::IterateBody(this, object_size, v); } break; default: PrintF("Unknown type: %d\n", type); UNREACHABLE(); } } bool HeapNumber::HeapNumberBooleanValue() { // NaN, +0, and -0 should return the false object #if __BYTE_ORDER == __LITTLE_ENDIAN union IeeeDoubleLittleEndianArchType u; #elif __BYTE_ORDER == __BIG_ENDIAN union IeeeDoubleBigEndianArchType u; #endif u.d = value(); if (u.bits.exp == 2047) { // Detect NaN for IEEE double precision floating point. if ((u.bits.man_low | u.bits.man_high) != 0) return false; } if (u.bits.exp == 0) { // Detect +0, and -0 for IEEE double precision floating point. if ((u.bits.man_low | u.bits.man_high) == 0) return false; } return true; } void HeapNumber::HeapNumberPrint(FILE* out) { PrintF(out, "%.16g", Number()); } void HeapNumber::HeapNumberPrint(StringStream* accumulator) { // The Windows version of vsnprintf can allocate when printing a %g string // into a buffer that may not be big enough. We don't want random memory // allocation when producing post-crash stack traces, so we print into a // buffer that is plenty big enough for any floating point number, then // print that using vsnprintf (which may truncate but never allocate if // there is no more space in the buffer). EmbeddedVector buffer; OS::SNPrintF(buffer, "%.16g", Number()); accumulator->Add("%s", buffer.start()); } String* JSReceiver::class_name() { if (IsJSFunction() && IsJSFunctionProxy()) { return GetHeap()->function_class_string(); } if (map()->constructor()->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(map()->constructor()); return String::cast(constructor->shared()->instance_class_name()); } // If the constructor is not present, return "Object". return GetHeap()->Object_string(); } String* Map::constructor_name() { if (constructor()->IsJSFunction()) { JSFunction* constructor = JSFunction::cast(this->constructor()); String* name = String::cast(constructor->shared()->name()); if (name->length() > 0) return name; String* inferred_name = constructor->shared()->inferred_name(); if (inferred_name->length() > 0) return inferred_name; Object* proto = prototype(); if (proto->IsJSObject()) return JSObject::cast(proto)->constructor_name(); } // TODO(rossberg): what about proxies? // If the constructor is not present, return "Object". return GetHeap()->Object_string(); } String* JSReceiver::constructor_name() { return map()->constructor_name(); } MaybeHandle Map::CopyWithField(Handle map, Handle name, Handle type, PropertyAttributes attributes, Representation representation, TransitionFlag flag) { ASSERT(DescriptorArray::kNotFound == map->instance_descriptors()->Search( *name, map->NumberOfOwnDescriptors())); // Ensure the descriptor array does not get too big. if (map->NumberOfOwnDescriptors() >= kMaxNumberOfDescriptors) { return MaybeHandle(); } // Normalize the object if the name is an actual name (not the // hidden strings) and is not a real identifier. // Normalize the object if it will have too many fast properties. Isolate* isolate = map->GetIsolate(); if (!name->IsCacheable(isolate)) return MaybeHandle(); // Compute the new index for new field. int index = map->NextFreePropertyIndex(); if (map->instance_type() == JS_CONTEXT_EXTENSION_OBJECT_TYPE) { representation = Representation::Tagged(); type = HeapType::Any(isolate); } FieldDescriptor new_field_desc(name, index, type, attributes, representation); Handle new_map = Map::CopyAddDescriptor(map, &new_field_desc, 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(); } // Allocate new instance descriptors with (name, constant) added. ConstantDescriptor new_constant_desc(name, constant, attributes); return Map::CopyAddDescriptor(map, &new_constant_desc, flag); } void JSObject::AddFastProperty(Handle object, Handle name, Handle value, PropertyAttributes attributes, StoreFromKeyed store_mode, ValueType value_type, TransitionFlag flag) { ASSERT(!object->IsJSGlobalProxy()); MaybeHandle maybe_map; if (value->IsJSFunction()) { maybe_map = Map::CopyWithConstant( handle(object->map()), name, value, attributes, flag); } else if (!object->TooManyFastProperties(store_mode)) { Isolate* isolate = object->GetIsolate(); Representation representation = value->OptimalRepresentation(value_type); maybe_map = Map::CopyWithField( handle(object->map(), isolate), name, value->OptimalType(isolate, representation), attributes, representation, flag); } Handle new_map; if (!maybe_map.ToHandle(&new_map)) { NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0); return; } JSObject::MigrateToNewProperty(object, new_map, value); } void JSObject::AddSlowProperty(Handle object, Handle name, Handle value, PropertyAttributes attributes) { ASSERT(!object->HasFastProperties()); Isolate* isolate = object->GetIsolate(); Handle dict(object->property_dictionary()); if (object->IsGlobalObject()) { // In case name is an orphaned property reuse the cell. int entry = dict->FindEntry(name); if (entry != NameDictionary::kNotFound) { Handle cell(PropertyCell::cast(dict->ValueAt(entry))); PropertyCell::SetValueInferType(cell, value); // Assign an enumeration index to the property and update // SetNextEnumerationIndex. int index = dict->NextEnumerationIndex(); PropertyDetails details = PropertyDetails(attributes, NORMAL, index); dict->SetNextEnumerationIndex(index + 1); dict->SetEntry(entry, name, cell, details); return; } Handle cell = isolate->factory()->NewPropertyCell(value); PropertyCell::SetValueInferType(cell, value); value = cell; } PropertyDetails details = PropertyDetails(attributes, NORMAL, 0); Handle result = NameDictionary::Add(dict, name, value, details); if (*dict != *result) object->set_properties(*result); } MaybeHandle JSObject::AddProperty( Handle object, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode, JSReceiver::StoreFromKeyed store_mode, ExtensibilityCheck extensibility_check, ValueType value_type, StoreMode mode, TransitionFlag transition_flag) { ASSERT(!object->IsJSGlobalProxy()); Isolate* isolate = object->GetIsolate(); if (!name->IsUniqueName()) { name = isolate->factory()->InternalizeString( Handle::cast(name)); } if (extensibility_check == PERFORM_EXTENSIBILITY_CHECK && !object->map()->is_extensible()) { if (strict_mode == SLOPPY) { return value; } else { Handle args[1] = { name }; Handle error = isolate->factory()->NewTypeError( "object_not_extensible", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } } if (object->HasFastProperties()) { AddFastProperty(object, name, value, attributes, store_mode, value_type, transition_flag); } if (!object->HasFastProperties()) { AddSlowProperty(object, name, value, attributes); } if (object->map()->is_observed() && *name != isolate->heap()->hidden_string()) { Handle old_value = isolate->factory()->the_hole_value(); EnqueueChangeRecord(object, "add", name, old_value); } return value; } Context* JSObject::GetCreationContext() { Object* constructor = this->map()->constructor(); JSFunction* function; if (!constructor->IsJSFunction()) { // Functions have null as a constructor, // but any JSFunction knows its context immediately. function = JSFunction::cast(this); } else { function = JSFunction::cast(constructor); } return function->context()->native_context(); } void JSObject::EnqueueChangeRecord(Handle object, const char* type_str, Handle name, Handle old_value) { ASSERT(!object->IsJSGlobalProxy()); ASSERT(!object->IsJSGlobalObject()); Isolate* isolate = object->GetIsolate(); HandleScope scope(isolate); Handle type = isolate->factory()->InternalizeUtf8String(type_str); Handle args[] = { type, object, name, old_value }; int argc = name.is_null() ? 2 : old_value->IsTheHole() ? 3 : 4; Execution::Call(isolate, Handle(isolate->observers_notify_change()), isolate->factory()->undefined_value(), argc, args).Assert(); } MaybeHandle JSObject::SetPropertyPostInterceptor( Handle object, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode) { // Check own property, ignore interceptor. Isolate* isolate = object->GetIsolate(); LookupResult result(isolate); object->LookupOwnRealNamedProperty(name, &result); if (!result.IsFound()) { object->map()->LookupTransition(*object, *name, &result); } if (result.IsFound()) { // An existing property or a map transition was found. Use set property to // handle all these cases. return SetPropertyForResult(object, &result, name, value, attributes, strict_mode, MAY_BE_STORE_FROM_KEYED); } bool done = false; Handle result_object; ASSIGN_RETURN_ON_EXCEPTION( isolate, result_object, SetPropertyViaPrototypes( object, name, value, attributes, strict_mode, &done), Object); if (done) return result_object; // Add a new real property. return AddProperty(object, name, value, attributes, strict_mode); } static void ReplaceSlowProperty(Handle object, Handle name, Handle value, PropertyAttributes attributes) { NameDictionary* dictionary = object->property_dictionary(); int old_index = dictionary->FindEntry(name); int new_enumeration_index = 0; // 0 means "Use the next available index." if (old_index != -1) { // All calls to ReplaceSlowProperty have had all transitions removed. new_enumeration_index = dictionary->DetailsAt(old_index).dictionary_index(); } PropertyDetails new_details(attributes, NORMAL, new_enumeration_index); JSObject::SetNormalizedProperty(object, name, value, new_details); } 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; } } static void ZapEndOfFixedArray(Address new_end, int to_trim) { // If we are doing a big trim in old space then we zap the space. Object** zap = reinterpret_cast(new_end); zap++; // Header of filler must be at least one word so skip that. for (int i = 1; i < to_trim; i++) { *zap++ = Smi::FromInt(0); } } template static void RightTrimFixedArray(Heap* heap, FixedArray* elms, int to_trim) { ASSERT(elms->map() != heap->fixed_cow_array_map()); // For now this trick is only applied to fixed arrays in new and paged space. ASSERT(!heap->lo_space()->Contains(elms)); const int len = elms->length(); ASSERT(to_trim < len); Address new_end = elms->address() + FixedArray::SizeFor(len - to_trim); if (mode != Heap::FROM_GC || Heap::ShouldZapGarbage()) { ZapEndOfFixedArray(new_end, to_trim); } int size_delta = to_trim * kPointerSize; // Technically in new space this write might be omitted (except for // debug mode which iterates through the heap), but to play safer // we still do it. heap->CreateFillerObjectAt(new_end, size_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. elms->synchronized_set_length(len - to_trim); heap->AdjustLiveBytes(elms->address(), -size_delta, mode); // The array may not be moved during GC, // and size has to be adjusted nevertheless. HeapProfiler* profiler = heap->isolate()->heap_profiler(); if (profiler->is_tracking_allocations()) { profiler->UpdateObjectSizeEvent(elms->address(), elms->Size()); } } bool Map::InstancesNeedRewriting(Map* target, int target_number_of_fields, int target_inobject, int target_unused) { // If fields were added (or removed), rewrite the instance. int number_of_fields = NumberOfFields(); ASSERT(target_number_of_fields >= number_of_fields); if (target_number_of_fields != 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 == inobject_properties()) 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. ASSERT(target_inobject < inobject_properties()); if (target_number_of_fields <= target_inobject) { ASSERT(target_number_of_fields + target_unused == target_inobject); return false; } // Otherwise, properties will need to be moved to the backing store. return true; } Handle Map::SetElementsTransitionMap( Handle map, Handle transitioned_map) { Handle transitions = TransitionArray::CopyInsert( map, map->GetIsolate()->factory()->elements_transition_symbol(), transitioned_map, FULL_TRANSITION); map->set_transitions(*transitions); return transitions; } // To migrate an instance to a 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 JSObject::MigrateToMap(Handle object, Handle new_map) { Isolate* isolate = object->GetIsolate(); Handle old_map(object->map()); int number_of_fields = new_map->NumberOfFields(); int inobject = new_map->inobject_properties(); 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)) { // Writing the new map here does not require synchronization since it does // not change the actual object size. 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. ASSERT(old_nof <= new_nof); for (int i = 0; i < old_nof; i++) { PropertyDetails details = new_descriptors->GetDetails(i); if (details.type() != FIELD) continue; PropertyDetails old_details = old_descriptors->GetDetails(i); if (old_details.type() == CALLBACKS) { ASSERT(details.representation().IsTagged()); continue; } ASSERT(old_details.type() == CONSTANT || old_details.type() == FIELD); Object* raw_value = old_details.type() == CONSTANT ? old_descriptors->GetValue(i) : object->RawFastPropertyAt(old_descriptors->GetFieldIndex(i)); Handle value(raw_value, isolate); if (!old_details.representation().IsDouble() && details.representation().IsDouble()) { if (old_details.representation().IsNone()) { value = handle(Smi::FromInt(0), isolate); } value = Object::NewStorageFor(isolate, value, details.representation()); } ASSERT(!(details.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.type() != FIELD) continue; Handle value; if (details.representation().IsDouble()) { value = isolate->factory()->NewHeapNumber(0); } 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; // 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++) { object->FastPropertyAtPut(i, array->get(external + i)); } // 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; ASSERT(instance_size_delta >= 0); Address address = object->address() + new_instance_size; // The trimming is performed on a newly allocated object, which is on a // fresly allocated page or on an already swept page. Hence, the sweeper // thread can not get confused with the filler creation. No synchronization // needed. isolate->heap()->CreateFillerObjectAt(address, instance_size_delta); // 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) { RightTrimFixedArray(isolate->heap(), *array, inobject); object->set_properties(*array); } // The trimming is performed on a newly allocated object, which is on a // fresly allocated page or on an already swept page. Hence, the sweeper // thread can not get confused with the filler creation. No synchronization // needed. object->set_map(*new_map); } void JSObject::GeneralizeFieldRepresentation(Handle object, int modify_index, Representation new_representation, Handle new_field_type, StoreMode store_mode) { Handle new_map = Map::GeneralizeRepresentation( handle(object->map()), modify_index, new_representation, new_field_type, store_mode); if (object->map() == *new_map) return; return 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).type() == FIELD) result++; } return result; } Handle Map::CopyGeneralizeAllRepresentations(Handle map, int modify_index, StoreMode store_mode, PropertyAttributes attributes, const char* reason) { Isolate* isolate = map->GetIsolate(); Handle new_map = Copy(map); DescriptorArray* descriptors = new_map->instance_descriptors(); int length = descriptors->number_of_descriptors(); for (int i = 0; i < length; i++) { descriptors->SetRepresentation(i, Representation::Tagged()); if (descriptors->GetDetails(i).type() == FIELD) { descriptors->SetValue(i, HeapType::Any()); } } // Unless the instance is being migrated, ensure that modify_index is a field. PropertyDetails details = descriptors->GetDetails(modify_index); if (store_mode == FORCE_FIELD && details.type() != FIELD) { FieldDescriptor d(handle(descriptors->GetKey(modify_index), isolate), new_map->NumberOfFields(), attributes, Representation::Tagged()); descriptors->Replace(modify_index, &d); 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); } if (FLAG_trace_generalization) { HeapType* field_type = (details.type() == FIELD) ? map->instance_descriptors()->GetFieldType(modify_index) : NULL; map->PrintGeneralization(stdout, reason, modify_index, new_map->NumberOfOwnDescriptors(), new_map->NumberOfOwnDescriptors(), details.type() == CONSTANT && store_mode == FORCE_FIELD, details.representation(), Representation::Tagged(), field_type, HeapType::Any()); } return new_map; } void Map::DeprecateTransitionTree() { if (is_deprecated()) return; if (HasTransitionArray()) { TransitionArray* transitions = this->transitions(); for (int i = 0; i < transitions->number_of_transitions(); i++) { transitions->GetTarget(i)->DeprecateTransitionTree(); } } deprecate(); dependent_code()->DeoptimizeDependentCodeGroup( GetIsolate(), DependentCode::kTransitionGroup); NotifyLeafMapLayoutChange(); } // Invalidates a transition target at |key|, and installs |new_descriptors| over // the current instance_descriptors to ensure proper sharing of descriptor // arrays. void Map::DeprecateTarget(Name* key, DescriptorArray* new_descriptors) { if (HasTransitionArray()) { TransitionArray* transitions = this->transitions(); int transition = transitions->Search(key); if (transition != TransitionArray::kNotFound) { transitions->GetTarget(transition)->DeprecateTransitionTree(); } } // Don't overwrite the empty descriptor array. if (NumberOfOwnDescriptors() == 0) return; DescriptorArray* to_replace = instance_descriptors(); Map* current = this; GetHeap()->incremental_marking()->RecordWrites(to_replace); while (current->instance_descriptors() == to_replace) { current->SetEnumLength(kInvalidEnumCacheSentinel); current->set_instance_descriptors(new_descriptors); Object* next = current->GetBackPointer(); if (next->IsUndefined()) break; current = Map::cast(next); } set_owns_descriptors(false); } Map* Map::FindRootMap() { Map* result = this; while (true) { Object* back = result->GetBackPointer(); if (back->IsUndefined()) return result; result = Map::cast(back); } } Map* Map::FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors) { DisallowHeapAllocation no_allocation; // This can only be called on roots of transition trees. ASSERT(GetBackPointer()->IsUndefined()); Map* current = this; for (int i = verbatim; i < length; i++) { if (!current->HasTransitionArray()) break; Name* name = descriptors->GetKey(i); TransitionArray* transitions = current->transitions(); int transition = transitions->Search(name); if (transition == TransitionArray::kNotFound) break; Map* next = transitions->GetTarget(transition); DescriptorArray* next_descriptors = next->instance_descriptors(); PropertyDetails details = descriptors->GetDetails(i); PropertyDetails next_details = next_descriptors->GetDetails(i); if (details.type() != next_details.type()) break; if (details.attributes() != next_details.attributes()) break; if (!details.representation().Equals(next_details.representation())) break; if (next_details.type() == FIELD) { if (!descriptors->GetFieldType(i)->NowIs( next_descriptors->GetFieldType(i))) break; } else { if (descriptors->GetValue(i) != next_descriptors->GetValue(i)) break; } current = next; } return current; } Map* Map::FindFieldOwner(int descriptor) { DisallowHeapAllocation no_allocation; ASSERT_EQ(FIELD, instance_descriptors()->GetDetails(descriptor).type()); Map* result = this; while (true) { Object* back = result->GetBackPointer(); if (back->IsUndefined()) break; Map* parent = Map::cast(back); if (parent->NumberOfOwnDescriptors() <= descriptor) break; result = parent; } return result; } void Map::UpdateDescriptor(int descriptor_number, Descriptor* desc) { DisallowHeapAllocation no_allocation; if (HasTransitionArray()) { TransitionArray* transitions = this->transitions(); for (int i = 0; i < transitions->number_of_transitions(); ++i) { transitions->GetTarget(i)->UpdateDescriptor(descriptor_number, desc); } } instance_descriptors()->Replace(descriptor_number, desc);; } // static Handle Map::GeneralizeFieldType(Handle type1, Handle type2, Isolate* isolate) { static const int kMaxClassesPerFieldType = 5; if (type1->NowIs(type2)) return type2; if (type2->NowIs(type1)) return type1; if (type1->NowStable() && type2->NowStable()) { Handle type = HeapType::Union(type1, type2, isolate); if (type->NumClasses() <= kMaxClassesPerFieldType) { ASSERT(type->NowStable()); ASSERT(type1->NowIs(type)); ASSERT(type2->NowIs(type)); return type; } } return HeapType::Any(isolate); } // static void Map::GeneralizeFieldType(Handle map, int modify_index, Handle new_field_type) { Isolate* isolate = map->GetIsolate(); // Check if we actually need to generalize the field type at all. Handle old_field_type( map->instance_descriptors()->GetFieldType(modify_index), isolate); if (new_field_type->NowIs(old_field_type)) { ASSERT(Map::GeneralizeFieldType(old_field_type, 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); ASSERT_EQ(*old_field_type, descriptors->GetFieldType(modify_index)); // Determine the generalized new field type. new_field_type = Map::GeneralizeFieldType( old_field_type, new_field_type, isolate); PropertyDetails details = descriptors->GetDetails(modify_index); FieldDescriptor d(handle(descriptors->GetKey(modify_index), isolate), descriptors->GetFieldIndex(modify_index), new_field_type, details.attributes(), details.representation()); field_owner->UpdateDescriptor(modify_index, &d); field_owner->dependent_code()->DeoptimizeDependentCodeGroup( isolate, DependentCode::kFieldTypeGroup); if (FLAG_trace_generalization) { map->PrintGeneralization( stdout, "field type generalization", modify_index, map->NumberOfOwnDescriptors(), map->NumberOfOwnDescriptors(), false, details.representation(), details.representation(), *old_field_type, *new_field_type); } } // Generalize the representation of the descriptor at |modify_index|. // This method rewrites the transition tree to reflect the new change. To avoid // high degrees over polymorphism, and to stabilize quickly, on every rewrite // the new type is deduced by merging the current type with any potential new // (partial) version of the type in the transition tree. // To do this, on each rewrite: // - Search the root of the transition tree using FindRootMap. // - Find |target_map|, the newest matching version of this map using the keys // in the |old_map|'s descriptor array to walk the transition tree. // - Merge/generalize the descriptor array of the |old_map| and |target_map|. // - Generalize the |modify_index| descriptor using |new_representation| and // |new_field_type|. // - Walk the tree again starting from the root towards |target_map|. Stop at // |split_map|, the first map who's descriptor array does not match the merged // descriptor array. // - If |target_map| == |split_map|, |target_map| is in the expected state. // Return it. // - Otherwise, invalidate the outdated transition target from |target_map|, and // replace its transition tree with a new branch for the updated descriptors. Handle Map::GeneralizeRepresentation(Handle old_map, int modify_index, Representation new_representation, Handle new_field_type, StoreMode store_mode) { Isolate* isolate = old_map->GetIsolate(); Handle old_descriptors( old_map->instance_descriptors(), isolate); int old_nof = old_map->NumberOfOwnDescriptors(); PropertyDetails old_details = old_descriptors->GetDetails(modify_index); Representation old_representation = old_details.representation(); // It's fine to transition from None to anything but double without any // modification to the object, because the default uninitialized value for // representation None can be overwritten by both smi and tagged values. // Doubles, however, would require a box allocation. if (old_representation.IsNone() && !new_representation.IsNone() && !new_representation.IsDouble()) { ASSERT(old_details.type() == FIELD); ASSERT(old_descriptors->GetFieldType(modify_index)->NowIs( HeapType::None())); if (FLAG_trace_generalization) { old_map->PrintGeneralization( stdout, "uninitialized field", modify_index, old_map->NumberOfOwnDescriptors(), old_map->NumberOfOwnDescriptors(), false, old_representation, new_representation, old_descriptors->GetFieldType(modify_index), *new_field_type); } old_descriptors->SetRepresentation(modify_index, new_representation); old_descriptors->SetValue(modify_index, *new_field_type); return old_map; } // Check the state of the root map. Handle root_map(old_map->FindRootMap(), isolate); if (!old_map->EquivalentToForTransition(*root_map)) { return CopyGeneralizeAllRepresentations(old_map, modify_index, store_mode, old_details.attributes(), "not equivalent"); } int root_nof = root_map->NumberOfOwnDescriptors(); if (modify_index < root_nof) { PropertyDetails old_details = old_descriptors->GetDetails(modify_index); if ((old_details.type() != FIELD && store_mode == FORCE_FIELD) || (old_details.type() == FIELD && (!new_field_type->NowIs(old_descriptors->GetFieldType(modify_index)) || !new_representation.fits_into(old_details.representation())))) { return CopyGeneralizeAllRepresentations(old_map, modify_index, store_mode, old_details.attributes(), "root modification"); } } Handle target_map = root_map; for (int i = root_nof; i < old_nof; ++i) { int j = target_map->SearchTransition(old_descriptors->GetKey(i)); if (j == TransitionArray::kNotFound) break; Handle tmp_map(target_map->GetTransition(j), isolate); Handle tmp_descriptors = handle( tmp_map->instance_descriptors(), isolate); // Check if target map is incompatible. PropertyDetails old_details = old_descriptors->GetDetails(i); PropertyDetails tmp_details = tmp_descriptors->GetDetails(i); PropertyType old_type = old_details.type(); PropertyType tmp_type = tmp_details.type(); if (tmp_details.attributes() != old_details.attributes() || ((tmp_type == CALLBACKS || old_type == CALLBACKS) && (tmp_type != old_type || tmp_descriptors->GetValue(i) != old_descriptors->GetValue(i)))) { return CopyGeneralizeAllRepresentations( old_map, modify_index, store_mode, old_details.attributes(), "incompatible"); } Representation old_representation = old_details.representation(); Representation tmp_representation = tmp_details.representation(); if (!old_representation.fits_into(tmp_representation) || (!new_representation.fits_into(tmp_representation) && modify_index == i)) { break; } if (tmp_type == FIELD) { // Generalize the field type as necessary. Handle old_field_type = (old_type == FIELD) ? handle(old_descriptors->GetFieldType(i), isolate) : old_descriptors->GetValue(i)->OptimalType( isolate, tmp_representation); if (modify_index == i) { old_field_type = GeneralizeFieldType( new_field_type, old_field_type, isolate); } GeneralizeFieldType(tmp_map, i, old_field_type); } else if (tmp_type == CONSTANT) { if (old_type != CONSTANT || old_descriptors->GetConstant(i) != tmp_descriptors->GetConstant(i)) { break; } } else { ASSERT_EQ(tmp_type, old_type); ASSERT_EQ(tmp_descriptors->GetValue(i), old_descriptors->GetValue(i)); } target_map = tmp_map; } // Directly change the map if the target map is more general. Handle target_descriptors( target_map->instance_descriptors(), isolate); int target_nof = target_map->NumberOfOwnDescriptors(); if (target_nof == old_nof && (store_mode != FORCE_FIELD || target_descriptors->GetDetails(modify_index).type() == FIELD)) { ASSERT(modify_index < target_nof); ASSERT(new_representation.fits_into( target_descriptors->GetDetails(modify_index).representation())); ASSERT(target_descriptors->GetDetails(modify_index).type() != FIELD || new_field_type->NowIs( target_descriptors->GetFieldType(modify_index))); return target_map; } // Find the last compatible target map in the transition tree. for (int i = target_nof; i < old_nof; ++i) { int j = target_map->SearchTransition(old_descriptors->GetKey(i)); if (j == TransitionArray::kNotFound) break; Handle tmp_map(target_map->GetTransition(j), isolate); Handle tmp_descriptors( tmp_map->instance_descriptors(), isolate); // Check if target map is compatible. PropertyDetails old_details = old_descriptors->GetDetails(i); PropertyDetails tmp_details = tmp_descriptors->GetDetails(i); if (tmp_details.attributes() != old_details.attributes() || ((tmp_details.type() == CALLBACKS || old_details.type() == CALLBACKS) && (tmp_details.type() != old_details.type() || tmp_descriptors->GetValue(i) != old_descriptors->GetValue(i)))) { return CopyGeneralizeAllRepresentations( old_map, modify_index, store_mode, old_details.attributes(), "incompatible"); } target_map = tmp_map; } target_nof = target_map->NumberOfOwnDescriptors(); target_descriptors = handle(target_map->instance_descriptors(), isolate); // Allocate a new descriptor array large enough to hold the required // descriptors, with minimally the exact same size as the old descriptor // array. int new_slack = Max( old_nof, old_descriptors->number_of_descriptors()) - old_nof; Handle new_descriptors = DescriptorArray::Allocate( isolate, old_nof, new_slack); ASSERT(new_descriptors->length() > target_descriptors->length() || new_descriptors->NumberOfSlackDescriptors() > 0 || new_descriptors->number_of_descriptors() == old_descriptors->number_of_descriptors()); ASSERT(new_descriptors->number_of_descriptors() == old_nof); // 0 -> |root_nof| int current_offset = 0; for (int i = 0; i < root_nof; ++i) { PropertyDetails old_details = old_descriptors->GetDetails(i); if (old_details.type() == FIELD) current_offset++; Descriptor d(handle(old_descriptors->GetKey(i), isolate), handle(old_descriptors->GetValue(i), isolate), old_details); new_descriptors->Set(i, &d); } // |root_nof| -> |target_nof| for (int i = root_nof; i < target_nof; ++i) { Handle target_key(target_descriptors->GetKey(i), isolate); PropertyDetails old_details = old_descriptors->GetDetails(i); PropertyDetails target_details = target_descriptors->GetDetails(i); target_details = target_details.CopyWithRepresentation( old_details.representation().generalize( target_details.representation())); if (modify_index == i) { target_details = target_details.CopyWithRepresentation( new_representation.generalize(target_details.representation())); } if (old_details.type() == FIELD || target_details.type() == FIELD || (modify_index == i && store_mode == FORCE_FIELD) || (target_descriptors->GetValue(i) != old_descriptors->GetValue(i))) { Handle old_field_type = (old_details.type() == FIELD) ? handle(old_descriptors->GetFieldType(i), isolate) : old_descriptors->GetValue(i)->OptimalType( isolate, target_details.representation()); Handle target_field_type = (target_details.type() == FIELD) ? handle(target_descriptors->GetFieldType(i), isolate) : target_descriptors->GetValue(i)->OptimalType( isolate, target_details.representation()); target_field_type = GeneralizeFieldType( target_field_type, old_field_type, isolate); if (modify_index == i) { target_field_type = GeneralizeFieldType( target_field_type, new_field_type, isolate); } FieldDescriptor d(target_key, current_offset++, target_field_type, target_details.attributes(), target_details.representation()); new_descriptors->Set(i, &d); } else { ASSERT_NE(FIELD, target_details.type()); Descriptor d(target_key, handle(target_descriptors->GetValue(i), isolate), target_details); new_descriptors->Set(i, &d); } } // |target_nof| -> |old_nof| for (int i = target_nof; i < old_nof; ++i) { PropertyDetails old_details = old_descriptors->GetDetails(i); Handle old_key(old_descriptors->GetKey(i), isolate); if (modify_index == i) { old_details = old_details.CopyWithRepresentation( new_representation.generalize(old_details.representation())); } if (old_details.type() == FIELD) { Handle old_field_type( old_descriptors->GetFieldType(i), isolate); if (modify_index == i) { old_field_type = GeneralizeFieldType( old_field_type, new_field_type, isolate); } FieldDescriptor d(old_key, current_offset++, old_field_type, old_details.attributes(), old_details.representation()); new_descriptors->Set(i, &d); } else { ASSERT(old_details.type() == CONSTANT || old_details.type() == CALLBACKS); if (modify_index == i && store_mode == FORCE_FIELD) { FieldDescriptor d(old_key, current_offset++, GeneralizeFieldType( old_descriptors->GetValue(i)->OptimalType( isolate, old_details.representation()), new_field_type, isolate), old_details.attributes(), old_details.representation()); new_descriptors->Set(i, &d); } else { ASSERT_NE(FIELD, old_details.type()); Descriptor d(old_key, handle(old_descriptors->GetValue(i), isolate), old_details); new_descriptors->Set(i, &d); } } } new_descriptors->Sort(); ASSERT(store_mode != FORCE_FIELD || new_descriptors->GetDetails(modify_index).type() == FIELD); Handle split_map(root_map->FindLastMatchMap( root_nof, old_nof, *new_descriptors), isolate); int split_nof = split_map->NumberOfOwnDescriptors(); ASSERT_NE(old_nof, split_nof); split_map->DeprecateTarget( old_descriptors->GetKey(split_nof), *new_descriptors); if (FLAG_trace_generalization) { PropertyDetails old_details = old_descriptors->GetDetails(modify_index); PropertyDetails new_details = new_descriptors->GetDetails(modify_index); Handle old_field_type = (old_details.type() == FIELD) ? handle(old_descriptors->GetFieldType(modify_index), isolate) : HeapType::Constant(handle(old_descriptors->GetValue(modify_index), isolate), isolate); Handle new_field_type = (new_details.type() == FIELD) ? handle(new_descriptors->GetFieldType(modify_index), isolate) : HeapType::Constant(handle(new_descriptors->GetValue(modify_index), isolate), isolate); old_map->PrintGeneralization( stdout, "", modify_index, split_nof, old_nof, old_details.type() == CONSTANT && store_mode == FORCE_FIELD, old_details.representation(), new_details.representation(), *old_field_type, *new_field_type); } // Add missing transitions. Handle new_map = split_map; for (int i = split_nof; i < old_nof; ++i) { new_map = CopyInstallDescriptors(new_map, i, new_descriptors); } new_map->set_owns_descriptors(true); return new_map; } // Generalize the representation of all FIELD descriptors. Handle Map::GeneralizeAllFieldRepresentations( Handle map) { Handle descriptors(map->instance_descriptors()); for (int i = 0; i < map->NumberOfOwnDescriptors(); ++i) { if (descriptors->GetDetails(i).type() == FIELD) { map = GeneralizeRepresentation(map, i, Representation::Tagged(), HeapType::Any(map->GetIsolate()), FORCE_FIELD); } } return map; } // static MaybeHandle Map::CurrentMapForDeprecated(Handle map) { Handle proto_map(map); while (proto_map->prototype()->IsJSObject()) { Handle holder(JSObject::cast(proto_map->prototype())); proto_map = Handle(holder->map()); if (proto_map->is_deprecated() && JSObject::TryMigrateInstance(holder)) { proto_map = Handle(holder->map()); } } return CurrentMapForDeprecatedInternal(map); } // static MaybeHandle Map::CurrentMapForDeprecatedInternal(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(); int root_nof = root_map->NumberOfOwnDescriptors(); int old_nof = old_map->NumberOfOwnDescriptors(); DescriptorArray* old_descriptors = old_map->instance_descriptors(); Map* new_map = root_map; for (int i = root_nof; i < old_nof; ++i) { int j = new_map->SearchTransition(old_descriptors->GetKey(i)); if (j == TransitionArray::kNotFound) return MaybeHandle(); new_map = new_map->GetTransition(j); DescriptorArray* new_descriptors = new_map->instance_descriptors(); PropertyDetails new_details = new_descriptors->GetDetails(i); PropertyDetails old_details = old_descriptors->GetDetails(i); if (old_details.attributes() != new_details.attributes() || !old_details.representation().fits_into(new_details.representation())) { return MaybeHandle(); } PropertyType new_type = new_details.type(); PropertyType old_type = old_details.type(); Object* new_value = new_descriptors->GetValue(i); Object* old_value = old_descriptors->GetValue(i); switch (new_type) { case FIELD: if ((old_type == FIELD && !HeapType::cast(old_value)->NowIs(HeapType::cast(new_value))) || (old_type == CONSTANT && !HeapType::cast(new_value)->NowContains(old_value)) || (old_type == CALLBACKS && !HeapType::Any()->Is(HeapType::cast(new_value)))) { return MaybeHandle(); } break; case CONSTANT: case CALLBACKS: if (old_type != new_type || old_value != new_value) { return MaybeHandle(); } break; case NORMAL: case HANDLER: case INTERCEPTOR: case NONEXISTENT: UNREACHABLE(); } } if (new_map->NumberOfOwnDescriptors() != old_nof) return MaybeHandle(); return handle(new_map); } MaybeHandle JSObject::SetPropertyWithInterceptor( Handle object, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode) { // TODO(rossberg): Support symbols in the API. if (name->IsSymbol()) return value; Isolate* isolate = object->GetIsolate(); Handle name_string = Handle::cast(name); Handle interceptor(object->GetNamedInterceptor()); if (!interceptor->setter()->IsUndefined()) { LOG(isolate, ApiNamedPropertyAccess("interceptor-named-set", *object, *name)); PropertyCallbackArguments args( isolate, interceptor->data(), *object, *object); v8::NamedPropertySetterCallback setter = v8::ToCData(interceptor->setter()); Handle value_unhole = value->IsTheHole() ? Handle(isolate->factory()->undefined_value()) : value; v8::Handle result = args.Call(setter, v8::Utils::ToLocal(name_string), v8::Utils::ToLocal(value_unhole)); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); if (!result.IsEmpty()) return value; } return SetPropertyPostInterceptor( object, name, value, attributes, strict_mode); } MaybeHandle JSReceiver::SetProperty(Handle object, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode, StoreFromKeyed store_mode) { LookupResult result(object->GetIsolate()); object->LookupOwn(name, &result, true); if (!result.IsFound()) { object->map()->LookupTransition(JSObject::cast(*object), *name, &result); } return SetProperty(object, &result, name, value, attributes, strict_mode, store_mode); } MaybeHandle JSObject::SetPropertyWithCallback(Handle object, Handle structure, Handle name, Handle value, Handle holder, StrictMode strict_mode) { Isolate* isolate = object->GetIsolate(); // We should never get here to initialize a const with the hole // value since a const declaration would conflict with the setter. ASSERT(!value->IsTheHole()); ASSERT(!structure->IsForeign()); if (structure->IsExecutableAccessorInfo()) { // api style callbacks ExecutableAccessorInfo* data = ExecutableAccessorInfo::cast(*structure); if (!data->IsCompatibleReceiver(*object)) { Handle args[2] = { name, object }; Handle error = isolate->factory()->NewTypeError("incompatible_method_receiver", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } // TODO(rossberg): Support symbols in the API. if (name->IsSymbol()) return value; Object* call_obj = data->setter(); v8::AccessorSetterCallback call_fun = v8::ToCData(call_obj); if (call_fun == NULL) return value; Handle key = Handle::cast(name); LOG(isolate, ApiNamedPropertyAccess("store", *object, *name)); PropertyCallbackArguments args(isolate, data->data(), *object, *holder); args.Call(call_fun, v8::Utils::ToLocal(key), v8::Utils::ToLocal(value)); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return value; } if (structure->IsAccessorPair()) { Handle setter(AccessorPair::cast(*structure)->setter(), isolate); if (setter->IsSpecFunction()) { // TODO(rossberg): nicer would be to cast to some JSCallable here... return SetPropertyWithDefinedSetter( object, Handle::cast(setter), value); } else { if (strict_mode == SLOPPY) return value; Handle args[2] = { name, holder }; Handle error = isolate->factory()->NewTypeError("no_setter_in_callback", HandleVector(args, 2)); return isolate->Throw(error); } } // TODO(dcarney): Handle correctly. if (structure->IsDeclaredAccessorInfo()) { return value; } UNREACHABLE(); return MaybeHandle(); } MaybeHandle JSReceiver::SetPropertyWithDefinedSetter( Handle object, Handle setter, Handle value) { Isolate* isolate = object->GetIsolate(); Debug* debug = isolate->debug(); // Handle stepping into a setter if step into is active. // TODO(rossberg): should this apply to getters that are function proxies? if (debug->StepInActive() && setter->IsJSFunction()) { debug->HandleStepIn( Handle::cast(setter), Handle::null(), 0, false); } Handle argv[] = { value }; RETURN_ON_EXCEPTION( isolate, Execution::Call(isolate, setter, object, ARRAY_SIZE(argv), argv), Object); return value; } MaybeHandle JSObject::SetElementWithCallbackSetterInPrototypes( Handle object, uint32_t index, Handle value, bool* found, StrictMode strict_mode) { Isolate *isolate = object->GetIsolate(); for (Handle proto = handle(object->GetPrototype(), isolate); !proto->IsNull(); proto = handle(proto->GetPrototype(isolate), isolate)) { if (proto->IsJSProxy()) { return JSProxy::SetPropertyViaPrototypesWithHandler( Handle::cast(proto), object, isolate->factory()->Uint32ToString(index), // name value, NONE, strict_mode, found); } Handle js_proto = Handle::cast(proto); if (!js_proto->HasDictionaryElements()) { continue; } Handle dictionary(js_proto->element_dictionary()); int entry = dictionary->FindEntry(index); if (entry != SeededNumberDictionary::kNotFound) { PropertyDetails details = dictionary->DetailsAt(entry); if (details.type() == CALLBACKS) { *found = true; Handle structure(dictionary->ValueAt(entry), isolate); return SetElementWithCallback(object, structure, index, value, js_proto, strict_mode); } } } *found = false; return isolate->factory()->the_hole_value(); } MaybeHandle JSObject::SetPropertyViaPrototypes( Handle object, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode, bool* done) { Isolate* isolate = object->GetIsolate(); *done = false; // We could not find an own property, so let's check whether there is an // accessor that wants to handle the property, or whether the property is // read-only on the prototype chain. LookupResult result(isolate); object->LookupRealNamedPropertyInPrototypes(name, &result); if (result.IsFound()) { switch (result.type()) { case NORMAL: case FIELD: case CONSTANT: *done = result.IsReadOnly(); break; case INTERCEPTOR: { PropertyAttributes attr = GetPropertyAttributeWithInterceptor( handle(result.holder()), object, name, true); *done = !!(attr & READ_ONLY); break; } case CALLBACKS: { *done = true; if (!result.IsReadOnly()) { Handle callback_object(result.GetCallbackObject(), isolate); return SetPropertyWithCallback(object, callback_object, name, value, handle(result.holder()), strict_mode); } break; } case HANDLER: { Handle proxy(result.proxy()); return JSProxy::SetPropertyViaPrototypesWithHandler( proxy, object, name, value, attributes, strict_mode, done); } case NONEXISTENT: UNREACHABLE(); break; } } // If we get here with *done true, we have encountered a read-only property. if (*done) { if (strict_mode == SLOPPY) return value; Handle args[] = { name, object }; Handle error = isolate->factory()->NewTypeError( "strict_read_only_property", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } return isolate->factory()->the_hole_value(); } void Map::EnsureDescriptorSlack(Handle map, int slack) { // Only supports adding slack to owned descriptors. ASSERT(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); if (old_size == 0) { map->set_instance_descriptors(*new_descriptors); 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); } // Replace descriptors by new_descriptors in all maps that share it. map->GetHeap()->incremental_marking()->RecordWrites(*descriptors); Map* walk_map; for (Object* current = map->GetBackPointer(); !current->IsUndefined(); current = walk_map->GetBackPointer()) { walk_map = Map::cast(current); if (walk_map->instance_descriptors() != *descriptors) break; walk_map->set_instance_descriptors(*new_descriptors); } map->set_instance_descriptors(*new_descriptors); } template static int AppendUniqueCallbacks(NeanderArray* 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; CallbacksDescriptor desc(key, entry, entry->property_attributes()); array->Append(&desc); } }; 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()); NeanderArray callbacks(descriptors); ASSERT(array->NumberOfSlackDescriptors() >= callbacks.length()); nof = AppendUniqueCallbacks(&callbacks, array, nof); map->SetNumberOfOwnDescriptors(nof); } int AccessorInfo::AppendUnique(Handle descriptors, Handle array, int valid_descriptors) { NeanderArray callbacks(descriptors); ASSERT(array->length() >= callbacks.length() + valid_descriptors); return AppendUniqueCallbacks(&callbacks, array, valid_descriptors); } static bool ContainsMap(MapHandleList* maps, Handle map) { ASSERT(!map.is_null()); for (int i = 0; i < maps->length(); ++i) { if (!maps->at(i).is_null() && maps->at(i).is_identical_to(map)) return true; } return false; } template static Handle MaybeNull(T* p) { if (p == NULL) return Handle::null(); return Handle(p); } Handle Map::FindTransitionedMap(MapHandleList* candidates) { ElementsKind kind = elements_kind(); Handle transitioned_map = Handle::null(); Handle current_map(this); bool packed = IsFastPackedElementsKind(kind); if (IsTransitionableFastElementsKind(kind)) { while (CanTransitionToMoreGeneralFastElementsKind(kind, false)) { kind = GetNextMoreGeneralFastElementsKind(kind, false); Handle maybe_transitioned_map = MaybeNull(current_map->LookupElementsTransitionMap(kind)); if (maybe_transitioned_map.is_null()) break; if (ContainsMap(candidates, maybe_transitioned_map) && (packed || !IsFastPackedElementsKind(kind))) { transitioned_map = maybe_transitioned_map; if (!IsFastPackedElementsKind(kind)) packed = false; } current_map = maybe_transitioned_map; } } return transitioned_map; } static Map* FindClosestElementsTransition(Map* map, ElementsKind to_kind) { Map* current_map = map; int target_kind = IsFastElementsKind(to_kind) || IsExternalArrayElementsKind(to_kind) ? to_kind : TERMINAL_FAST_ELEMENTS_KIND; // Support for legacy API: SetIndexedPropertiesTo{External,Pixel}Data // allows to change elements from arbitrary kind to any ExternalArray // elements kind. Satisfy its requirements, checking whether we already // have the cached transition. if (IsExternalArrayElementsKind(to_kind) && !IsFixedTypedArrayElementsKind(map->elements_kind())) { if (map->HasElementsTransition()) { Map* next_map = map->elements_transition_map(); if (next_map->elements_kind() == to_kind) return next_map; } return map; } ElementsKind kind = map->elements_kind(); while (kind != target_kind) { kind = GetNextTransitionElementsKind(kind); if (!current_map->HasElementsTransition()) return current_map; current_map = current_map->elements_transition_map(); } if (to_kind != kind && current_map->HasElementsTransition()) { ASSERT(to_kind == DICTIONARY_ELEMENTS); Map* next_map = current_map->elements_transition_map(); if (next_map->elements_kind() == to_kind) return next_map; } ASSERT(current_map->elements_kind() == target_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 NULL; } 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; } static Handle AddMissingElementsTransitions(Handle map, ElementsKind to_kind) { ASSERT(IsTransitionElementsKind(map->elements_kind())); Handle current_map = map; ElementsKind kind = map->elements_kind(); while (kind != to_kind && !IsTerminalElementsKind(kind)) { kind = GetNextTransitionElementsKind(kind); current_map = Map::CopyAsElementsKind( current_map, kind, INSERT_TRANSITION); } // 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, INSERT_TRANSITION); } ASSERT(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(); Object* maybe_array_maps = native_context->js_array_maps(); if (maybe_array_maps->IsFixedArray()) { DisallowHeapAllocation no_gc; FixedArray* array_maps = FixedArray::cast(maybe_array_maps); if (array_maps->get(from_kind) == *map) { Object* maybe_transitioned_map = array_maps->get(to_kind); if (maybe_transitioned_map->IsMap()) { return handle(Map::cast(maybe_transitioned_map)); } } } return TransitionElementsToSlow(map, to_kind); } Handle Map::TransitionElementsToSlow(Handle map, ElementsKind to_kind) { ElementsKind from_kind = map->elements_kind(); if (from_kind == to_kind) { return map; } bool allow_store_transition = // Only remember the map transition if there is not an already existing // non-matching element transition. !map->IsUndefined() && !map->is_shared() && IsTransitionElementsKind(from_kind); // Only store fast element maps in ascending generality. if (IsFastElementsKind(to_kind)) { 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::AsElementsKind(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 JSObject::LookupOwnRealNamedProperty(Handle name, LookupResult* result) { DisallowHeapAllocation no_gc; if (IsJSGlobalProxy()) { Object* proto = GetPrototype(); if (proto->IsNull()) return result->NotFound(); ASSERT(proto->IsJSGlobalObject()); return JSObject::cast(proto)->LookupOwnRealNamedProperty(name, result); } if (HasFastProperties()) { map()->LookupDescriptor(this, *name, result); // A property or a map transition was found. We return all of these result // types because LookupOwnRealNamedProperty is used when setting // properties where map transitions are handled. ASSERT(!result->IsFound() || (result->holder() == this && result->IsFastPropertyType())); // Disallow caching for uninitialized constants. These can only // occur as fields. if (result->IsField() && result->IsReadOnly() && RawFastPropertyAt(result->GetFieldIndex().field_index())->IsTheHole()) { result->DisallowCaching(); } return; } int entry = property_dictionary()->FindEntry(name); if (entry != NameDictionary::kNotFound) { Object* value = property_dictionary()->ValueAt(entry); if (IsGlobalObject()) { PropertyDetails d = property_dictionary()->DetailsAt(entry); if (d.IsDeleted()) { result->NotFound(); return; } value = PropertyCell::cast(value)->value(); } // Make sure to disallow caching for uninitialized constants // found in the dictionary-mode objects. if (value->IsTheHole()) result->DisallowCaching(); result->DictionaryResult(this, entry); return; } result->NotFound(); } void JSObject::LookupRealNamedProperty(Handle name, LookupResult* result) { DisallowHeapAllocation no_gc; LookupOwnRealNamedProperty(name, result); if (result->IsFound()) return; LookupRealNamedPropertyInPrototypes(name, result); } void JSObject::LookupRealNamedPropertyInPrototypes(Handle name, LookupResult* result) { DisallowHeapAllocation no_gc; Isolate* isolate = GetIsolate(); Heap* heap = isolate->heap(); for (Object* pt = GetPrototype(); pt != heap->null_value(); pt = pt->GetPrototype(isolate)) { if (pt->IsJSProxy()) { return result->HandlerResult(JSProxy::cast(pt)); } JSObject::cast(pt)->LookupOwnRealNamedProperty(name, result); ASSERT(!(result->IsFound() && result->type() == INTERCEPTOR)); if (result->IsFound()) return; } result->NotFound(); } // We only need to deal with CALLBACKS and INTERCEPTORS MaybeHandle JSObject::SetPropertyWithFailedAccessCheck( Handle object, LookupResult* result, Handle name, Handle value, bool check_prototype, StrictMode strict_mode) { if (check_prototype && !result->IsProperty()) { object->LookupRealNamedPropertyInPrototypes(name, result); } if (result->IsProperty()) { if (!result->IsReadOnly()) { switch (result->type()) { case CALLBACKS: { Object* obj = result->GetCallbackObject(); if (obj->IsAccessorInfo()) { Handle info(AccessorInfo::cast(obj)); if (info->all_can_write()) { return SetPropertyWithCallback(object, info, name, value, handle(result->holder()), strict_mode); } } else if (obj->IsAccessorPair()) { Handle pair(AccessorPair::cast(obj)); if (pair->all_can_read()) { return SetPropertyWithCallback(object, pair, name, value, handle(result->holder()), strict_mode); } } break; } case INTERCEPTOR: { // Try lookup real named properties. Note that only property can be // set is callbacks marked as ALL_CAN_WRITE on the prototype chain. LookupResult r(object->GetIsolate()); object->LookupRealNamedProperty(name, &r); if (r.IsProperty()) { return SetPropertyWithFailedAccessCheck(object, &r, name, value, check_prototype, strict_mode); } break; } default: { break; } } } } Isolate* isolate = object->GetIsolate(); isolate->ReportFailedAccessCheck(object, v8::ACCESS_SET); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return value; } MaybeHandle JSReceiver::SetProperty(Handle object, LookupResult* result, Handle key, Handle value, PropertyAttributes attributes, StrictMode strict_mode, StoreFromKeyed store_mode) { if (result->IsHandler()) { return JSProxy::SetPropertyWithHandler(handle(result->proxy()), object, key, value, attributes, strict_mode); } else { return JSObject::SetPropertyForResult(Handle::cast(object), result, key, value, attributes, strict_mode, store_mode); } } bool JSProxy::HasPropertyWithHandler(Handle proxy, Handle name) { Isolate* isolate = proxy->GetIsolate(); // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (name->IsSymbol()) return false; Handle args[] = { name }; Handle result; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, result, CallTrap(proxy, "has", isolate->derived_has_trap(), ARRAY_SIZE(args), args), false); return result->BooleanValue(); } MaybeHandle JSProxy::SetPropertyWithHandler( Handle proxy, Handle receiver, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode) { Isolate* isolate = proxy->GetIsolate(); // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (name->IsSymbol()) return value; Handle args[] = { receiver, name, value }; RETURN_ON_EXCEPTION( isolate, CallTrap(proxy, "set", isolate->derived_set_trap(), ARRAY_SIZE(args), args), Object); return value; } MaybeHandle JSProxy::SetPropertyViaPrototypesWithHandler( Handle proxy, Handle receiver, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode, bool* done) { Isolate* isolate = proxy->GetIsolate(); Handle handler(proxy->handler(), isolate); // Trap might morph proxy. // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (name->IsSymbol()) { *done = false; return isolate->factory()->the_hole_value(); } *done = true; // except where redefined... Handle args[] = { name }; Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, CallTrap(proxy, "getPropertyDescriptor", Handle(), ARRAY_SIZE(args), args), Object); if (result->IsUndefined()) { *done = false; return isolate->factory()->the_hole_value(); } // Emulate [[GetProperty]] semantics for proxies. Handle argv[] = { result }; Handle desc; ASSIGN_RETURN_ON_EXCEPTION( isolate, desc, Execution::Call(isolate, isolate->to_complete_property_descriptor(), result, ARRAY_SIZE(argv), argv), Object); // [[GetProperty]] requires to check that all properties are configurable. Handle configurable_name = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("configurable_")); Handle configurable = Object::GetProperty(desc, configurable_name).ToHandleChecked(); ASSERT(configurable->IsBoolean()); if (configurable->IsFalse()) { Handle trap = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("getPropertyDescriptor")); Handle args[] = { handler, trap, name }; Handle error = isolate->factory()->NewTypeError( "proxy_prop_not_configurable", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } ASSERT(configurable->IsTrue()); // Check for DataDescriptor. Handle hasWritable_name = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("hasWritable_")); Handle hasWritable = Object::GetProperty(desc, hasWritable_name).ToHandleChecked(); ASSERT(hasWritable->IsBoolean()); if (hasWritable->IsTrue()) { Handle writable_name = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("writable_")); Handle writable = Object::GetProperty(desc, writable_name).ToHandleChecked(); ASSERT(writable->IsBoolean()); *done = writable->IsFalse(); if (!*done) return isolate->factory()->the_hole_value(); if (strict_mode == SLOPPY) return value; Handle args[] = { name, receiver }; Handle error = isolate->factory()->NewTypeError( "strict_read_only_property", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } // We have an AccessorDescriptor. Handle set_name = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("set_")); Handle setter = Object::GetProperty(desc, set_name).ToHandleChecked(); if (!setter->IsUndefined()) { // TODO(rossberg): nicer would be to cast to some JSCallable here... return SetPropertyWithDefinedSetter( receiver, Handle::cast(setter), value); } if (strict_mode == SLOPPY) return value; Handle args2[] = { name, proxy }; Handle error = isolate->factory()->NewTypeError( "no_setter_in_callback", HandleVector(args2, ARRAY_SIZE(args2))); return isolate->Throw(error); } MaybeHandle JSProxy::DeletePropertyWithHandler( Handle proxy, Handle name, DeleteMode mode) { Isolate* isolate = proxy->GetIsolate(); // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (name->IsSymbol()) return isolate->factory()->false_value(); Handle args[] = { name }; Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, CallTrap(proxy, "delete", Handle(), ARRAY_SIZE(args), args), Object); bool result_bool = result->BooleanValue(); if (mode == STRICT_DELETION && !result_bool) { Handle handler(proxy->handler(), isolate); Handle trap_name = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("delete")); Handle args[] = { handler, trap_name }; Handle error = isolate->factory()->NewTypeError( "handler_failed", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } return isolate->factory()->ToBoolean(result_bool); } MaybeHandle JSProxy::DeleteElementWithHandler( Handle proxy, uint32_t index, DeleteMode mode) { Isolate* isolate = proxy->GetIsolate(); Handle name = isolate->factory()->Uint32ToString(index); return JSProxy::DeletePropertyWithHandler(proxy, name, mode); } PropertyAttributes JSProxy::GetPropertyAttributeWithHandler( Handle proxy, Handle receiver, Handle name) { Isolate* isolate = proxy->GetIsolate(); HandleScope scope(isolate); // TODO(rossberg): adjust once there is a story for symbols vs proxies. if (name->IsSymbol()) return ABSENT; Handle args[] = { name }; Handle result; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, result, proxy->CallTrap(proxy, "getPropertyDescriptor", Handle(), ARRAY_SIZE(args), args), NONE); if (result->IsUndefined()) return ABSENT; Handle argv[] = { result }; Handle desc; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, desc, Execution::Call(isolate, isolate->to_complete_property_descriptor(), result, ARRAY_SIZE(argv), argv), NONE); // Convert result to PropertyAttributes. Handle enum_n = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("enumerable_")); Handle enumerable; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, enumerable, Object::GetProperty(desc, enum_n), NONE); Handle conf_n = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("configurable_")); Handle configurable; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, configurable, Object::GetProperty(desc, conf_n), NONE); Handle writ_n = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("writable_")); Handle writable; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, writable, Object::GetProperty(desc, writ_n), NONE); if (!writable->BooleanValue()) { Handle set_n = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("set_")); Handle setter; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, setter, Object::GetProperty(desc, set_n), NONE); writable = isolate->factory()->ToBoolean(!setter->IsUndefined()); } if (configurable->IsFalse()) { Handle handler(proxy->handler(), isolate); Handle trap = isolate->factory()->InternalizeOneByteString( STATIC_ASCII_VECTOR("getPropertyDescriptor")); Handle args[] = { handler, trap, name }; Handle error = isolate->factory()->NewTypeError( "proxy_prop_not_configurable", HandleVector(args, ARRAY_SIZE(args))); isolate->Throw(*error); return NONE; } int attributes = NONE; if (!enumerable->BooleanValue()) attributes |= DONT_ENUM; if (!configurable->BooleanValue()) attributes |= DONT_DELETE; if (!writable->BooleanValue()) attributes |= READ_ONLY; return static_cast(attributes); } PropertyAttributes JSProxy::GetElementAttributeWithHandler( Handle proxy, Handle receiver, uint32_t index) { Isolate* isolate = proxy->GetIsolate(); Handle name = isolate->factory()->Uint32ToString(index); return GetPropertyAttributeWithHandler(proxy, receiver, name); } void JSProxy::Fix(Handle proxy) { Isolate* isolate = proxy->GetIsolate(); // Save identity hash. Handle hash(proxy->GetIdentityHash(), isolate); if (proxy->IsJSFunctionProxy()) { isolate->factory()->BecomeJSFunction(proxy); // Code will be set on the JavaScript side. } else { isolate->factory()->BecomeJSObject(proxy); } ASSERT(proxy->IsJSObject()); // Inherit identity, if it was present. if (hash->IsSmi()) { JSObject::SetIdentityHash(Handle::cast(proxy), Handle::cast(hash)); } } MaybeHandle JSProxy::CallTrap(Handle proxy, const char* name, Handle derived, int argc, Handle argv[]) { Isolate* isolate = proxy->GetIsolate(); Handle handler(proxy->handler(), isolate); Handle trap_name = isolate->factory()->InternalizeUtf8String(name); Handle trap; ASSIGN_RETURN_ON_EXCEPTION( isolate, trap, Object::GetPropertyOrElement(handler, trap_name), Object); if (trap->IsUndefined()) { if (derived.is_null()) { Handle args[] = { handler, trap_name }; Handle error = isolate->factory()->NewTypeError( "handler_trap_missing", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } trap = Handle(derived); } return Execution::Call(isolate, trap, handler, argc, argv); } void JSObject::AllocateStorageForMap(Handle object, Handle map) { ASSERT(object->map()->inobject_properties() == map->inobject_properties()); ElementsKind obj_kind = object->map()->elements_kind(); ElementsKind map_kind = map->elements_kind(); if (map_kind != obj_kind) { ElementsKind to_kind = map_kind; if (IsMoreGeneralElementsKindTransition(map_kind, obj_kind) || IsDictionaryElementsKind(obj_kind)) { to_kind = obj_kind; } if (IsDictionaryElementsKind(to_kind)) { NormalizeElements(object); } else { TransitionElementsKind(object, to_kind); } map = Map::AsElementsKind(map, to_kind); } JSObject::MigrateToMap(object, map); } void JSObject::MigrateInstance(Handle object) { // Converting any field to the most specific type will cause the // GeneralizeFieldRepresentation algorithm to create the most general existing // transition that matches the object. This achieves what is needed. Handle original_map(object->map()); GeneralizeFieldRepresentation( object, 0, Representation::None(), HeapType::None(object->GetIsolate()), ALLOW_AS_CONSTANT); object->map()->set_migration_target(true); if (FLAG_trace_migration) { object->PrintInstanceMigration(stdout, *original_map, object->map()); } } // 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::CurrentMapForDeprecatedInternal(original_map).ToHandle(&new_map)) { return false; } JSObject::MigrateToMap(object, new_map); if (FLAG_trace_migration) { object->PrintInstanceMigration(stdout, *original_map, object->map()); } return true; } MaybeHandle JSObject::SetPropertyUsingTransition( Handle object, LookupResult* lookup, Handle name, Handle value, PropertyAttributes attributes) { Handle transition_map(lookup->GetTransitionTarget()); int descriptor = transition_map->LastAdded(); Handle descriptors(transition_map->instance_descriptors()); PropertyDetails details = descriptors->GetDetails(descriptor); if (details.type() == CALLBACKS || attributes != details.attributes()) { // AddProperty will either normalize the object, or create a new fast copy // of the map. If we get a fast copy of the map, all field representations // will be tagged since the transition is omitted. return JSObject::AddProperty( object, name, value, attributes, SLOPPY, JSReceiver::CERTAINLY_NOT_STORE_FROM_KEYED, JSReceiver::OMIT_EXTENSIBILITY_CHECK, JSObject::FORCE_TAGGED, FORCE_FIELD, OMIT_TRANSITION); } // Keep the target CONSTANT if the same value is stored. // TODO(verwaest): Also support keeping the placeholder // (value->IsUninitialized) as constant. if (!lookup->CanHoldValue(value)) { Representation field_representation = value->OptimalRepresentation(); Handle field_type = value->OptimalType( lookup->isolate(), field_representation); transition_map = Map::GeneralizeRepresentation( transition_map, descriptor, field_representation, field_type, FORCE_FIELD); } JSObject::MigrateToNewProperty(object, transition_map, value); return value; } void JSObject::MigrateToNewProperty(Handle object, Handle map, Handle value) { JSObject::MigrateToMap(object, map); if (map->GetLastDescriptorDetails().type() != FIELD) return; object->WriteToField(map->LastAdded(), *value); } void JSObject::WriteToField(int descriptor, Object* value) { DisallowHeapAllocation no_gc; DescriptorArray* desc = map()->instance_descriptors(); PropertyDetails details = desc->GetDetails(descriptor); ASSERT(details.type() == FIELD); int field_index = desc->GetFieldIndex(descriptor); if (details.representation().IsDouble()) { // Nothing more to be done. if (value->IsUninitialized()) return; HeapNumber* box = HeapNumber::cast(RawFastPropertyAt(field_index)); box->set_value(value->Number()); } else { FastPropertyAtPut(field_index, value); } } static void SetPropertyToField(LookupResult* lookup, Handle value) { if (lookup->type() == CONSTANT || !lookup->CanHoldValue(value)) { Representation field_representation = value->OptimalRepresentation(); Handle field_type = value->OptimalType( lookup->isolate(), field_representation); JSObject::GeneralizeFieldRepresentation(handle(lookup->holder()), lookup->GetDescriptorIndex(), field_representation, field_type, FORCE_FIELD); } lookup->holder()->WriteToField(lookup->GetDescriptorIndex(), *value); } static void ConvertAndSetOwnProperty(LookupResult* lookup, Handle name, Handle value, PropertyAttributes attributes) { Handle object(lookup->holder()); if (object->TooManyFastProperties()) { JSObject::NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0); } if (!object->HasFastProperties()) { ReplaceSlowProperty(object, name, value, attributes); return; } int descriptor_index = lookup->GetDescriptorIndex(); if (lookup->GetAttributes() == attributes) { JSObject::GeneralizeFieldRepresentation( object, descriptor_index, Representation::Tagged(), HeapType::Any(lookup->isolate()), FORCE_FIELD); } else { Handle old_map(object->map()); Handle new_map = Map::CopyGeneralizeAllRepresentations(old_map, descriptor_index, FORCE_FIELD, attributes, "attributes mismatch"); JSObject::MigrateToMap(object, new_map); } object->WriteToField(descriptor_index, *value); } static void SetPropertyToFieldWithAttributes(LookupResult* lookup, Handle name, Handle value, PropertyAttributes attributes) { if (lookup->GetAttributes() == attributes) { if (value->IsUninitialized()) return; SetPropertyToField(lookup, value); } else { ConvertAndSetOwnProperty(lookup, name, value, attributes); } } MaybeHandle JSObject::SetPropertyForResult( Handle object, LookupResult* lookup, Handle name, Handle value, PropertyAttributes attributes, StrictMode strict_mode, StoreFromKeyed store_mode) { Isolate* isolate = object->GetIsolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); // Optimization for 2-byte strings often used as keys in a decompression // dictionary. We internalize these short keys to avoid constantly // reallocating them. if (name->IsString() && !name->IsInternalizedString() && Handle::cast(name)->length() <= 2) { name = isolate->factory()->InternalizeString(Handle::cast(name)); } // Check access rights if needed. if (object->IsAccessCheckNeeded()) { if (!isolate->MayNamedAccess(object, name, v8::ACCESS_SET)) { return SetPropertyWithFailedAccessCheck(object, lookup, name, value, true, strict_mode); } } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return value; ASSERT(proto->IsJSGlobalObject()); return SetPropertyForResult(Handle::cast(proto), lookup, name, value, attributes, strict_mode, store_mode); } ASSERT(!lookup->IsFound() || lookup->holder() == *object || lookup->holder()->map()->is_hidden_prototype()); if (!lookup->IsProperty() && !object->IsJSContextExtensionObject()) { bool done = false; Handle result_object; ASSIGN_RETURN_ON_EXCEPTION( isolate, result_object, SetPropertyViaPrototypes( object, name, value, attributes, strict_mode, &done), Object); if (done) return result_object; } if (!lookup->IsFound()) { // Neither properties nor transitions found. return AddProperty( object, name, value, attributes, strict_mode, store_mode); } if (lookup->IsProperty() && lookup->IsReadOnly()) { if (strict_mode == STRICT) { Handle args[] = { name, object }; Handle error = isolate->factory()->NewTypeError( "strict_read_only_property", HandleVector(args, ARRAY_SIZE(args))); return isolate->Throw(error); } else { return value; } } Handle old_value = isolate->factory()->the_hole_value(); bool is_observed = object->map()->is_observed() && *name != isolate->heap()->hidden_string(); if (is_observed && lookup->IsDataProperty()) { old_value = Object::GetPropertyOrElement(object, name).ToHandleChecked(); } // This is a real property that is not read-only, or it is a // transition or null descriptor and there are no setters in the prototypes. MaybeHandle maybe_result = value; if (lookup->IsTransition()) { maybe_result = SetPropertyUsingTransition(handle(lookup->holder()), lookup, name, value, attributes); } else { switch (lookup->type()) { case NORMAL: SetNormalizedProperty(handle(lookup->holder()), lookup, value); break; case FIELD: SetPropertyToField(lookup, value); break; case CONSTANT: // Only replace the constant if necessary. if (*value == lookup->GetConstant()) return value; SetPropertyToField(lookup, value); break; case CALLBACKS: { Handle callback_object(lookup->GetCallbackObject(), isolate); return SetPropertyWithCallback(object, callback_object, name, value, handle(lookup->holder()), strict_mode); } case INTERCEPTOR: maybe_result = SetPropertyWithInterceptor( handle(lookup->holder()), name, value, attributes, strict_mode); break; case HANDLER: case NONEXISTENT: UNREACHABLE(); } } Handle result; ASSIGN_RETURN_ON_EXCEPTION(isolate, result, maybe_result, Object); if (is_observed) { if (lookup->IsTransition()) { EnqueueChangeRecord(object, "add", name, old_value); } else { LookupResult new_lookup(isolate); object->LookupOwn(name, &new_lookup, true); if (new_lookup.IsDataProperty()) { Handle new_value = Object::GetPropertyOrElement(object, name).ToHandleChecked(); if (!new_value->SameValue(*old_value)) { EnqueueChangeRecord(object, "update", name, old_value); } } } } return result; } // Set a real own property, even if it is READ_ONLY. If the property is not // present, add it with attributes NONE. This code is an exact clone of // SetProperty, with the check for IsReadOnly and the check for a // callback setter removed. The two lines looking up the LookupResult // result are also added. If one of the functions is changed, the other // should be. // Note that this method cannot be used to set the prototype of a function // because ConvertDescriptorToField() which is called in "case CALLBACKS:" // doesn't handle function prototypes correctly. MaybeHandle JSObject::SetOwnPropertyIgnoreAttributes( Handle object, Handle name, Handle value, PropertyAttributes attributes, ValueType value_type, StoreMode mode, ExtensibilityCheck extensibility_check, StoreFromKeyed store_from_keyed) { Isolate* isolate = object->GetIsolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); LookupResult lookup(isolate); object->LookupOwn(name, &lookup, true); if (!lookup.IsFound()) { object->map()->LookupTransition(*object, *name, &lookup); } // Check access rights if needed. if (object->IsAccessCheckNeeded()) { if (!isolate->MayNamedAccess(object, name, v8::ACCESS_SET)) { return SetPropertyWithFailedAccessCheck(object, &lookup, name, value, false, SLOPPY); } } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return value; ASSERT(proto->IsJSGlobalObject()); return SetOwnPropertyIgnoreAttributes(Handle::cast(proto), name, value, attributes, value_type, mode, extensibility_check); } if (lookup.IsInterceptor() || (lookup.IsDescriptorOrDictionary() && lookup.type() == CALLBACKS)) { object->LookupOwnRealNamedProperty(name, &lookup); } // Check for accessor in prototype chain removed here in clone. if (!lookup.IsFound()) { object->map()->LookupTransition(*object, *name, &lookup); TransitionFlag flag = lookup.IsFound() ? OMIT_TRANSITION : INSERT_TRANSITION; // Neither properties nor transitions found. return AddProperty(object, name, value, attributes, SLOPPY, store_from_keyed, extensibility_check, value_type, mode, flag); } Handle old_value = isolate->factory()->the_hole_value(); PropertyAttributes old_attributes = ABSENT; bool is_observed = object->map()->is_observed() && *name != isolate->heap()->hidden_string(); if (is_observed && lookup.IsProperty()) { if (lookup.IsDataProperty()) { old_value = Object::GetPropertyOrElement(object, name).ToHandleChecked(); } old_attributes = lookup.GetAttributes(); } // Check of IsReadOnly removed from here in clone. if (lookup.IsTransition()) { Handle result; ASSIGN_RETURN_ON_EXCEPTION( isolate, result, SetPropertyUsingTransition( handle(lookup.holder()), &lookup, name, value, attributes), Object); } else { switch (lookup.type()) { case NORMAL: ReplaceSlowProperty(object, name, value, attributes); break; case FIELD: SetPropertyToFieldWithAttributes(&lookup, name, value, attributes); break; case CONSTANT: // Only replace the constant if necessary. if (lookup.GetAttributes() != attributes || *value != lookup.GetConstant()) { SetPropertyToFieldWithAttributes(&lookup, name, value, attributes); } break; case CALLBACKS: ConvertAndSetOwnProperty(&lookup, name, value, attributes); break; case NONEXISTENT: case HANDLER: case INTERCEPTOR: UNREACHABLE(); } } if (is_observed) { if (lookup.IsTransition()) { EnqueueChangeRecord(object, "add", name, old_value); } else if (old_value->IsTheHole()) { EnqueueChangeRecord(object, "reconfigure", name, old_value); } else { LookupResult new_lookup(isolate); object->LookupOwn(name, &new_lookup, true); bool value_changed = false; if (new_lookup.IsDataProperty()) { Handle new_value = Object::GetPropertyOrElement(object, name).ToHandleChecked(); value_changed = !old_value->SameValue(*new_value); } if (new_lookup.GetAttributes() != old_attributes) { if (!value_changed) old_value = isolate->factory()->the_hole_value(); EnqueueChangeRecord(object, "reconfigure", name, old_value); } else if (value_changed) { EnqueueChangeRecord(object, "update", name, old_value); } } } return value; } PropertyAttributes JSObject::GetPropertyAttributePostInterceptor( Handle object, Handle receiver, Handle name, bool continue_search) { // Check own property, ignore interceptor. Isolate* isolate = object->GetIsolate(); LookupResult result(isolate); object->LookupOwnRealNamedProperty(name, &result); if (result.IsFound()) return result.GetAttributes(); if (continue_search) { // Continue searching via the prototype chain. Handle proto(object->GetPrototype(), isolate); if (!proto->IsNull()) { return JSReceiver::GetPropertyAttributeWithReceiver( Handle::cast(proto), receiver, name); } } return ABSENT; } PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor( Handle object, Handle receiver, Handle name, bool continue_search) { // TODO(rossberg): Support symbols in the API. if (name->IsSymbol()) return ABSENT; Isolate* isolate = object->GetIsolate(); HandleScope scope(isolate); // Make sure that the top context does not change when doing // callbacks or interceptor calls. AssertNoContextChange ncc(isolate); Handle interceptor(object->GetNamedInterceptor()); PropertyCallbackArguments args( isolate, interceptor->data(), *receiver, *object); if (!interceptor->query()->IsUndefined()) { v8::NamedPropertyQueryCallback query = v8::ToCData(interceptor->query()); LOG(isolate, ApiNamedPropertyAccess("interceptor-named-has", *object, *name)); v8::Handle result = args.Call(query, v8::Utils::ToLocal(Handle::cast(name))); if (!result.IsEmpty()) { ASSERT(result->IsInt32()); return static_cast(result->Int32Value()); } } else if (!interceptor->getter()->IsUndefined()) { v8::NamedPropertyGetterCallback getter = v8::ToCData(interceptor->getter()); LOG(isolate, ApiNamedPropertyAccess("interceptor-named-get-has", *object, *name)); v8::Handle result = args.Call(getter, v8::Utils::ToLocal(Handle::cast(name))); if (!result.IsEmpty()) return DONT_ENUM; } return GetPropertyAttributePostInterceptor( object, receiver, name, continue_search); } PropertyAttributes JSReceiver::GetPropertyAttributeWithReceiver( Handle object, Handle receiver, Handle key) { uint32_t index = 0; if (object->IsJSObject() && key->AsArrayIndex(&index)) { return JSObject::GetElementAttributeWithReceiver( Handle::cast(object), receiver, index, true); } // Named property. LookupResult lookup(object->GetIsolate()); object->Lookup(key, &lookup); return GetPropertyAttributeForResult(object, receiver, &lookup, key, true); } PropertyAttributes JSReceiver::GetPropertyAttributeForResult( Handle object, Handle receiver, LookupResult* lookup, Handle name, bool continue_search) { // Check access rights if needed. if (object->IsAccessCheckNeeded()) { Heap* heap = object->GetHeap(); Handle obj = Handle::cast(object); if (!heap->isolate()->MayNamedAccess(obj, name, v8::ACCESS_HAS)) { return JSObject::GetPropertyAttributeWithFailedAccessCheck( obj, lookup, name, continue_search); } } if (lookup->IsFound()) { switch (lookup->type()) { case NORMAL: // fall through case FIELD: case CONSTANT: case CALLBACKS: return lookup->GetAttributes(); case HANDLER: { return JSProxy::GetPropertyAttributeWithHandler( handle(lookup->proxy()), receiver, name); } case INTERCEPTOR: return JSObject::GetPropertyAttributeWithInterceptor( handle(lookup->holder()), Handle::cast(receiver), name, continue_search); case NONEXISTENT: UNREACHABLE(); } } return ABSENT; } PropertyAttributes JSReceiver::GetOwnPropertyAttribute( Handle object, Handle name) { // Check whether the name is an array index. uint32_t index = 0; if (object->IsJSObject() && name->AsArrayIndex(&index)) { return GetOwnElementAttribute(object, index); } // Named property. LookupResult lookup(object->GetIsolate()); object->LookupOwn(name, &lookup, true); return GetPropertyAttributeForResult(object, object, &lookup, name, false); } PropertyAttributes JSObject::GetElementAttributeWithReceiver( Handle object, Handle receiver, uint32_t index, bool continue_search) { Isolate* isolate = object->GetIsolate(); // Check access rights if needed. if (object->IsAccessCheckNeeded()) { if (!isolate->MayIndexedAccess(object, index, v8::ACCESS_HAS)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_HAS); // TODO(yangguo): Issue 3269, check for scheduled exception missing? return ABSENT; } } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return ABSENT; ASSERT(proto->IsJSGlobalObject()); return JSObject::GetElementAttributeWithReceiver( Handle::cast(proto), receiver, index, continue_search); } // Check for lookup interceptor except when bootstrapping. if (object->HasIndexedInterceptor() && !isolate->bootstrapper()->IsActive()) { return JSObject::GetElementAttributeWithInterceptor( object, receiver, index, continue_search); } return GetElementAttributeWithoutInterceptor( object, receiver, index, continue_search); } PropertyAttributes JSObject::GetElementAttributeWithInterceptor( Handle object, Handle receiver, uint32_t index, bool continue_search) { Isolate* isolate = object->GetIsolate(); HandleScope scope(isolate); // Make sure that the top context does not change when doing // callbacks or interceptor calls. AssertNoContextChange ncc(isolate); Handle interceptor(object->GetIndexedInterceptor()); PropertyCallbackArguments args( isolate, interceptor->data(), *receiver, *object); if (!interceptor->query()->IsUndefined()) { v8::IndexedPropertyQueryCallback query = v8::ToCData(interceptor->query()); LOG(isolate, ApiIndexedPropertyAccess("interceptor-indexed-has", *object, index)); v8::Handle result = args.Call(query, index); if (!result.IsEmpty()) return static_cast(result->Int32Value()); } else if (!interceptor->getter()->IsUndefined()) { v8::IndexedPropertyGetterCallback getter = v8::ToCData(interceptor->getter()); LOG(isolate, ApiIndexedPropertyAccess( "interceptor-indexed-get-has", *object, index)); v8::Handle result = args.Call(getter, index); if (!result.IsEmpty()) return NONE; } return GetElementAttributeWithoutInterceptor( object, receiver, index, continue_search); } PropertyAttributes JSObject::GetElementAttributeWithoutInterceptor( Handle object, Handle receiver, uint32_t index, bool continue_search) { PropertyAttributes attr = object->GetElementsAccessor()->GetAttributes( receiver, object, index); if (attr != ABSENT) return attr; // Handle [] on String objects. if (object->IsStringObjectWithCharacterAt(index)) { return static_cast(READ_ONLY | DONT_DELETE); } if (!continue_search) return ABSENT; Handle proto(object->GetPrototype(), object->GetIsolate()); if (proto->IsJSProxy()) { // We need to follow the spec and simulate a call to [[GetOwnProperty]]. return JSProxy::GetElementAttributeWithHandler( Handle::cast(proto), receiver, index); } if (proto->IsNull()) return ABSENT; return GetElementAttributeWithReceiver( Handle::cast(proto), receiver, index, true); } 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; ASSERT(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) { if (!object->HasFastProperties()) return; // The global object is always normalized. ASSERT(!object->IsGlobalObject()); // JSGlobalProxy must never be normalized ASSERT(!object->IsJSGlobalProxy()); Isolate* isolate = object->GetIsolate(); HandleScope scope(isolate); Handle map(object->map()); Handle new_map = Map::Normalize(map, mode); // Allocate new content. int real_size = map->NumberOfOwnDescriptors(); int property_count = real_size; if (expected_additional_properties > 0) { property_count += expected_additional_properties; } else { property_count += 2; // Make space for two more properties. } 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); switch (details.type()) { case CONSTANT: { Handle key(descs->GetKey(i)); Handle value(descs->GetConstant(i), isolate); PropertyDetails d = PropertyDetails( details.attributes(), NORMAL, i + 1); dictionary = NameDictionary::Add(dictionary, key, value, d); break; } case FIELD: { Handle key(descs->GetKey(i)); Handle value( object->RawFastPropertyAt(descs->GetFieldIndex(i)), isolate); PropertyDetails d = PropertyDetails(details.attributes(), NORMAL, i + 1); dictionary = NameDictionary::Add(dictionary, key, value, d); break; } case CALLBACKS: { Handle key(descs->GetKey(i)); Handle value(descs->GetCallbacksObject(i), isolate); PropertyDetails d = PropertyDetails( details.attributes(), CALLBACKS, i + 1); dictionary = NameDictionary::Add(dictionary, key, value, d); break; } case INTERCEPTOR: break; case HANDLER: case NORMAL: case NONEXISTENT: UNREACHABLE(); break; } } // 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; // 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; ASSERT(instance_size_delta >= 0); Heap* heap = isolate->heap(); heap->CreateFillerObjectAt(object->address() + new_instance_size, instance_size_delta); heap->AdjustLiveBytes(object->address(), -instance_size_delta, Heap::FROM_MUTATOR); // 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); isolate->counters()->props_to_dictionary()->Increment(); #ifdef DEBUG if (FLAG_trace_normalization) { PrintF("Object properties have been normalized:\n"); object->Print(); } #endif } void JSObject::TransformToFastProperties(Handle object, int unused_property_fields) { if (object->HasFastProperties()) return; ASSERT(!object->IsGlobalObject()); 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; if (number_of_elements != dictionary->NextEnumerationIndex()) { NameDictionary::DoGenerateNewEnumerationIndices(dictionary); } int instance_descriptor_length = 0; int number_of_fields = 0; // Compute the length of the instance descriptor. int capacity = dictionary->Capacity(); for (int i = 0; i < capacity; i++) { Object* k = dictionary->KeyAt(i); if (dictionary->IsKey(k)) { Object* value = dictionary->ValueAt(i); PropertyType type = dictionary->DetailsAt(i).type(); ASSERT(type != FIELD); instance_descriptor_length++; if (type == NORMAL && !value->IsJSFunction()) { number_of_fields += 1; } } } int inobject_props = object->map()->inobject_properties(); // Allocate new map. Handle new_map = Map::CopyDropDescriptors(handle(object->map())); new_map->set_dictionary_map(false); if (instance_descriptor_length == 0) { DisallowHeapAllocation no_gc; ASSERT_LE(unused_property_fields, inobject_props); // Transform the object. new_map->set_unused_property_fields(inobject_props); object->set_map(*new_map); object->set_properties(isolate->heap()->empty_fixed_array()); // Check that it really works. ASSERT(object->HasFastProperties()); return; } // Allocate the instance descriptor. Handle descriptors = DescriptorArray::Allocate( isolate, instance_descriptor_length); 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 < capacity; i++) { Object* k = dictionary->KeyAt(i); if (dictionary->IsKey(k)) { Object* value = dictionary->ValueAt(i); Handle key; if (k->IsSymbol()) { key = handle(Symbol::cast(k)); } else { // Ensure the key is a unique name before writing into the // instance descriptor. key = factory->InternalizeString(handle(String::cast(k))); } PropertyDetails details = dictionary->DetailsAt(i); int enumeration_index = details.dictionary_index(); PropertyType type = details.type(); if (value->IsJSFunction()) { ConstantDescriptor d(key, handle(value, isolate), details.attributes()); descriptors->Set(enumeration_index - 1, &d); } else if (type == NORMAL) { if (current_offset < inobject_props) { object->InObjectPropertyAtPut(current_offset, value, UPDATE_WRITE_BARRIER); } else { int offset = current_offset - inobject_props; fields->set(offset, value); } FieldDescriptor d(key, current_offset++, details.attributes(), // TODO(verwaest): value->OptimalRepresentation(); Representation::Tagged()); descriptors->Set(enumeration_index - 1, &d); } else if (type == CALLBACKS) { CallbacksDescriptor d(key, handle(value, isolate), details.attributes()); descriptors->Set(enumeration_index - 1, &d); } else { UNREACHABLE(); } } } ASSERT(current_offset == number_of_fields); descriptors->Sort(); DisallowHeapAllocation no_gc; new_map->InitializeDescriptors(*descriptors); new_map->set_unused_property_fields(unused_property_fields); // Transform the object. object->set_map(*new_map); object->set_properties(*fields); ASSERT(object->IsJSObject()); // Check that it really works. ASSERT(object->HasFastProperties()); } void JSObject::ResetElements(Handle object) { if (object->map()->is_observed()) { // Maintain invariant that observed elements are always in dictionary mode. Isolate* isolate = object->GetIsolate(); Factory* factory = isolate->factory(); Handle dictionary = SeededNumberDictionary::New(isolate, 0); if (object->map() == *factory->sloppy_arguments_elements_map()) { FixedArray::cast(object->elements())->set(1, *dictionary); } else { object->set_elements(*dictionary); } return; } ElementsKind elements_kind = GetInitialFastElementsKind(); if (!FLAG_smi_only_arrays) { elements_kind = FastSmiToObjectElementsKind(elements_kind); } Handle map = JSObject::GetElementsTransitionMap(object, elements_kind); DisallowHeapAllocation no_gc; Handle elements(map->GetInitialElements()); JSObject::SetMapAndElements(object, map, elements); } static Handle CopyFastElementsToDictionary( Handle array, int length, Handle dictionary) { Isolate* isolate = array->GetIsolate(); Factory* factory = isolate->factory(); bool has_double_elements = array->IsFixedDoubleArray(); for (int i = 0; i < length; i++) { Handle value; if (has_double_elements) { Handle double_array = Handle::cast(array); if (double_array->is_the_hole(i)) { value = factory->the_hole_value(); } else { value = factory->NewHeapNumber(double_array->get_scalar(i)); } } else { value = handle(Handle::cast(array)->get(i), isolate); } if (!value->IsTheHole()) { PropertyDetails details = PropertyDetails(NONE, NORMAL, 0); dictionary = SeededNumberDictionary::AddNumberEntry(dictionary, i, value, details); } } return dictionary; } Handle JSObject::NormalizeElements( Handle object) { ASSERT(!object->HasExternalArrayElements() && !object->HasFixedTypedArrayElements()); Isolate* isolate = object->GetIsolate(); // Find the backing store. Handle array(FixedArrayBase::cast(object->elements())); bool is_arguments = (array->map() == isolate->heap()->sloppy_arguments_elements_map()); if (is_arguments) { array = handle(FixedArrayBase::cast( Handle::cast(array)->get(1))); } if (array->IsDictionary()) return Handle::cast(array); ASSERT(object->HasFastSmiOrObjectElements() || object->HasFastDoubleElements() || object->HasFastArgumentsElements()); // Compute the effective length and allocate a new backing store. int length = object->IsJSArray() ? Smi::cast(Handle::cast(object)->length())->value() : array->length(); int old_capacity = 0; int used_elements = 0; object->GetElementsCapacityAndUsage(&old_capacity, &used_elements); Handle dictionary = SeededNumberDictionary::New(isolate, used_elements); dictionary = CopyFastElementsToDictionary(array, length, dictionary); // Switch to using the dictionary as the backing storage for elements. if (is_arguments) { FixedArray::cast(object->elements())->set(1, *dictionary); } else { // Set the new map first to satify the elements type assert in // set_elements(). Handle new_map = JSObject::GetElementsTransitionMap(object, DICTIONARY_ELEMENTS); JSObject::MigrateToMap(object, new_map); object->set_elements(*dictionary); } isolate->counters()->elements_to_dictionary()->Increment(); #ifdef DEBUG if (FLAG_trace_normalization) { PrintF("Object elements have been normalized:\n"); object->Print(); } #endif ASSERT(object->HasDictionaryElements() || object->HasDictionaryArgumentsElements()); return dictionary; } static Smi* GenerateIdentityHash(Isolate* isolate) { int hash_value; int attempts = 0; do { // Generate a random 32-bit hash value but limit range to fit // within a smi. hash_value = isolate->random_number_generator()->NextInt() & Smi::kMaxValue; attempts++; } while (hash_value == 0 && attempts < 30); hash_value = hash_value != 0 ? hash_value : 1; // never return 0 return Smi::FromInt(hash_value); } void JSObject::SetIdentityHash(Handle object, Handle hash) { ASSERT(!object->IsJSGlobalProxy()); Isolate* isolate = object->GetIsolate(); SetHiddenProperty(object, isolate->factory()->identity_hash_string(), hash); } template static Handle GetOrCreateIdentityHashHelper(Handle proxy) { Isolate* isolate = proxy->GetIsolate(); Handle maybe_hash(proxy->hash(), isolate); if (maybe_hash->IsSmi()) return Handle::cast(maybe_hash); Handle hash(GenerateIdentityHash(isolate), isolate); proxy->set_hash(*hash); return hash; } Object* JSObject::GetIdentityHash() { DisallowHeapAllocation no_gc; Isolate* isolate = GetIsolate(); if (IsJSGlobalProxy()) { return JSGlobalProxy::cast(this)->hash(); } Object* stored_value = GetHiddenProperty(isolate->factory()->identity_hash_string()); return stored_value->IsSmi() ? stored_value : isolate->heap()->undefined_value(); } Handle JSObject::GetOrCreateIdentityHash(Handle object) { if (object->IsJSGlobalProxy()) { return GetOrCreateIdentityHashHelper(Handle::cast(object)); } Isolate* isolate = object->GetIsolate(); Handle maybe_hash(object->GetIdentityHash(), isolate); if (maybe_hash->IsSmi()) return Handle::cast(maybe_hash); Handle hash(GenerateIdentityHash(isolate), isolate); SetHiddenProperty(object, isolate->factory()->identity_hash_string(), hash); return hash; } Object* JSProxy::GetIdentityHash() { return this->hash(); } Handle JSProxy::GetOrCreateIdentityHash(Handle proxy) { return GetOrCreateIdentityHashHelper(proxy); } Object* JSObject::GetHiddenProperty(Handle key) { DisallowHeapAllocation no_gc; ASSERT(key->IsUniqueName()); if (IsJSGlobalProxy()) { // JSGlobalProxies store their hash internally. ASSERT(*key != GetHeap()->identity_hash_string()); // For a proxy, use the prototype as target object. Object* proxy_parent = GetPrototype(); // If the proxy is detached, return undefined. if (proxy_parent->IsNull()) return GetHeap()->the_hole_value(); ASSERT(proxy_parent->IsJSGlobalObject()); return JSObject::cast(proxy_parent)->GetHiddenProperty(key); } ASSERT(!IsJSGlobalProxy()); Object* inline_value = GetHiddenPropertiesHashTable(); if (inline_value->IsSmi()) { // Handle inline-stored identity hash. if (*key == GetHeap()->identity_hash_string()) { return inline_value; } else { return GetHeap()->the_hole_value(); } } if (inline_value->IsUndefined()) return GetHeap()->the_hole_value(); ObjectHashTable* hashtable = ObjectHashTable::cast(inline_value); Object* entry = hashtable->Lookup(key); return entry; } Handle JSObject::SetHiddenProperty(Handle object, Handle key, Handle value) { Isolate* isolate = object->GetIsolate(); ASSERT(key->IsUniqueName()); if (object->IsJSGlobalProxy()) { // JSGlobalProxies store their hash internally. ASSERT(*key != *isolate->factory()->identity_hash_string()); // For a proxy, use the prototype as target object. Handle proxy_parent(object->GetPrototype(), isolate); // If the proxy is detached, return undefined. if (proxy_parent->IsNull()) return isolate->factory()->undefined_value(); ASSERT(proxy_parent->IsJSGlobalObject()); return SetHiddenProperty(Handle::cast(proxy_parent), key, value); } ASSERT(!object->IsJSGlobalProxy()); Handle inline_value(object->GetHiddenPropertiesHashTable(), isolate); // If there is no backing store yet, store the identity hash inline. if (value->IsSmi() && *key == *isolate->factory()->identity_hash_string() && (inline_value->IsUndefined() || inline_value->IsSmi())) { return JSObject::SetHiddenPropertiesHashTable(object, value); } Handle hashtable = GetOrCreateHiddenPropertiesHashtable(object); // If it was found, check if the key is already in the dictionary. Handle new_table = ObjectHashTable::Put(hashtable, key, value); if (*new_table != *hashtable) { // If adding the key expanded the dictionary (i.e., Add returned a new // dictionary), store it back to the object. SetHiddenPropertiesHashTable(object, new_table); } // Return this to mark success. return object; } void JSObject::DeleteHiddenProperty(Handle object, Handle key) { Isolate* isolate = object->GetIsolate(); ASSERT(key->IsUniqueName()); if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return; ASSERT(proto->IsJSGlobalObject()); return DeleteHiddenProperty(Handle::cast(proto), key); } Object* inline_value = object->GetHiddenPropertiesHashTable(); // We never delete (inline-stored) identity hashes. ASSERT(*key != *isolate->factory()->identity_hash_string()); if (inline_value->IsUndefined() || inline_value->IsSmi()) return; Handle hashtable(ObjectHashTable::cast(inline_value)); ObjectHashTable::Put(hashtable, key, isolate->factory()->the_hole_value()); } bool JSObject::HasHiddenProperties(Handle object) { Handle hidden = object->GetIsolate()->factory()->hidden_string(); return GetPropertyAttributePostInterceptor( object, object, hidden, false) != ABSENT; } Object* JSObject::GetHiddenPropertiesHashTable() { ASSERT(!IsJSGlobalProxy()); if (HasFastProperties()) { // If the object has fast properties, check whether the first slot // in the descriptor array matches the hidden string. Since the // hidden strings hash code is zero (and no other name has hash // code zero) it will always occupy the first entry if present. DescriptorArray* descriptors = this->map()->instance_descriptors(); if (descriptors->number_of_descriptors() > 0) { int sorted_index = descriptors->GetSortedKeyIndex(0); if (descriptors->GetKey(sorted_index) == GetHeap()->hidden_string() && sorted_index < map()->NumberOfOwnDescriptors()) { ASSERT(descriptors->GetType(sorted_index) == FIELD); ASSERT(descriptors->GetDetails(sorted_index).representation(). IsCompatibleForLoad(Representation::Tagged())); return this->RawFastPropertyAt( descriptors->GetFieldIndex(sorted_index)); } else { return GetHeap()->undefined_value(); } } else { return GetHeap()->undefined_value(); } } else { Isolate* isolate = GetIsolate(); LookupResult result(isolate); LookupOwnRealNamedProperty(isolate->factory()->hidden_string(), &result); if (result.IsFound()) { ASSERT(result.IsNormal()); ASSERT(result.holder() == this); Object* value = GetNormalizedProperty(&result); if (!value->IsTheHole()) return value; } return GetHeap()->undefined_value(); } } Handle JSObject::GetOrCreateHiddenPropertiesHashtable( Handle object) { Isolate* isolate = object->GetIsolate(); static const int kInitialCapacity = 4; Handle inline_value(object->GetHiddenPropertiesHashTable(), isolate); if (inline_value->IsHashTable()) { return Handle::cast(inline_value); } Handle hashtable = ObjectHashTable::New( isolate, kInitialCapacity, USE_CUSTOM_MINIMUM_CAPACITY); if (inline_value->IsSmi()) { // We were storing the identity hash inline and now allocated an actual // dictionary. Put the identity hash into the new dictionary. hashtable = ObjectHashTable::Put(hashtable, isolate->factory()->identity_hash_string(), inline_value); } JSObject::SetOwnPropertyIgnoreAttributes( object, isolate->factory()->hidden_string(), hashtable, DONT_ENUM, OPTIMAL_REPRESENTATION, ALLOW_AS_CONSTANT, OMIT_EXTENSIBILITY_CHECK).Assert(); return hashtable; } Handle JSObject::SetHiddenPropertiesHashTable(Handle object, Handle value) { ASSERT(!object->IsJSGlobalProxy()); Isolate* isolate = object->GetIsolate(); // We can store the identity hash inline iff there is no backing store // for hidden properties yet. ASSERT(JSObject::HasHiddenProperties(object) != value->IsSmi()); if (object->HasFastProperties()) { // If the object has fast properties, check whether the first slot // in the descriptor array matches the hidden string. Since the // hidden strings hash code is zero (and no other name has hash // code zero) it will always occupy the first entry if present. DescriptorArray* descriptors = object->map()->instance_descriptors(); if (descriptors->number_of_descriptors() > 0) { int sorted_index = descriptors->GetSortedKeyIndex(0); if (descriptors->GetKey(sorted_index) == isolate->heap()->hidden_string() && sorted_index < object->map()->NumberOfOwnDescriptors()) { object->WriteToField(sorted_index, *value); return object; } } } SetOwnPropertyIgnoreAttributes(object, isolate->factory()->hidden_string(), value, DONT_ENUM, OPTIMAL_REPRESENTATION, ALLOW_AS_CONSTANT, OMIT_EXTENSIBILITY_CHECK).Assert(); return object; } Handle JSObject::DeletePropertyPostInterceptor(Handle object, Handle name, DeleteMode mode) { // Check own property, ignore interceptor. Isolate* isolate = object->GetIsolate(); LookupResult result(isolate); object->LookupOwnRealNamedProperty(name, &result); if (!result.IsFound()) return isolate->factory()->true_value(); // Normalize object if needed. NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0); return DeleteNormalizedProperty(object, name, mode); } MaybeHandle JSObject::DeletePropertyWithInterceptor( Handle object, Handle name) { Isolate* isolate = object->GetIsolate(); // TODO(rossberg): Support symbols in the API. if (name->IsSymbol()) return isolate->factory()->false_value(); Handle interceptor(object->GetNamedInterceptor()); if (!interceptor->deleter()->IsUndefined()) { v8::NamedPropertyDeleterCallback deleter = v8::ToCData(interceptor->deleter()); LOG(isolate, ApiNamedPropertyAccess("interceptor-named-delete", *object, *name)); PropertyCallbackArguments args( isolate, interceptor->data(), *object, *object); v8::Handle result = args.Call(deleter, v8::Utils::ToLocal(Handle::cast(name))); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); if (!result.IsEmpty()) { ASSERT(result->IsBoolean()); Handle result_internal = v8::Utils::OpenHandle(*result); result_internal->VerifyApiCallResultType(); // Rebox CustomArguments::kReturnValueOffset before returning. return handle(*result_internal, isolate); } } Handle result = DeletePropertyPostInterceptor(object, name, NORMAL_DELETION); return result; } MaybeHandle JSObject::DeleteElementWithInterceptor( Handle object, uint32_t index) { Isolate* isolate = object->GetIsolate(); Factory* factory = isolate->factory(); // Make sure that the top context does not change when doing // callbacks or interceptor calls. AssertNoContextChange ncc(isolate); Handle interceptor(object->GetIndexedInterceptor()); if (interceptor->deleter()->IsUndefined()) return factory->false_value(); v8::IndexedPropertyDeleterCallback deleter = v8::ToCData(interceptor->deleter()); LOG(isolate, ApiIndexedPropertyAccess("interceptor-indexed-delete", *object, index)); PropertyCallbackArguments args( isolate, interceptor->data(), *object, *object); v8::Handle result = args.Call(deleter, index); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); if (!result.IsEmpty()) { ASSERT(result->IsBoolean()); Handle result_internal = v8::Utils::OpenHandle(*result); result_internal->VerifyApiCallResultType(); // Rebox CustomArguments::kReturnValueOffset before returning. return handle(*result_internal, isolate); } MaybeHandle delete_result = object->GetElementsAccessor()->Delete( object, index, NORMAL_DELETION); return delete_result; } MaybeHandle JSObject::DeleteElement(Handle object, uint32_t index, DeleteMode mode) { Isolate* isolate = object->GetIsolate(); Factory* factory = isolate->factory(); // Check access rights if needed. if (object->IsAccessCheckNeeded() && !isolate->MayIndexedAccess(object, index, v8::ACCESS_DELETE)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_DELETE); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return factory->false_value(); } if (object->IsStringObjectWithCharacterAt(index)) { if (mode == STRICT_DELETION) { // Deleting a non-configurable property in strict mode. Handle name = factory->NewNumberFromUint(index); Handle args[2] = { name, object }; Handle error = factory->NewTypeError("strict_delete_property", HandleVector(args, 2)); isolate->Throw(*error); return Handle(); } return factory->false_value(); } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return factory->false_value(); ASSERT(proto->IsJSGlobalObject()); return DeleteElement(Handle::cast(proto), index, mode); } Handle old_value; bool should_enqueue_change_record = false; if (object->map()->is_observed()) { should_enqueue_change_record = HasOwnElement(object, index); if (should_enqueue_change_record) { if (!GetOwnElementAccessorPair(object, index).is_null()) { old_value = Handle::cast(factory->the_hole_value()); } else { old_value = Object::GetElement( isolate, object, index).ToHandleChecked(); } } } // Skip interceptor if forcing deletion. MaybeHandle maybe_result; if (object->HasIndexedInterceptor() && mode != FORCE_DELETION) { maybe_result = DeleteElementWithInterceptor(object, index); } else { maybe_result = object->GetElementsAccessor()->Delete(object, index, mode); } Handle result; ASSIGN_RETURN_ON_EXCEPTION(isolate, result, maybe_result, Object); if (should_enqueue_change_record && !HasOwnElement(object, index)) { Handle name = factory->Uint32ToString(index); EnqueueChangeRecord(object, "delete", name, old_value); } return result; } MaybeHandle JSObject::DeleteProperty(Handle object, Handle name, DeleteMode mode) { Isolate* isolate = object->GetIsolate(); // ECMA-262, 3rd, 8.6.2.5 ASSERT(name->IsName()); // Check access rights if needed. if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(object, name, v8::ACCESS_DELETE)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_DELETE); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->false_value(); } if (object->IsJSGlobalProxy()) { Object* proto = object->GetPrototype(); if (proto->IsNull()) return isolate->factory()->false_value(); ASSERT(proto->IsJSGlobalObject()); return JSGlobalObject::DeleteProperty( handle(JSGlobalObject::cast(proto)), name, mode); } uint32_t index = 0; if (name->AsArrayIndex(&index)) { return DeleteElement(object, index, mode); } LookupResult lookup(isolate); object->LookupOwn(name, &lookup, true); if (!lookup.IsFound()) return isolate->factory()->true_value(); // Ignore attributes if forcing a deletion. if (lookup.IsDontDelete() && mode != FORCE_DELETION) { if (mode == STRICT_DELETION) { // Deleting a non-configurable property in strict mode. Handle args[2] = { name, object }; Handle error = isolate->factory()->NewTypeError( "strict_delete_property", HandleVector(args, ARRAY_SIZE(args))); isolate->Throw(*error); return Handle(); } return isolate->factory()->false_value(); } Handle old_value = isolate->factory()->the_hole_value(); bool is_observed = object->map()->is_observed() && *name != isolate->heap()->hidden_string(); if (is_observed && lookup.IsDataProperty()) { old_value = Object::GetPropertyOrElement(object, name).ToHandleChecked(); } Handle result; // Check for interceptor. if (lookup.IsInterceptor()) { // Skip interceptor if forcing a deletion. if (mode == FORCE_DELETION) { result = DeletePropertyPostInterceptor(object, name, mode); } else { ASSIGN_RETURN_ON_EXCEPTION( isolate, result, DeletePropertyWithInterceptor(object, name), Object); } } else { // Normalize object if needed. NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0); // Make sure the properties are normalized before removing the entry. result = DeleteNormalizedProperty(object, name, mode); } if (is_observed && !HasOwnProperty(object, name)) { EnqueueChangeRecord(object, "delete", name, old_value); } return result; } MaybeHandle JSReceiver::DeleteElement(Handle object, uint32_t index, DeleteMode mode) { if (object->IsJSProxy()) { return JSProxy::DeleteElementWithHandler( Handle::cast(object), index, mode); } return JSObject::DeleteElement(Handle::cast(object), index, mode); } MaybeHandle JSReceiver::DeleteProperty(Handle object, Handle name, DeleteMode mode) { if (object->IsJSProxy()) { return JSProxy::DeletePropertyWithHandler( Handle::cast(object), name, mode); } return JSObject::DeleteProperty(Handle::cast(object), name, mode); } bool JSObject::ReferencesObjectFromElements(FixedArray* elements, ElementsKind kind, Object* object) { ASSERT(IsFastObjectElementsKind(kind) || kind == DICTIONARY_ELEMENTS); if (IsFastObjectElementsKind(kind)) { 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() && element == object) return true; } } else { Object* key = SeededNumberDictionary::cast(elements)->SlowReverseLookup(object); if (!key->IsUndefined()) 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->constructor() == 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()) { 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 EXTERNAL_##TYPE##_ELEMENTS: \ 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: { FixedArray* elements = FixedArray::cast(this->elements()); if (ReferencesObjectFromElements(elements, kind, obj)) return true; break; } case 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() && 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; } } // For functions check the context. if (IsJSFunction()) { // Get the constructor function for arguments array. JSObject* arguments_boilerplate = heap->isolate()->context()->native_context()-> sloppy_arguments_boilerplate(); JSFunction* arguments_function = JSFunction::cast(arguments_boilerplate->map()->constructor()); // 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()->constructor() == 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 global context. // TODO(mvstanton): walk into the ScopeInfo. if (FLAG_harmony_scoping && context->IsGlobalContext()) { return false; } return JSObject::cast(context->extension())->ReferencesObject(obj); } } // No references to object. return false; } MaybeHandle JSObject::PreventExtensions(Handle object) { Isolate* isolate = object->GetIsolate(); if (!object->map()->is_extensible()) return object; if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess( object, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_KEYS); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->false_value(); } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return object; ASSERT(proto->IsJSGlobalObject()); return PreventExtensions(Handle::cast(proto)); } // It's not possible to seal objects with external array elements if (object->HasExternalArrayElements() || object->HasFixedTypedArrayElements()) { Handle error = isolate->factory()->NewTypeError( "cant_prevent_ext_external_array_elements", HandleVector(&object, 1)); return isolate->Throw(error); } // If there are fast elements we normalize. Handle dictionary = NormalizeElements(object); ASSERT(object->HasDictionaryElements() || object->HasDictionaryArgumentsElements()); // Make sure that we never go back to fast case. dictionary->set_requires_slow_elements(); // 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())); new_map->set_is_extensible(false); JSObject::MigrateToMap(object, new_map); ASSERT(!object->map()->is_extensible()); if (object->map()->is_observed()) { EnqueueChangeRecord(object, "preventExtensions", Handle(), isolate->factory()->the_hole_value()); } return object; } template static void FreezeDictionary(Dictionary* dictionary) { int capacity = dictionary->Capacity(); for (int i = 0; i < capacity; i++) { Object* k = dictionary->KeyAt(i); if (dictionary->IsKey(k)) { PropertyDetails details = dictionary->DetailsAt(i); int attrs = DONT_DELETE; // READ_ONLY is an invalid attribute for JS setters/getters. if (details.type() == CALLBACKS) { Object* v = dictionary->ValueAt(i); if (v->IsPropertyCell()) v = PropertyCell::cast(v)->value(); if (!v->IsAccessorPair()) attrs |= READ_ONLY; } else { attrs |= READ_ONLY; } details = details.CopyAddAttributes( static_cast(attrs)); dictionary->DetailsAtPut(i, details); } } } MaybeHandle JSObject::Freeze(Handle object) { // Freezing sloppy arguments should be handled elsewhere. ASSERT(!object->HasSloppyArgumentsElements()); ASSERT(!object->map()->is_observed()); if (object->map()->is_frozen()) return object; Isolate* isolate = object->GetIsolate(); if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess( object, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_KEYS); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->false_value(); } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return object; ASSERT(proto->IsJSGlobalObject()); return Freeze(Handle::cast(proto)); } // It's not possible to freeze objects with external array elements if (object->HasExternalArrayElements() || object->HasFixedTypedArrayElements()) { Handle error = isolate->factory()->NewTypeError( "cant_prevent_ext_external_array_elements", HandleVector(&object, 1)); return isolate->Throw(error); } Handle new_element_dictionary; if (!object->elements()->IsDictionary()) { int length = object->IsJSArray() ? Smi::cast(Handle::cast(object)->length())->value() : object->elements()->length(); if (length > 0) { int capacity = 0; int used = 0; object->GetElementsCapacityAndUsage(&capacity, &used); new_element_dictionary = SeededNumberDictionary::New(isolate, used); // Move elements to a dictionary; avoid calling NormalizeElements to avoid // unnecessary transitions. new_element_dictionary = CopyFastElementsToDictionary( handle(object->elements()), length, new_element_dictionary); } else { // No existing elements, use a pre-allocated empty backing store new_element_dictionary = isolate->factory()->empty_slow_element_dictionary(); } } Handle old_map(object->map(), isolate); int transition_index = old_map->SearchTransition( isolate->heap()->frozen_symbol()); if (transition_index != TransitionArray::kNotFound) { Handle transition_map(old_map->GetTransition(transition_index)); ASSERT(transition_map->has_dictionary_elements()); ASSERT(transition_map->is_frozen()); ASSERT(!transition_map->is_extensible()); JSObject::MigrateToMap(object, transition_map); } else if (object->HasFastProperties() && old_map->CanHaveMoreTransitions()) { // Create a new descriptor array with fully-frozen properties Handle new_map = Map::CopyForFreeze(old_map); JSObject::MigrateToMap(object, new_map); } else { // Slow path: need to normalize properties for safety NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0); // 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())); new_map->freeze(); new_map->set_is_extensible(false); new_map->set_elements_kind(DICTIONARY_ELEMENTS); JSObject::MigrateToMap(object, new_map); // Freeze dictionary-mode properties FreezeDictionary(object->property_dictionary()); } ASSERT(object->map()->has_dictionary_elements()); if (!new_element_dictionary.is_null()) { object->set_elements(*new_element_dictionary); } if (object->elements() != isolate->heap()->empty_slow_element_dictionary()) { SeededNumberDictionary* dictionary = object->element_dictionary(); // Make sure we never go back to the fast case dictionary->set_requires_slow_elements(); // Freeze all elements in the dictionary FreezeDictionary(dictionary); } return object; } void JSObject::SetObserved(Handle object) { ASSERT(!object->IsJSGlobalProxy()); ASSERT(!object->IsJSGlobalObject()); Isolate* isolate = object->GetIsolate(); Handle new_map; Handle old_map(object->map(), isolate); ASSERT(!old_map->is_observed()); int transition_index = old_map->SearchTransition( isolate->heap()->observed_symbol()); if (transition_index != TransitionArray::kNotFound) { new_map = handle(old_map->GetTransition(transition_index), isolate); ASSERT(new_map->is_observed()); } else if (object->HasFastProperties() && old_map->CanHaveMoreTransitions()) { new_map = Map::CopyForObserved(old_map); } else { new_map = Map::Copy(old_map); new_map->set_is_observed(); } JSObject::MigrateToMap(object, new_map); } Handle JSObject::FastPropertyAt(Handle object, Representation representation, int index) { Isolate* isolate = object->GetIsolate(); Handle raw_value(object->RawFastPropertyAt(index), isolate); return Object::NewStorageFor(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::kObjectIsShallowArray; if (!shallow) { StackLimitCheck check(isolate); if (check.HasOverflowed()) { isolate->StackOverflow(); return MaybeHandle(); } } if (object->map()->is_deprecated()) { JSObject::MigrateInstance(object); } Handle copy; if (copying) { 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; } ASSERT(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.type() != FIELD) continue; int index = descriptors->GetFieldIndex(i); Handle value(object->RawFastPropertyAt(index), isolate); if (value->IsJSObject()) { ASSIGN_RETURN_ON_EXCEPTION( isolate, value, VisitElementOrProperty(copy, Handle::cast(value)), JSObject); } else { Representation representation = details.representation(); value = Object::NewStorageFor(isolate, value, representation); } if (copying) { copy->FastPropertyAtPut(index, *value); } } } else { Handle names = isolate->factory()->NewFixedArray(copy->NumberOfOwnProperties()); copy->GetOwnPropertyNames(*names, 0); for (int i = 0; i < names->length(); i++) { ASSERT(names->get(i)->IsString()); Handle key_string(String::cast(names->get(i))); PropertyAttributes attributes = JSReceiver::GetOwnPropertyAttribute(copy, key_string); // Only deep copy fields from the object literal expression. // In particular, don't try to copy the length attribute of // an array. if (attributes != NONE) continue; Handle value = Object::GetProperty(copy, key_string).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, key_string, result, NONE, SLOPPY).Assert(); } } } } // Deep copy own elements. // Pixel elements cannot be created using an object literal. ASSERT(!copy->HasExternalArrayElements()); switch (kind) { case FAST_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_HOLEY_SMI_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++) { ASSERT(!elements->get(i)->IsJSObject()); } #endif } else { for (int i = 0; i < elements->length(); i++) { Handle value(elements->get(i), isolate); ASSERT(value->IsSmi() || value->IsTheHole() || (IsFastObjectElementsKind(copy->GetElementsKind()))); 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(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 SLOPPY_ARGUMENTS_ELEMENTS: UNIMPLEMENTED(); break; #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ELEMENTS: \ case TYPE##_ELEMENTS: \ TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_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; ASSERT(!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; ASSERT(!copy.ToHandle(&for_assert) || !for_assert.is_identical_to(object)); return copy; } Handle JSObject::GetDataProperty(Handle object, Handle key) { Isolate* isolate = object->GetIsolate(); LookupResult lookup(isolate); { DisallowHeapAllocation no_allocation; object->LookupRealNamedProperty(key, &lookup); } Handle result = isolate->factory()->undefined_value(); if (lookup.IsFound() && !lookup.IsTransition()) { switch (lookup.type()) { case NORMAL: result = GetNormalizedProperty( Handle(lookup.holder(), isolate), &lookup); break; case FIELD: result = FastPropertyAt(Handle(lookup.holder(), isolate), lookup.representation(), lookup.GetFieldIndex().field_index()); break; case CONSTANT: result = Handle(lookup.GetConstant(), isolate); break; case CALLBACKS: case HANDLER: case INTERCEPTOR: break; case NONEXISTENT: UNREACHABLE(); } } return result; } // Tests for the fast common case for property enumeration: // - This object and all prototypes has an enum cache (which means that // it is no proxy, has no interceptors and needs no access checks). // - This object has no elements. // - No prototype has enumerable properties/elements. bool JSReceiver::IsSimpleEnum() { Heap* heap = GetHeap(); for (Object* o = this; o != heap->null_value(); o = JSObject::cast(o)->GetPrototype()) { if (!o->IsJSObject()) return false; JSObject* curr = JSObject::cast(o); int enum_length = curr->map()->EnumLength(); if (enum_length == kInvalidEnumCacheSentinel) return false; if (curr->IsAccessCheckNeeded()) return false; ASSERT(!curr->HasNamedInterceptor()); ASSERT(!curr->HasIndexedInterceptor()); if (curr->NumberOfEnumElements() > 0) return false; if (curr != this && enum_length != 0) return false; } return true; } static bool FilterKey(Object* key, PropertyAttributes filter) { if ((filter & SYMBOLIC) && key->IsSymbol()) { return true; } if ((filter & PRIVATE_SYMBOL) && key->IsSymbol() && Symbol::cast(key)->is_private()) { return true; } if ((filter & STRING) && !key->IsSymbol()) { return true; } return false; } int Map::NumberOfDescribedProperties(DescriptorFlag which, PropertyAttributes 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 && !FilterKey(descs->GetKey(i), filter)) { result++; } } return result; } int Map::NextFreePropertyIndex() { int max_index = -1; int number_of_own_descriptors = NumberOfOwnDescriptors(); DescriptorArray* descs = instance_descriptors(); for (int i = 0; i < number_of_own_descriptors; i++) { if (descs->GetType(i) == FIELD) { int current_index = descs->GetFieldIndex(i); if (current_index > max_index) max_index = current_index; } } return max_index + 1; } void JSReceiver::LookupOwn( Handle name, LookupResult* result, bool search_hidden_prototypes) { DisallowHeapAllocation no_gc; ASSERT(name->IsName()); if (IsJSGlobalProxy()) { Object* proto = GetPrototype(); if (proto->IsNull()) return result->NotFound(); ASSERT(proto->IsJSGlobalObject()); return JSReceiver::cast(proto)->LookupOwn( name, result, search_hidden_prototypes); } if (IsJSProxy()) { result->HandlerResult(JSProxy::cast(this)); return; } // Do not use inline caching if the object is a non-global object // that requires access checks. if (IsAccessCheckNeeded()) { result->DisallowCaching(); } JSObject* js_object = JSObject::cast(this); // Check for lookup interceptor except when bootstrapping. if (js_object->HasNamedInterceptor() && !GetIsolate()->bootstrapper()->IsActive()) { result->InterceptorResult(js_object); return; } js_object->LookupOwnRealNamedProperty(name, result); if (result->IsFound() || !search_hidden_prototypes) return; Object* proto = js_object->GetPrototype(); if (!proto->IsJSReceiver()) return; JSReceiver* receiver = JSReceiver::cast(proto); if (receiver->map()->is_hidden_prototype()) { receiver->LookupOwn(name, result, search_hidden_prototypes); } } void JSReceiver::Lookup(Handle name, LookupResult* result) { DisallowHeapAllocation no_gc; // Ecma-262 3rd 8.6.2.4 Handle null_value = GetIsolate()->factory()->null_value(); for (Object* current = this; current != *null_value; current = JSObject::cast(current)->GetPrototype()) { JSReceiver::cast(current)->LookupOwn(name, result, false); if (result->IsFound()) return; } result->NotFound(); } // Search object and its prototype chain for callback properties. void JSObject::LookupCallbackProperty(Handle name, LookupResult* result) { DisallowHeapAllocation no_gc; Handle null_value = GetIsolate()->factory()->null_value(); for (Object* current = this; current != *null_value && current->IsJSObject(); current = JSObject::cast(current)->GetPrototype()) { JSObject::cast(current)->LookupOwnRealNamedProperty(name, result); if (result->IsPropertyCallbacks()) return; } result->NotFound(); } static bool ContainsOnlyValidKeys(Handle array) { int len = array->length(); for (int i = 0; i < len; i++) { Object* e = array->get(i); if (!(e->IsString() || e->IsNumber())) return false; } return true; } static Handle ReduceFixedArrayTo( Handle array, int length) { ASSERT(array->length() >= length); if (array->length() == length) return array; Handle new_array = array->GetIsolate()->factory()->NewFixedArray(length); for (int i = 0; i < length; ++i) new_array->set(i, array->get(i)); return new_array; } static Handle GetEnumPropertyKeys(Handle object, bool cache_result) { Isolate* isolate = object->GetIsolate(); if (object->HasFastProperties()) { int own_property_count = object->map()->EnumLength(); // If the enum length of the given map is set to kInvalidEnumCache, this // means that the map itself has never used the present enum cache. The // first step to using the cache is to set the enum length of the map by // counting the number of own descriptors that are not DONT_ENUM or // SYMBOLIC. if (own_property_count == kInvalidEnumCacheSentinel) { own_property_count = object->map()->NumberOfDescribedProperties( OWN_DESCRIPTORS, DONT_SHOW); } else { ASSERT(own_property_count == object->map()->NumberOfDescribedProperties( OWN_DESCRIPTORS, DONT_SHOW)); } if (object->map()->instance_descriptors()->HasEnumCache()) { DescriptorArray* desc = object->map()->instance_descriptors(); Handle keys(desc->GetEnumCache(), isolate); // In case the number of properties required in the enum are actually // present, we can reuse the enum cache. Otherwise, this means that the // enum cache was generated for a previous (smaller) version of the // Descriptor Array. In that case we regenerate the enum cache. if (own_property_count <= keys->length()) { if (cache_result) object->map()->SetEnumLength(own_property_count); isolate->counters()->enum_cache_hits()->Increment(); return ReduceFixedArrayTo(keys, own_property_count); } } Handle map(object->map()); if (map->instance_descriptors()->IsEmpty()) { isolate->counters()->enum_cache_hits()->Increment(); if (cache_result) map->SetEnumLength(0); return isolate->factory()->empty_fixed_array(); } isolate->counters()->enum_cache_misses()->Increment(); Handle storage = isolate->factory()->NewFixedArray( own_property_count); Handle indices = isolate->factory()->NewFixedArray( own_property_count); Handle descs = Handle(object->map()->instance_descriptors(), isolate); int size = map->NumberOfOwnDescriptors(); int index = 0; for (int i = 0; i < size; i++) { PropertyDetails details = descs->GetDetails(i); Object* key = descs->GetKey(i); if (!(details.IsDontEnum() || key->IsSymbol())) { storage->set(index, key); if (!indices.is_null()) { if (details.type() != FIELD) { indices = Handle(); } else { int field_index = descs->GetFieldIndex(i); if (field_index >= map->inobject_properties()) { field_index = -(field_index - map->inobject_properties() + 1); } field_index = field_index << 1; if (details.representation().IsDouble()) { field_index |= 1; } indices->set(index, Smi::FromInt(field_index)); } } index++; } } ASSERT(index == storage->length()); Handle bridge_storage = isolate->factory()->NewFixedArray( DescriptorArray::kEnumCacheBridgeLength); DescriptorArray* desc = object->map()->instance_descriptors(); desc->SetEnumCache(*bridge_storage, *storage, indices.is_null() ? Object::cast(Smi::FromInt(0)) : Object::cast(*indices)); if (cache_result) { object->map()->SetEnumLength(own_property_count); } return storage; } else { Handle dictionary(object->property_dictionary()); int length = dictionary->NumberOfEnumElements(); if (length == 0) { return Handle(isolate->heap()->empty_fixed_array()); } Handle storage = isolate->factory()->NewFixedArray(length); dictionary->CopyEnumKeysTo(*storage); return storage; } } MaybeHandle JSReceiver::GetKeys(Handle object, KeyCollectionType type) { USE(ContainsOnlyValidKeys); Isolate* isolate = object->GetIsolate(); Handle content = isolate->factory()->empty_fixed_array(); Handle arguments_boilerplate = Handle( isolate->context()->native_context()->sloppy_arguments_boilerplate(), isolate); Handle arguments_function = Handle( JSFunction::cast(arguments_boilerplate->map()->constructor()), isolate); // Only collect keys if access is permitted. for (Handle p = object; *p != isolate->heap()->null_value(); p = Handle(p->GetPrototype(isolate), isolate)) { if (p->IsJSProxy()) { Handle proxy(JSProxy::cast(*p), isolate); Handle args[] = { proxy }; Handle names; ASSIGN_RETURN_ON_EXCEPTION( isolate, names, Execution::Call(isolate, isolate->proxy_enumerate(), object, ARRAY_SIZE(args), args), FixedArray); ASSIGN_RETURN_ON_EXCEPTION( isolate, content, FixedArray::AddKeysFromArrayLike( content, Handle::cast(names)), FixedArray); break; } Handle current(JSObject::cast(*p), isolate); // Check access rights if required. if (current->IsAccessCheckNeeded() && !isolate->MayNamedAccess( current, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) { isolate->ReportFailedAccessCheck(current, v8::ACCESS_KEYS); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, FixedArray); break; } // Compute the element keys. Handle element_keys = isolate->factory()->NewFixedArray(current->NumberOfEnumElements()); current->GetEnumElementKeys(*element_keys); ASSIGN_RETURN_ON_EXCEPTION( isolate, content, FixedArray::UnionOfKeys(content, element_keys), FixedArray); ASSERT(ContainsOnlyValidKeys(content)); // Add the element keys from the interceptor. if (current->HasIndexedInterceptor()) { Handle result; if (JSObject::GetKeysForIndexedInterceptor( current, object).ToHandle(&result)) { ASSIGN_RETURN_ON_EXCEPTION( isolate, content, FixedArray::AddKeysFromArrayLike(content, result), FixedArray); } ASSERT(ContainsOnlyValidKeys(content)); } // We can cache the computed property keys if access checks are // not needed and no interceptors are involved. // // We do not use the cache if the object has elements and // therefore it does not make sense to cache the property names // for arguments objects. Arguments objects will always have // elements. // Wrapped strings have elements, but don't have an elements // array or dictionary. So the fast inline test for whether to // use the cache says yes, so we should not create a cache. bool cache_enum_keys = ((current->map()->constructor() != *arguments_function) && !current->IsJSValue() && !current->IsAccessCheckNeeded() && !current->HasNamedInterceptor() && !current->HasIndexedInterceptor()); // Compute the property keys and cache them if possible. ASSIGN_RETURN_ON_EXCEPTION( isolate, content, FixedArray::UnionOfKeys( content, GetEnumPropertyKeys(current, cache_enum_keys)), FixedArray); ASSERT(ContainsOnlyValidKeys(content)); // Add the property keys from the interceptor. if (current->HasNamedInterceptor()) { Handle result; if (JSObject::GetKeysForNamedInterceptor( current, object).ToHandle(&result)) { ASSIGN_RETURN_ON_EXCEPTION( isolate, content, FixedArray::AddKeysFromArrayLike(content, result), FixedArray); } ASSERT(ContainsOnlyValidKeys(content)); } // If we only want own properties we bail out after the first // iteration. if (type == OWN_ONLY) break; } return content; } // Try to update an accessor in an elements dictionary. Return true if the // update succeeded, and false otherwise. static bool UpdateGetterSetterInDictionary( SeededNumberDictionary* dictionary, uint32_t index, Object* getter, Object* setter, PropertyAttributes attributes) { int entry = dictionary->FindEntry(index); if (entry != SeededNumberDictionary::kNotFound) { Object* result = dictionary->ValueAt(entry); PropertyDetails details = dictionary->DetailsAt(entry); if (details.type() == CALLBACKS && result->IsAccessorPair()) { ASSERT(!details.IsDontDelete()); if (details.attributes() != attributes) { dictionary->DetailsAtPut( entry, PropertyDetails(attributes, CALLBACKS, index)); } AccessorPair::cast(result)->SetComponents(getter, setter); return true; } } return false; } void JSObject::DefineElementAccessor(Handle object, uint32_t index, Handle getter, Handle setter, PropertyAttributes attributes, v8::AccessControl access_control) { switch (object->GetElementsKind()) { case FAST_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: break; #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ELEMENTS: \ case TYPE##_ELEMENTS: \ TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE // Ignore getters and setters on pixel and external array elements. return; case DICTIONARY_ELEMENTS: if (UpdateGetterSetterInDictionary(object->element_dictionary(), index, *getter, *setter, attributes)) { return; } break; case SLOPPY_ARGUMENTS_ELEMENTS: { // Ascertain whether we have read-only properties or an existing // getter/setter pair in an arguments elements dictionary backing // store. FixedArray* parameter_map = FixedArray::cast(object->elements()); uint32_t length = parameter_map->length(); Object* probe = index < (length - 2) ? parameter_map->get(index + 2) : NULL; if (probe == NULL || probe->IsTheHole()) { FixedArray* arguments = FixedArray::cast(parameter_map->get(1)); if (arguments->IsDictionary()) { SeededNumberDictionary* dictionary = SeededNumberDictionary::cast(arguments); if (UpdateGetterSetterInDictionary(dictionary, index, *getter, *setter, attributes)) { return; } } } break; } } Isolate* isolate = object->GetIsolate(); Handle accessors = isolate->factory()->NewAccessorPair(); accessors->SetComponents(*getter, *setter); accessors->set_access_flags(access_control); SetElementCallback(object, index, accessors, attributes); } Handle JSObject::CreateAccessorPairFor(Handle object, Handle name) { Isolate* isolate = object->GetIsolate(); LookupResult result(isolate); object->LookupOwnRealNamedProperty(name, &result); if (result.IsPropertyCallbacks()) { // Note that the result can actually have IsDontDelete() == true when we // e.g. have to fall back to the slow case while adding a setter after // successfully reusing a map transition for a getter. Nevertheless, this is // OK, because the assertion only holds for the whole addition of both // accessors, not for the addition of each part. See first comment in // DefinePropertyAccessor below. Object* obj = result.GetCallbackObject(); if (obj->IsAccessorPair()) { return AccessorPair::Copy(handle(AccessorPair::cast(obj), isolate)); } } return isolate->factory()->NewAccessorPair(); } void JSObject::DefinePropertyAccessor(Handle object, Handle name, Handle getter, Handle setter, PropertyAttributes attributes, v8::AccessControl access_control) { // We could assert that the property is configurable here, but we would need // to do a lookup, which seems to be a bit of overkill. bool only_attribute_changes = getter->IsNull() && setter->IsNull(); if (object->HasFastProperties() && !only_attribute_changes && access_control == v8::DEFAULT && (object->map()->NumberOfOwnDescriptors() <= kMaxNumberOfDescriptors)) { bool getterOk = getter->IsNull() || DefineFastAccessor(object, name, ACCESSOR_GETTER, getter, attributes); bool setterOk = !getterOk || setter->IsNull() || DefineFastAccessor(object, name, ACCESSOR_SETTER, setter, attributes); if (getterOk && setterOk) return; } Handle accessors = CreateAccessorPairFor(object, name); accessors->SetComponents(*getter, *setter); accessors->set_access_flags(access_control); SetPropertyCallback(object, name, accessors, attributes); } bool JSObject::CanSetCallback(Handle object, Handle name) { Isolate* isolate = object->GetIsolate(); ASSERT(!object->IsAccessCheckNeeded() || isolate->MayNamedAccess(object, name, v8::ACCESS_SET)); // Check if there is an API defined callback object which prohibits // callback overwriting in this object or its prototype chain. // This mechanism is needed for instance in a browser setting, where // certain accessors such as window.location should not be allowed // to be overwritten because allowing overwriting could potentially // cause security problems. LookupResult callback_result(isolate); object->LookupCallbackProperty(name, &callback_result); if (callback_result.IsFound()) { Object* callback_obj = callback_result.GetCallbackObject(); if (callback_obj->IsAccessorInfo()) { return !AccessorInfo::cast(callback_obj)->prohibits_overwriting(); } if (callback_obj->IsAccessorPair()) { return !AccessorPair::cast(callback_obj)->prohibits_overwriting(); } } return true; } bool Map::DictionaryElementsInPrototypeChainOnly() { Heap* heap = GetHeap(); if (IsDictionaryElementsKind(elements_kind())) { return false; } for (Object* prototype = this->prototype(); prototype != heap->null_value(); prototype = prototype->GetPrototype(GetIsolate())) { if (prototype->IsJSProxy()) { // Be conservative, don't walk into proxies. return true; } if (IsDictionaryElementsKind( JSObject::cast(prototype)->map()->elements_kind())) { return true; } } return false; } void JSObject::SetElementCallback(Handle object, uint32_t index, Handle structure, PropertyAttributes attributes) { Heap* heap = object->GetHeap(); PropertyDetails details = PropertyDetails(attributes, CALLBACKS, 0); // Normalize elements to make this operation simple. bool had_dictionary_elements = object->HasDictionaryElements(); Handle dictionary = NormalizeElements(object); ASSERT(object->HasDictionaryElements() || object->HasDictionaryArgumentsElements()); // Update the dictionary with the new CALLBACKS property. dictionary = SeededNumberDictionary::Set(dictionary, index, structure, details); dictionary->set_requires_slow_elements(); // Update the dictionary backing store on the object. if (object->elements()->map() == heap->sloppy_arguments_elements_map()) { // Also delete any parameter alias. // // TODO(kmillikin): when deleting the last parameter alias we could // switch to a direct backing store without the parameter map. This // would allow GC of the context. FixedArray* parameter_map = FixedArray::cast(object->elements()); if (index < static_cast(parameter_map->length()) - 2) { parameter_map->set(index + 2, heap->the_hole_value()); } parameter_map->set(1, *dictionary); } else { object->set_elements(*dictionary); if (!had_dictionary_elements) { // KeyedStoreICs (at least the non-generic ones) need a reset. heap->ClearAllICsByKind(Code::KEYED_STORE_IC); } } } void JSObject::SetPropertyCallback(Handle object, Handle name, Handle structure, PropertyAttributes attributes) { // Normalize object to make this operation simple. NormalizeProperties(object, CLEAR_INOBJECT_PROPERTIES, 0); // For the global object allocate a new map to invalidate the global inline // caches which have a global property cell reference directly in the code. if (object->IsGlobalObject()) { Handle new_map = Map::CopyDropDescriptors(handle(object->map())); ASSERT(new_map->is_dictionary_map()); object->set_map(*new_map); // When running crankshaft, changing the map is not enough. We // need to deoptimize all functions that rely on this global // object. Deoptimizer::DeoptimizeGlobalObject(*object); } // Update the dictionary with the new CALLBACKS property. PropertyDetails details = PropertyDetails(attributes, CALLBACKS, 0); SetNormalizedProperty(object, name, structure, details); } void JSObject::DefineAccessor(Handle object, Handle name, Handle getter, Handle setter, PropertyAttributes attributes, v8::AccessControl access_control) { Isolate* isolate = object->GetIsolate(); // Check access rights if needed. if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(object, name, v8::ACCESS_SET)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_SET); // TODO(yangguo): Issue 3269, check for scheduled exception missing? return; } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return; ASSERT(proto->IsJSGlobalObject()); DefineAccessor(Handle::cast(proto), name, getter, setter, attributes, access_control); return; } // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); // Try to flatten before operating on the string. if (name->IsString()) name = String::Flatten(Handle::cast(name)); if (!JSObject::CanSetCallback(object, name)) return; uint32_t index = 0; bool is_element = name->AsArrayIndex(&index); Handle old_value = isolate->factory()->the_hole_value(); bool is_observed = object->map()->is_observed() && *name != isolate->heap()->hidden_string(); bool preexists = false; if (is_observed) { if (is_element) { preexists = HasOwnElement(object, index); if (preexists && GetOwnElementAccessorPair(object, index).is_null()) { old_value = Object::GetElement(isolate, object, index).ToHandleChecked(); } } else { LookupResult lookup(isolate); object->LookupOwn(name, &lookup, true); preexists = lookup.IsProperty(); if (preexists && lookup.IsDataProperty()) { old_value = Object::GetPropertyOrElement(object, name).ToHandleChecked(); } } } if (is_element) { DefineElementAccessor( object, index, getter, setter, attributes, access_control); } else { DefinePropertyAccessor( object, name, getter, setter, attributes, access_control); } if (is_observed) { const char* type = preexists ? "reconfigure" : "add"; EnqueueChangeRecord(object, type, name, old_value); } } static bool TryAccessorTransition(Handle self, Handle transitioned_map, int target_descriptor, AccessorComponent component, Handle accessor, PropertyAttributes attributes) { DescriptorArray* descs = transitioned_map->instance_descriptors(); PropertyDetails details = descs->GetDetails(target_descriptor); // If the transition target was not callbacks, fall back to the slow case. if (details.type() != CALLBACKS) return false; Object* descriptor = descs->GetCallbacksObject(target_descriptor); if (!descriptor->IsAccessorPair()) return false; Object* target_accessor = AccessorPair::cast(descriptor)->get(component); PropertyAttributes target_attributes = details.attributes(); // Reuse transition if adding same accessor with same attributes. if (target_accessor == *accessor && target_attributes == attributes) { JSObject::MigrateToMap(self, transitioned_map); return true; } // If either not the same accessor, or not the same attributes, fall back to // the slow case. return false; } bool JSObject::DefineFastAccessor(Handle object, Handle name, AccessorComponent component, Handle accessor, PropertyAttributes attributes) { ASSERT(accessor->IsSpecFunction() || accessor->IsUndefined()); Isolate* isolate = object->GetIsolate(); LookupResult result(isolate); object->LookupOwn(name, &result); if (result.IsFound() && !result.IsPropertyCallbacks()) { return false; } // Return success if the same accessor with the same attributes already exist. AccessorPair* source_accessors = NULL; if (result.IsPropertyCallbacks()) { Object* callback_value = result.GetCallbackObject(); if (callback_value->IsAccessorPair()) { source_accessors = AccessorPair::cast(callback_value); Object* entry = source_accessors->get(component); if (entry == *accessor && result.GetAttributes() == attributes) { return true; } } else { return false; } int descriptor_number = result.GetDescriptorIndex(); object->map()->LookupTransition(*object, *name, &result); if (result.IsFound()) { Handle target(result.GetTransitionTarget()); ASSERT(target->NumberOfOwnDescriptors() == object->map()->NumberOfOwnDescriptors()); // This works since descriptors are sorted in order of addition. ASSERT(object->map()->instance_descriptors()-> GetKey(descriptor_number) == *name); return TryAccessorTransition(object, target, descriptor_number, component, accessor, attributes); } } else { // If not, lookup a transition. object->map()->LookupTransition(*object, *name, &result); // If there is a transition, try to follow it. if (result.IsFound()) { Handle target(result.GetTransitionTarget()); int descriptor_number = target->LastAdded(); ASSERT(Name::Equals(name, handle(target->instance_descriptors()->GetKey(descriptor_number)))); return TryAccessorTransition(object, target, descriptor_number, component, accessor, attributes); } } // If there is no transition yet, add a transition to the a new accessor pair // containing the accessor. Allocate a new pair if there were no source // accessors. Otherwise, copy the pair and modify the accessor. Handle accessors = source_accessors != NULL ? AccessorPair::Copy(Handle(source_accessors)) : isolate->factory()->NewAccessorPair(); accessors->set(component, *accessor); CallbacksDescriptor new_accessors_desc(name, accessors, attributes); Handle new_map = Map::CopyInsertDescriptor( handle(object->map()), &new_accessors_desc, INSERT_TRANSITION); JSObject::MigrateToMap(object, new_map); return true; } MaybeHandle JSObject::SetAccessor(Handle object, Handle info) { Isolate* isolate = object->GetIsolate(); Factory* factory = isolate->factory(); Handle name(Name::cast(info->name())); // Check access rights if needed. if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(object, name, v8::ACCESS_SET)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_SET); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return factory->undefined_value(); } if (object->IsJSGlobalProxy()) { Handle proto(object->GetPrototype(), isolate); if (proto->IsNull()) return object; ASSERT(proto->IsJSGlobalObject()); return SetAccessor(Handle::cast(proto), info); } // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); // Try to flatten before operating on the string. if (name->IsString()) name = String::Flatten(Handle::cast(name)); if (!JSObject::CanSetCallback(object, name)) { return factory->undefined_value(); } uint32_t index = 0; bool is_element = name->AsArrayIndex(&index); if (is_element) { if (object->IsJSArray()) return factory->undefined_value(); // Accessors overwrite previous callbacks (cf. with getters/setters). switch (object->GetElementsKind()) { case FAST_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: break; #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case EXTERNAL_##TYPE##_ELEMENTS: \ case TYPE##_ELEMENTS: \ TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE // Ignore getters and setters on pixel and external array // elements. return factory->undefined_value(); case DICTIONARY_ELEMENTS: break; case SLOPPY_ARGUMENTS_ELEMENTS: UNIMPLEMENTED(); break; } SetElementCallback(object, index, info, info->property_attributes()); } else { // Lookup the name. LookupResult result(isolate); object->LookupOwn(name, &result, true); // ES5 forbids turning a property into an accessor if it's not // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5). if (result.IsFound() && (result.IsReadOnly() || result.IsDontDelete())) { return factory->undefined_value(); } SetPropertyCallback(object, name, info, info->property_attributes()); } return object; } MaybeHandle JSObject::GetAccessor(Handle object, Handle name, AccessorComponent component) { Isolate* isolate = object->GetIsolate(); // Make sure that the top context does not change when doing callbacks or // interceptor calls. AssertNoContextChange ncc(isolate); // Check access rights if needed. if (object->IsAccessCheckNeeded() && !isolate->MayNamedAccess(object, name, v8::ACCESS_HAS)) { isolate->ReportFailedAccessCheck(object, v8::ACCESS_HAS); RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, Object); return isolate->factory()->undefined_value(); } // Make the lookup and include prototypes. uint32_t index = 0; if (name->AsArrayIndex(&index)) { for (Handle obj = object; !obj->IsNull(); obj = handle(JSReceiver::cast(*obj)->GetPrototype(), isolate)) { if (obj->IsJSObject() && JSObject::cast(*obj)->HasDictionaryElements()) { JSObject* js_object = JSObject::cast(*obj); SeededNumberDictionary* dictionary = js_object->element_dictionary(); int entry = dictionary->FindEntry(index); if (entry != SeededNumberDictionary::kNotFound) { Object* element = dictionary->ValueAt(entry); if (dictionary->DetailsAt(entry).type() == CALLBACKS && element->IsAccessorPair()) { return handle(AccessorPair::cast(element)->GetComponent(component), isolate); } } } } } else { for (Handle obj = object; !obj->IsNull(); obj = handle(JSReceiver::cast(*obj)->GetPrototype(), isolate)) { LookupResult result(isolate); JSReceiver::cast(*obj)->LookupOwn(name, &result); if (result.IsFound()) { if (result.IsReadOnly()) return isolate->factory()->undefined_value(); if (result.IsPropertyCallbacks()) { Object* obj = result.GetCallbackObject(); if (obj->IsAccessorPair()) { return handle(AccessorPair::cast(obj)->GetComponent(component), isolate); } } } } } return isolate->factory()->undefined_value(); } Object* JSObject::SlowReverseLookup(Object* value) { if (HasFastProperties()) { int number_of_own_descriptors = map()->NumberOfOwnDescriptors(); DescriptorArray* descs = map()->instance_descriptors(); for (int i = 0; i < number_of_own_descriptors; i++) { if (descs->GetType(i) == FIELD) { Object* property = RawFastPropertyAt(descs->GetFieldIndex(i)); if (descs->GetDetails(i).representation().IsDouble()) { ASSERT(property->IsHeapNumber()); if (value->IsNumber() && property->Number() == value->Number()) { return descs->GetKey(i); } } else if (property == value) { return descs->GetKey(i); } } else if (descs->GetType(i) == CONSTANT) { if (descs->GetConstant(i) == value) { return descs->GetKey(i); } } } return GetHeap()->undefined_value(); } else { return property_dictionary()->SlowReverseLookup(value); } } Handle Map::RawCopy(Handle map, int instance_size) { Handle result = map->GetIsolate()->factory()->NewMap( map->instance_type(), instance_size); result->set_prototype(map->prototype()); result->set_constructor(map->constructor()); 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); } new_bit_field3 = ConstructionCount::update(new_bit_field3, JSFunction::kNoSlackTracking); result->set_bit_field3(new_bit_field3); return result; } Handle Map::Normalize(Handle fast_map, PropertyNormalizationMode mode) { ASSERT(!fast_map->is_dictionary_map()); Isolate* isolate = fast_map->GetIsolate(); Handle cache( isolate->context()->native_context()->normalized_map_cache()); Handle new_map; if (cache->Get(fast_map, mode).ToHandle(&new_map)) { #ifdef VERIFY_HEAP if (FLAG_verify_heap) { new_map->SharedMapVerify(); } #endif #ifdef ENABLE_SLOW_ASSERTS 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. Handle fresh = Map::CopyNormalized( fast_map, mode, SHARED_NORMALIZED_MAP); ASSERT(memcmp(fresh->address(), new_map->address(), Map::kCodeCacheOffset) == 0); STATIC_ASSERT(Map::kDependentCodeOffset == Map::kCodeCacheOffset + kPointerSize); int offset = Map::kDependentCodeOffset + kPointerSize; ASSERT(memcmp(fresh->address() + offset, new_map->address() + offset, Map::kSize - offset) == 0); } #endif } else { new_map = Map::CopyNormalized(fast_map, mode, SHARED_NORMALIZED_MAP); cache->Set(fast_map, new_map); isolate->counters()->normalized_maps()->Increment(); } fast_map->NotifyLeafMapLayoutChange(); return new_map; } Handle Map::CopyNormalized(Handle map, PropertyNormalizationMode mode, NormalizedMapSharingMode sharing) { int new_instance_size = map->instance_size(); if (mode == CLEAR_INOBJECT_PROPERTIES) { new_instance_size -= map->inobject_properties() * kPointerSize; } Handle result = RawCopy(map, new_instance_size); if (mode != CLEAR_INOBJECT_PROPERTIES) { result->set_inobject_properties(map->inobject_properties()); } result->set_is_shared(sharing == SHARED_NORMALIZED_MAP); result->set_dictionary_map(true); result->set_migration_target(false); #ifdef VERIFY_HEAP if (FLAG_verify_heap && result->is_shared()) { result->SharedMapVerify(); } #endif 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. result->set_inobject_properties(map->inobject_properties()); result->set_unused_property_fields(map->unused_property_fields()); result->set_pre_allocated_property_fields( map->pre_allocated_property_fields()); result->set_is_shared(false); 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. ASSERT(map->NumberOfOwnDescriptors() == map->instance_descriptors()->number_of_descriptors()); Handle result = CopyDropDescriptors(map); Handle name = descriptor->GetKey(); Handle transitions = TransitionArray::CopyInsert(map, name, result, SIMPLE_TRANSITION); // 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 { EnsureDescriptorSlack(map, old_size < 4 ? 1 : old_size / 2); descriptors = handle(map->instance_descriptors()); } } // Commit the state atomically. DisallowHeapAllocation no_gc; descriptors->Append(descriptor); result->SetBackPointer(*map); result->InitializeDescriptors(*descriptors); ASSERT(result->NumberOfOwnDescriptors() == map->NumberOfOwnDescriptors() + 1); map->set_transitions(*transitions); map->set_owns_descriptors(false); return result; } Handle Map::CopyReplaceDescriptors(Handle map, Handle descriptors, TransitionFlag flag, MaybeHandle maybe_name, SimpleTransitionFlag simple_flag) { ASSERT(descriptors->IsSortedNoDuplicates()); Handle result = CopyDropDescriptors(map); result->InitializeDescriptors(*descriptors); if (flag == INSERT_TRANSITION && map->CanHaveMoreTransitions()) { Handle name; CHECK(maybe_name.ToHandle(&name)); Handle transitions = TransitionArray::CopyInsert( map, name, result, simple_flag); map->set_transitions(*transitions); result->SetBackPointer(*map); } else { int length = descriptors->number_of_descriptors(); for (int i = 0; i < length; i++) { descriptors->SetRepresentation(i, Representation::Tagged()); if (descriptors->GetDetails(i).type() == FIELD) { descriptors->SetValue(i, HeapType::Any()); } } } return result; } // Since this method is used to rewrite an existing transition tree, it can // always insert transitions without checking. Handle Map::CopyInstallDescriptors(Handle map, int new_descriptor, Handle descriptors) { ASSERT(descriptors->IsSortedNoDuplicates()); Handle result = CopyDropDescriptors(map); result->InitializeDescriptors(*descriptors); result->SetNumberOfOwnDescriptors(new_descriptor + 1); int unused_property_fields = map->unused_property_fields(); if (descriptors->GetDetails(new_descriptor).type() == FIELD) { unused_property_fields = map->unused_property_fields() - 1; if (unused_property_fields < 0) { unused_property_fields += JSObject::kFieldsAdded; } } result->set_unused_property_fields(unused_property_fields); result->set_owns_descriptors(false); Handle name = handle(descriptors->GetKey(new_descriptor)); Handle transitions = TransitionArray::CopyInsert( map, name, result, SIMPLE_TRANSITION); map->set_transitions(*transitions); result->SetBackPointer(*map); return result; } Handle Map::CopyAsElementsKind(Handle map, ElementsKind kind, TransitionFlag flag) { if (flag == INSERT_TRANSITION) { ASSERT(!map->HasElementsTransition() || ((map->elements_transition_map()->elements_kind() == DICTIONARY_ELEMENTS || IsExternalArrayElementsKind( map->elements_transition_map()->elements_kind())) && (kind == DICTIONARY_ELEMENTS || IsExternalArrayElementsKind(kind)))); ASSERT(!IsFastElementsKind(kind) || IsMoreGeneralElementsKindTransition(map->elements_kind(), kind)); ASSERT(kind != map->elements_kind()); } bool insert_transition = flag == INSERT_TRANSITION && !map->HasElementsTransition(); if (insert_transition && map->owns_descriptors()) { // In case the map owned its own descriptors, share the descriptors and // transfer ownership to the new map. Handle new_map = CopyDropDescriptors(map); SetElementsTransitionMap(map, new_map); new_map->set_elements_kind(kind); new_map->InitializeDescriptors(map->instance_descriptors()); new_map->SetBackPointer(*map); map->set_owns_descriptors(false); return new_map; } // In case the map did not own its own descriptors, a split is forced by // copying the map; creating a new descriptor array cell. // Create a new free-floating map only if we are not allowed to store it. Handle new_map = Copy(map); new_map->set_elements_kind(kind); if (insert_transition) { SetElementsTransitionMap(map, new_map); new_map->SetBackPointer(*map); } return new_map; } Handle Map::CopyForObserved(Handle map) { ASSERT(!map->is_observed()); Isolate* isolate = map->GetIsolate(); // In case the map owned its own descriptors, share the descriptors and // transfer ownership to the new map. Handle new_map; if (map->owns_descriptors()) { new_map = CopyDropDescriptors(map); } else { new_map = Copy(map); } Handle transitions = TransitionArray::CopyInsert( map, isolate->factory()->observed_symbol(), new_map, FULL_TRANSITION); map->set_transitions(*transitions); new_map->set_is_observed(); if (map->owns_descriptors()) { new_map->InitializeDescriptors(map->instance_descriptors()); map->set_owns_descriptors(false); } new_map->SetBackPointer(*map); return new_map; } Handle Map::Copy(Handle map) { Handle descriptors(map->instance_descriptors()); int number_of_own_descriptors = map->NumberOfOwnDescriptors(); Handle new_descriptors = DescriptorArray::CopyUpTo(descriptors, number_of_own_descriptors); return CopyReplaceDescriptors( map, new_descriptors, OMIT_TRANSITION, MaybeHandle()); } Handle Map::Create(Handle constructor, int extra_inobject_properties) { Handle copy = Copy(handle(constructor->initial_map())); // Check that we do not overflow the instance size when adding the // extra inobject properties. int instance_size_delta = extra_inobject_properties * kPointerSize; int max_instance_size_delta = JSObject::kMaxInstanceSize - copy->instance_size(); int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2; // If the instance size overflows, we allocate as many properties as we can as // inobject properties. if (extra_inobject_properties > max_extra_properties) { instance_size_delta = max_instance_size_delta; extra_inobject_properties = max_extra_properties; } // Adjust the map with the extra inobject properties. int inobject_properties = copy->inobject_properties() + extra_inobject_properties; copy->set_inobject_properties(inobject_properties); copy->set_unused_property_fields(inobject_properties); copy->set_instance_size(copy->instance_size() + instance_size_delta); copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy)); return copy; } Handle Map::CopyForFreeze(Handle map) { int num_descriptors = map->NumberOfOwnDescriptors(); Isolate* isolate = map->GetIsolate(); Handle new_desc = DescriptorArray::CopyUpToAddAttributes( handle(map->instance_descriptors(), isolate), num_descriptors, FROZEN); Handle new_map = CopyReplaceDescriptors( map, new_desc, INSERT_TRANSITION, isolate->factory()->frozen_symbol()); new_map->freeze(); new_map->set_is_extensible(false); new_map->set_elements_kind(DICTIONARY_ELEMENTS); return new_map; } Handle Map::CopyAddDescriptor(Handle map, Descriptor* descriptor, TransitionFlag flag) { Handle descriptors(map->instance_descriptors()); // Ensure the key is unique. descriptor->KeyToUniqueName(); if (flag == INSERT_TRANSITION && map->owns_descriptors() && map->CanHaveMoreTransitions()) { return ShareDescriptor(map, descriptors, descriptor); } Handle new_descriptors = DescriptorArray::CopyUpTo( descriptors, map->NumberOfOwnDescriptors(), 1); new_descriptors->Append(descriptor); return CopyReplaceDescriptors( map, new_descriptors, flag, descriptor->GetKey(), SIMPLE_TRANSITION); } Handle Map::CopyInsertDescriptor(Handle map, Descriptor* descriptor, TransitionFlag flag) { Handle old_descriptors(map->instance_descriptors()); // Ensure the key is unique. descriptor->KeyToUniqueName(); // We replace the key if it is already present. int index = old_descriptors->SearchWithCache(*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); DescriptorArray::WhitenessWitness witness(*descriptors); if (attributes != NONE) { for (int i = 0; i < size; ++i) { Object* value = desc->GetValue(i); PropertyDetails details = desc->GetDetails(i); int mask = DONT_DELETE | DONT_ENUM; // READ_ONLY is an invalid attribute for JS setters/getters. if (details.type() != CALLBACKS || !value->IsAccessorPair()) { mask |= READ_ONLY; } details = details.CopyAddAttributes( static_cast(attributes & mask)); Descriptor inner_desc(handle(desc->GetKey(i)), handle(value, desc->GetIsolate()), details); descriptors->Set(i, &inner_desc, witness); } } else { for (int i = 0; i < size; ++i) { descriptors->CopyFrom(i, *desc, witness); } } if (desc->number_of_descriptors() != enumeration_index) descriptors->Sort(); return descriptors; } Handle Map::CopyReplaceDescriptor(Handle map, Handle descriptors, Descriptor* descriptor, int insertion_index, TransitionFlag flag) { // Ensure the key is unique. descriptor->KeyToUniqueName(); Handle key = descriptor->GetKey(); ASSERT(*key == descriptors->GetKey(insertion_index)); Handle new_descriptors = DescriptorArray::CopyUpTo( descriptors, map->NumberOfOwnDescriptors()); new_descriptors->Replace(insertion_index, descriptor); SimpleTransitionFlag simple_flag = (insertion_index == descriptors->number_of_descriptors() - 1) ? SIMPLE_TRANSITION : FULL_TRANSITION; return CopyReplaceDescriptors(map, new_descriptors, flag, key, simple_flag); } void Map::UpdateCodeCache(Handle map, Handle name, Handle code) { Isolate* isolate = map->GetIsolate(); HandleScope scope(isolate); // Allocate the code cache if not present. if (map->code_cache()->IsFixedArray()) { Handle result = isolate->factory()->NewCodeCache(); map->set_code_cache(*result); } // Update the code cache. Handle code_cache(CodeCache::cast(map->code_cache()), isolate); CodeCache::Update(code_cache, name, code); } Object* Map::FindInCodeCache(Name* name, Code::Flags flags) { // Do a lookup if a code cache exists. if (!code_cache()->IsFixedArray()) { return CodeCache::cast(code_cache())->Lookup(name, flags); } else { return GetHeap()->undefined_value(); } } int Map::IndexInCodeCache(Object* name, Code* code) { // Get the internal index if a code cache exists. if (!code_cache()->IsFixedArray()) { return CodeCache::cast(code_cache())->GetIndex(name, code); } return -1; } void Map::RemoveFromCodeCache(Name* name, Code* code, int index) { // No GC is supposed to happen between a call to IndexInCodeCache and // RemoveFromCodeCache so the code cache must be there. ASSERT(!code_cache()->IsFixedArray()); CodeCache::cast(code_cache())->RemoveByIndex(name, code, index); } // An iterator over all map transitions in an descriptor array, reusing the // constructor field of the map while it is running. Negative values in // the constructor field indicate an active map transition iteration. The // original constructor is restored after iterating over all entries. class IntrusiveMapTransitionIterator { public: IntrusiveMapTransitionIterator( Map* map, TransitionArray* transition_array, Object* constructor) : map_(map), transition_array_(transition_array), constructor_(constructor) { } void StartIfNotStarted() { ASSERT(!(*IteratorField())->IsSmi() || IsIterating()); if (!(*IteratorField())->IsSmi()) { ASSERT(*IteratorField() == constructor_); *IteratorField() = Smi::FromInt(-1); } } bool IsIterating() { return (*IteratorField())->IsSmi() && Smi::cast(*IteratorField())->value() < 0; } Map* Next() { ASSERT(IsIterating()); int value = Smi::cast(*IteratorField())->value(); int index = -value - 1; int number_of_transitions = transition_array_->number_of_transitions(); while (index < number_of_transitions) { *IteratorField() = Smi::FromInt(value - 1); return transition_array_->GetTarget(index); } *IteratorField() = constructor_; return NULL; } private: Object** IteratorField() { return HeapObject::RawField(map_, Map::kConstructorOffset); } Map* map_; TransitionArray* transition_array_; Object* constructor_; }; // An iterator over all prototype transitions, reusing the constructor field // of the map while it is running. Positive values in the constructor field // indicate an active prototype transition iteration. The original constructor // is restored after iterating over all entries. class IntrusivePrototypeTransitionIterator { public: IntrusivePrototypeTransitionIterator( Map* map, HeapObject* proto_trans, Object* constructor) : map_(map), proto_trans_(proto_trans), constructor_(constructor) { } void StartIfNotStarted() { if (!(*IteratorField())->IsSmi()) { ASSERT(*IteratorField() == constructor_); *IteratorField() = Smi::FromInt(0); } } bool IsIterating() { return (*IteratorField())->IsSmi() && Smi::cast(*IteratorField())->value() >= 0; } Map* Next() { ASSERT(IsIterating()); int transitionNumber = Smi::cast(*IteratorField())->value(); if (transitionNumber < NumberOfTransitions()) { *IteratorField() = Smi::FromInt(transitionNumber + 1); return GetTransition(transitionNumber); } *IteratorField() = constructor_; return NULL; } private: Object** IteratorField() { return HeapObject::RawField(map_, Map::kConstructorOffset); } int NumberOfTransitions() { FixedArray* proto_trans = reinterpret_cast(proto_trans_); Object* num = proto_trans->get(Map::kProtoTransitionNumberOfEntriesOffset); return Smi::cast(num)->value(); } Map* GetTransition(int transitionNumber) { FixedArray* proto_trans = reinterpret_cast(proto_trans_); return Map::cast(proto_trans->get(IndexFor(transitionNumber))); } int IndexFor(int transitionNumber) { return Map::kProtoTransitionHeaderSize + Map::kProtoTransitionMapOffset + transitionNumber * Map::kProtoTransitionElementsPerEntry; } Map* map_; HeapObject* proto_trans_; Object* constructor_; }; // To traverse the transition tree iteratively, we have to store two kinds of // information in a map: The parent map in the traversal and which children of a // node have already been visited. To do this without additional memory, we // temporarily reuse two fields with known values: // // (1) The map of the map temporarily holds the parent, and is restored to the // meta map afterwards. // // (2) The info which children have already been visited depends on which part // of the map we currently iterate. We use the constructor field of the // map to store the current index. We can do that because the constructor // is the same for all involved maps. // // (a) If we currently follow normal map transitions, we temporarily store // the current index in the constructor field, and restore it to the // original constructor afterwards. Note that a single descriptor can // have 0, 1, or 2 transitions. // // (b) If we currently follow prototype transitions, we temporarily store // the current index in the constructor field, and restore it to the // original constructor afterwards. // // Note that the child iterator is just a concatenation of two iterators: One // iterating over map transitions and one iterating over prototype transisitons. class TraversableMap : public Map { public: // Record the parent in the traversal within this map. Note that this destroys // this map's map! void SetParent(TraversableMap* parent) { set_map_no_write_barrier(parent); } // Reset the current map's map, returning the parent previously stored in it. TraversableMap* GetAndResetParent() { TraversableMap* old_parent = static_cast(map()); set_map_no_write_barrier(GetHeap()->meta_map()); return old_parent; } // If we have an unvisited child map, return that one and advance. If we have // none, return NULL and restore the overwritten constructor field. TraversableMap* ChildIteratorNext(Object* constructor) { if (!HasTransitionArray()) return NULL; TransitionArray* transition_array = transitions(); if (transition_array->HasPrototypeTransitions()) { HeapObject* proto_transitions = transition_array->GetPrototypeTransitions(); IntrusivePrototypeTransitionIterator proto_iterator(this, proto_transitions, constructor); proto_iterator.StartIfNotStarted(); if (proto_iterator.IsIterating()) { Map* next = proto_iterator.Next(); if (next != NULL) return static_cast(next); } } IntrusiveMapTransitionIterator transition_iterator(this, transition_array, constructor); transition_iterator.StartIfNotStarted(); if (transition_iterator.IsIterating()) { Map* next = transition_iterator.Next(); if (next != NULL) return static_cast(next); } return NULL; } }; // Traverse the transition tree in postorder without using the C++ stack by // doing pointer reversal. void Map::TraverseTransitionTree(TraverseCallback callback, void* data) { // Make sure that we do not allocate in the callback. DisallowHeapAllocation no_allocation; TraversableMap* current = static_cast(this); // Get the root constructor here to restore it later when finished iterating // over maps. Object* root_constructor = constructor(); while (true) { TraversableMap* child = current->ChildIteratorNext(root_constructor); if (child != NULL) { child->SetParent(current); current = child; } else { TraversableMap* parent = current->GetAndResetParent(); callback(current, data); if (current == this) break; current = parent; } } } void CodeCache::Update( Handle code_cache, Handle name, Handle code) { // The number of monomorphic stubs for normal load/store/call IC's can grow to // a large number and therefore they need to go into a hash table. They are // used to load global properties from cells. if (code->type() == Code::NORMAL) { // Make sure that a hash table is allocated for the normal load code cache. if (code_cache->normal_type_cache()->IsUndefined()) { Handle result = CodeCacheHashTable::New(code_cache->GetIsolate(), CodeCacheHashTable::kInitialSize); code_cache->set_normal_type_cache(*result); } UpdateNormalTypeCache(code_cache, name, code); } else { ASSERT(code_cache->default_cache()->IsFixedArray()); UpdateDefaultCache(code_cache, name, code); } } void CodeCache::UpdateDefaultCache( Handle code_cache, Handle name, Handle code) { // When updating the default code cache we disregard the type encoded in the // flags. This allows call constant stubs to overwrite call field // stubs, etc. Code::Flags flags = Code::RemoveTypeFromFlags(code->flags()); // First check whether we can update existing code cache without // extending it. Handle cache = handle(code_cache->default_cache()); int length = cache->length(); { DisallowHeapAllocation no_alloc; int deleted_index = -1; for (int i = 0; i < length; i += kCodeCacheEntrySize) { Object* key = cache->get(i); if (key->IsNull()) { if (deleted_index < 0) deleted_index = i; continue; } if (key->IsUndefined()) { if (deleted_index >= 0) i = deleted_index; cache->set(i + kCodeCacheEntryNameOffset, *name); cache->set(i + kCodeCacheEntryCodeOffset, *code); return; } if (name->Equals(Name::cast(key))) { Code::Flags found = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags(); if (Code::RemoveTypeFromFlags(found) == flags) { cache->set(i + kCodeCacheEntryCodeOffset, *code); return; } } } // Reached the end of the code cache. If there were deleted // elements, reuse the space for the first of them. if (deleted_index >= 0) { cache->set(deleted_index + kCodeCacheEntryNameOffset, *name); cache->set(deleted_index + kCodeCacheEntryCodeOffset, *code); return; } } // Extend the code cache with some new entries (at least one). Must be a // multiple of the entry size. int new_length = length + ((length >> 1)) + kCodeCacheEntrySize; new_length = new_length - new_length % kCodeCacheEntrySize; ASSERT((new_length % kCodeCacheEntrySize) == 0); cache = FixedArray::CopySize(cache, new_length); // Add the (name, code) pair to the new cache. cache->set(length + kCodeCacheEntryNameOffset, *name); cache->set(length + kCodeCacheEntryCodeOffset, *code); code_cache->set_default_cache(*cache); } void CodeCache::UpdateNormalTypeCache( Handle code_cache, Handle name, Handle code) { // Adding a new entry can cause a new cache to be allocated. Handle cache( CodeCacheHashTable::cast(code_cache->normal_type_cache())); Handle new_cache = CodeCacheHashTable::Put(cache, name, code); code_cache->set_normal_type_cache(*new_cache); } Object* CodeCache::Lookup(Name* name, Code::Flags flags) { Object* result = LookupDefaultCache(name, Code::RemoveTypeFromFlags(flags)); if (result->IsCode()) { if (Code::cast(result)->flags() == flags) return result; return GetHeap()->undefined_value(); } return LookupNormalTypeCache(name, flags); } Object* CodeCache::LookupDefaultCache(Name* name, Code::Flags flags) { FixedArray* cache = default_cache(); int length = cache->length(); for (int i = 0; i < length; i += kCodeCacheEntrySize) { Object* key = cache->get(i + kCodeCacheEntryNameOffset); // Skip deleted elements. if (key->IsNull()) continue; if (key->IsUndefined()) return key; if (name->Equals(Name::cast(key))) { Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset)); if (Code::RemoveTypeFromFlags(code->flags()) == flags) { return code; } } } return GetHeap()->undefined_value(); } Object* CodeCache::LookupNormalTypeCache(Name* name, Code::Flags flags) { if (!normal_type_cache()->IsUndefined()) { CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache()); return cache->Lookup(name, flags); } else { return GetHeap()->undefined_value(); } } int CodeCache::GetIndex(Object* name, Code* code) { if (code->type() == Code::NORMAL) { if (normal_type_cache()->IsUndefined()) return -1; CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache()); return cache->GetIndex(Name::cast(name), code->flags()); } FixedArray* array = default_cache(); int len = array->length(); for (int i = 0; i < len; i += kCodeCacheEntrySize) { if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1; } return -1; } void CodeCache::RemoveByIndex(Object* name, Code* code, int index) { if (code->type() == Code::NORMAL) { ASSERT(!normal_type_cache()->IsUndefined()); CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache()); ASSERT(cache->GetIndex(Name::cast(name), code->flags()) == index); cache->RemoveByIndex(index); } else { FixedArray* array = default_cache(); ASSERT(array->length() >= index && array->get(index)->IsCode()); // Use null instead of undefined for deleted elements to distinguish // deleted elements from unused elements. This distinction is used // when looking up in the cache and when updating the cache. ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset); array->set_null(index - 1); // Name. array->set_null(index); // Code. } } // 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_() { } CodeCacheHashTableKey(Handle name, Handle code) : name_(name), flags_(code->flags()), code_(code) { } bool IsMatch(Object* other) V8_OVERRIDE { if (!other->IsFixedArray()) return false; 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; } return name_->Equals(name); } static uint32_t NameFlagsHashHelper(Name* name, Code::Flags flags) { return name->Hash() ^ flags; } uint32_t Hash() V8_OVERRIDE { return NameFlagsHashHelper(*name_, flags_); } uint32_t HashForObject(Object* obj) V8_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) V8_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_; }; Object* CodeCacheHashTable::Lookup(Name* name, Code::Flags flags) { DisallowHeapAllocation no_alloc; CodeCacheHashTableKey key(handle(name), flags); int entry = FindEntry(&key); if (entry == kNotFound) return GetHeap()->undefined_value(); return get(EntryToIndex(entry) + 1); } 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->set(EntryToIndex(entry) + 1, *code); new_cache->ElementAdded(); return new_cache; } int CodeCacheHashTable::GetIndex(Name* name, Code::Flags flags) { DisallowHeapAllocation no_alloc; CodeCacheHashTableKey key(handle(name), flags); int entry = FindEntry(&key); return (entry == kNotFound) ? -1 : entry; } void CodeCacheHashTable::RemoveByIndex(int index) { ASSERT(index >= 0); Heap* heap = GetHeap(); set(EntryToIndex(index), heap->the_hole_value()); set(EntryToIndex(index) + 1, heap->the_hole_value()); ElementRemoved(); } void PolymorphicCodeCache::Update(Handle code_cache, MapHandleList* maps, Code::Flags flags, Handle code) { Isolate* isolate = code_cache->GetIsolate(); if (code_cache->cache()->IsUndefined()) { Handle result = PolymorphicCodeCacheHashTable::New( isolate, PolymorphicCodeCacheHashTable::kInitialSize); code_cache->set_cache(*result); } else { // This entry shouldn't be contained in the cache yet. ASSERT(PolymorphicCodeCacheHashTable::cast(code_cache->cache()) ->Lookup(maps, flags)->IsUndefined()); } Handle hash_table = handle(PolymorphicCodeCacheHashTable::cast(code_cache->cache())); Handle new_cache = PolymorphicCodeCacheHashTable::Put(hash_table, maps, flags, code); code_cache->set_cache(*new_cache); } Handle PolymorphicCodeCache::Lookup(MapHandleList* maps, Code::Flags flags) { if (!cache()->IsUndefined()) { PolymorphicCodeCacheHashTable* hash_table = PolymorphicCodeCacheHashTable::cast(cache()); return Handle(hash_table->Lookup(maps, flags), GetIsolate()); } else { return GetIsolate()->factory()->undefined_value(); } } // Despite their name, object of this class are not stored in the actual // hash table; instead they're temporarily used for lookups. It is therefore // safe to have a weak (non-owning) pointer to a MapList as a member field. class PolymorphicCodeCacheHashTableKey : public HashTableKey { public: // Callers must ensure that |maps| outlives the newly constructed object. PolymorphicCodeCacheHashTableKey(MapHandleList* maps, int code_flags) : maps_(maps), code_flags_(code_flags) {} bool IsMatch(Object* other) V8_OVERRIDE { MapHandleList other_maps(kDefaultListAllocationSize); int other_flags; FromObject(other, &other_flags, &other_maps); if (code_flags_ != other_flags) return false; if (maps_->length() != other_maps.length()) return false; // Compare just the hashes first because it's faster. int this_hash = MapsHashHelper(maps_, code_flags_); int other_hash = MapsHashHelper(&other_maps, other_flags); if (this_hash != other_hash) return false; // Full comparison: for each map in maps_, look for an equivalent map in // other_maps. This implementation is slow, but probably good enough for // now because the lists are short (<= 4 elements currently). for (int i = 0; i < maps_->length(); ++i) { bool match_found = false; for (int j = 0; j < other_maps.length(); ++j) { if (*(maps_->at(i)) == *(other_maps.at(j))) { match_found = true; break; } } if (!match_found) return false; } return true; } static uint32_t MapsHashHelper(MapHandleList* maps, int code_flags) { uint32_t hash = code_flags; for (int i = 0; i < maps->length(); ++i) { hash ^= maps->at(i)->Hash(); } return hash; } uint32_t Hash() V8_OVERRIDE { return MapsHashHelper(maps_, code_flags_); } uint32_t HashForObject(Object* obj) V8_OVERRIDE { MapHandleList other_maps(kDefaultListAllocationSize); int other_flags; FromObject(obj, &other_flags, &other_maps); return MapsHashHelper(&other_maps, other_flags); } MUST_USE_RESULT Handle AsHandle(Isolate* isolate) V8_OVERRIDE { // The maps in |maps_| must be copied to a newly allocated FixedArray, // both because the referenced MapList is short-lived, and because C++ // objects can't be stored in the heap anyway. Handle list = isolate->factory()->NewUninitializedFixedArray(maps_->length() + 1); list->set(0, Smi::FromInt(code_flags_)); for (int i = 0; i < maps_->length(); ++i) { list->set(i + 1, *maps_->at(i)); } return list; } private: static MapHandleList* FromObject(Object* obj, int* code_flags, MapHandleList* maps) { FixedArray* list = FixedArray::cast(obj); maps->Rewind(0); *code_flags = Smi::cast(list->get(0))->value(); for (int i = 1; i < list->length(); ++i) { maps->Add(Handle(Map::cast(list->get(i)))); } return maps; } MapHandleList* maps_; // weak. int code_flags_; static const int kDefaultListAllocationSize = kMaxKeyedPolymorphism + 1; }; Object* PolymorphicCodeCacheHashTable::Lookup(MapHandleList* maps, int code_kind) { DisallowHeapAllocation no_alloc; PolymorphicCodeCacheHashTableKey key(maps, code_kind); int entry = FindEntry(&key); if (entry == kNotFound) return GetHeap()->undefined_value(); return get(EntryToIndex(entry) + 1); } Handle PolymorphicCodeCacheHashTable::Put( Handle hash_table, MapHandleList* maps, int code_kind, Handle code) { PolymorphicCodeCacheHashTableKey key(maps, code_kind); Handle cache = EnsureCapacity(hash_table, 1, &key); int entry = cache->FindInsertionEntry(key.Hash()); Handle obj = key.AsHandle(hash_table->GetIsolate()); cache->set(EntryToIndex(entry), *obj); cache->set(EntryToIndex(entry) + 1, *code); cache->ElementAdded(); return cache; } void FixedArray::Shrink(int new_length) { ASSERT(0 <= new_length && new_length <= length()); if (new_length < length()) { RightTrimFixedArray( GetHeap(), this, length() - new_length); } } MaybeHandle FixedArray::AddKeysFromArrayLike( Handle content, Handle array) { ASSERT(array->IsJSArray() || array->HasSloppyArgumentsElements()); ElementsAccessor* accessor = array->GetElementsAccessor(); Handle result; ASSIGN_RETURN_ON_EXCEPTION( array->GetIsolate(), result, accessor->AddElementsToFixedArray(array, array, content), FixedArray); #ifdef ENABLE_SLOW_ASSERTS if (FLAG_enable_slow_asserts) { DisallowHeapAllocation no_allocation; for (int i = 0; i < result->length(); i++) { Object* current = result->get(i); ASSERT(current->IsNumber() || current->IsName()); } } #endif return result; } MaybeHandle FixedArray::UnionOfKeys(Handle first, Handle second) { ElementsAccessor* accessor = ElementsAccessor::ForArray(second); Handle result; ASSIGN_RETURN_ON_EXCEPTION( first->GetIsolate(), result, accessor->AddElementsToFixedArray( Handle::null(), // receiver Handle::null(), // holder first, Handle::cast(second)), FixedArray); #ifdef ENABLE_SLOW_ASSERTS if (FLAG_enable_slow_asserts) { DisallowHeapAllocation no_allocation; for (int i = 0; i < result->length(); i++) { Object* current = result->get(i); ASSERT(current->IsNumber() || current->IsName()); } } #endif return result; } Handle FixedArray::CopySize( Handle array, int new_length, PretenureFlag pretenure) { Isolate* isolate = array->GetIsolate(); if (new_length == 0) return isolate->factory()->empty_fixed_array(); Handle result = isolate->factory()->NewFixedArray(new_length, pretenure); // Copy the content DisallowHeapAllocation no_gc; int len = array->length(); if (new_length < len) len = new_length; // We are taking the map from the old fixed array so the map is sure to // be an immortal immutable object. result->set_map_no_write_barrier(array->map()); WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc); for (int i = 0; i < len; i++) { result->set(i, array->get(i), mode); } return result; } 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 Handle DescriptorArray::Allocate(Isolate* isolate, int number_of_descriptors, int slack) { ASSERT(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)); result->set(kDescriptorLengthIndex, Smi::FromInt(number_of_descriptors)); result->set(kEnumCacheIndex, Smi::FromInt(0)); return Handle::cast(result); } void DescriptorArray::ClearEnumCache() { set(kEnumCacheIndex, Smi::FromInt(0)); } void DescriptorArray::Replace(int index, Descriptor* descriptor) { descriptor->SetSortedKeyIndex(GetSortedKeyIndex(index)); Set(index, descriptor); } void DescriptorArray::SetEnumCache(FixedArray* bridge_storage, FixedArray* new_cache, Object* new_index_cache) { ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength); ASSERT(new_index_cache->IsSmi() || new_index_cache->IsFixedArray()); ASSERT(!IsEmpty()); ASSERT(!HasEnumCache() || new_cache->length() > GetEnumCache()->length()); FixedArray::cast(bridge_storage)-> set(kEnumCacheBridgeCacheIndex, new_cache); FixedArray::cast(bridge_storage)-> set(kEnumCacheBridgeIndicesCacheIndex, new_index_cache); set(kEnumCacheIndex, bridge_storage); } void DescriptorArray::CopyFrom(int index, DescriptorArray* src, const WhitenessWitness& witness) { Object* value = src->GetValue(index); PropertyDetails details = src->GetDetails(index); Descriptor desc(handle(src->GetKey(index)), handle(value, src->GetIsolate()), details); Set(index, &desc, witness); } // We need the whiteness witness since sort will reshuffle the entries in the // descriptor array. If the descriptor array were to be black, the shuffling // would move a slot that was already recorded as pointing into an evacuation // candidate. This would result in missing updates upon evacuation. 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; } } ASSERT(IsSortedNoDuplicates()); } Handle AccessorPair::Copy(Handle pair) { Handle copy = pair->GetIsolate()->factory()->NewAccessorPair(); copy->set_getter(pair->getter()); copy->set_setter(pair->setter()); return copy; } Object* AccessorPair::GetComponent(AccessorComponent component) { Object* accessor = get(component); return accessor->IsTheHole() ? GetHeap()->undefined_value() : accessor; } Handle DeoptimizationInputData::New( Isolate* isolate, int deopt_entry_count, PretenureFlag pretenure) { ASSERT(deopt_entry_count > 0); 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); } #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 bool IsIdentifier(UnicodeCache* cache, Name* name) { // Checks whether the buffer contains an identifier (no escape). if (!name->IsString()) return false; String* string = String::cast(name); if (string->length() == 0) return true; ConsStringIteratorOp op; StringCharacterStream stream(string, &op); if (!cache->IsIdentifierStart(stream.GetNext())) { return false; } while (stream.HasMore()) { if (!cache->IsIdentifierPart(stream.GetNext())) { return false; } } return true; } bool Name::IsCacheable(Isolate* isolate) { return IsSymbol() || IsIdentifier(isolate->unicode_cache(), this); } bool String::LooksValid() { if (!GetIsolate()->heap()->Contains(this)) return false; return true; } String::FlatContent String::GetFlatContent() { ASSERT(!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); } if (shape.representation_tag() == kSlicedStringTag) { SlicedString* slice = SlicedString::cast(string); offset = slice->offset(); string = slice->parent(); shape = StringShape(string); ASSERT(shape.representation_tag() != kConsStringTag && shape.representation_tag() != kSlicedStringTag); } if (shape.encoding_tag() == kOneByteStringTag) { const uint8_t* start; if (shape.representation_tag() == kSeqStringTag) { start = SeqOneByteString::cast(string)->GetChars(); } else { start = ExternalAsciiString::cast(string)->GetChars(); } return FlatContent(start + offset, length); } else { ASSERT(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); } } SmartArrayPointer String::ToCString(AllowNullsFlag allow_nulls, RobustnessFlag robust_flag, int offset, int length, int* length_return) { if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) { return SmartArrayPointer(NULL); } Heap* heap = GetHeap(); // 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. Access op( heap->isolate()->objects_string_iterator()); StringCharacterStream stream(this, op.value(), 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 SmartArrayPointer(result); } SmartArrayPointer 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) { ASSERT(!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: UNREACHABLE(); return NULL; } UNREACHABLE(); return NULL; } SmartArrayPointer String::ToWideCString(RobustnessFlag robust_flag) { if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) { return SmartArrayPointer(); } Heap* heap = GetHeap(); Access op( heap->isolate()->objects_string_iterator()); StringCharacterStream stream(this, op.value()); uc16* result = NewArray(length() + 1); int i = 0; while (stream.HasMore()) { uint16_t character = stream.GetNext(); result[i++] = character; } result[i] = 0; return SmartArrayPointer(result); } 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_ascii_(true), length_(input.length()), start_(input.start()) { } void FlatStringReader::PostGarbageCollection() { if (str_ == NULL) return; Handle str(str_); ASSERT(str->IsFlat()); DisallowHeapAllocation no_gc; // This does not actually prevent the vector from being relocated later. String::FlatContent content = str->GetFlatContent(); ASSERT(content.IsFlat()); is_ascii_ = content.IsAscii(); if (is_ascii_) { start_ = content.ToOneByteVector().start(); } else { start_ = content.ToUC16Vector().start(); } } void ConsStringIteratorOp::Initialize(ConsString* cons_string, int offset) { ASSERT(cons_string != NULL); root_ = cons_string; consumed_ = offset; // Force stack blown condition to trigger restart. depth_ = 1; maximum_depth_ = kStackSize + depth_; ASSERT(StackBlown()); } String* ConsStringIteratorOp::Continue(int* offset_out) { ASSERT(depth_ != 0); ASSERT_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) { ASSERT(string == NULL); string = Search(offset_out); } // Ensure future calls return null immediately. if (string == NULL) Reset(NULL); return string; } String* ConsStringIteratorOp::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(); } ASSERT(length != 0); // Adjust return values and exit. consumed_ = offset + length; *offset_out = consumed - offset; return string; } UNREACHABLE(); return NULL; } String* ConsStringIteratorOp::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(); ASSERT(length != 0); consumed_ += length; return string; } cons_string = ConsString::cast(string); PushLeft(cons_string); } } UNREACHABLE(); return NULL; } uint16_t ConsString::ConsStringGet(int index) { ASSERT(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 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) { ASSERT(0 <= from && from <= to && to <= source->length()); switch (StringShape(source).full_representation_tag()) { case kOneByteStringTag | kExternalStringTag: { CopyChars(sink, ExternalAsciiString::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); 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 ascii 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; } } } } template static void CalculateLineEndsImpl(Isolate* isolate, List* line_ends, Vector src, bool include_ending_line) { const int src_len = src.length(); StringSearch search(isolate, STATIC_ASCII_VECTOR("\n")); // Find and record line ends. int position = 0; while (position != -1 && position < src_len) { position = search.Search(src, position); if (position != -1) { line_ends->Add(position); position++; } else if (include_ending_line) { // Even if the last line misses a line end, it is counted. line_ends->Add(src_len); return; } } } 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(); ASSERT(content.IsFlat()); if (content.IsAscii()) { 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) { int i = 0; #ifndef V8_HOST_CAN_READ_UNALIGNED // If this architecture isn't comfortable reading unaligned ints // then we have to check that the strings are aligned before // comparing them blockwise. const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT uint32_t pa_addr = reinterpret_cast(a); uint32_t pb_addr = reinterpret_cast(b); if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) { #endif const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT int endpoint = length - kStepSize; // Compare blocks until we reach near the end of the string. for (; i <= endpoint; i += kStepSize) { uint32_t wa = *reinterpret_cast(a + i); uint32_t wb = *reinterpret_cast(b + i); if (wa != wb) { return false; } } #ifndef V8_HOST_CAN_READ_UNALIGNED } #endif // Compare the remaining characters that didn't fit into a block. for (; i < length; i++) { if (a[i] != b[i]) { return false; } } return true; } template class RawStringComparator : public AllStatic { public: static inline bool compare(const Chars1* a, const Chars2* b, int len) { ASSERT(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: explicit inline State(ConsStringIteratorOp* op) : op_(op), is_one_byte_(true), length_(0), buffer8_(NULL) {} inline void Init(String* string) { ConsString* cons_string = String::VisitFlat(this, string); op_->Reset(cons_string); if (cons_string != NULL) { int offset; string = op_->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) { ASSERT(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 = op_->Next(&offset); ASSERT_EQ(0, offset); ASSERT(next != NULL); String::VisitFlat(this, next); } ConsStringIteratorOp* const op_; bool is_one_byte_; int length_; union { const uint8_t* buffer8_; const uint16_t* buffer16_; }; private: DISALLOW_IMPLICIT_CONSTRUCTORS(State); }; public: inline StringComparator(ConsStringIteratorOp* op_1, ConsStringIteratorOp* op_2) : state_1_(op_1), state_2_(op_2) { } 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_); ASSERT(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_IMPLICIT_CONSTRUCTORS(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 hash code is computed for both strings // a fast negative check can be performed. if (HasHashCode() && other->HasHashCode()) { #ifdef ENABLE_SLOW_ASSERTS 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; } } ASSERT(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); } Isolate* isolate = GetIsolate(); StringComparator comparator(isolate->objects_string_compare_iterator_a(), isolate->objects_string_compare_iterator_b()); 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 hash code is computed for both strings // a fast negative check can be performed. if (one->HasHashCode() && two->HasHashCode()) { #ifdef ENABLE_SLOW_ASSERTS 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; } } ASSERT(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.IsAscii() && flat2.IsAscii()) { 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; } } bool String::MarkAsUndetectable() { if (StringShape(this).IsInternalized()) return false; Map* map = this->map(); Heap* heap = GetHeap(); if (map == heap->string_map()) { this->set_map(heap->undetectable_string_map()); return true; } else if (map == heap->ascii_string_map()) { this->set_map(heap->undetectable_ascii_string_map()); return true; } // Rest cannot be marked as undetectable return false; } 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; unsigned 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++) { unsigned cursor = 0; uint32_t r = unibrow::Utf8::ValueOf(utf8_data, remaining_in_str, &cursor); ASSERT(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.IsAscii()) { 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; } class IteratingStringHasher: public StringHasher { public: static inline uint32_t Hash(String* string, uint32_t seed) { IteratingStringHasher hasher(string->length(), seed); // Nothing to do. if (hasher.has_trivial_hash()) return hasher.GetHashField(); ConsString* cons_string = String::VisitFlat(&hasher, string); // The string was flat. if (cons_string == NULL) return hasher.GetHashField(); // This is a ConsString, iterate across it. ConsStringIteratorOp op(cons_string); int offset; while (NULL != (string = op.Next(&offset))) { String::VisitFlat(&hasher, string, offset); } return hasher.GetHashField(); } inline void VisitOneByteString(const uint8_t* chars, int length) { AddCharacters(chars, length); } inline void VisitTwoByteString(const uint16_t* chars, int length) { AddCharacters(chars, length); } private: inline IteratingStringHasher(int len, uint32_t seed) : StringHasher(len, seed) { } DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher); }; uint32_t String::ComputeAndSetHash() { // Should only be called if hash code has not yet been computed. ASSERT(!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. ASSERT(HasHashCode()); uint32_t result = field >> kHashShift; ASSERT(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; ConsStringIteratorOp op; StringCharacterStream stream(this, &op); uint16_t ch = stream.GetNext(); // If the string begins with a '0' character, it must only consist // of it to be a legal array index. if (ch == '0') { *index = 0; return length == 1; } // Convert string to uint32 array index; character by character. int d = ch - '0'; if (d < 0 || d > 9) return false; uint32_t result = d; while (stream.HasMore()) { d = stream.GetNext() - '0'; if (d < 0 || d > 9) return false; // Check that the new result is below the 32 bit limit. if (result > 429496729U - ((d > 5) ? 1 : 0)) return false; result = (result * 10) + d; } *index = result; return true; } 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 = (kArrayIndexHashMask & field) >> kHashShift; return true; } else { return ComputeArrayIndex(index); } } Handle SeqString::Truncate(Handle string, int new_length) { 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 { ASSERT(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(); ASSERT_OBJECT_ALIGNED(start_of_string); ASSERT_OBJECT_ALIGNED(start_of_string + new_size); Heap* heap = string->GetHeap(); NewSpace* newspace = heap->new_space(); if (newspace->Contains(start_of_string) && newspace->top() == start_of_string + old_size) { // Last allocated object in new space. Simply lower allocation top. newspace->set_top(start_of_string + new_size); } else { // 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); } heap->AdjustLiveBytes(start_of_string, -delta, Heap::FROM_MUTATOR); // 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); if (new_length == 0) return heap->isolate()->factory()->empty_string(); 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. ASSERT(length > 0); ASSERT(length <= String::kMaxArrayIndexSize); ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) < (1 << String::kArrayIndexValueBits)); value <<= String::kHashShift; value |= length << String::kArrayIndexHashLengthShift; ASSERT((value & String::kIsNotArrayIndexMask) == 0); ASSERT((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) { ASSERT(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); unsigned remaining = static_cast(vector_length); const uint8_t* stream = reinterpret_cast(chars.start()); int utf16_length = 0; bool is_index = true; ASSERT(hasher.is_array_index_); while (remaining > 0) { unsigned consumed = 0; uint32_t c = unibrow::Utf8::ValueOf(stream, remaining, &consumed); ASSERT(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 String::PrintOn(FILE* file) { int length = this->length(); for (int i = 0; i < length; i++) { PrintF(file, "%c", Get(i)); } } static void TrimEnumCache(Heap* heap, Map* map, DescriptorArray* descriptors) { int live_enum = map->EnumLength(); if (live_enum == kInvalidEnumCacheSentinel) { live_enum = map->NumberOfDescribedProperties(OWN_DESCRIPTORS, DONT_ENUM); } if (live_enum == 0) return descriptors->ClearEnumCache(); FixedArray* enum_cache = descriptors->GetEnumCache(); int to_trim = enum_cache->length() - live_enum; if (to_trim <= 0) return; RightTrimFixedArray( heap, descriptors->GetEnumCache(), to_trim); if (!descriptors->HasEnumIndicesCache()) return; FixedArray* enum_indices_cache = descriptors->GetEnumIndicesCache(); RightTrimFixedArray(heap, enum_indices_cache, to_trim); } static void TrimDescriptorArray(Heap* heap, Map* map, DescriptorArray* descriptors, int number_of_own_descriptors) { int number_of_descriptors = descriptors->number_of_descriptors_storage(); int to_trim = number_of_descriptors - number_of_own_descriptors; if (to_trim == 0) return; RightTrimFixedArray( heap, descriptors, to_trim * DescriptorArray::kDescriptorSize); descriptors->SetNumberOfDescriptors(number_of_own_descriptors); if (descriptors->HasEnumCache()) TrimEnumCache(heap, map, descriptors); descriptors->Sort(); } // Clear a possible back pointer in case the transition leads to a dead map. // Return true in case a back pointer has been cleared and false otherwise. static bool ClearBackPointer(Heap* heap, Map* target) { if (Marking::MarkBitFrom(target).Get()) return false; target->SetBackPointer(heap->undefined_value(), SKIP_WRITE_BARRIER); return true; } // TODO(mstarzinger): This method should be moved into MarkCompactCollector, // because it cannot be called from outside the GC and we already have methods // depending on the transitions layout in the GC anyways. void Map::ClearNonLiveTransitions(Heap* heap) { // If there are no transitions to be cleared, return. // TODO(verwaest) Should be an assert, otherwise back pointers are not // properly cleared. if (!HasTransitionArray()) return; TransitionArray* t = transitions(); MarkCompactCollector* collector = heap->mark_compact_collector(); int transition_index = 0; DescriptorArray* descriptors = instance_descriptors(); bool descriptors_owner_died = false; // Compact all live descriptors to the left. for (int i = 0; i < t->number_of_transitions(); ++i) { Map* target = t->GetTarget(i); if (ClearBackPointer(heap, target)) { if (target->instance_descriptors() == descriptors) { descriptors_owner_died = true; } } else { if (i != transition_index) { Name* key = t->GetKey(i); t->SetKey(transition_index, key); Object** key_slot = t->GetKeySlot(transition_index); collector->RecordSlot(key_slot, key_slot, key); // Target slots do not need to be recorded since maps are not compacted. t->SetTarget(transition_index, t->GetTarget(i)); } transition_index++; } } // If there are no transitions to be cleared, return. // TODO(verwaest) Should be an assert, otherwise back pointers are not // properly cleared. if (transition_index == t->number_of_transitions()) return; int number_of_own_descriptors = NumberOfOwnDescriptors(); if (descriptors_owner_died) { if (number_of_own_descriptors > 0) { TrimDescriptorArray(heap, this, descriptors, number_of_own_descriptors); ASSERT(descriptors->number_of_descriptors() == number_of_own_descriptors); set_owns_descriptors(true); } else { ASSERT(descriptors == GetHeap()->empty_descriptor_array()); } } // Note that we never eliminate a transition array, though we might right-trim // such that number_of_transitions() == 0. If this assumption changes, // TransitionArray::CopyInsert() will need to deal with the case that a // transition array disappeared during GC. int trim = t->number_of_transitions() - transition_index; if (trim > 0) { RightTrimFixedArray(heap, t, t->IsSimpleTransition() ? trim : trim * TransitionArray::kTransitionSize); } ASSERT(HasTransitionArray()); } int Map::Hash() { // For performance reasons we only hash the 3 most variable fields of a map: // constructor, prototype and bit_field2. // Shift away the tag. int hash = (static_cast( reinterpret_cast(constructor())) >> 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 4 bits relatively to the constructor. hash ^= (static_cast( reinterpret_cast(prototype())) << 2); return hash ^ (hash >> 16) ^ bit_field2(); } static bool CheckEquivalent(Map* first, Map* second) { return first->constructor() == second->constructor() && first->prototype() == second->prototype() && first->instance_type() == second->instance_type() && first->bit_field() == second->bit_field() && first->bit_field2() == second->bit_field2() && first->is_frozen() == second->is_frozen() && first->has_instance_call_handler() == second->has_instance_call_handler(); } bool Map::EquivalentToForTransition(Map* other) { return CheckEquivalent(this, other); } bool Map::EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode) { int properties = mode == CLEAR_INOBJECT_PROPERTIES ? 0 : other->inobject_properties(); return CheckEquivalent(this, other) && inobject_properties() == properties; } void ConstantPoolArray::ConstantPoolIterateBody(ObjectVisitor* v) { for (int i = 0; i < count_of_code_ptr_entries(); i++) { int index = first_code_ptr_index() + i; v->VisitCodeEntry(reinterpret_cast
(RawFieldOfElementAt(index))); } for (int i = 0; i < count_of_heap_ptr_entries(); i++) { int index = first_heap_ptr_index() + i; v->VisitPointer(RawFieldOfElementAt(index)); } } void JSFunction::JSFunctionIterateBody(int object_size, ObjectVisitor* v) { // Iterate over all fields in the body but take care in dealing with // the code entry. IteratePointers(v, kPropertiesOffset, kCodeEntryOffset); v->VisitCodeEntry(this->address() + kCodeEntryOffset); IteratePointers(v, kCodeEntryOffset + kPointerSize, object_size); } void JSFunction::MarkForOptimization() { ASSERT(is_compiled() || GetIsolate()->DebuggerHasBreakPoints()); ASSERT(!IsOptimized()); ASSERT(shared()->allows_lazy_compilation() || code()->optimizable()); ASSERT(!shared()->is_generator()); set_code_no_write_barrier( GetIsolate()->builtins()->builtin(Builtins::kCompileOptimized)); // No write barrier required, since the builtin is part of the root set. } void JSFunction::MarkForConcurrentOptimization() { ASSERT(is_compiled() || GetIsolate()->DebuggerHasBreakPoints()); ASSERT(!IsOptimized()); ASSERT(shared()->allows_lazy_compilation() || code()->optimizable()); ASSERT(!shared()->is_generator()); ASSERT(GetIsolate()->concurrent_recompilation_enabled()); if (FLAG_trace_concurrent_recompilation) { PrintF(" ** Marking "); PrintName(); PrintF(" for concurrent recompilation.\n"); } set_code_no_write_barrier( GetIsolate()->builtins()->builtin(Builtins::kCompileOptimizedConcurrent)); // No write barrier required, since the builtin is part of the root set. } void JSFunction::MarkInOptimizationQueue() { // We can only arrive here via the concurrent-recompilation builtin. If // break points were set, the code would point to the lazy-compile builtin. ASSERT(!GetIsolate()->DebuggerHasBreakPoints()); ASSERT(IsMarkedForConcurrentOptimization() && !IsOptimized()); ASSERT(shared()->allows_lazy_compilation() || code()->optimizable()); ASSERT(GetIsolate()->concurrent_recompilation_enabled()); if (FLAG_trace_concurrent_recompilation) { PrintF(" ** Queueing "); PrintName(); PrintF(" for concurrent recompilation.\n"); } set_code_no_write_barrier( GetIsolate()->builtins()->builtin(Builtins::kInOptimizationQueue)); // No write barrier required, since the builtin is part of the root set. } void SharedFunctionInfo::AddToOptimizedCodeMap( Handle shared, Handle native_context, Handle code, Handle literals, BailoutId osr_ast_id) { Isolate* isolate = shared->GetIsolate(); ASSERT(code->kind() == Code::OPTIMIZED_FUNCTION); ASSERT(native_context->IsNativeContext()); STATIC_ASSERT(kEntryLength == 4); Handle new_code_map; Handle value(shared->optimized_code_map(), isolate); int old_length; if (value->IsSmi()) { // No optimized code map. ASSERT_EQ(0, Smi::cast(*value)->value()); // Create 3 entries per context {context, code, literals}. new_code_map = isolate->factory()->NewFixedArray(kInitialLength); old_length = kEntriesStart; } else { // Copy old map and append one new entry. Handle old_code_map = Handle::cast(value); ASSERT_EQ(-1, shared->SearchOptimizedCodeMap(*native_context, osr_ast_id)); old_length = old_code_map->length(); new_code_map = FixedArray::CopySize( old_code_map, old_length + kEntryLength); // Zap the old map for the sake of the heap verifier. if (Heap::ShouldZapGarbage()) { Object** data = old_code_map->data_start(); MemsetPointer(data, isolate->heap()->the_hole_value(), old_length); } } new_code_map->set(old_length + kContextOffset, *native_context); new_code_map->set(old_length + kCachedCodeOffset, *code); new_code_map->set(old_length + kLiteralsOffset, *literals); new_code_map->set(old_length + kOsrAstIdOffset, Smi::FromInt(osr_ast_id.ToInt())); #ifdef DEBUG for (int i = kEntriesStart; i < new_code_map->length(); i += kEntryLength) { ASSERT(new_code_map->get(i + kContextOffset)->IsNativeContext()); ASSERT(new_code_map->get(i + kCachedCodeOffset)->IsCode()); ASSERT(Code::cast(new_code_map->get(i + kCachedCodeOffset))->kind() == Code::OPTIMIZED_FUNCTION); ASSERT(new_code_map->get(i + kLiteralsOffset)->IsFixedArray()); ASSERT(new_code_map->get(i + kOsrAstIdOffset)->IsSmi()); } #endif shared->set_optimized_code_map(*new_code_map); } FixedArray* SharedFunctionInfo::GetLiteralsFromOptimizedCodeMap(int index) { ASSERT(index > kEntriesStart); FixedArray* code_map = FixedArray::cast(optimized_code_map()); if (!bound()) { FixedArray* cached_literals = FixedArray::cast(code_map->get(index + 1)); ASSERT_NE(NULL, cached_literals); return cached_literals; } return NULL; } Code* SharedFunctionInfo::GetCodeFromOptimizedCodeMap(int index) { ASSERT(index > kEntriesStart); FixedArray* code_map = FixedArray::cast(optimized_code_map()); Code* code = Code::cast(code_map->get(index)); ASSERT_NE(NULL, code); return code; } void SharedFunctionInfo::ClearOptimizedCodeMap() { FixedArray* code_map = FixedArray::cast(optimized_code_map()); // If the next map link slot is already used then the function was // enqueued with code flushing and we remove it now. if (!code_map->get(kNextMapIndex)->IsUndefined()) { CodeFlusher* flusher = GetHeap()->mark_compact_collector()->code_flusher(); flusher->EvictOptimizedCodeMap(this); } ASSERT(code_map->get(kNextMapIndex)->IsUndefined()); set_optimized_code_map(Smi::FromInt(0)); } void SharedFunctionInfo::EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason) { DisallowHeapAllocation no_gc; if (optimized_code_map()->IsSmi()) return; FixedArray* code_map = FixedArray::cast(optimized_code_map()); int dst = kEntriesStart; int length = code_map->length(); for (int src = kEntriesStart; src < length; src += kEntryLength) { ASSERT(code_map->get(src)->IsNativeContext()); if (Code::cast(code_map->get(src + kCachedCodeOffset)) == optimized_code) { // Evict the src entry by not copying it to the dst entry. if (FLAG_trace_opt) { PrintF("[evicting entry from optimizing code map (%s) for ", reason); ShortPrint(); BailoutId osr(Smi::cast(code_map->get(src + kOsrAstIdOffset))->value()); if (osr.IsNone()) { PrintF("]\n"); } else { PrintF(" (osr ast id %d)]\n", osr.ToInt()); } } } else { // Keep the src entry by copying it to the dst entry. if (dst != src) { code_map->set(dst + kContextOffset, code_map->get(src + kContextOffset)); code_map->set(dst + kCachedCodeOffset, code_map->get(src + kCachedCodeOffset)); code_map->set(dst + kLiteralsOffset, code_map->get(src + kLiteralsOffset)); code_map->set(dst + kOsrAstIdOffset, code_map->get(src + kOsrAstIdOffset)); } dst += kEntryLength; } } if (dst != length) { // Always trim even when array is cleared because of heap verifier. RightTrimFixedArray(GetHeap(), code_map, length - dst); if (code_map->length() == kEntriesStart) ClearOptimizedCodeMap(); } } void SharedFunctionInfo::TrimOptimizedCodeMap(int shrink_by) { FixedArray* code_map = FixedArray::cast(optimized_code_map()); ASSERT(shrink_by % kEntryLength == 0); ASSERT(shrink_by <= code_map->length() - kEntriesStart); // Always trim even when array is cleared because of heap verifier. RightTrimFixedArray(GetHeap(), code_map, shrink_by); if (code_map->length() == kEntriesStart) { ClearOptimizedCodeMap(); } } void JSObject::OptimizeAsPrototype(Handle object) { if (object->IsGlobalObject()) return; // Make sure prototypes are fast objects and their maps have the bit set // so they remain fast. if (!object->HasFastProperties()) { TransformToFastProperties(object, 0); } } 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. Factory* factory = native_context->GetIsolate()->factory(); Handle maps = factory->NewFixedArrayWithHoles( kElementsKindCount, TENURED); Handle current_map = initial_map; ElementsKind kind = current_map->elements_kind(); ASSERT(kind == GetInitialFastElementsKind()); maps->set(kind, *current_map); for (int i = GetSequenceIndexFromFastElementsKind(kind) + 1; i < kFastElementsKindCount; ++i) { Handle new_map; ElementsKind next_kind = GetFastElementsKindFromSequenceIndex(i); if (current_map->HasElementsTransition()) { new_map = handle(current_map->elements_transition_map()); ASSERT(new_map->elements_kind() == next_kind); } else { new_map = Map::CopyAsElementsKind( current_map, next_kind, INSERT_TRANSITION); } maps->set(next_kind, *new_map); current_map = new_map; } native_context->set_js_array_maps(*maps); return initial_map; } void JSFunction::SetInstancePrototype(Handle function, Handle value) { Isolate* isolate = function->GetIsolate(); ASSERT(value->IsJSReceiver()); // First some logic for the map of the prototype to make sure it is in fast // mode. if (value->IsJSObject()) { JSObject::OptimizeAsPrototype(Handle::cast(value)); } // 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. if (function->IsInobjectSlackTrackingInProgress()) { function->CompleteInobjectSlackTracking(); } Handle initial_map(function->initial_map(), isolate); Handle new_map = Map::Copy(initial_map); new_map->set_prototype(*value); // If the function is used as the global Array function, cache the // initial map (and transitioned versions) in the native context. Context* native_context = function->context()->native_context(); Object* array_function = native_context->get(Context::ARRAY_FUNCTION_INDEX); if (array_function->IsJSFunction() && *function == JSFunction::cast(array_function)) { CacheInitialJSArrayMaps(handle(native_context, isolate), new_map); } function->set_initial_map(*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); } isolate->heap()->ClearInstanceofCache(); } void JSFunction::SetPrototype(Handle function, Handle value) { ASSERT(function->should_have_prototype()); 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())); JSObject::MigrateToMap(function, new_map); new_map->set_constructor(*value); new_map->set_non_instance_prototype(true); Isolate* isolate = new_map->GetIsolate(); construct_prototype = handle( isolate->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 = shared()->strict_mode() == SLOPPY ? native_context->sloppy_function_without_prototype_map() : native_context->strict_function_without_prototype_map(); if (map() == no_prototype_map) return true; #ifdef DEBUG if (map() != (shared()->strict_mode() == SLOPPY ? native_context->sloppy_function_map() : native_context->strict_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::EnsureHasInitialMap(Handle function) { if (function->has_initial_map()) return; Isolate* isolate = function->GetIsolate(); // First create a new map with the size and number of in-object properties // suggested by the function. InstanceType instance_type; int instance_size; int in_object_properties; if (function->shared()->is_generator()) { instance_type = JS_GENERATOR_OBJECT_TYPE; instance_size = JSGeneratorObject::kSize; in_object_properties = 0; } else { instance_type = JS_OBJECT_TYPE; instance_size = function->shared()->CalculateInstanceSize(); in_object_properties = function->shared()->CalculateInObjectProperties(); } 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->set_inobject_properties(in_object_properties); map->set_unused_property_fields(in_object_properties); map->set_prototype(*prototype); ASSERT(map->has_fast_object_elements()); // Finally link initial map and constructor function. function->set_initial_map(*map); map->set_constructor(*function); if (!function->shared()->is_generator()) { function->StartInobjectSlackTracking(); } } void JSFunction::SetInstanceClassName(String* name) { shared()->set_instance_class_name(name); } void JSFunction::PrintName(FILE* out) { SmartArrayPointer name = shared()->DebugName()->ToCString(); PrintF(out, "%s", name.get()); } Context* JSFunction::NativeContextFromLiterals(FixedArray* literals) { return Context::cast(literals->get(JSFunction::kLiteralNativeContextIndex)); } // The filter is a pattern that matches function names in this way: // "*" all; the default // "-" all but the top-level function // "-name" all but the function "name" // "" only the top-level function // "name" only the function "name" // "name*" only functions starting with "name" bool JSFunction::PassesFilter(const char* raw_filter) { if (*raw_filter == '*') return true; String* name = shared()->DebugName(); Vector filter = CStrVector(raw_filter); if (filter.length() == 0) return name->length() == 0; if (filter[0] == '-') { // Negative filter. if (filter.length() == 1) { return (name->length() != 0); } else if (name->IsUtf8EqualTo(filter.SubVector(1, filter.length()))) { return false; } if (filter[filter.length() - 1] == '*' && name->IsUtf8EqualTo(filter.SubVector(1, filter.length() - 1), true)) { return false; } return true; } else if (name->IsUtf8EqualTo(filter)) { return true; } if (filter[filter.length() - 1] == '*' && name->IsUtf8EqualTo(filter.SubVector(0, filter.length() - 1), true)) { return true; } return false; } void Oddball::Initialize(Isolate* isolate, Handle oddball, const char* to_string, Handle to_number, byte kind) { Handle internalized_to_string = isolate->factory()->InternalizeUtf8String(to_string); oddball->set_to_string(*internalized_to_string); oddball->set_to_number(*to_number); oddball->set_kind(kind); } void Script::InitLineEnds(Handle