// Copyright 2010 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 "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 "liveedit.h" #include "liveobjectlist-inl.h" #include "parser.h" #include "platform.h" #include "runtime.h" #include "runtime-profiler.h" #include "scopeinfo.h" #include "smart-pointer.h" #include "stub-cache.h" #include "v8threads.h" #include "string-search.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; MUST_USE_RESULT static MaybeObject* DeepCopyBoilerplate(JSObject* boilerplate) { StackLimitCheck check; if (check.HasOverflowed()) return Top::StackOverflow(); 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(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(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(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->HasPixelElements() && !copy->HasExternalArrayElements()); switch (copy->GetElementsKind()) { case JSObject::FAST_ELEMENTS: { FixedArray* elements = FixedArray::cast(copy->elements()); if (elements->map() == Heap::fixed_cow_array_map()) { 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(js_object); if (!maybe_result->ToObject(&result)) return maybe_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); { MaybeObject* maybe_result = DeepCopyBoilerplate(js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } element_dictionary->ValueAtPut(i, result); } } } break; } default: UNREACHABLE(); break; } return copy; } static MaybeObject* Runtime_CloneLiteralBoilerplate(Arguments args) { CONVERT_CHECKED(JSObject, boilerplate, args[0]); return DeepCopyBoilerplate(boilerplate); } static MaybeObject* 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 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 = 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 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, bool should_have_fast_elements) { // 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); // 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(); 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 (Handle::cast(key)->AsArrayIndex(&element_index)) { // Array index as string (uint32). result = SetOwnElement(boilerplate, element_index, value); } 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); } 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 = 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; } } return boilerplate; } static Handle CreateArrayLiteralBoilerplate( Handle literals, Handle elements) { // Create the JSArray. Handle constructor( JSFunction::GlobalContextFromLiterals(*literals)->array_function()); Handle object = Factory::NewJSObject(constructor); const bool is_cow = (elements->map() == Heap::fixed_cow_array_map()); Handle copied_elements = is_cow ? elements : 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 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_FAST_ELEMENTS: return CreateObjectLiteralBoilerplate(literals, elements, true); case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS: return CreateObjectLiteralBoilerplate(literals, elements, false); case CompileTimeValue::ARRAY_LITERAL: return CreateArrayLiteralBoilerplate(literals, elements); default: UNREACHABLE(); return Handle::null(); } } static MaybeObject* 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 MaybeObject* Runtime_CreateObjectLiteral(Arguments args) { HandleScope scope; ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_CHECKED(fast_elements, args[3]); bool should_have_fast_elements = fast_elements == 1; // 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, should_have_fast_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 MaybeObject* Runtime_CreateObjectLiteralShallow(Arguments args) { HandleScope scope; ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(FixedArray, literals, 0); CONVERT_SMI_CHECKED(literals_index, args[1]); CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_CHECKED(fast_elements, args[3]); bool should_have_fast_elements = fast_elements == 1; // 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, should_have_fast_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 MaybeObject* 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 MaybeObject* 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); } if (JSObject::cast(*boilerplate)->elements()->map() == Heap::fixed_cow_array_map()) { Counters::cow_arrays_created_runtime.Increment(); } return Heap::CopyJSObject(JSObject::cast(*boilerplate)); } static MaybeObject* 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; { MaybeObject* maybe_object = Heap::AllocateJSObject(constructor); if (!maybe_object->ToObject(&object)) return maybe_object; } // Assign the exception value to the catch variable and make sure // that the catch variable is DontDelete. { MaybeObject* maybe_value = // Passing non-strict per ECMA-262 5th Ed. 12.14. Catch, bullet #4. JSObject::cast(object)->SetProperty( key, value, DONT_DELETE, kNonStrictMode); if (!maybe_value->ToObject(&value)) return maybe_value; } return object; } static MaybeObject* 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 MaybeObject* 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 MaybeObject* 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; { 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 Heap::undefined_value(); } static MaybeObject* 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); } } 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; while (true) { if (current->IsAccessCheckNeeded() && !Top::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; } Top::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() && !Top::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] static MaybeObject* Runtime_GetOwnProperty(Arguments args) { ASSERT(args.length() == 2); HandleScope scope; Handle elms = Factory::NewFixedArray(DESCRIPTOR_SIZE); Handle desc = 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); 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)); } NumberDictionary* dictionary = holder->element_dictionary(); 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); 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; } static MaybeObject* Runtime_PreventExtensions(Arguments args) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSObject, obj, args[0]); return obj->PreventExtensions(); } static MaybeObject* Runtime_IsExtensible(Arguments args) { ASSERT(args.length() == 1); CONVERT_CHECKED(JSObject, obj, args[0]); if (obj->IsJSGlobalProxy()) { Object* proto = obj->GetPrototype(); if (proto->IsNull()) return Heap::false_value(); ASSERT(proto->IsJSGlobalObject()); obj = JSObject::cast(proto); } return obj->map()->is_extensible() ? Heap::true_value() : Heap::false_value(); } static MaybeObject* 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 MaybeObject* Runtime_CreateApiFunction(Arguments args) { HandleScope scope; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(FunctionTemplateInfo, data, 0); return *Factory::CreateApiFunction(data); } static MaybeObject* Runtime_IsTemplate(Arguments args) { ASSERT(args.length() == 1); Object* arg = args[0]; bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo(); return Heap::ToBoolean(result); } static MaybeObject* 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 MaybeObject* 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; { 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 needs_access_checks ? Heap::true_value() : Heap::false_value(); } static MaybeObject* 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; { 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 Heap::undefined_value(); } static Failure* 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 MaybeObject* Runtime_DeclareGlobals(Arguments args) { ASSERT(args.length() == 4); 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; StrictModeFlag strict_mode = static_cast(Smi::cast(args[3])->value()); ASSERT(strict_mode == kStrictMode || strict_mode == kNonStrictMode); // 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 { // 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("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(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 shared = Handle::cast(value); Handle function = Factory::NewFunctionFromSharedFunctionInfo(shared, context, TENURED); value = function; } LookupResult lookup; global->LocalLookup(*name, &lookup); PropertyAttributes attributes = is_const_property ? static_cast(base | READ_ONLY) : base; // 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(type, name); } // 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)) { attributes = static_cast( attributes | (lookup.GetAttributes() & DONT_DELETE)); } RETURN_IF_EMPTY_HANDLE(SetLocalPropertyIgnoreAttributes(global, name, value, attributes)); } else { RETURN_IF_EMPTY_HANDLE(SetProperty(global, name, value, attributes, strict_mode)); } } ASSERT(!Top::has_pending_exception()); return Heap::undefined_value(); } static MaybeObject* 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()); RUNTIME_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 { // The holder is an arguments object. Handle arguments(Handle::cast(holder)); Handle result = SetElement(arguments, index, initial_value); 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( 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(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; // 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("const", name); } } RETURN_IF_EMPTY_HANDLE(SetProperty(context_ext, name, value, mode, kNonStrictMode)); } return Heap::undefined_value(); } static MaybeObject* Runtime_InitializeVarGlobal(Arguments args) { 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 = Top::context()->global(); RUNTIME_ASSERT(args[1]->IsSmi()); StrictModeFlag strict_mode = static_cast(Smi::cast(args[1])->value()); 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 != 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[2] : 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 = Top::context()->global(); if (assign) { return global->SetProperty(*name, args[2], attributes, strict_mode); } return Heap::undefined_value(); } static MaybeObject* 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 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("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. HandleScope handle_scope; Handle global(Top::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(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; } static MaybeObject* 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 arguments(Handle::cast(holder)); SetElement(arguments, 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()); // Strict mode not needed (const disallowed in strict mode). RETURN_IF_EMPTY_HANDLE( 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( SetProperty(context_ext, name, value, attributes, kNonStrictMode)); } } return *value; } static MaybeObject* 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 MaybeObject* 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 MaybeObject* Runtime_RegExpConstructResult(Arguments args) { ASSERT(args.length() == 3); CONVERT_SMI_CHECKED(elements_count, args[0]); if (elements_count > JSArray::kMaxFastElementsLength) { return Top::ThrowIllegalOperation(); } Object* new_object; { MaybeObject* maybe_new_object = 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 = 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; reinterpret_cast(new_object)-> set_map(Top::global_context()->regexp_result_map()); } JSArray* array = JSArray::cast(new_object); array->set_properties(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; } static MaybeObject* Runtime_RegExpInitializeObject(Arguments args) { 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 = Heap::false_value(); Object* ignoreCase = args[3]; if (!ignoreCase->IsTrue()) ignoreCase = Heap::false_value(); Object* multiline = args[4]; if (!multiline->IsTrue()) multiline = 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. Since these // properties were all added as DONT_DELETE they must be present and // normal so no failures can be expected. PropertyAttributes final = static_cast(READ_ONLY | DONT_ENUM | DONT_DELETE); PropertyAttributes writable = static_cast(DONT_ENUM | DONT_DELETE); 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; } static MaybeObject* Runtime_FinishArrayPrototypeSetup(Arguments args) { HandleScope scope; 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(Heap::empty_fixed_array()); return Smi::FromInt(0); } static Handle InstallBuiltin(Handle holder, const char* name, Builtins::Name builtin_name) { Handle key = Factory::LookupAsciiSymbol(name); Handle code(Builtins::builtin(builtin_name)); Handle optimized = Factory::NewFunction(key, JS_OBJECT_TYPE, JSObject::kHeaderSize, code, false); optimized->shared()->DontAdaptArguments(); SetProperty(holder, key, optimized, NONE, kStrictMode); return optimized; } static MaybeObject* Runtime_SpecialArrayFunctions(Arguments args) { HandleScope scope; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, holder, 0); InstallBuiltin(holder, "pop", Builtins::ArrayPop); InstallBuiltin(holder, "push", Builtins::ArrayPush); InstallBuiltin(holder, "shift", Builtins::ArrayShift); InstallBuiltin(holder, "unshift", Builtins::ArrayUnshift); InstallBuiltin(holder, "slice", Builtins::ArraySlice); InstallBuiltin(holder, "splice", Builtins::ArraySplice); InstallBuiltin(holder, "concat", Builtins::ArrayConcat); return *holder; } static MaybeObject* Runtime_GetGlobalReceiver(Arguments args) { // Returns a real global receiver, not one of builtins object. Context* global_context = Top::context()->global()->global_context(); return global_context->global()->global_receiver(); } static MaybeObject* 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 MaybeObject* Runtime_FunctionGetName(Arguments args) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); return f->shared()->name(); } static MaybeObject* 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 MaybeObject* Runtime_FunctionRemovePrototype(Arguments args) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_CHECKED(JSFunction, f, args[0]); Object* obj; { MaybeObject* maybe_obj = f->RemovePrototype(); if (!maybe_obj->ToObject(&obj)) return maybe_obj; } return Heap::undefined_value(); } static MaybeObject* 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