// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "v8.h" #include "accessors.h" #include "api.h" #include "arguments.h" #include "bootstrapper.h" #include "codegen.h" #include "compilation-cache.h" #include "compiler.h" #include "cpu.h" #include "dateparser-inl.h" #include "debug.h" #include "deoptimizer.h" #include "execution.h" #include "global-handles.h" #include "jsregexp.h" #include "json-parser.h" #include "liveedit.h" #include "liveobjectlist-inl.h" #include "misc-intrinsics.h" #include "parser.h" #include "platform.h" #include "runtime-profiler.h" #include "runtime.h" #include "scopeinfo.h" #include "smart-array-pointer.h" #include "string-search.h" #include "stub-cache.h" #include "v8threads.h" #include "vm-state-inl.h" namespace v8 { namespace internal { #define RUNTIME_ASSERT(value) \ if (!(value)) return isolate->ThrowIllegalOperation(); // Cast the given object to a value of the specified type and store // it in a variable with the given name. If the object is not of the // expected type call IllegalOperation and return. #define CONVERT_CHECKED(Type, name, obj) \ RUNTIME_ASSERT(obj->Is##Type()); \ Type* name = Type::cast(obj); #define CONVERT_ARG_CHECKED(Type, name, index) \ RUNTIME_ASSERT(args[index]->Is##Type()); \ Handle name = args.at(index); // Cast the given object to a boolean and store it in a variable with // the given name. If the object is not a boolean call IllegalOperation // and return. #define CONVERT_BOOLEAN_CHECKED(name, obj) \ RUNTIME_ASSERT(obj->IsBoolean()); \ bool name = (obj)->IsTrue(); // Cast the given argument to a Smi and store its value in an int variable // with the given name. If the argument is not a Smi call IllegalOperation // and return. #define CONVERT_SMI_ARG_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsSmi()); \ int name = args.smi_at(index); // Cast the given argument to a double and store it in a variable with // the given name. If the argument is not a number (as opposed to // the number not-a-number) call IllegalOperation and return. #define CONVERT_DOUBLE_ARG_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsNumber()); \ double name = args.number_at(index); // Call the specified converter on the object *comand store the result in // a variable of the specified type with the given name. If the // object is not a Number call IllegalOperation and return. #define CONVERT_NUMBER_CHECKED(type, name, Type, obj) \ RUNTIME_ASSERT(obj->IsNumber()); \ type name = NumberTo##Type(obj); MUST_USE_RESULT static MaybeObject* DeepCopyBoilerplate(Isolate* isolate, JSObject* boilerplate) { StackLimitCheck check(isolate); if (check.HasOverflowed()) return isolate->StackOverflow(); Heap* heap = isolate->heap(); Object* result; { MaybeObject* maybe_result = heap->CopyJSObject(boilerplate); if (!maybe_result->ToObject(&result)) return maybe_result; } JSObject* copy = JSObject::cast(result); // Deep copy local properties. if (copy->HasFastProperties()) { FixedArray* properties = copy->properties(); for (int i = 0; i < properties->length(); i++) { Object* value = properties->get(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } properties->set(i, result); } } int nof = copy->map()->inobject_properties(); for (int i = 0; i < nof; i++) { Object* value = copy->InObjectPropertyAt(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } copy->InObjectPropertyAtPut(i, result); } } } else { { MaybeObject* maybe_result = heap->AllocateFixedArray(copy->NumberOfLocalProperties(NONE)); if (!maybe_result->ToObject(&result)) return maybe_result; } FixedArray* names = FixedArray::cast(result); copy->GetLocalPropertyNames(names, 0); for (int i = 0; i < names->length(); i++) { ASSERT(names->get(i)->IsString()); String* key_string = String::cast(names->get(i)); PropertyAttributes attributes = copy->GetLocalPropertyAttribute(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; Object* value = copy->GetProperty(key_string, &attributes)->ToObjectUnchecked(); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } { MaybeObject* maybe_result = // Creating object copy for literals. No strict mode needed. copy->SetProperty(key_string, result, NONE, kNonStrictMode); if (!maybe_result->ToObject(&result)) return maybe_result; } } } } // Deep copy local elements. // Pixel elements cannot be created using an object literal. ASSERT(!copy->HasExternalArrayElements()); switch (copy->GetElementsKind()) { case FAST_ELEMENTS: { FixedArray* elements = FixedArray::cast(copy->elements()); if (elements->map() == heap->fixed_cow_array_map()) { isolate->counters()->cow_arrays_created_runtime()->Increment(); #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++) { Object* value = elements->get(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } elements->set(i, result); } } } break; } case DICTIONARY_ELEMENTS: { NumberDictionary* 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)) { Object* value = element_dictionary->ValueAt(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } element_dictionary->ValueAtPut(i, result); } } } break; } case NON_STRICT_ARGUMENTS_ELEMENTS: UNIMPLEMENTED(); break; case EXTERNAL_PIXEL_ELEMENTS: case EXTERNAL_BYTE_ELEMENTS: case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: case EXTERNAL_SHORT_ELEMENTS: case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: case EXTERNAL_INT_ELEMENTS: case EXTERNAL_UNSIGNED_INT_ELEMENTS: case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_DOUBLE_ELEMENTS: // No contained objects, nothing to do. break; } return copy; } RUNTIME_FUNCTION(MaybeObject*, Runtime_CloneLiteralBoilerplate) { CONVERT_CHECKED(JSObject, boilerplate, args[0]); return DeepCopyBoilerplate(isolate, boilerplate); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CloneShallowLiteralBoilerplate) { CONVERT_CHECKED(JSObject, boilerplate, args[0]); return isolate->heap()->CopyJSObject(boilerplate); } static Handle ComputeObjectLiteralMap( Handle context, Handle constant_properties, bool* is_result_from_cache) { Isolate* isolate = context->GetIsolate(); int properties_length = constant_properties->length(); int number_of_properties = properties_length / 2; if (FLAG_canonicalize_object_literal_maps) { // Check that there are only symbols and array indices among keys. int number_of_symbol_keys = 0; for (int p = 0; p != properties_length; p += 2) { Object* key = constant_properties->get(p); uint32_t element_index = 0; if (key->IsSymbol()) { number_of_symbol_keys++; } else if (key->ToArrayIndex(&element_index)) { // An index key does not require space in the property backing store. number_of_properties--; } else { // Bail out as a non-symbol non-index key makes caching impossible. // ASSERT to make sure that the if condition after the loop is false. ASSERT(number_of_symbol_keys != number_of_properties); break; } } // If we only have symbols and array indices among keys then we can // use the map cache in the global context. const int kMaxKeys = 10; if ((number_of_symbol_keys == number_of_properties) && (number_of_symbol_keys < kMaxKeys)) { // Create the fixed array with the key. Handle keys = isolate->factory()->NewFixedArray(number_of_symbol_keys); if (number_of_symbol_keys > 0) { int index = 0; for (int p = 0; p < properties_length; p += 2) { Object* key = constant_properties->get(p); if (key->IsSymbol()) { keys->set(index++, key); } } ASSERT(index == number_of_symbol_keys); } *is_result_from_cache = true; return isolate->factory()->ObjectLiteralMapFromCache(context, keys); } } *is_result_from_cache = false; return isolate->factory()->CopyMap( Handle(context->object_function()->initial_map()), number_of_properties); } static Handle CreateLiteralBoilerplate( Isolate* isolate, Handle literals, Handle constant_properties); static Handle CreateObjectLiteralBoilerplate( Isolate* isolate, Handle literals, Handle constant_properties, bool should_have_fast_elements, bool has_function_literal) { // Get the global context from the literals array. This is the // context in which the function was created and we use the object // function from this context to create the object literal. We do // not use the object function from the current global context // because this might be the object function from another context // which we should not have access to. Handle context = Handle(JSFunction::GlobalContextFromLiterals(*literals)); // In case we have function literals, we want the object to be in // slow properties mode for now. We don't go in the map cache because // maps with constant functions can't be shared if the functions are // not the same (which is the common case). bool is_result_from_cache = false; Handle map = has_function_literal ? Handle(context->object_function()->initial_map()) : ComputeObjectLiteralMap(context, constant_properties, &is_result_from_cache); Handle boilerplate = isolate->factory()->NewJSObjectFromMap(map); // Normalize the elements of the boilerplate to save space if needed. if (!should_have_fast_elements) NormalizeElements(boilerplate); // Add the constant properties to the boilerplate. int length = constant_properties->length(); bool should_transform = !is_result_from_cache && boilerplate->HasFastProperties(); if (should_transform || has_function_literal) { // Normalize the properties of object to avoid n^2 behavior // when extending the object multiple properties. Indicate the number of // properties to be added. NormalizeProperties(boilerplate, KEEP_INOBJECT_PROPERTIES, length / 2); } for (int index = 0; index < length; index +=2) { Handle key(constant_properties->get(index+0), isolate); Handle value(constant_properties->get(index+1), isolate); if (value->IsFixedArray()) { // The value contains the constant_properties of a // simple object or array literal. Handle array = Handle::cast(value); value = CreateLiteralBoilerplate(isolate, literals, array); if (value.is_null()) return value; } Handle result; uint32_t element_index = 0; if (key->IsSymbol()) { if (Handle::cast(key)->AsArrayIndex(&element_index)) { // Array index as string (uint32). result = SetOwnElement(boilerplate, element_index, value, kNonStrictMode); } else { Handle name(String::cast(*key)); ASSERT(!name->AsArrayIndex(&element_index)); result = SetLocalPropertyIgnoreAttributes(boilerplate, name, value, NONE); } } else if (key->ToArrayIndex(&element_index)) { // Array index (uint32). result = SetOwnElement(boilerplate, element_index, value, kNonStrictMode); } else { // Non-uint32 number. ASSERT(key->IsNumber()); double num = key->Number(); char arr[100]; Vector buffer(arr, ARRAY_SIZE(arr)); const char* str = DoubleToCString(num, buffer); Handle name = isolate->factory()->NewStringFromAscii(CStrVector(str)); result = SetLocalPropertyIgnoreAttributes(boilerplate, name, value, NONE); } // If setting the property on the boilerplate throws an // exception, the exception is converted to an empty handle in // the handle based operations. In that case, we need to // convert back to an exception. if (result.is_null()) return result; } // Transform to fast properties if necessary. For object literals with // containing function literals we defer this operation until after all // computed properties have been assigned so that we can generate // constant function properties. if (should_transform && !has_function_literal) { TransformToFastProperties(boilerplate, boilerplate->map()->unused_property_fields()); } return boilerplate; } static Handle CreateArrayLiteralBoilerplate( Isolate* isolate, Handle literals, Handle elements) { // Create the JSArray. Handle constructor( JSFunction::GlobalContextFromLiterals(*literals)->array_function()); Handle object = isolate->factory()->NewJSObject(constructor); const bool is_cow = (elements->map() == isolate->heap()->fixed_cow_array_map()); Handle copied_elements = is_cow ? elements : isolate->factory()->CopyFixedArray(elements); Handle content = Handle::cast(copied_elements); if (is_cow) { #ifdef DEBUG // Copy-on-write arrays must be shallow (and simple). for (int i = 0; i < content->length(); i++) { ASSERT(!content->get(i)->IsFixedArray()); } #endif } else { for (int i = 0; i < content->length(); i++) { if (content->get(i)->IsFixedArray()) { // The value contains the constant_properties of a // simple object or array literal. Handle fa(FixedArray::cast(content->get(i))); Handle result = CreateLiteralBoilerplate(isolate, literals, fa); if (result.is_null()) return result; content->set(i, *result); } } } // Set the elements. Handle::cast(object)->SetContent(*content); return object; } static Handle CreateLiteralBoilerplate( Isolate* isolate, Handle literals, Handle array) { Handle elements = CompileTimeValue::GetElements(array); const bool kHasNoFunctionLiteral = false; switch (CompileTimeValue::GetType(array)) { case CompileTimeValue::OBJECT_LITERAL_FAST_ELEMENTS: return CreateObjectLiteralBoilerplate(isolate, literals, elements, true, kHasNoFunctionLiteral); case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS: return CreateObjectLiteralBoilerplate(isolate, literals, elements, false, kHasNoFunctionLiteral); case CompileTimeValue::ARRAY_LITERAL: return CreateArrayLiteralBoilerplate(isolate, literals, elements); default: UNREACHABLE(); return Handle::null(); } } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateArrayLiteralBoilerplate) { // Takes a FixedArray of elements containing the literal elements of // the array literal and produces JSArray with those elements. // Additionally takes the literals array of the surrounding function // which contains the context from which to get the Array function // to use for creating the array literal. HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_CHECKED(FixedArray, elements, 2); Handle object = CreateArrayLiteralBoilerplate(isolate, literals, elements); if (object.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *object); return *object; } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateObjectLiteral) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_ARG_CHECKED(flags, 3); bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0; bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0; // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = CreateObjectLiteralBoilerplate(isolate, literals, constant_properties, should_have_fast_elements, has_function_literal); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return DeepCopyBoilerplate(isolate, JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateObjectLiteralShallow) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_ARG_CHECKED(flags, 3); bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0; bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0; // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = CreateObjectLiteralBoilerplate(isolate, literals, constant_properties, should_have_fast_elements, has_function_literal); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return isolate->heap()->CopyJSObject(JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateArrayLiteral) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_CHECKED(FixedArray, elements, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = CreateArrayLiteralBoilerplate(isolate, literals, elements); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return DeepCopyBoilerplate(isolate, JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateArrayLiteralShallow) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_CHECKED(FixedArray, elements, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = CreateArrayLiteralBoilerplate(isolate, literals, elements); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } if (JSObject::cast(*boilerplate)->elements()->map() == isolate->heap()->fixed_cow_array_map()) { isolate->counters()->cow_arrays_created_runtime()->Increment(); } return isolate->heap()->CopyJSObject(JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateJSProxy) { ASSERT(args.length() == 2); Object* handler = args[0]; Object* prototype = args[1]; Object* used_prototype = prototype->IsJSReceiver() ? prototype : isolate->heap()->null_value(); return isolate->heap()->AllocateJSProxy(handler, used_prototype); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateJSFunctionProxy) { ASSERT(args.length() == 4); Object* handler = args[0]; Object* call_trap = args[1]; Object* construct_trap = args[2]; Object* prototype = args[3]; Object* used_prototype = prototype->IsJSReceiver() ? prototype : isolate->heap()->null_value(); return isolate->heap()->AllocateJSFunctionProxy( handler, call_trap, construct_trap, used_prototype); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsJSProxy) { ASSERT(args.length() == 1); Object* obj = args[0]; return isolate->heap()->ToBoolean(obj->IsJSProxy()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsJSFunctionProxy) { ASSERT(args.length() == 1); Object* obj = args[0]; return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetHandler) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSProxy, proxy, args[0]); return proxy->handler(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetCallTrap) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunctionProxy, proxy, args[0]); return proxy->call_trap(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetConstructTrap) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunctionProxy, proxy, args[0]); return proxy->construct_trap(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_Fix) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSProxy, proxy, args[0]); proxy->Fix(); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakMapInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSWeakMap, weakmap, 0); ASSERT(weakmap->map()->inobject_properties() == 0); Handle table = isolate->factory()->NewObjectHashTable(0); weakmap->set_table(*table); weakmap->set_next(Smi::FromInt(0)); return *weakmap; } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakMapGet) { NoHandleAllocation ha; ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(JSWeakMap, weakmap, 0); // TODO(mstarzinger): Currently we cannot use JSProxy objects as keys // because they cannot be cast to JSObject to get an identity hash code. CONVERT_ARG_CHECKED(JSObject, key, 1); return weakmap->table()->Lookup(*key); } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakMapSet) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(JSWeakMap, weakmap, 0); // TODO(mstarzinger): See Runtime_WeakMapGet above. CONVERT_ARG_CHECKED(JSObject, key, 1); Handle value(args[2]); Handle table(weakmap->table()); Handle new_table = PutIntoObjectHashTable(table, key, value); weakmap->set_table(*new_table); return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_ClassOf) { NoHandleAllocation ha; ASSERT(args.length() == 1); Object* obj = args[0]; if (!obj->IsJSObject()) return isolate->heap()->null_value(); return JSObject::cast(obj)->class_name(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetPrototype) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSReceiver, input_obj, args[0]); Object* obj = input_obj; // We don't expect access checks to be needed on JSProxy objects. ASSERT(!obj->IsAccessCheckNeeded() || obj->IsJSObject()); do { if (obj->IsAccessCheckNeeded() && !isolate->MayNamedAccess(JSObject::cast(obj), isolate->heap()->Proto_symbol(), v8::ACCESS_GET)) { isolate->ReportFailedAccessCheck(JSObject::cast(obj), v8::ACCESS_GET); return isolate->heap()->undefined_value(); } obj = obj->GetPrototype(); } while (obj->IsJSObject() && JSObject::cast(obj)->map()->is_hidden_prototype()); return obj; } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsInPrototypeChain) { NoHandleAllocation ha; ASSERT(args.length() == 2); // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8). Object* O = args[0]; Object* V = args[1]; while (true) { Object* prototype = V->GetPrototype(); if (prototype->IsNull()) return isolate->heap()->false_value(); if (O == prototype) return isolate->heap()->true_value(); V = prototype; } } // Inserts an object as the hidden prototype of another object. RUNTIME_FUNCTION(MaybeObject*, Runtime_SetHiddenPrototype) { NoHandleAllocation ha; ASSERT(args.length() == 2); CONVERT_CHECKED(JSObject, jsobject, args[0]); CONVERT_CHECKED(JSObject, proto, args[1]); // Sanity checks. The old prototype (that we are replacing) could // theoretically be null, but if it is not null then check that we // didn't already install a hidden prototype here. RUNTIME_ASSERT(!jsobject->GetPrototype()->IsHeapObject() || !HeapObject::cast(jsobject->GetPrototype())->map()->is_hidden_prototype()); RUNTIME_ASSERT(!proto->map()->is_hidden_prototype()); // Allocate up front before we start altering state in case we get a GC. Object* map_or_failure; { MaybeObject* maybe_map_or_failure = proto->map()->CopyDropTransitions(); if (!maybe_map_or_failure->ToObject(&map_or_failure)) { return maybe_map_or_failure; } } Map* new_proto_map = Map::cast(map_or_failure); { MaybeObject* maybe_map_or_failure = jsobject->map()->CopyDropTransitions(); if (!maybe_map_or_failure->ToObject(&map_or_failure)) { return maybe_map_or_failure; } } Map* new_map = Map::cast(map_or_failure); // Set proto's prototype to be the old prototype of the object. new_proto_map->set_prototype(jsobject->GetPrototype()); proto->set_map(new_proto_map); new_proto_map->set_is_hidden_prototype(); // Set the object's prototype to proto. new_map->set_prototype(proto); jsobject->set_map(new_map); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsConstructCall) { NoHandleAllocation ha; ASSERT(args.length() == 0); JavaScriptFrameIterator it(isolate); return isolate->heap()->ToBoolean(it.frame()->IsConstructor()); } // Recursively traverses hidden prototypes if property is not found static void GetOwnPropertyImplementation(JSObject* obj, String* name, LookupResult* result) { obj->LocalLookupRealNamedProperty(name, result); if (!result->IsProperty()) { Object* proto = obj->GetPrototype(); if (proto->IsJSObject() && JSObject::cast(proto)->map()->is_hidden_prototype()) GetOwnPropertyImplementation(JSObject::cast(proto), name, result); } } static bool CheckAccessException(LookupResult* result, v8::AccessType access_type) { if (result->type() == CALLBACKS) { Object* callback = result->GetCallbackObject(); if (callback->IsAccessorInfo()) { AccessorInfo* info = AccessorInfo::cast(callback); bool can_access = (access_type == v8::ACCESS_HAS && (info->all_can_read() || info->all_can_write())) || (access_type == v8::ACCESS_GET && info->all_can_read()) || (access_type == v8::ACCESS_SET && info->all_can_write()); return can_access; } } return false; } static bool CheckAccess(JSObject* obj, String* name, LookupResult* result, v8::AccessType access_type) { ASSERT(result->IsProperty()); JSObject* holder = result->holder(); JSObject* current = obj; Isolate* isolate = obj->GetIsolate(); while (true) { if (current->IsAccessCheckNeeded() && !isolate->MayNamedAccess(current, name, access_type)) { // Access check callback denied the access, but some properties // can have a special permissions which override callbacks descision // (currently see v8::AccessControl). break; } if (current == holder) { return true; } current = JSObject::cast(current->GetPrototype()); } // API callbacks can have per callback access exceptions. switch (result->type()) { case CALLBACKS: { if (CheckAccessException(result, access_type)) { return true; } break; } case INTERCEPTOR: { // If the object has an interceptor, try real named properties. // Overwrite the result to fetch the correct property later. holder->LookupRealNamedProperty(name, result); if (result->IsProperty()) { if (CheckAccessException(result, access_type)) { return true; } } break; } default: break; } isolate->ReportFailedAccessCheck(current, access_type); return false; } // TODO(1095): we should traverse hidden prototype hierachy as well. static bool CheckElementAccess(JSObject* obj, uint32_t index, v8::AccessType access_type) { if (obj->IsAccessCheckNeeded() && !obj->GetIsolate()->MayIndexedAccess(obj, index, access_type)) { return false; } return true; } // Enumerator used as indices into the array returned from GetOwnProperty enum PropertyDescriptorIndices { IS_ACCESSOR_INDEX, VALUE_INDEX, GETTER_INDEX, SETTER_INDEX, WRITABLE_INDEX, ENUMERABLE_INDEX, CONFIGURABLE_INDEX, DESCRIPTOR_SIZE }; // Returns an array with the property description: // if args[1] is not a property on args[0] // returns undefined // if args[1] is a data property on args[0] // [false, value, Writeable, Enumerable, Configurable] // if args[1] is an accessor on args[0] // [true, GetFunction, SetFunction, Enumerable, Configurable] RUNTIME_FUNCTION(MaybeObject*, Runtime_GetOwnProperty) { ASSERT(args.length() == 2); Heap* heap = isolate->heap(); HandleScope scope(isolate); Handle elms = isolate->factory()->NewFixedArray(DESCRIPTOR_SIZE); Handle desc = isolate->factory()->NewJSArrayWithElements(elms); LookupResult result; CONVERT_ARG_CHECKED(JSObject, obj, 0); CONVERT_ARG_CHECKED(String, name, 1); // This could be an element. uint32_t index; if (name->AsArrayIndex(&index)) { switch (obj->HasLocalElement(index)) { case JSObject::UNDEFINED_ELEMENT: return heap->undefined_value(); case JSObject::STRING_CHARACTER_ELEMENT: { // Special handling of string objects according to ECMAScript 5 // 15.5.5.2. Note that this might be a string object with elements // other than the actual string value. This is covered by the // subsequent cases. Handle js_value = Handle::cast(obj); Handle str(String::cast(js_value->value())); Handle substr = SubString(str, index, index + 1, NOT_TENURED); elms->set(IS_ACCESSOR_INDEX, heap->false_value()); elms->set(VALUE_INDEX, *substr); elms->set(WRITABLE_INDEX, heap->false_value()); elms->set(ENUMERABLE_INDEX, heap->false_value()); elms->set(CONFIGURABLE_INDEX, heap->false_value()); return *desc; } case JSObject::INTERCEPTED_ELEMENT: case JSObject::FAST_ELEMENT: { elms->set(IS_ACCESSOR_INDEX, heap->false_value()); Handle value = GetElement(obj, index); RETURN_IF_EMPTY_HANDLE(isolate, value); elms->set(VALUE_INDEX, *value); elms->set(WRITABLE_INDEX, heap->true_value()); elms->set(ENUMERABLE_INDEX, heap->true_value()); elms->set(CONFIGURABLE_INDEX, heap->true_value()); return *desc; } case JSObject::DICTIONARY_ELEMENT: { Handle holder = obj; if (obj->IsJSGlobalProxy()) { Object* proto = obj->GetPrototype(); if (proto->IsNull()) return heap->undefined_value(); ASSERT(proto->IsJSGlobalObject()); holder = Handle(JSObject::cast(proto)); } FixedArray* elements = FixedArray::cast(holder->elements()); NumberDictionary* dictionary = NULL; if (elements->map() == heap->non_strict_arguments_elements_map()) { dictionary = NumberDictionary::cast(elements->get(1)); } else { dictionary = NumberDictionary::cast(elements); } int entry = dictionary->FindEntry(index); ASSERT(entry != NumberDictionary::kNotFound); PropertyDetails details = dictionary->DetailsAt(entry); switch (details.type()) { case CALLBACKS: { // This is an accessor property with getter and/or setter. FixedArray* callbacks = FixedArray::cast(dictionary->ValueAt(entry)); elms->set(IS_ACCESSOR_INDEX, heap->true_value()); if (CheckElementAccess(*obj, index, v8::ACCESS_GET)) { elms->set(GETTER_INDEX, callbacks->get(0)); } if (CheckElementAccess(*obj, index, v8::ACCESS_SET)) { elms->set(SETTER_INDEX, callbacks->get(1)); } break; } case NORMAL: { // This is a data property. elms->set(IS_ACCESSOR_INDEX, heap->false_value()); Handle value = GetElement(obj, index); ASSERT(!value.is_null()); elms->set(VALUE_INDEX, *value); elms->set(WRITABLE_INDEX, heap->ToBoolean(!details.IsReadOnly())); break; } default: UNREACHABLE(); break; } elms->set(ENUMERABLE_INDEX, heap->ToBoolean(!details.IsDontEnum())); elms->set(CONFIGURABLE_INDEX, heap->ToBoolean(!details.IsDontDelete())); return *desc; } } } // Use recursive implementation to also traverse hidden prototypes GetOwnPropertyImplementation(*obj, *name, &result); if (!result.IsProperty()) { return heap->undefined_value(); } if (!CheckAccess(*obj, *name, &result, v8::ACCESS_HAS)) { return heap->false_value(); } elms->set(ENUMERABLE_INDEX, heap->ToBoolean(!result.IsDontEnum())); elms->set(CONFIGURABLE_INDEX, heap->ToBoolean(!result.IsDontDelete())); bool is_js_accessor = (result.type() == CALLBACKS) && (result.GetCallbackObject()->IsFixedArray()); if (is_js_accessor) { // __defineGetter__/__defineSetter__ callback. elms->set(IS_ACCESSOR_INDEX, heap->true_value()); FixedArray* structure = FixedArray::cast(result.GetCallbackObject()); if (CheckAccess(*obj, *name, &result, v8::ACCESS_GET)) { elms->set(GETTER_INDEX, structure->get(0)); } if (CheckAccess(*obj, *name, &result, v8::ACCESS_SET)) { elms->set(SETTER_INDEX, structure->get(1)); } } else { elms->set(IS_ACCESSOR_INDEX, heap->false_value()); elms->set(WRITABLE_INDEX, heap->ToBoolean(!result.IsReadOnly())); PropertyAttributes attrs; Object* value; // GetProperty will check access and report any violations. { MaybeObject* maybe_value = obj->GetProperty(*obj, &result, *name, &attrs); if (!maybe_value->ToObject(&value)) return maybe_value; } elms->set(VALUE_INDEX, value); } return *desc; } RUNTIME_FUNCTION(MaybeObject*, Runtime_PreventExtensions) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSObject, obj, args[0]); return obj->PreventExtensions(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsExtensible) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSObject, obj, args[0]); if (obj->IsJSGlobalProxy()) { Object* proto = obj->GetPrototype(); if (proto->IsNull()) return isolate->heap()->false_value(); ASSERT(proto->IsJSGlobalObject()); obj = JSObject::cast(proto); } return isolate->heap()->ToBoolean(obj->map()->is_extensible()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpCompile) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(JSRegExp, re, 0); CONVERT_ARG_CHECKED(String, pattern, 1); CONVERT_ARG_CHECKED(String, flags, 2); Handle result = RegExpImpl::Compile(re, pattern, flags); if (result.is_null()) return Failure::Exception(); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateApiFunction) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(FunctionTemplateInfo, data, 0); return *isolate->factory()->CreateApiFunction(data); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsTemplate) { ASSERT(args.length() == 1); Object* arg = args[0]; bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo(); return isolate->heap()->ToBoolean(result); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetTemplateField) { ASSERT(args.length() == 2); CONVERT_CHECKED(HeapObject, templ, args[0]); CONVERT_CHECKED(Smi, field, args[1]); int index = field->value(); int offset = index * kPointerSize + HeapObject::kHeaderSize; InstanceType type = templ->map()->instance_type(); RUNTIME_ASSERT(type == FUNCTION_TEMPLATE_INFO_TYPE || type == OBJECT_TEMPLATE_INFO_TYPE); RUNTIME_ASSERT(offset > 0); if (type == FUNCTION_TEMPLATE_INFO_TYPE) { RUNTIME_ASSERT(offset < FunctionTemplateInfo::kSize); } else { RUNTIME_ASSERT(offset < ObjectTemplateInfo::kSize); } return *HeapObject::RawField(templ, offset); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DisableAccessChecks) { ASSERT(args.length() == 1); CONVERT_CHECKED(HeapObject, object, args[0]); Map* old_map = object->map(); bool needs_access_checks = old_map->is_access_check_needed(); if (needs_access_checks) { // Copy map so it won't interfere constructor's initial map. Object* new_map; { MaybeObject* maybe_new_map = old_map->CopyDropTransitions(); if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map; } Map::cast(new_map)->set_is_access_check_needed(false); object->set_map(Map::cast(new_map)); } return isolate->heap()->ToBoolean(needs_access_checks); } RUNTIME_FUNCTION(MaybeObject*, Runtime_EnableAccessChecks) { ASSERT(args.length() == 1); CONVERT_CHECKED(HeapObject, object, args[0]); Map* old_map = object->map(); if (!old_map->is_access_check_needed()) { // Copy map so it won't interfere constructor's initial map. Object* new_map; { MaybeObject* maybe_new_map = old_map->CopyDropTransitions(); if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map; } Map::cast(new_map)->set_is_access_check_needed(true); object->set_map(Map::cast(new_map)); } return isolate->heap()->undefined_value(); } static Failure* ThrowRedeclarationError(Isolate* isolate, const char* type, Handle name) { HandleScope scope(isolate); Handle type_handle = isolate->factory()->NewStringFromAscii(CStrVector(type)); Handle args[2] = { type_handle, name }; Handle error = isolate->factory()->NewTypeError("redeclaration", HandleVector(args, 2)); return isolate->Throw(*error); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DeclareGlobals) { ASSERT(args.length() == 3); HandleScope scope(isolate); Handle global = Handle( isolate->context()->global()); Handle context = args.at(0); CONVERT_ARG_CHECKED(FixedArray, pairs, 1); CONVERT_SMI_ARG_CHECKED(flags, 2); // Traverse the name/value pairs and set the properties. int length = pairs->length(); for (int i = 0; i < length; i += 2) { HandleScope scope(isolate); Handle name(String::cast(pairs->get(i))); Handle value(pairs->get(i + 1), isolate); // We have to declare a global const property. To capture we only // assign to it when evaluating the assignment for "const x = // " the initial value is the hole. bool is_const_property = value->IsTheHole(); bool is_function_declaration = false; if (value->IsUndefined() || is_const_property) { // Lookup the property in the global object, and don't set the // value of the variable if the property is already there. LookupResult lookup; global->Lookup(*name, &lookup); if (lookup.IsProperty()) { // Determine if the property is local by comparing the holder // against the global object. The information will be used to // avoid throwing re-declaration errors when declaring // variables or constants that exist in the prototype chain. bool is_local = (*global == lookup.holder()); // Get the property attributes and determine if the property is // read-only. PropertyAttributes attributes = global->GetPropertyAttribute(*name); bool is_read_only = (attributes & READ_ONLY) != 0; if (lookup.type() == INTERCEPTOR) { // If the interceptor says the property is there, we // just return undefined without overwriting the property. // Otherwise, we continue to setting the property. if (attributes != ABSENT) { // Check if the existing property conflicts with regards to const. if (is_local && (is_read_only || is_const_property)) { const char* type = (is_read_only) ? "const" : "var"; return ThrowRedeclarationError(isolate, type, name); }; // The property already exists without conflicting: Go to // the next declaration. continue; } // Fall-through and introduce the absent property by using // SetProperty. } else { // For const properties, we treat a callback with this name // even in the prototype as a conflicting declaration. if (is_const_property && (lookup.type() == CALLBACKS)) { return ThrowRedeclarationError(isolate, "const", name); } // Otherwise, we check for locally conflicting declarations. if (is_local && (is_read_only || is_const_property)) { const char* type = (is_read_only) ? "const" : "var"; return ThrowRedeclarationError(isolate, type, name); } // The property already exists without conflicting: Go to // the next declaration. continue; } } } else { is_function_declaration = true; // Copy the function and update its context. Use it as value. Handle shared = Handle::cast(value); Handle function = isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context, TENURED); value = function; } LookupResult lookup; global->LocalLookup(*name, &lookup); // There's a local property that we need to overwrite because // we're either declaring a function or there's an interceptor // that claims the property is absent. // // Check for conflicting re-declarations. We cannot have // conflicting types in case of intercepted properties because // they are absent. if (lookup.IsProperty() && (lookup.type() != INTERCEPTOR) && (lookup.IsReadOnly() || is_const_property)) { const char* type = (lookup.IsReadOnly()) ? "const" : "var"; return ThrowRedeclarationError(isolate, type, name); } // Compute the property attributes. According to ECMA-262, section // 13, page 71, the property must be read-only and // non-deletable. However, neither SpiderMonkey nor KJS creates the // property as read-only, so we don't either. int attr = NONE; if ((flags & kDeclareGlobalsEvalFlag) == 0) { attr |= DONT_DELETE; } bool is_native = (flags & kDeclareGlobalsNativeFlag) != 0; if (is_const_property || (is_native && is_function_declaration)) { attr |= READ_ONLY; } // Safari does not allow the invocation of callback setters for // function declarations. To mimic this behavior, we do not allow // the invocation of setters for function values. This makes a // difference for global functions with the same names as event // handlers such as "function onload() {}". Firefox does call the // onload setter in those case and Safari does not. We follow // Safari for compatibility. if (value->IsJSFunction()) { // Do not change DONT_DELETE to false from true. if (lookup.IsProperty() && (lookup.type() != INTERCEPTOR)) { attr |= lookup.GetAttributes() & DONT_DELETE; } PropertyAttributes attributes = static_cast(attr); RETURN_IF_EMPTY_HANDLE(isolate, SetLocalPropertyIgnoreAttributes(global, name, value, attributes)); } else { StrictModeFlag strict_mode = ((flags & kDeclareGlobalsStrictModeFlag) != 0) ? kStrictMode : kNonStrictMode; RETURN_IF_EMPTY_HANDLE(isolate, SetProperty(global, name, value, static_cast(attr), strict_mode)); } } ASSERT(!isolate->has_pending_exception()); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DeclareContextSlot) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(Context, context, 0); Handle name(String::cast(args[1])); PropertyAttributes mode = static_cast(args.smi_at(2)); RUNTIME_ASSERT(mode == READ_ONLY || mode == NONE); Handle initial_value(args[3], isolate); // Declarations are always done in a function or global context. context = Handle(context->declaration_context()); int index; PropertyAttributes attributes; ContextLookupFlags flags = DONT_FOLLOW_CHAINS; BindingFlags binding_flags; Handle holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); if (attributes != ABSENT) { // The name was declared before; check for conflicting // re-declarations: This is similar to the code in parser.cc in // the AstBuildingParser::Declare function. if (((attributes & READ_ONLY) != 0) || (mode == READ_ONLY)) { // Functions are not read-only. ASSERT(mode != READ_ONLY || initial_value->IsTheHole()); const char* type = ((attributes & READ_ONLY) != 0) ? "const" : "var"; return ThrowRedeclarationError(isolate, type, name); } // Initialize it if necessary. if (*initial_value != NULL) { if (index >= 0) { // The variable or constant context slot should always be in // the function context or the arguments object. if (holder->IsContext()) { ASSERT(holder.is_identical_to(context)); if (((attributes & READ_ONLY) == 0) || context->get(index)->IsTheHole()) { context->set(index, *initial_value); } } else { // The holder is an arguments object. Handle arguments(Handle::cast(holder)); Handle result = SetElement(arguments, index, initial_value, kNonStrictMode); if (result.is_null()) return Failure::Exception(); } } else { // Slow case: The property is not in the FixedArray part of the context. Handle context_ext = Handle::cast(holder); RETURN_IF_EMPTY_HANDLE( isolate, SetProperty(context_ext, name, initial_value, mode, kNonStrictMode)); } } } else { // The property is not in the function context. It needs to be // "declared" in the function context's extension context, or in the // global context. Handle context_ext; if (context->has_extension()) { // The function context's extension context exists - use it. context_ext = Handle(JSObject::cast(context->extension())); } else { // The function context's extension context does not exists - allocate // it. context_ext = isolate->factory()->NewJSObject( isolate->context_extension_function()); // And store it in the extension slot. context->set_extension(*context_ext); } ASSERT(*context_ext != NULL); // Declare the property by setting it to the initial value if provided, // or undefined, and use the correct mode (e.g. READ_ONLY attribute for // constant declarations). ASSERT(!context_ext->HasLocalProperty(*name)); Handle value(isolate->heap()->undefined_value(), isolate); if (*initial_value != NULL) value = initial_value; // Declaring a const context slot is a conflicting declaration if // there is a callback with that name in a prototype. It is // allowed to introduce const variables in // JSContextExtensionObjects. They are treated specially in // SetProperty and no setters are invoked for those since they are // not real JSObjects. if (initial_value->IsTheHole() && !context_ext->IsJSContextExtensionObject()) { LookupResult lookup; context_ext->Lookup(*name, &lookup); if (lookup.IsProperty() && (lookup.type() == CALLBACKS)) { return ThrowRedeclarationError(isolate, "const", name); } } RETURN_IF_EMPTY_HANDLE(isolate, SetProperty(context_ext, name, value, mode, kNonStrictMode)); } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeVarGlobal) { NoHandleAllocation nha; // args[0] == name // args[1] == strict_mode // args[2] == value (optional) // Determine if we need to assign to the variable if it already // exists (based on the number of arguments). RUNTIME_ASSERT(args.length() == 2 || args.length() == 3); bool assign = args.length() == 3; CONVERT_ARG_CHECKED(String, name, 0); GlobalObject* global = isolate->context()->global(); RUNTIME_ASSERT(args[1]->IsSmi()); StrictModeFlag strict_mode = static_cast(args.smi_at(1)); ASSERT(strict_mode == kStrictMode || strict_mode == kNonStrictMode); // According to ECMA-262, section 12.2, page 62, the property must // not be deletable. PropertyAttributes attributes = DONT_DELETE; // Lookup the property locally in the global object. If it isn't // there, there is a property with this name in the prototype chain. // We follow Safari and Firefox behavior and only set the property // locally if there is an explicit initialization value that we have // to assign to the property. // Note that objects can have hidden prototypes, so we need to traverse // the whole chain of hidden prototypes to do a 'local' lookup. JSObject* real_holder = global; LookupResult lookup; while (true) { real_holder->LocalLookup(*name, &lookup); if (lookup.IsProperty()) { // Determine if this is a redeclaration of something read-only. if (lookup.IsReadOnly()) { // If we found readonly property on one of hidden prototypes, // just shadow it. if (real_holder != isolate->context()->global()) break; return ThrowRedeclarationError(isolate, "const", name); } // Determine if this is a redeclaration of an intercepted read-only // property and figure out if the property exists at all. bool found = true; PropertyType type = lookup.type(); if (type == INTERCEPTOR) { HandleScope handle_scope(isolate); Handle holder(real_holder); PropertyAttributes intercepted = holder->GetPropertyAttribute(*name); real_holder = *holder; if (intercepted == ABSENT) { // The interceptor claims the property isn't there. We need to // make sure to introduce it. found = false; } else if ((intercepted & READ_ONLY) != 0) { // The property is present, but read-only. Since we're trying to // overwrite it with a variable declaration we must throw a // re-declaration error. However if we found readonly property // on one of hidden prototypes, just shadow it. if (real_holder != isolate->context()->global()) break; return ThrowRedeclarationError(isolate, "const", name); } } if (found && !assign) { // The global property is there and we're not assigning any value // to it. Just return. return isolate->heap()->undefined_value(); } // Assign the value (or undefined) to the property. Object* value = (assign) ? args[2] : isolate->heap()->undefined_value(); return real_holder->SetProperty( &lookup, *name, value, attributes, strict_mode); } Object* proto = real_holder->GetPrototype(); if (!proto->IsJSObject()) break; if (!JSObject::cast(proto)->map()->is_hidden_prototype()) break; real_holder = JSObject::cast(proto); } global = isolate->context()->global(); if (assign) { return global->SetProperty(*name, args[2], attributes, strict_mode); } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeConstGlobal) { // All constants are declared with an initial value. The name // of the constant is the first argument and the initial value // is the second. RUNTIME_ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(String, name, 0); Handle value = args.at(1); // Get the current global object from top. GlobalObject* global = isolate->context()->global(); // According to ECMA-262, section 12.2, page 62, the property must // not be deletable. Since it's a const, it must be READ_ONLY too. PropertyAttributes attributes = static_cast(DONT_DELETE | READ_ONLY); // Lookup the property locally in the global object. If it isn't // there, we add the property and take special precautions to always // add it as a local property even in case of callbacks in the // prototype chain (this rules out using SetProperty). // We use SetLocalPropertyIgnoreAttributes instead LookupResult lookup; global->LocalLookup(*name, &lookup); if (!lookup.IsProperty()) { return global->SetLocalPropertyIgnoreAttributes(*name, *value, attributes); } // Determine if this is a redeclaration of something not // read-only. In case the result is hidden behind an interceptor we // need to ask it for the property attributes. if (!lookup.IsReadOnly()) { if (lookup.type() != INTERCEPTOR) { return ThrowRedeclarationError(isolate, "var", name); } PropertyAttributes intercepted = global->GetPropertyAttribute(*name); // Throw re-declaration error if the intercepted property is present // but not read-only. if (intercepted != ABSENT && (intercepted & READ_ONLY) == 0) { return ThrowRedeclarationError(isolate, "var", name); } // Restore global object from context (in case of GC) and continue // with setting the value because the property is either absent or // read-only. We also have to do redo the lookup. HandleScope handle_scope(isolate); Handle global(isolate->context()->global()); // BUG 1213575: Handle the case where we have to set a read-only // property through an interceptor and only do it if it's // uninitialized, e.g. the hole. Nirk... // Passing non-strict mode because the property is writable. RETURN_IF_EMPTY_HANDLE(isolate, SetProperty(global, name, value, attributes, kNonStrictMode)); return *value; } // Set the value, but only we're assigning the initial value to a // constant. For now, we determine this by checking if the // current value is the hole. // Strict mode handling not needed (const disallowed in strict mode). PropertyType type = lookup.type(); if (type == FIELD) { FixedArray* properties = global->properties(); int index = lookup.GetFieldIndex(); if (properties->get(index)->IsTheHole()) { properties->set(index, *value); } } else if (type == NORMAL) { if (global->GetNormalizedProperty(&lookup)->IsTheHole()) { global->SetNormalizedProperty(&lookup, *value); } } else { // Ignore re-initialization of constants that have already been // assigned a function value. ASSERT(lookup.IsReadOnly() && type == CONSTANT_FUNCTION); } // Use the set value as the result of the operation. return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeConstContextSlot) { HandleScope scope(isolate); ASSERT(args.length() == 3); Handle value(args[0], isolate); ASSERT(!value->IsTheHole()); CONVERT_ARG_CHECKED(Context, context, 1); Handle name(String::cast(args[2])); // Initializations are always done in a function or global context. context = Handle(context->declaration_context()); int index; PropertyAttributes attributes; ContextLookupFlags flags = FOLLOW_CHAINS; BindingFlags binding_flags; Handle holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); // In most situations, the property introduced by the const // declaration should be present in the context extension object. // However, because declaration and initialization are separate, the // property might have been deleted (if it was introduced by eval) // before we reach the initialization point. // // Example: // // function f() { eval("delete x; const x;"); } // // In that case, the initialization behaves like a normal assignment // to property 'x'. if (index >= 0) { if (holder->IsContext()) { // Property was found in a context. Perform the assignment if we // found some non-constant or an uninitialized constant. Handle context = Handle::cast(holder); if ((attributes & READ_ONLY) == 0 || context->get(index)->IsTheHole()) { context->set(index, *value); } } else { // The holder is an arguments object. ASSERT((attributes & READ_ONLY) == 0); Handle arguments(Handle::cast(holder)); RETURN_IF_EMPTY_HANDLE( isolate, SetElement(arguments, index, value, kNonStrictMode)); } return *value; } // The property could not be found, we introduce it in the global // context. if (attributes == ABSENT) { Handle global = Handle( isolate->context()->global()); // Strict mode not needed (const disallowed in strict mode). RETURN_IF_EMPTY_HANDLE( isolate, SetProperty(global, name, value, NONE, kNonStrictMode)); return *value; } // The property was present in a context extension object. Handle context_ext = Handle::cast(holder); if (*context_ext == context->extension()) { // This is the property that was introduced by the const // declaration. Set it if it hasn't been set before. NOTE: We // cannot use GetProperty() to get the current value as it // 'unholes' the value. LookupResult lookup; context_ext->LocalLookupRealNamedProperty(*name, &lookup); ASSERT(lookup.IsProperty()); // the property was declared ASSERT(lookup.IsReadOnly()); // and it was declared as read-only PropertyType type = lookup.type(); if (type == FIELD) { FixedArray* properties = context_ext->properties(); int index = lookup.GetFieldIndex(); if (properties->get(index)->IsTheHole()) { properties->set(index, *value); } } else if (type == NORMAL) { if (context_ext->GetNormalizedProperty(&lookup)->IsTheHole()) { context_ext->SetNormalizedProperty(&lookup, *value); } } else { // We should not reach here. Any real, named property should be // either a field or a dictionary slot. UNREACHABLE(); } } else { // The property was found in a different context extension object. // Set it if it is not a read-only property. if ((attributes & READ_ONLY) == 0) { // Strict mode not needed (const disallowed in strict mode). RETURN_IF_EMPTY_HANDLE( isolate, SetProperty(context_ext, name, value, attributes, kNonStrictMode)); } } return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_OptimizeObjectForAddingMultipleProperties) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(JSObject, object, 0); CONVERT_SMI_ARG_CHECKED(properties, 1); if (object->HasFastProperties()) { NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties); } return *object; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpExec) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(JSRegExp, regexp, 0); CONVERT_ARG_CHECKED(String, subject, 1); // Due to the way the JS calls are constructed this must be less than the // length of a string, i.e. it is always a Smi. We check anyway for security. CONVERT_SMI_ARG_CHECKED(index, 2); CONVERT_ARG_CHECKED(JSArray, last_match_info, 3); RUNTIME_ASSERT(last_match_info->HasFastElements()); RUNTIME_ASSERT(index >= 0); RUNTIME_ASSERT(index <= subject->length()); isolate->counters()->regexp_entry_runtime()->Increment(); Handle result = RegExpImpl::Exec(regexp, subject, index, last_match_info); if (result.is_null()) return Failure::Exception(); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpConstructResult) { ASSERT(args.length() == 3); CONVERT_SMI_ARG_CHECKED(elements_count, 0); if (elements_count < 0 || elements_count > FixedArray::kMaxLength || !Smi::IsValid(elements_count)) { return isolate->ThrowIllegalOperation(); } Object* new_object; { MaybeObject* maybe_new_object = isolate->heap()->AllocateFixedArrayWithHoles(elements_count); if (!maybe_new_object->ToObject(&new_object)) return maybe_new_object; } FixedArray* elements = FixedArray::cast(new_object); { MaybeObject* maybe_new_object = isolate->heap()->AllocateRaw( JSRegExpResult::kSize, NEW_SPACE, OLD_POINTER_SPACE); if (!maybe_new_object->ToObject(&new_object)) return maybe_new_object; } { AssertNoAllocation no_gc; HandleScope scope(isolate); reinterpret_cast(new_object)-> set_map(isolate->global_context()->regexp_result_map()); } JSArray* array = JSArray::cast(new_object); array->set_properties(isolate->heap()->empty_fixed_array()); array->set_elements(elements); array->set_length(Smi::FromInt(elements_count)); // Write in-object properties after the length of the array. array->InObjectPropertyAtPut(JSRegExpResult::kIndexIndex, args[1]); array->InObjectPropertyAtPut(JSRegExpResult::kInputIndex, args[2]); return array; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpInitializeObject) { AssertNoAllocation no_alloc; ASSERT(args.length() == 5); CONVERT_CHECKED(JSRegExp, regexp, args[0]); CONVERT_CHECKED(String, source, args[1]); Object* global = args[2]; if (!global->IsTrue()) global = isolate->heap()->false_value(); Object* ignoreCase = args[3]; if (!ignoreCase->IsTrue()) ignoreCase = isolate->heap()->false_value(); Object* multiline = args[4]; if (!multiline->IsTrue()) multiline = isolate->heap()->false_value(); Map* map = regexp->map(); Object* constructor = map->constructor(); if (constructor->IsJSFunction() && JSFunction::cast(constructor)->initial_map() == map) { // If we still have the original map, set in-object properties directly. regexp->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex, source); // TODO(lrn): Consider skipping write barrier on booleans as well. // Both true and false should be in oldspace at all times. regexp->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex, global); regexp->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex, ignoreCase); regexp->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex, multiline); regexp->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex, Smi::FromInt(0), SKIP_WRITE_BARRIER); return regexp; } // Map has changed, so use generic, but slower, method. PropertyAttributes final = static_cast(READ_ONLY | DONT_ENUM | DONT_DELETE); PropertyAttributes writable = static_cast(DONT_ENUM | DONT_DELETE); Heap* heap = isolate->heap(); MaybeObject* result; result = regexp->SetLocalPropertyIgnoreAttributes(heap->source_symbol(), source, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->global_symbol(), global, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->ignore_case_symbol(), ignoreCase, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->multiline_symbol(), multiline, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->last_index_symbol(), Smi::FromInt(0), writable); ASSERT(!result->IsFailure()); USE(result); return regexp; } RUNTIME_FUNCTION(MaybeObject*, Runtime_FinishArrayPrototypeSetup) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSArray, prototype, 0); // This is necessary to enable fast checks for absence of elements // on Array.prototype and below. prototype->set_elements(isolate->heap()->empty_fixed_array()); return Smi::FromInt(0); } static Handle InstallBuiltin(Isolate* isolate, Handle holder, const char* name, Builtins::Name builtin_name) { Handle key = isolate->factory()->LookupAsciiSymbol(name); Handle code(isolate->builtins()->builtin(builtin_name)); Handle optimized = isolate->factory()->NewFunction(key, JS_OBJECT_TYPE, JSObject::kHeaderSize, code, false); optimized->shared()->DontAdaptArguments(); SetProperty(holder, key, optimized, NONE, kStrictMode); return optimized; } RUNTIME_FUNCTION(MaybeObject*, Runtime_SpecialArrayFunctions) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, holder, 0); InstallBuiltin(isolate, holder, "pop", Builtins::kArrayPop); InstallBuiltin(isolate, holder, "push", Builtins::kArrayPush); InstallBuiltin(isolate, holder, "shift", Builtins::kArrayShift); InstallBuiltin(isolate, holder, "unshift", Builtins::kArrayUnshift); InstallBuiltin(isolate, holder, "slice", Builtins::kArraySlice); InstallBuiltin(isolate, holder, "splice", Builtins::kArraySplice); InstallBuiltin(isolate, holder, "concat", Builtins::kArrayConcat); return *holder; } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetDefaultReceiver) { NoHandleAllocation handle_free; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, function, args[0]); SharedFunctionInfo* shared = function->shared(); if (shared->native() || shared->strict_mode()) { return isolate->heap()->undefined_value(); } // Returns undefined for strict or native functions, or // the associated global receiver for "normal" functions. Context* global_context = function->context()->global()->global_context(); return global_context->global()->global_receiver(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MaterializeRegExpLiteral) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(FixedArray, literals, 0); int index = args.smi_at(1); Handle pattern = args.at(2); Handle flags = args.at(3); // Get the RegExp function from the context in the literals array. // This is the RegExp function from the context in which the // function was created. We do not use the RegExp function from the // current global context because this might be the RegExp function // from another context which we should not have access to. Handle constructor = Handle( JSFunction::GlobalContextFromLiterals(*literals)->regexp_function()); // Compute the regular expression literal. bool has_pending_exception; Handle regexp = RegExpImpl::CreateRegExpLiteral(constructor, pattern, flags, &has_pending_exception); if (has_pending_exception) { ASSERT(isolate->has_pending_exception()); return Failure::Exception(); } literals->set(index, *regexp); return *regexp; } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionGetName) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); return f->shared()->name(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionSetName) { NoHandleAllocation ha; ASSERT(args.length() == 2); CONVERT_CHECKED(JSFunction, f, args[0]); CONVERT_CHECKED(String, name, args[1]); f->shared()->set_name(name); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionNameShouldPrintAsAnonymous) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); return isolate->heap()->ToBoolean( f->shared()->name_should_print_as_anonymous()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionMarkNameShouldPrintAsAnonymous) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); f->shared()->set_name_should_print_as_anonymous(true); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionSetBound) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, fun, args[0]); fun->shared()->set_bound(true); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionRemovePrototype) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); Object* obj = f->RemovePrototype(); if (obj->IsFailure()) return obj; return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionGetScript) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, fun, args[0]); Handle script = Handle(fun->shared()->script(), isolate); if (!script->IsScript()) return isolate->heap()->undefined_value(); return *GetScriptWrapper(Handle