// Copyright 2006-2009 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 "compiler.h" #include "cpu.h" #include "dateparser-inl.h" #include "debug.h" #include "execution.h" #include "jsregexp.h" #include "parser.h" #include "platform.h" #include "runtime.h" #include "scopeinfo.h" #include "smart-pointer.h" #include "stub-cache.h" #include "v8threads.h" namespace v8 { namespace internal { #define RUNTIME_ASSERT(value) \ if (!(value)) return Top::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 object to a Smi and store its value in an int variable // with the given name. If the object is not a Smi call IllegalOperation // and return. #define CONVERT_SMI_CHECKED(name, obj) \ RUNTIME_ASSERT(obj->IsSmi()); \ int name = Smi::cast(obj)->value(); // Cast the given object to a double and store it in a variable with // the given name. If the object is not a number (as opposed to // the number not-a-number) call IllegalOperation and return. #define CONVERT_DOUBLE_CHECKED(name, obj) \ RUNTIME_ASSERT(obj->IsNumber()); \ double name = (obj)->Number(); // 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); // Non-reentrant string buffer for efficient general use in this file. static StaticResource runtime_string_input_buffer; static Object* DeepCopyBoilerplate(JSObject* boilerplate) { StackLimitCheck check; if (check.HasOverflowed()) return Top::StackOverflow(); Object* result = Heap::CopyJSObject(boilerplate); if (result->IsFailure()) return 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); result = DeepCopyBoilerplate(js_object); if (result->IsFailure()) return 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); result = DeepCopyBoilerplate(js_object); if (result->IsFailure()) return result; copy->InObjectPropertyAtPut(i, result); } } } else { result = Heap::AllocateFixedArray(copy->NumberOfLocalProperties(NONE)); if (result->IsFailure()) return 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); ASSERT(!value->IsFailure()); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); result = DeepCopyBoilerplate(js_object); if (result->IsFailure()) return result; result = copy->SetProperty(key_string, result, NONE); if (result->IsFailure()) return result; } } } // Deep copy local elements. // Pixel elements cannot be created using an object literal. ASSERT(!copy->HasPixelElements() && !copy->HasExternalArrayElements()); switch (copy->GetElementsKind()) { case JSObject::FAST_ELEMENTS: { FixedArray* elements = FixedArray::cast(copy->elements()); for (int i = 0; i < elements->length(); i++) { Object* value = elements->get(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); result = DeepCopyBoilerplate(js_object); if (result->IsFailure()) return result; elements->set(i, result); } } break; } case JSObject::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); result = DeepCopyBoilerplate(js_object); if (result->IsFailure()) return result; element_dictionary->ValueAtPut(i, result); } } } break; } default: UNREACHABLE(); break; } return copy; } static Object* Runtime_CloneLiteralBoilerplate(Arguments args) { CONVERT_CHECKED(JSObject, boilerplate, args[0]); return DeepCopyBoilerplate(boilerplate); } static Object* Runtime_CloneShallowLiteralBoilerplate(Arguments args) { CONVERT_CHECKED(JSObject, boilerplate, args[0]); return Heap::CopyJSObject(boilerplate); } static Handle ComputeObjectLiteralMap( Handle context, Handle constant_properties, bool* is_result_from_cache) { int number_of_properties = constant_properties->length() / 2; if (FLAG_canonicalize_object_literal_maps) { // First find prefix of consecutive symbol keys. int number_of_symbol_keys = 0; while ((number_of_symbol_keys < number_of_properties) && (constant_properties->get(number_of_symbol_keys*2)->IsSymbol())) { number_of_symbol_keys++; } // Based on the number of prefix symbols key we decide whether // to 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 = Factory::NewFixedArray(number_of_symbol_keys); for (int i = 0; i < number_of_symbol_keys; i++) { keys->set(i, constant_properties->get(i*2)); } *is_result_from_cache = true; return Factory::ObjectLiteralMapFromCache(context, keys); } } *is_result_from_cache = false; return Factory::CopyMap( Handle(context->object_function()->initial_map()), number_of_properties); } static Handle CreateLiteralBoilerplate( Handle literals, Handle constant_properties); static Handle CreateObjectLiteralBoilerplate( Handle literals, Handle constant_properties) { // 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)); bool is_result_from_cache; Handle map = ComputeObjectLiteralMap(context, constant_properties, &is_result_from_cache); Handle boilerplate = Factory::NewJSObjectFromMap(map); { // Add the constant properties to the boilerplate. int length = constant_properties->length(); OptimizedObjectForAddingMultipleProperties opt(boilerplate, length / 2, !is_result_from_cache); for (int index = 0; index < length; index +=2) { Handle key(constant_properties->get(index+0)); Handle value(constant_properties->get(index+1)); if (value->IsFixedArray()) { // The value contains the constant_properties of a // simple object literal. Handle array = Handle::cast(value); value = CreateLiteralBoilerplate(literals, array); if (value.is_null()) return value; } Handle result; uint32_t element_index = 0; if (key->IsSymbol()) { // If key is a symbol it is not an array element. Handle name(String::cast(*key)); ASSERT(!name->AsArrayIndex(&element_index)); result = SetProperty(boilerplate, name, value, NONE); } else if (Array::IndexFromObject(*key, &element_index)) { // Array index (uint32). result = SetElement(boilerplate, element_index, value); } 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 = Factory::NewStringFromAscii(CStrVector(str)); result = SetProperty(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; } } return boilerplate; } static Handle CreateArrayLiteralBoilerplate( Handle literals, Handle elements) { // Create the JSArray. Handle constructor( JSFunction::GlobalContextFromLiterals(*literals)->array_function()); Handle object = Factory::NewJSObject(constructor); Handle copied_elements = Factory::CopyFixedArray(elements); Handle content = Handle::cast(copied_elements); for (int i = 0; i < content->length(); i++) { if (content->get(i)->IsFixedArray()) { // The value contains the constant_properties of a // simple object literal. Handle fa(FixedArray::cast(content->get(i))); Handle result = CreateLiteralBoilerplate(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( Handle literals, Handle array) { Handle elements = CompileTimeValue::GetElements(array); switch (CompileTimeValue::GetType(array)) { case CompileTimeValue::OBJECT_LITERAL: return CreateObjectLiteralBoilerplate(literals, elements); case CompileTimeValue::ARRAY_LITERAL: return CreateArrayLiteralBoilerplate(literals, elements); default: UNREACHABLE(); return Handle::null(); } } static Object* Runtime_CreateObjectLiteralBoilerplate(Arguments args) { HandleScope scope; ASSERT(args.length() == 3); // Copy the arguments. CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); Handle result = CreateObjectLiteralBoilerplate(literals, constant_properties); if (result.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *result); return *result; } static Object* Runtime_CreateArrayLiteralBoilerplate(Arguments args) { // 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; ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, elements, 2); Handle object = CreateArrayLiteralBoilerplate(literals, elements); if (object.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *object); return *object; } static Object* Runtime_CreateObjectLiteral(Arguments args) { HandleScope scope; ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index)); if (*boilerplate == Heap::undefined_value()) { boilerplate = CreateObjectLiteralBoilerplate(literals, constant_properties); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return DeepCopyBoilerplate(JSObject::cast(*boilerplate)); } static Object* Runtime_CreateObjectLiteralShallow(Arguments args) { HandleScope scope; ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index)); if (*boilerplate == Heap::undefined_value()) { boilerplate = CreateObjectLiteralBoilerplate(literals, constant_properties); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return Heap::CopyJSObject(JSObject::cast(*boilerplate)); } static Object* Runtime_CreateArrayLiteral(Arguments args) { HandleScope scope; ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, elements, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index)); if (*boilerplate == Heap::undefined_value()) { boilerplate = CreateArrayLiteralBoilerplate(literals, elements); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return DeepCopyBoilerplate(JSObject::cast(*boilerplate)); } static Object* Runtime_CreateArrayLiteralShallow(Arguments args) { HandleScope scope; ASSERT(args.length() == 3); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, elements, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index)); if (*boilerplate == Heap::undefined_value()) { boilerplate = CreateArrayLiteralBoilerplate(literals, elements); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return Heap::CopyJSObject(JSObject::cast(*boilerplate)); } static Object* Runtime_CreateCatchExtensionObject(Arguments args) { ASSERT(args.length() == 2); CONVERT_CHECKED(String, key, args[0]); Object* value = args[1]; // Create a catch context extension object. JSFunction* constructor = Top::context()->global_context()->context_extension_function(); Object* object = Heap::AllocateJSObject(constructor); if (object->IsFailure()) return object; // Assign the exception value to the catch variable and make sure // that the catch variable is DontDelete. value = JSObject::cast(object)->SetProperty(key, value, DONT_DELETE); if (value->IsFailure()) return value; return object; } static Object* Runtime_ClassOf(Arguments args) { NoHandleAllocation ha; ASSERT(args.length() == 1); Object* obj = args[0]; if (!obj->IsJSObject()) return Heap::null_value(); return JSObject::cast(obj)->class_name(); } static Object* Runtime_IsInPrototypeChain(Arguments args) { 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 Heap::false_value(); if (O == prototype) return Heap::true_value(); V = prototype; } } // Inserts an object as the hidden prototype of another object. static Object* Runtime_SetHiddenPrototype(Arguments args) { 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 = proto->map()->CopyDropTransitions(); if (map_or_failure->IsFailure()) return map_or_failure; Map* new_proto_map = Map::cast(map_or_failure); map_or_failure = jsobject->map()->CopyDropTransitions(); if (map_or_failure->IsFailure()) return 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 Heap::undefined_value(); } static Object* Runtime_IsConstructCall(Arguments args) { NoHandleAllocation ha; ASSERT(args.length() == 0); JavaScriptFrameIterator it; return 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); } } // 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] static Object* Runtime_GetOwnProperty(Arguments args) { ASSERT(args.length() == 2); HandleScope scope; Handle elms = Factory::NewFixedArray(5); Handle desc = Factory::NewJSArrayWithElements(elms); LookupResult result; CONVERT_CHECKED(JSObject, obj, args[0]); CONVERT_CHECKED(String, name, args[1]); // Use recursive implementation to also traverse hidden prototypes GetOwnPropertyImplementation(obj, name, &result); if (!result.IsProperty()) return Heap::undefined_value(); if (result.type() == CALLBACKS) { Object* structure = result.GetCallbackObject(); if (structure->IsProxy() || structure->IsAccessorInfo()) { // Property that is internally implemented as a callback or // an API defined callback. Object* value = obj->GetPropertyWithCallback( obj, structure, name, result.holder()); elms->set(0, Heap::false_value()); elms->set(1, value); elms->set(2, Heap::ToBoolean(!result.IsReadOnly())); } else if (structure->IsFixedArray()) { // __defineGetter__/__defineSetter__ callback. elms->set(0, Heap::true_value()); elms->set(1, FixedArray::cast(structure)->get(0)); elms->set(2, FixedArray::cast(structure)->get(1)); } else { return Heap::undefined_value(); } } else { elms->set(0, Heap::false_value()); elms->set(1, result.GetLazyValue()); elms->set(2, Heap::ToBoolean(!result.IsReadOnly())); } elms->set(3, Heap::ToBoolean(!result.IsDontEnum())); elms->set(4, Heap::ToBoolean(!result.IsDontDelete())); return *desc; } static Object* Runtime_IsExtensible(Arguments args) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSObject, obj, args[0]); return obj->map()->is_extensible() ? Heap::true_value() : Heap::false_value(); } static Object* Runtime_RegExpCompile(Arguments args) { HandleScope scope; 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; } static Object* Runtime_CreateApiFunction(Arguments args) { HandleScope scope; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(FunctionTemplateInfo, data, 0); return *Factory::CreateApiFunction(data); } static Object* Runtime_IsTemplate(Arguments args) { ASSERT(args.length() == 1); Object* arg = args[0]; bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo(); return Heap::ToBoolean(result); } static Object* Runtime_GetTemplateField(Arguments args) { 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); } static Object* Runtime_DisableAccessChecks(Arguments args) { 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 = old_map->CopyDropTransitions(); if (new_map->IsFailure()) return new_map; Map::cast(new_map)->set_is_access_check_needed(false); object->set_map(Map::cast(new_map)); } return needs_access_checks ? Heap::true_value() : Heap::false_value(); } static Object* Runtime_EnableAccessChecks(Arguments args) { 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 = old_map->CopyDropTransitions(); if (new_map->IsFailure()) return new_map; Map::cast(new_map)->set_is_access_check_needed(true); object->set_map(Map::cast(new_map)); } return Heap::undefined_value(); } static Object* ThrowRedeclarationError(const char* type, Handle name) { HandleScope scope; Handle type_handle = Factory::NewStringFromAscii(CStrVector(type)); Handle args[2] = { type_handle, name }; Handle error = Factory::NewTypeError("redeclaration", HandleVector(args, 2)); return Top::Throw(*error); } static Object* Runtime_DeclareGlobals(Arguments args) { HandleScope scope; Handle global = Handle(Top::context()->global()); Handle context = args.at(0); CONVERT_ARG_CHECKED(FixedArray, pairs, 1); bool is_eval = Smi::cast(args[2])->value() == 1; // 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. PropertyAttributes base = is_eval ? NONE : DONT_DELETE; // Traverse the name/value pairs and set the properties. int length = pairs->length(); for (int i = 0; i < length; i += 2) { HandleScope scope; Handle name(String::cast(pairs->get(i))); Handle value(pairs->get(i + 1)); // 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(); 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(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 { if (is_local && (is_read_only || is_const_property)) { const char* type = (is_read_only) ? "const" : "var"; return ThrowRedeclarationError(type, name); } // The property already exists without conflicting: Go to // the next declaration. continue; } } } else { // Copy the function and update its context. Use it as value. Handle boilerplate = Handle::cast(value); Handle function = Factory::NewFunctionFromBoilerplate(boilerplate, context, TENURED); value = function; } LookupResult lookup; global->LocalLookup(*name, &lookup); PropertyAttributes attributes = is_const_property ? static_cast(base | READ_ONLY) : base; if (lookup.IsProperty()) { // 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.type() != INTERCEPTOR && (lookup.IsReadOnly() || is_const_property)) { const char* type = (lookup.IsReadOnly()) ? "const" : "var"; return ThrowRedeclarationError(type, name); } SetProperty(global, name, value, attributes); } else { // If a property with this name does not already exist on the // global object add the property locally. We 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). Also, we must use the handle-based version to // avoid GC issues. IgnoreAttributesAndSetLocalProperty(global, name, value, attributes); } } return Heap::undefined_value(); } static Object* Runtime_DeclareContextSlot(Arguments args) { HandleScope scope; ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(Context, context, 0); Handle name(String::cast(args[1])); PropertyAttributes mode = static_cast(Smi::cast(args[2])->value()); ASSERT(mode == READ_ONLY || mode == NONE); Handle initial_value(args[3]); // Declarations are always done in the function context. context = Handle(context->fcontext()); int index; PropertyAttributes attributes; ContextLookupFlags flags = DONT_FOLLOW_CHAINS; Handle holder = context->Lookup(name, flags, &index, &attributes); 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(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 { Handle::cast(holder)->SetElement(index, *initial_value); } } else { // Slow case: The property is not in the FixedArray part of the context. Handle context_ext = Handle::cast(holder); SetProperty(context_ext, name, initial_value, mode); } } } 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(context->extension()); } else { // The function context's extension context does not exists - allocate // it. context_ext = Factory::NewJSObject(Top::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(Heap::undefined_value()); if (*initial_value != NULL) value = initial_value; SetProperty(context_ext, name, value, mode); ASSERT(context_ext->GetLocalPropertyAttribute(*name) == mode); } return Heap::undefined_value(); } static Object* Runtime_InitializeVarGlobal(Arguments args) { NoHandleAllocation nha; // Determine if we need to assign to the variable if it already // exists (based on the number of arguments). RUNTIME_ASSERT(args.length() == 1 || args.length() == 2); bool assign = args.length() == 2; CONVERT_ARG_CHECKED(String, name, 0); GlobalObject* global = Top::context()->global(); // 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. When adding the property we 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 have IgnoreAttributesAndSetLocalProperty for // this. // 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 != Top::context()->global()) break; return ThrowRedeclarationError("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; 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 != Top::context()->global()) break; return ThrowRedeclarationError("const", name); } } if (found && !assign) { // The global property is there and we're not assigning any value // to it. Just return. return Heap::undefined_value(); } // Assign the value (or undefined) to the property. Object* value = (assign) ? args[1] : Heap::undefined_value(); return real_holder->SetProperty(&lookup, *name, value, attributes); } Object* proto = real_holder->GetPrototype(); if (!proto->IsJSObject()) break; if (!JSObject::cast(proto)->map()->is_hidden_prototype()) break; real_holder = JSObject::cast(proto); } global = Top::context()->global(); if (assign) { return global->IgnoreAttributesAndSetLocalProperty(*name, args[1], attributes); } return Heap::undefined_value(); } static Object* Runtime_InitializeConstGlobal(Arguments args) { // 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 = Top::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 IgnoreAttributesAndSetLocalProperty instead LookupResult lookup; global->LocalLookup(*name, &lookup); if (!lookup.IsProperty()) { return global->IgnoreAttributesAndSetLocalProperty(*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("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("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. global = Top::context()->global(); // BUG 1213579: 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... global->SetProperty(*name, *value, attributes); 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. 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; } static Object* Runtime_InitializeConstContextSlot(Arguments args) { HandleScope scope; ASSERT(args.length() == 3); Handle value(args[0]); ASSERT(!value->IsTheHole()); CONVERT_ARG_CHECKED(Context, context, 1); Handle name(String::cast(args[2])); // Initializations are always done in the function context. context = Handle(context->fcontext()); int index; PropertyAttributes attributes; ContextLookupFlags flags = FOLLOW_CHAINS; Handle holder = context->Lookup(name, flags, &index, &attributes); // 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) { // Property was found in a context. if (holder->IsContext()) { // The holder cannot be the function context. If it is, there // should have been a const redeclaration error when declaring // the const property. ASSERT(!holder.is_identical_to(context)); if ((attributes & READ_ONLY) == 0) { Handle::cast(holder)->set(index, *value); } } else { // The holder is an arguments object. ASSERT((attributes & READ_ONLY) == 0); Handle::cast(holder)->SetElement(index, *value); } return *value; } // The property could not be found, we introduce it in the global // context. if (attributes == ABSENT) { Handle global = Handle(Top::context()->global()); SetProperty(global, name, value, NONE); 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) { Handle set = SetProperty(context_ext, name, value, attributes); // Setting a property might throw an exception. Exceptions // are converted to empty handles in handle operations. We // need to convert back to exceptions here. if (set.is_null()) { ASSERT(Top::has_pending_exception()); return Failure::Exception(); } } } return *value; } static Object* Runtime_OptimizeObjectForAddingMultipleProperties( Arguments args) { HandleScope scope; ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(JSObject, object, 0); CONVERT_SMI_CHECKED(properties, args[1]); if (object->HasFastProperties()) { NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties); } return *object; } static Object* Runtime_TransformToFastProperties(Arguments args) { HandleScope scope; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, object, 0); if (!object->HasFastProperties() && !object->IsGlobalObject()) { TransformToFastProperties(object, 0); } return *object; } static Object* Runtime_RegExpExec(Arguments args) { HandleScope scope; 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_CHECKED(index, args[2]); CONVERT_ARG_CHECKED(JSArray, last_match_info, 3); RUNTIME_ASSERT(last_match_info->HasFastElements()); RUNTIME_ASSERT(index >= 0); RUNTIME_ASSERT(index <= subject->length()); Counters::regexp_entry_runtime.Increment(); Handle result = RegExpImpl::Exec(regexp, subject, index, last_match_info); if (result.is_null()) return Failure::Exception(); return *result; } static Object* Runtime_MaterializeRegExpLiteral(Arguments args) { HandleScope scope; ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(FixedArray, literals, 0); int index = Smi::cast(args[1])->value(); 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(Top::has_pending_exception()); return Failure::Exception(); } literals->set(index, *regexp); return *regexp; } static Object* Runtime_FunctionGetName(Arguments args) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); return f->shared()->name(); } static Object* Runtime_FunctionSetName(Arguments args) { NoHandleAllocation ha; ASSERT(args.length() == 2); CONVERT_CHECKED(JSFunction, f, args[0]); CONVERT_CHECKED(String, name, args[1]); f->shared()->set_name(name); return Heap::undefined_value(); } static Object* Runtime_FunctionGetScript(Arguments args) { HandleScope scope; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, fun, args[0]); Handle script = Handle(fun->shared()->script()); if (!script->IsScript()) return Heap::undefined_value(); return *GetScriptWrapper(Handle