// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include "v8.h" #include "accessors.h" #include "api.h" #include "arguments.h" #include "bootstrapper.h" #include "codegen.h" #include "compilation-cache.h" #include "compiler.h" #include "cpu.h" #include "dateparser-inl.h" #include "debug.h" #include "deoptimizer.h" #include "date.h" #include "execution.h" #include "global-handles.h" #include "isolate-inl.h" #include "jsregexp.h" #include "json-parser.h" #include "liveedit.h" #include "liveobjectlist-inl.h" #include "misc-intrinsics.h" #include "parser.h" #include "platform.h" #include "runtime-profiler.h" #include "runtime.h" #include "scopeinfo.h" #include "smart-array-pointer.h" #include "string-search.h" #include "stub-cache.h" #include "v8threads.h" #include "vm-state-inl.h" namespace v8 { namespace internal { #define RUNTIME_ASSERT(value) \ if (!(value)) return isolate->ThrowIllegalOperation(); // Cast the given object to a value of the specified type and store // it in a variable with the given name. If the object is not of the // expected type call IllegalOperation and return. #define CONVERT_ARG_CHECKED(Type, name, index) \ RUNTIME_ASSERT(args[index]->Is##Type()); \ Type* name = Type::cast(args[index]); #define CONVERT_ARG_HANDLE_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_ARG_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsBoolean()); \ bool name = args[index]->IsTrue(); // Cast the given argument to a Smi and store its value in an int variable // with the given name. If the argument is not a Smi call IllegalOperation // and return. #define CONVERT_SMI_ARG_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsSmi()); \ int name = args.smi_at(index); // Cast the given argument to a double and store it in a variable with // the given name. If the argument is not a number (as opposed to // the number not-a-number) call IllegalOperation and return. #define CONVERT_DOUBLE_ARG_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsNumber()); \ double name = args.number_at(index); // Call the specified converter on the object *comand store the result in // a variable of the specified type with the given name. If the // object is not a Number call IllegalOperation and return. #define CONVERT_NUMBER_CHECKED(type, name, Type, obj) \ RUNTIME_ASSERT(obj->IsNumber()); \ type name = NumberTo##Type(obj); // Cast the given argument to PropertyDetails and store its value in a // variable with the given name. If the argument is not a Smi call // IllegalOperation and return. #define CONVERT_PROPERTY_DETAILS_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsSmi()); \ PropertyDetails name = PropertyDetails(Smi::cast(args[index])); // Assert that the given argument has a valid value for a StrictModeFlag // and store it in a StrictModeFlag variable with the given name. #define CONVERT_STRICT_MODE_ARG_CHECKED(name, index) \ RUNTIME_ASSERT(args[index]->IsSmi()); \ RUNTIME_ASSERT(args.smi_at(index) == kStrictMode || \ args.smi_at(index) == kNonStrictMode); \ StrictModeFlag name = \ static_cast(args.smi_at(index)); // Assert that the given argument has a valid value for a LanguageMode // and store it in a LanguageMode variable with the given name. #define CONVERT_LANGUAGE_MODE_ARG(name, index) \ ASSERT(args[index]->IsSmi()); \ ASSERT(args.smi_at(index) == CLASSIC_MODE || \ args.smi_at(index) == STRICT_MODE || \ args.smi_at(index) == EXTENDED_MODE); \ LanguageMode name = \ static_cast(args.smi_at(index)); MUST_USE_RESULT static MaybeObject* DeepCopyBoilerplate(Isolate* isolate, JSObject* boilerplate) { StackLimitCheck check(isolate); if (check.HasOverflowed()) return isolate->StackOverflow(); Heap* heap = isolate->heap(); Object* result; { MaybeObject* maybe_result = heap->CopyJSObject(boilerplate); if (!maybe_result->ToObject(&result)) return maybe_result; } JSObject* copy = JSObject::cast(result); // Deep copy local properties. if (copy->HasFastProperties()) { FixedArray* properties = copy->properties(); for (int i = 0; i < properties->length(); i++) { Object* value = properties->get(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } properties->set(i, result); } } int nof = copy->map()->inobject_properties(); for (int i = 0; i < nof; i++) { Object* value = copy->InObjectPropertyAt(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } copy->InObjectPropertyAtPut(i, result); } } } else { { MaybeObject* maybe_result = heap->AllocateFixedArray(copy->NumberOfLocalProperties()); if (!maybe_result->ToObject(&result)) return maybe_result; } FixedArray* names = FixedArray::cast(result); copy->GetLocalPropertyNames(names, 0); for (int i = 0; i < names->length(); i++) { ASSERT(names->get(i)->IsString()); String* key_string = String::cast(names->get(i)); PropertyAttributes attributes = copy->GetLocalPropertyAttribute(key_string); // Only deep copy fields from the object literal expression. // In particular, don't try to copy the length attribute of // an array. if (attributes != NONE) continue; Object* value = copy->GetProperty(key_string, &attributes)->ToObjectUnchecked(); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } { MaybeObject* maybe_result = // Creating object copy for literals. No strict mode needed. copy->SetProperty(key_string, result, NONE, kNonStrictMode); if (!maybe_result->ToObject(&result)) return maybe_result; } } } } // Deep copy local elements. // Pixel elements cannot be created using an object literal. ASSERT(!copy->HasExternalArrayElements()); switch (copy->GetElementsKind()) { case FAST_SMI_ONLY_ELEMENTS: case FAST_ELEMENTS: { FixedArray* elements = FixedArray::cast(copy->elements()); if (elements->map() == heap->fixed_cow_array_map()) { isolate->counters()->cow_arrays_created_runtime()->Increment(); #ifdef DEBUG for (int i = 0; i < elements->length(); i++) { ASSERT(!elements->get(i)->IsJSObject()); } #endif } else { for (int i = 0; i < elements->length(); i++) { Object* value = elements->get(i); ASSERT(value->IsSmi() || value->IsTheHole() || (copy->GetElementsKind() == FAST_ELEMENTS)); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } elements->set(i, result); } } } break; } case DICTIONARY_ELEMENTS: { SeededNumberDictionary* element_dictionary = copy->element_dictionary(); int capacity = element_dictionary->Capacity(); for (int i = 0; i < capacity; i++) { Object* k = element_dictionary->KeyAt(i); if (element_dictionary->IsKey(k)) { Object* value = element_dictionary->ValueAt(i); if (value->IsJSObject()) { JSObject* js_object = JSObject::cast(value); { MaybeObject* maybe_result = DeepCopyBoilerplate(isolate, js_object); if (!maybe_result->ToObject(&result)) return maybe_result; } element_dictionary->ValueAtPut(i, result); } } } break; } case NON_STRICT_ARGUMENTS_ELEMENTS: UNIMPLEMENTED(); break; case EXTERNAL_PIXEL_ELEMENTS: case EXTERNAL_BYTE_ELEMENTS: case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: case EXTERNAL_SHORT_ELEMENTS: case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: case EXTERNAL_INT_ELEMENTS: case EXTERNAL_UNSIGNED_INT_ELEMENTS: case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_DOUBLE_ELEMENTS: // No contained objects, nothing to do. break; } return copy; } static Handle ComputeObjectLiteralMap( Handle context, Handle constant_properties, bool* is_result_from_cache) { Isolate* isolate = context->GetIsolate(); int properties_length = constant_properties->length(); int number_of_properties = properties_length / 2; // Check that there are only symbols and array indices among keys. int number_of_symbol_keys = 0; for (int p = 0; p != properties_length; p += 2) { Object* key = constant_properties->get(p); uint32_t element_index = 0; if (key->IsSymbol()) { number_of_symbol_keys++; } else if (key->ToArrayIndex(&element_index)) { // An index key does not require space in the property backing store. number_of_properties--; } else { // Bail out as a non-symbol non-index key makes caching impossible. // ASSERT to make sure that the if condition after the loop is false. ASSERT(number_of_symbol_keys != number_of_properties); break; } } // If we only have symbols and array indices among keys then we can // use the map cache in the global context. const int kMaxKeys = 10; if ((number_of_symbol_keys == number_of_properties) && (number_of_symbol_keys < kMaxKeys)) { // Create the fixed array with the key. Handle keys = isolate->factory()->NewFixedArray(number_of_symbol_keys); if (number_of_symbol_keys > 0) { int index = 0; for (int p = 0; p < properties_length; p += 2) { Object* key = constant_properties->get(p); if (key->IsSymbol()) { keys->set(index++, key); } } ASSERT(index == number_of_symbol_keys); } *is_result_from_cache = true; return isolate->factory()->ObjectLiteralMapFromCache(context, keys); } *is_result_from_cache = false; return isolate->factory()->CopyMap( Handle(context->object_function()->initial_map()), number_of_properties); } static Handle CreateLiteralBoilerplate( Isolate* isolate, Handle literals, Handle constant_properties); static Handle CreateObjectLiteralBoilerplate( Isolate* isolate, Handle literals, Handle constant_properties, bool should_have_fast_elements, bool has_function_literal) { // Get the global context from the literals array. This is the // context in which the function was created and we use the object // function from this context to create the object literal. We do // not use the object function from the current global context // because this might be the object function from another context // which we should not have access to. Handle context = Handle(JSFunction::GlobalContextFromLiterals(*literals)); // In case we have function literals, we want the object to be in // slow properties mode for now. We don't go in the map cache because // maps with constant functions can't be shared if the functions are // not the same (which is the common case). bool is_result_from_cache = false; Handle map = has_function_literal ? Handle(context->object_function()->initial_map()) : ComputeObjectLiteralMap(context, constant_properties, &is_result_from_cache); Handle boilerplate = isolate->factory()->NewJSObjectFromMap(map); // Normalize the elements of the boilerplate to save space if needed. if (!should_have_fast_elements) JSObject::NormalizeElements(boilerplate); // Add the constant properties to the boilerplate. int length = constant_properties->length(); bool should_transform = !is_result_from_cache && boilerplate->HasFastProperties(); if (should_transform || has_function_literal) { // Normalize the properties of object to avoid n^2 behavior // when extending the object multiple properties. Indicate the number of // properties to be added. JSObject::NormalizeProperties( boilerplate, KEEP_INOBJECT_PROPERTIES, length / 2); } for (int index = 0; index < length; index +=2) { Handle key(constant_properties->get(index+0), isolate); Handle value(constant_properties->get(index+1), isolate); if (value->IsFixedArray()) { // The value contains the constant_properties of a // simple object or array literal. Handle array = Handle::cast(value); value = CreateLiteralBoilerplate(isolate, literals, array); if (value.is_null()) return value; } Handle result; uint32_t element_index = 0; if (key->IsSymbol()) { if (Handle::cast(key)->AsArrayIndex(&element_index)) { // Array index as string (uint32). result = JSObject::SetOwnElement( boilerplate, element_index, value, kNonStrictMode); } else { Handle name(String::cast(*key)); ASSERT(!name->AsArrayIndex(&element_index)); result = JSObject::SetLocalPropertyIgnoreAttributes( boilerplate, name, value, NONE); } } else if (key->ToArrayIndex(&element_index)) { // Array index (uint32). result = JSObject::SetOwnElement( boilerplate, element_index, value, kNonStrictMode); } else { // Non-uint32 number. ASSERT(key->IsNumber()); double num = key->Number(); char arr[100]; Vector buffer(arr, ARRAY_SIZE(arr)); const char* str = DoubleToCString(num, buffer); Handle name = isolate->factory()->NewStringFromAscii(CStrVector(str)); result = JSObject::SetLocalPropertyIgnoreAttributes( boilerplate, name, value, NONE); } // If setting the property on the boilerplate throws an // exception, the exception is converted to an empty handle in // the handle based operations. In that case, we need to // convert back to an exception. if (result.is_null()) return result; } // Transform to fast properties if necessary. For object literals with // containing function literals we defer this operation until after all // computed properties have been assigned so that we can generate // constant function properties. if (should_transform && !has_function_literal) { JSObject::TransformToFastProperties( boilerplate, boilerplate->map()->unused_property_fields()); } return boilerplate; } MaybeObject* TransitionElements(Handle object, ElementsKind to_kind, Isolate* isolate) { HandleScope scope(isolate); if (!object->IsJSObject()) return isolate->ThrowIllegalOperation(); ElementsKind from_kind = Handle::cast(object)->map()->elements_kind(); if (Map::IsValidElementsTransition(from_kind, to_kind)) { Handle result = JSObject::TransitionElementsKind( Handle::cast(object), to_kind); if (result.is_null()) return isolate->ThrowIllegalOperation(); return *result; } return isolate->ThrowIllegalOperation(); } static const int kSmiOnlyLiteralMinimumLength = 1024; Handle Runtime::CreateArrayLiteralBoilerplate( Isolate* isolate, Handle literals, Handle elements) { // Create the JSArray. Handle constructor( JSFunction::GlobalContextFromLiterals(*literals)->array_function()); Handle object = Handle::cast(isolate->factory()->NewJSObject(constructor)); ElementsKind constant_elements_kind = static_cast(Smi::cast(elements->get(0))->value()); Handle constant_elements_values( FixedArrayBase::cast(elements->get(1))); Context* global_context = isolate->context()->global_context(); if (constant_elements_kind == FAST_SMI_ONLY_ELEMENTS) { object->set_map(Map::cast(global_context->smi_js_array_map())); } else if (constant_elements_kind == FAST_DOUBLE_ELEMENTS) { object->set_map(Map::cast(global_context->double_js_array_map())); } else { object->set_map(Map::cast(global_context->object_js_array_map())); } Handle copied_elements_values; if (constant_elements_kind == FAST_DOUBLE_ELEMENTS) { ASSERT(FLAG_smi_only_arrays); copied_elements_values = isolate->factory()->CopyFixedDoubleArray( Handle::cast(constant_elements_values)); } else { ASSERT(constant_elements_kind == FAST_SMI_ONLY_ELEMENTS || constant_elements_kind == FAST_ELEMENTS); const bool is_cow = (constant_elements_values->map() == isolate->heap()->fixed_cow_array_map()); if (is_cow) { copied_elements_values = constant_elements_values; #if DEBUG Handle fixed_array_values = Handle::cast(copied_elements_values); for (int i = 0; i < fixed_array_values->length(); i++) { ASSERT(!fixed_array_values->get(i)->IsFixedArray()); } #endif } else { Handle fixed_array_values = Handle::cast(constant_elements_values); Handle fixed_array_values_copy = isolate->factory()->CopyFixedArray(fixed_array_values); copied_elements_values = fixed_array_values_copy; for (int i = 0; i < fixed_array_values->length(); i++) { Object* current = fixed_array_values->get(i); if (current->IsFixedArray()) { // The value contains the constant_properties of a // simple object or array literal. Handle fa(FixedArray::cast(fixed_array_values->get(i))); Handle result = CreateLiteralBoilerplate(isolate, literals, fa); if (result.is_null()) return result; fixed_array_values_copy->set(i, *result); } } } } object->set_elements(*copied_elements_values); object->set_length(Smi::FromInt(copied_elements_values->length())); // Ensure that the boilerplate object has FAST_ELEMENTS, unless the flag is // on or the object is larger than the threshold. if (!FLAG_smi_only_arrays && constant_elements_values->length() < kSmiOnlyLiteralMinimumLength) { if (object->GetElementsKind() != FAST_ELEMENTS) { CHECK(!TransitionElements(object, FAST_ELEMENTS, isolate)->IsFailure()); } } return object; } static Handle CreateLiteralBoilerplate( Isolate* isolate, Handle literals, Handle array) { Handle elements = CompileTimeValue::GetElements(array); const bool kHasNoFunctionLiteral = false; switch (CompileTimeValue::GetType(array)) { case CompileTimeValue::OBJECT_LITERAL_FAST_ELEMENTS: return CreateObjectLiteralBoilerplate(isolate, literals, elements, true, kHasNoFunctionLiteral); case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS: return CreateObjectLiteralBoilerplate(isolate, literals, elements, false, kHasNoFunctionLiteral); case CompileTimeValue::ARRAY_LITERAL: return Runtime::CreateArrayLiteralBoilerplate( isolate, literals, elements); default: UNREACHABLE(); return Handle::null(); } } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateObjectLiteral) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_ARG_CHECKED(flags, 3); bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0; bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0; // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = CreateObjectLiteralBoilerplate(isolate, literals, constant_properties, should_have_fast_elements, has_function_literal); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return DeepCopyBoilerplate(isolate, JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateObjectLiteralShallow) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, constant_properties, 2); CONVERT_SMI_ARG_CHECKED(flags, 3); bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0; bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0; // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = CreateObjectLiteralBoilerplate(isolate, literals, constant_properties, should_have_fast_elements, has_function_literal); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return isolate->heap()->CopyJSObject(JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateArrayLiteral) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { boilerplate = Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } return DeepCopyBoilerplate(isolate, JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateArrayLiteralShallow) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); CONVERT_SMI_ARG_CHECKED(literals_index, 1); CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2); // Check if boilerplate exists. If not, create it first. Handle boilerplate(literals->get(literals_index), isolate); if (*boilerplate == isolate->heap()->undefined_value()) { ASSERT(*elements != isolate->heap()->empty_fixed_array()); boilerplate = Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements); if (boilerplate.is_null()) return Failure::Exception(); // Update the functions literal and return the boilerplate. literals->set(literals_index, *boilerplate); } if (JSObject::cast(*boilerplate)->elements()->map() == isolate->heap()->fixed_cow_array_map()) { isolate->counters()->cow_arrays_created_runtime()->Increment(); } return isolate->heap()->CopyJSObject(JSObject::cast(*boilerplate)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateJSProxy) { ASSERT(args.length() == 2); Object* handler = args[0]; Object* prototype = args[1]; Object* used_prototype = prototype->IsJSReceiver() ? prototype : isolate->heap()->null_value(); return isolate->heap()->AllocateJSProxy(handler, used_prototype); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateJSFunctionProxy) { ASSERT(args.length() == 4); Object* handler = args[0]; Object* call_trap = args[1]; Object* construct_trap = args[2]; Object* prototype = args[3]; Object* used_prototype = prototype->IsJSReceiver() ? prototype : isolate->heap()->null_value(); return isolate->heap()->AllocateJSFunctionProxy( handler, call_trap, construct_trap, used_prototype); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsJSProxy) { ASSERT(args.length() == 1); Object* obj = args[0]; return isolate->heap()->ToBoolean(obj->IsJSProxy()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsJSFunctionProxy) { ASSERT(args.length() == 1); Object* obj = args[0]; return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetHandler) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSProxy, proxy, 0); return proxy->handler(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetCallTrap) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0); return proxy->call_trap(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetConstructTrap) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0); return proxy->construct_trap(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_Fix) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSProxy, proxy, 0); proxy->Fix(); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0); Handle table = isolate->factory()->NewObjectHashSet(0); holder->set_table(*table); return *holder; } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetAdd) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0); Handle key(args[1]); Handle table(ObjectHashSet::cast(holder->table())); table = ObjectHashSetAdd(table, key); holder->set_table(*table); return isolate->heap()->undefined_symbol(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetHas) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0); Handle key(args[1]); Handle table(ObjectHashSet::cast(holder->table())); return isolate->heap()->ToBoolean(table->Contains(*key)); } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetDelete) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0); Handle key(args[1]); Handle table(ObjectHashSet::cast(holder->table())); table = ObjectHashSetRemove(table, key); holder->set_table(*table); return isolate->heap()->undefined_symbol(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); Handle table = isolate->factory()->NewObjectHashTable(0); holder->set_table(*table); return *holder; } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapGet) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); Handle key(args[1]); return ObjectHashTable::cast(holder->table())->Lookup(*key); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapSet) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); Handle key(args[1]); Handle value(args[2]); Handle table(ObjectHashTable::cast(holder->table())); Handle new_table = PutIntoObjectHashTable(table, key, value); holder->set_table(*new_table); return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakMapInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSWeakMap, weakmap, 0); ASSERT(weakmap->map()->inobject_properties() == 0); Handle table = isolate->factory()->NewObjectHashTable(0); weakmap->set_table(*table); weakmap->set_next(Smi::FromInt(0)); return *weakmap; } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakMapGet) { NoHandleAllocation ha; ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSWeakMap, weakmap, 0); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, key, 1); return ObjectHashTable::cast(weakmap->table())->Lookup(*key); } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakMapSet) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSWeakMap, weakmap, 0); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, key, 1); Handle value(args[2]); Handle table(ObjectHashTable::cast(weakmap->table())); Handle new_table = PutIntoObjectHashTable(table, key, value); weakmap->set_table(*new_table); return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_ClassOf) { NoHandleAllocation ha; ASSERT(args.length() == 1); Object* obj = args[0]; if (!obj->IsJSObject()) return isolate->heap()->null_value(); return JSObject::cast(obj)->class_name(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetPrototype) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, input_obj, 0); Object* obj = input_obj; // We don't expect access checks to be needed on JSProxy objects. ASSERT(!obj->IsAccessCheckNeeded() || obj->IsJSObject()); do { if (obj->IsAccessCheckNeeded() && !isolate->MayNamedAccess(JSObject::cast(obj), isolate->heap()->Proto_symbol(), v8::ACCESS_GET)) { isolate->ReportFailedAccessCheck(JSObject::cast(obj), v8::ACCESS_GET); return isolate->heap()->undefined_value(); } obj = obj->GetPrototype(); } while (obj->IsJSObject() && JSObject::cast(obj)->map()->is_hidden_prototype()); return obj; } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsInPrototypeChain) { NoHandleAllocation ha; ASSERT(args.length() == 2); // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8). Object* O = args[0]; Object* V = args[1]; while (true) { Object* prototype = V->GetPrototype(); if (prototype->IsNull()) return isolate->heap()->false_value(); if (O == prototype) return isolate->heap()->true_value(); V = prototype; } } // Recursively traverses hidden prototypes if property is not found static void GetOwnPropertyImplementation(JSObject* obj, String* name, LookupResult* result) { obj->LocalLookupRealNamedProperty(name, result); if (!result->IsProperty()) { Object* proto = obj->GetPrototype(); if (proto->IsJSObject() && JSObject::cast(proto)->map()->is_hidden_prototype()) GetOwnPropertyImplementation(JSObject::cast(proto), name, result); } } static bool CheckAccessException(LookupResult* result, v8::AccessType access_type) { if (result->type() == CALLBACKS) { Object* callback = result->GetCallbackObject(); if (callback->IsAccessorInfo()) { AccessorInfo* info = AccessorInfo::cast(callback); bool can_access = (access_type == v8::ACCESS_HAS && (info->all_can_read() || info->all_can_write())) || (access_type == v8::ACCESS_GET && info->all_can_read()) || (access_type == v8::ACCESS_SET && info->all_can_write()); return can_access; } } return false; } static bool CheckAccess(JSObject* obj, String* name, LookupResult* result, v8::AccessType access_type) { ASSERT(result->IsProperty()); JSObject* holder = result->holder(); JSObject* current = obj; Isolate* isolate = obj->GetIsolate(); while (true) { if (current->IsAccessCheckNeeded() && !isolate->MayNamedAccess(current, name, access_type)) { // Access check callback denied the access, but some properties // can have a special permissions which override callbacks descision // (currently see v8::AccessControl). break; } if (current == holder) { return true; } current = JSObject::cast(current->GetPrototype()); } // API callbacks can have per callback access exceptions. switch (result->type()) { case CALLBACKS: { if (CheckAccessException(result, access_type)) { return true; } break; } case INTERCEPTOR: { // If the object has an interceptor, try real named properties. // Overwrite the result to fetch the correct property later. holder->LookupRealNamedProperty(name, result); if (result->IsProperty()) { if (CheckAccessException(result, access_type)) { return true; } } break; } default: break; } isolate->ReportFailedAccessCheck(current, access_type); return false; } // TODO(1095): we should traverse hidden prototype hierachy as well. static bool CheckElementAccess(JSObject* obj, uint32_t index, v8::AccessType access_type) { if (obj->IsAccessCheckNeeded() && !obj->GetIsolate()->MayIndexedAccess(obj, index, access_type)) { return false; } return true; } // Enumerator used as indices into the array returned from GetOwnProperty enum PropertyDescriptorIndices { IS_ACCESSOR_INDEX, VALUE_INDEX, GETTER_INDEX, SETTER_INDEX, WRITABLE_INDEX, ENUMERABLE_INDEX, CONFIGURABLE_INDEX, DESCRIPTOR_SIZE }; static MaybeObject* GetOwnProperty(Isolate* isolate, Handle obj, Handle name) { Heap* heap = isolate->heap(); Handle elms = isolate->factory()->NewFixedArray(DESCRIPTOR_SIZE); Handle desc = isolate->factory()->NewJSArrayWithElements(elms); LookupResult result(isolate); // 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->true_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 = Object::GetElement(obj, index); RETURN_IF_EMPTY_HANDLE(isolate, value); elms->set(VALUE_INDEX, *value); elms->set(WRITABLE_INDEX, heap->true_value()); elms->set(ENUMERABLE_INDEX, heap->true_value()); elms->set(CONFIGURABLE_INDEX, heap->true_value()); return *desc; } case JSObject::DICTIONARY_ELEMENT: { Handle holder = obj; if (obj->IsJSGlobalProxy()) { Object* proto = obj->GetPrototype(); if (proto->IsNull()) return heap->undefined_value(); ASSERT(proto->IsJSGlobalObject()); holder = Handle(JSObject::cast(proto)); } FixedArray* elements = FixedArray::cast(holder->elements()); SeededNumberDictionary* dictionary = NULL; if (elements->map() == heap->non_strict_arguments_elements_map()) { dictionary = SeededNumberDictionary::cast(elements->get(1)); } else { dictionary = SeededNumberDictionary::cast(elements); } int entry = dictionary->FindEntry(index); ASSERT(entry != SeededNumberDictionary::kNotFound); PropertyDetails details = dictionary->DetailsAt(entry); switch (details.type()) { case CALLBACKS: { // This is an accessor property with getter and/or setter. AccessorPair* accessors = AccessorPair::cast(dictionary->ValueAt(entry)); elms->set(IS_ACCESSOR_INDEX, heap->true_value()); if (CheckElementAccess(*obj, index, v8::ACCESS_GET)) { elms->set(GETTER_INDEX, accessors->GetComponent(ACCESSOR_GETTER)); } if (CheckElementAccess(*obj, index, v8::ACCESS_SET)) { elms->set(SETTER_INDEX, accessors->GetComponent(ACCESSOR_SETTER)); } break; } case NORMAL: { // This is a data property. elms->set(IS_ACCESSOR_INDEX, heap->false_value()); Handle value = Object::GetElement(obj, index); ASSERT(!value.is_null()); elms->set(VALUE_INDEX, *value); elms->set(WRITABLE_INDEX, heap->ToBoolean(!details.IsReadOnly())); break; } default: UNREACHABLE(); break; } elms->set(ENUMERABLE_INDEX, heap->ToBoolean(!details.IsDontEnum())); elms->set(CONFIGURABLE_INDEX, heap->ToBoolean(!details.IsDontDelete())); return *desc; } } } // Use recursive implementation to also traverse hidden prototypes GetOwnPropertyImplementation(*obj, *name, &result); if (!result.IsProperty()) { return heap->undefined_value(); } if (!CheckAccess(*obj, *name, &result, v8::ACCESS_HAS)) { return heap->false_value(); } elms->set(ENUMERABLE_INDEX, heap->ToBoolean(!result.IsDontEnum())); elms->set(CONFIGURABLE_INDEX, heap->ToBoolean(!result.IsDontDelete())); bool is_js_accessor = (result.type() == CALLBACKS) && (result.GetCallbackObject()->IsAccessorPair()); if (is_js_accessor) { // __defineGetter__/__defineSetter__ callback. elms->set(IS_ACCESSOR_INDEX, heap->true_value()); AccessorPair* accessors = AccessorPair::cast(result.GetCallbackObject()); if (CheckAccess(*obj, *name, &result, v8::ACCESS_GET)) { elms->set(GETTER_INDEX, accessors->GetComponent(ACCESSOR_GETTER)); } if (CheckAccess(*obj, *name, &result, v8::ACCESS_SET)) { elms->set(SETTER_INDEX, accessors->GetComponent(ACCESSOR_SETTER)); } } 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; } // Returns an array with the property description: // if args[1] is not a property on args[0] // returns undefined // if args[1] is a data property on args[0] // [false, value, Writeable, Enumerable, Configurable] // if args[1] is an accessor on args[0] // [true, GetFunction, SetFunction, Enumerable, Configurable] RUNTIME_FUNCTION(MaybeObject*, Runtime_GetOwnProperty) { ASSERT(args.length() == 2); HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(String, name, 1); return GetOwnProperty(isolate, obj, name); } RUNTIME_FUNCTION(MaybeObject*, Runtime_PreventExtensions) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, obj, 0); return obj->PreventExtensions(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsExtensible) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSObject, obj, 0); if (obj->IsJSGlobalProxy()) { Object* proto = obj->GetPrototype(); if (proto->IsNull()) return isolate->heap()->false_value(); ASSERT(proto->IsJSGlobalObject()); obj = JSObject::cast(proto); } return isolate->heap()->ToBoolean(obj->map()->is_extensible()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpCompile) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSRegExp, re, 0); CONVERT_ARG_HANDLE_CHECKED(String, pattern, 1); CONVERT_ARG_HANDLE_CHECKED(String, flags, 2); Handle result = RegExpImpl::Compile(re, pattern, flags); if (result.is_null()) return Failure::Exception(); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateApiFunction) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(FunctionTemplateInfo, data, 0); return *isolate->factory()->CreateApiFunction(data); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsTemplate) { ASSERT(args.length() == 1); Object* arg = args[0]; bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo(); return isolate->heap()->ToBoolean(result); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetTemplateField) { ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(HeapObject, templ, 0); CONVERT_SMI_ARG_CHECKED(index, 1) int offset = index * kPointerSize + HeapObject::kHeaderSize; InstanceType type = templ->map()->instance_type(); RUNTIME_ASSERT(type == FUNCTION_TEMPLATE_INFO_TYPE || type == OBJECT_TEMPLATE_INFO_TYPE); RUNTIME_ASSERT(offset > 0); if (type == FUNCTION_TEMPLATE_INFO_TYPE) { RUNTIME_ASSERT(offset < FunctionTemplateInfo::kSize); } else { RUNTIME_ASSERT(offset < ObjectTemplateInfo::kSize); } return *HeapObject::RawField(templ, offset); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DisableAccessChecks) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(HeapObject, object, 0); Map* old_map = object->map(); bool needs_access_checks = old_map->is_access_check_needed(); if (needs_access_checks) { // Copy map so it won't interfere constructor's initial map. Object* new_map; { MaybeObject* maybe_new_map = old_map->CopyDropTransitions(); if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map; } Map::cast(new_map)->set_is_access_check_needed(false); object->set_map(Map::cast(new_map)); } return isolate->heap()->ToBoolean(needs_access_checks); } RUNTIME_FUNCTION(MaybeObject*, Runtime_EnableAccessChecks) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(HeapObject, object, 0); Map* old_map = object->map(); if (!old_map->is_access_check_needed()) { // Copy map so it won't interfere constructor's initial map. Object* new_map; { MaybeObject* maybe_new_map = old_map->CopyDropTransitions(); if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map; } Map::cast(new_map)->set_is_access_check_needed(true); object->set_map(Map::cast(new_map)); } return isolate->heap()->undefined_value(); } static Failure* ThrowRedeclarationError(Isolate* isolate, const char* type, Handle name) { HandleScope scope(isolate); Handle type_handle = isolate->factory()->NewStringFromAscii(CStrVector(type)); Handle args[2] = { type_handle, name }; Handle error = isolate->factory()->NewTypeError("redeclaration", HandleVector(args, 2)); return isolate->Throw(*error); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DeclareGlobals) { ASSERT(args.length() == 3); HandleScope scope(isolate); Handle global = Handle( isolate->context()->global()); Handle context = args.at(0); CONVERT_ARG_HANDLE_CHECKED(FixedArray, pairs, 1); CONVERT_SMI_ARG_CHECKED(flags, 2); // Traverse the name/value pairs and set the properties. int length = pairs->length(); for (int i = 0; i < length; i += 2) { HandleScope scope(isolate); Handle name(String::cast(pairs->get(i))); Handle value(pairs->get(i + 1), isolate); // We have to declare a global const property. To capture we only // assign to it when evaluating the assignment for "const x = // " the initial value is the hole. bool is_var = value->IsUndefined(); bool is_const = value->IsTheHole(); bool is_function = value->IsSharedFunctionInfo(); bool is_module = value->IsJSModule(); ASSERT(is_var + is_const + is_function + is_module == 1); if (is_var || is_const) { // Lookup the property in the global object, and don't set the // value of the variable if the property is already there. // Do the lookup locally only, see ES5 errata. LookupResult lookup(isolate); if (FLAG_es52_globals) global->LocalLookup(*name, &lookup); else global->Lookup(*name, &lookup); if (lookup.IsProperty()) { // We found an existing property. Unless it was an interceptor // that claims the property is absent, skip this declaration. if (lookup.type() != INTERCEPTOR) continue; PropertyAttributes attributes = global->GetPropertyAttribute(*name); if (attributes != ABSENT) continue; // Fall-through and introduce the absent property by using // SetProperty. } } else if (is_function) { // Copy the function and update its context. Use it as value. Handle shared = Handle::cast(value); Handle function = isolate->factory()->NewFunctionFromSharedFunctionInfo( shared, context, TENURED); value = function; } LookupResult lookup(isolate); global->LocalLookup(*name, &lookup); // Compute the property attributes. According to ECMA-262, // the property must be non-configurable except in eval. int attr = NONE; bool is_eval = DeclareGlobalsEvalFlag::decode(flags); if (!is_eval || is_module) { attr |= DONT_DELETE; } bool is_native = DeclareGlobalsNativeFlag::decode(flags); if (is_const || is_module || (is_native && is_function)) { attr |= READ_ONLY; } LanguageMode language_mode = DeclareGlobalsLanguageMode::decode(flags); if (!lookup.IsProperty() || is_function || is_module) { // If the local property exists, check that we can reconfigure it // as required for function declarations. if (lookup.IsProperty() && lookup.IsDontDelete()) { if (lookup.IsReadOnly() || lookup.IsDontEnum() || lookup.type() == CALLBACKS) { return ThrowRedeclarationError( isolate, is_function ? "function" : "module", name); } // If the existing property is not configurable, keep its attributes. attr = lookup.GetAttributes(); } // Define or redefine own property. RETURN_IF_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes( global, name, value, static_cast(attr))); } else { // Do a [[Put]] on the existing (own) property. RETURN_IF_EMPTY_HANDLE(isolate, JSObject::SetProperty( global, name, value, static_cast(attr), language_mode == CLASSIC_MODE ? kNonStrictMode : kStrictMode)); } } ASSERT(!isolate->has_pending_exception()); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DeclareContextSlot) { HandleScope scope(isolate); ASSERT(args.length() == 4); // Declarations are always made in a function or global context. In the // case of eval code, the context passed is the context of the caller, // which may be some nested context and not the declaration context. RUNTIME_ASSERT(args[0]->IsContext()); Handle context(Context::cast(args[0])->declaration_context()); Handle name(String::cast(args[1])); PropertyAttributes mode = static_cast(args.smi_at(2)); RUNTIME_ASSERT(mode == READ_ONLY || mode == NONE); Handle initial_value(args[3], isolate); int index; PropertyAttributes attributes; ContextLookupFlags flags = DONT_FOLLOW_CHAINS; BindingFlags binding_flags; Handle holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); if (attributes != ABSENT) { // The name was declared before; check for conflicting re-declarations. // Note: this is actually inconsistent with what happens for globals (where // we silently ignore such declarations). if (((attributes & READ_ONLY) != 0) || (mode == READ_ONLY)) { // Functions are not read-only. ASSERT(mode != READ_ONLY || initial_value->IsTheHole()); const char* type = ((attributes & READ_ONLY) != 0) ? "const" : "var"; return ThrowRedeclarationError(isolate, type, name); } // Initialize it if necessary. if (*initial_value != NULL) { if (index >= 0) { ASSERT(holder.is_identical_to(context)); if (((attributes & READ_ONLY) == 0) || context->get(index)->IsTheHole()) { context->set(index, *initial_value); } } else { // Slow case: The property is in the context extension object of a // function context or the global object of a global context. Handle object = Handle::cast(holder); RETURN_IF_EMPTY_HANDLE( isolate, JSReceiver::SetProperty(object, 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 as a // property of the the global object. Handle object; if (context->has_extension()) { object = Handle(JSObject::cast(context->extension())); } else { // Context extension objects are allocated lazily. ASSERT(context->IsFunctionContext()); object = isolate->factory()->NewJSObject( isolate->context_extension_function()); context->set_extension(*object); } ASSERT(*object != 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(!object->HasLocalProperty(*name)); Handle value(isolate->heap()->undefined_value(), isolate); if (*initial_value != NULL) value = initial_value; // Declaring a const context slot is a conflicting declaration if // there is a callback with that name in a prototype. It is // allowed to introduce const variables in // JSContextExtensionObjects. They are treated specially in // SetProperty and no setters are invoked for those since they are // not real JSObjects. if (initial_value->IsTheHole() && !object->IsJSContextExtensionObject()) { LookupResult lookup(isolate); object->Lookup(*name, &lookup); if (lookup.IsFound() && (lookup.type() == CALLBACKS)) { return ThrowRedeclarationError(isolate, "const", name); } } if (object->IsJSGlobalObject()) { // Define own property on the global object. RETURN_IF_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes(object, name, value, mode)); } else { RETURN_IF_EMPTY_HANDLE(isolate, JSReceiver::SetProperty(object, name, value, mode, kNonStrictMode)); } } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeVarGlobal) { NoHandleAllocation nha; // args[0] == name // args[1] == language_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_HANDLE_CHECKED(String, name, 0); GlobalObject* global = isolate->context()->global(); RUNTIME_ASSERT(args[1]->IsSmi()); CONVERT_LANGUAGE_MODE_ARG(language_mode, 1); StrictModeFlag strict_mode_flag = (language_mode == CLASSIC_MODE) ? kNonStrictMode : kStrictMode; // 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. Object* object = global; LookupResult lookup(isolate); while (object->IsJSObject() && JSObject::cast(object)->map()->is_hidden_prototype()) { JSObject* raw_holder = JSObject::cast(object); raw_holder->LocalLookup(*name, &lookup); if (lookup.IsFound() && lookup.type() == INTERCEPTOR) { HandleScope handle_scope(isolate); Handle holder(raw_holder); PropertyAttributes intercepted = holder->GetPropertyAttribute(*name); // Update the raw pointer in case it's changed due to GC. raw_holder = *holder; if (intercepted != ABSENT && (intercepted & READ_ONLY) == 0) { // Found an interceptor that's not read only. if (assign) { return raw_holder->SetProperty( &lookup, *name, args[2], attributes, strict_mode_flag); } else { return isolate->heap()->undefined_value(); } } } object = raw_holder->GetPrototype(); } // Reload global in case the loop above performed a GC. global = isolate->context()->global(); if (assign) { return global->SetProperty(*name, args[2], attributes, strict_mode_flag); } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeConstGlobal) { // All constants are declared with an initial value. The name // of the constant is the first argument and the initial value // is the second. RUNTIME_ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(String, name, 0); Handle value = args.at(1); // Get the current global object from top. GlobalObject* global = isolate->context()->global(); // According to ECMA-262, section 12.2, page 62, the property must // not be deletable. Since it's a const, it must be READ_ONLY too. PropertyAttributes attributes = static_cast(DONT_DELETE | READ_ONLY); // Lookup the property locally in the global object. If it isn't // there, we add the property and take special precautions to always // add it as a local property even in case of callbacks in the // prototype chain (this rules out using SetProperty). // We use SetLocalPropertyIgnoreAttributes instead LookupResult lookup(isolate); global->LocalLookup(*name, &lookup); if (!lookup.IsProperty()) { return global->SetLocalPropertyIgnoreAttributes(*name, *value, attributes); } if (!lookup.IsReadOnly()) { // Restore global object from context (in case of GC) and continue // with setting the value. HandleScope handle_scope(isolate); Handle global(isolate->context()->global()); // BUG 1213575: Handle the case where we have to set a read-only // property through an interceptor and only do it if it's // uninitialized, e.g. the hole. Nirk... // Passing non-strict mode because the property is writable. RETURN_IF_EMPTY_HANDLE( isolate, JSReceiver::SetProperty(global, name, value, attributes, kNonStrictMode)); return *value; } // Set the value, but only if 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 is disallowed in strict mode). PropertyType type = lookup.type(); if (type == FIELD) { FixedArray* properties = global->properties(); int index = lookup.GetFieldIndex(); if (properties->get(index)->IsTheHole() || !lookup.IsReadOnly()) { properties->set(index, *value); } } else if (type == NORMAL) { if (global->GetNormalizedProperty(&lookup)->IsTheHole() || !lookup.IsReadOnly()) { global->SetNormalizedProperty(&lookup, *value); } } else { // Ignore re-initialization of constants that have already been // assigned a function value. ASSERT(lookup.IsReadOnly() && type == CONSTANT_FUNCTION); } // Use the set value as the result of the operation. return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeConstContextSlot) { HandleScope scope(isolate); ASSERT(args.length() == 3); Handle value(args[0], isolate); ASSERT(!value->IsTheHole()); // Initializations are always done in a function or global context. RUNTIME_ASSERT(args[1]->IsContext()); Handle context(Context::cast(args[1])->declaration_context()); Handle name(String::cast(args[2])); int index; PropertyAttributes attributes; ContextLookupFlags flags = FOLLOW_CHAINS; BindingFlags binding_flags; Handle holder = context->Lookup(name, flags, &index, &attributes, &binding_flags); if (index >= 0) { ASSERT(holder->IsContext()); // Property was found in a context. Perform the assignment if we // found some non-constant or an uninitialized constant. Handle context = Handle::cast(holder); if ((attributes & READ_ONLY) == 0 || context->get(index)->IsTheHole()) { context->set(index, *value); } return *value; } // The property could not be found, we introduce it as a property of the // global object. if (attributes == ABSENT) { Handle global = Handle( isolate->context()->global()); // Strict mode not needed (const disallowed in strict mode). RETURN_IF_EMPTY_HANDLE( isolate, JSReceiver::SetProperty(global, name, value, NONE, kNonStrictMode)); return *value; } // The property was present in some function's context extension object, // as a property on the subject of a with, or as a property of the global // object. // // In most situations, eval-introduced consts should still be present in // the context extension object. However, because declaration and // initialization are separate, the property might have been deleted // before we reach the initialization point. // // Example: // // function f() { eval("delete x; const x;"); } // // In that case, the initialization behaves like a normal assignment. Handle object = Handle::cast(holder); if (*object == 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(isolate); object->LocalLookupRealNamedProperty(*name, &lookup); ASSERT(lookup.IsFound()); // the property was declared ASSERT(lookup.IsReadOnly()); // and it was declared as read-only PropertyType type = lookup.type(); if (type == FIELD) { FixedArray* properties = object->properties(); int index = lookup.GetFieldIndex(); if (properties->get(index)->IsTheHole()) { properties->set(index, *value); } } else if (type == NORMAL) { if (object->GetNormalizedProperty(&lookup)->IsTheHole()) { object->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 on some other object. Set it if it is not a // read-only property. if ((attributes & READ_ONLY) == 0) { // Strict mode not needed (const disallowed in strict mode). RETURN_IF_EMPTY_HANDLE( isolate, JSReceiver::SetProperty(object, name, value, attributes, kNonStrictMode)); } } return *value; } RUNTIME_FUNCTION(MaybeObject*, Runtime_OptimizeObjectForAddingMultipleProperties) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_SMI_ARG_CHECKED(properties, 1); if (object->HasFastProperties()) { JSObject::NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties); } return *object; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpExec) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0); CONVERT_ARG_HANDLE_CHECKED(String, subject, 1); // Due to the way the JS calls are constructed this must be less than the // length of a string, i.e. it is always a Smi. We check anyway for security. CONVERT_SMI_ARG_CHECKED(index, 2); CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 3); RUNTIME_ASSERT(last_match_info->HasFastElements()); RUNTIME_ASSERT(index >= 0); RUNTIME_ASSERT(index <= subject->length()); isolate->counters()->regexp_entry_runtime()->Increment(); Handle result = RegExpImpl::Exec(regexp, subject, index, last_match_info); if (result.is_null()) return Failure::Exception(); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpConstructResult) { ASSERT(args.length() == 3); CONVERT_SMI_ARG_CHECKED(elements_count, 0); if (elements_count < 0 || elements_count > FixedArray::kMaxLength || !Smi::IsValid(elements_count)) { return isolate->ThrowIllegalOperation(); } Object* new_object; { MaybeObject* maybe_new_object = isolate->heap()->AllocateFixedArrayWithHoles(elements_count); if (!maybe_new_object->ToObject(&new_object)) return maybe_new_object; } FixedArray* elements = FixedArray::cast(new_object); { MaybeObject* maybe_new_object = isolate->heap()->AllocateRaw( JSRegExpResult::kSize, NEW_SPACE, OLD_POINTER_SPACE); if (!maybe_new_object->ToObject(&new_object)) return maybe_new_object; } { AssertNoAllocation no_gc; HandleScope scope(isolate); reinterpret_cast(new_object)-> set_map(isolate->global_context()->regexp_result_map()); } JSArray* array = JSArray::cast(new_object); array->set_properties(isolate->heap()->empty_fixed_array()); array->set_elements(elements); array->set_length(Smi::FromInt(elements_count)); // Write in-object properties after the length of the array. array->InObjectPropertyAtPut(JSRegExpResult::kIndexIndex, args[1]); array->InObjectPropertyAtPut(JSRegExpResult::kInputIndex, args[2]); return array; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpInitializeObject) { AssertNoAllocation no_alloc; ASSERT(args.length() == 5); CONVERT_ARG_CHECKED(JSRegExp, regexp, 0); CONVERT_ARG_CHECKED(String, source, 1); // If source is the empty string we set it to "(?:)" instead as // suggested by ECMA-262, 5th, section 15.10.4.1. if (source->length() == 0) source = isolate->heap()->query_colon_symbol(); Object* global = args[2]; if (!global->IsTrue()) global = isolate->heap()->false_value(); Object* ignoreCase = args[3]; if (!ignoreCase->IsTrue()) ignoreCase = isolate->heap()->false_value(); Object* multiline = args[4]; if (!multiline->IsTrue()) multiline = isolate->heap()->false_value(); Map* map = regexp->map(); Object* constructor = map->constructor(); if (constructor->IsJSFunction() && JSFunction::cast(constructor)->initial_map() == map) { // If we still have the original map, set in-object properties directly. regexp->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex, source); // Both true and false are immovable immortal objects so no need for write // barrier. regexp->InObjectPropertyAtPut( JSRegExp::kGlobalFieldIndex, global, SKIP_WRITE_BARRIER); regexp->InObjectPropertyAtPut( JSRegExp::kIgnoreCaseFieldIndex, ignoreCase, SKIP_WRITE_BARRIER); regexp->InObjectPropertyAtPut( JSRegExp::kMultilineFieldIndex, multiline, SKIP_WRITE_BARRIER); regexp->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex, Smi::FromInt(0), SKIP_WRITE_BARRIER); // It's a Smi. return regexp; } // Map has changed, so use generic, but slower, method. PropertyAttributes final = static_cast(READ_ONLY | DONT_ENUM | DONT_DELETE); PropertyAttributes writable = static_cast(DONT_ENUM | DONT_DELETE); Heap* heap = isolate->heap(); MaybeObject* result; result = regexp->SetLocalPropertyIgnoreAttributes(heap->source_symbol(), source, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->global_symbol(), global, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->ignore_case_symbol(), ignoreCase, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->multiline_symbol(), multiline, final); ASSERT(!result->IsFailure()); result = regexp->SetLocalPropertyIgnoreAttributes(heap->last_index_symbol(), Smi::FromInt(0), writable); ASSERT(!result->IsFailure()); USE(result); return regexp; } RUNTIME_FUNCTION(MaybeObject*, Runtime_FinishArrayPrototypeSetup) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSArray, prototype, 0); // This is necessary to enable fast checks for absence of elements // on Array.prototype and below. prototype->set_elements(isolate->heap()->empty_fixed_array()); return Smi::FromInt(0); } static Handle InstallBuiltin(Isolate* isolate, Handle holder, const char* name, Builtins::Name builtin_name) { Handle key = isolate->factory()->LookupAsciiSymbol(name); Handle code(isolate->builtins()->builtin(builtin_name)); Handle optimized = isolate->factory()->NewFunction(key, JS_OBJECT_TYPE, JSObject::kHeaderSize, code, false); optimized->shared()->DontAdaptArguments(); JSReceiver::SetProperty(holder, key, optimized, NONE, kStrictMode); return optimized; } RUNTIME_FUNCTION(MaybeObject*, Runtime_SpecialArrayFunctions) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, holder, 0); InstallBuiltin(isolate, holder, "pop", Builtins::kArrayPop); InstallBuiltin(isolate, holder, "push", Builtins::kArrayPush); InstallBuiltin(isolate, holder, "shift", Builtins::kArrayShift); InstallBuiltin(isolate, holder, "unshift", Builtins::kArrayUnshift); InstallBuiltin(isolate, holder, "slice", Builtins::kArraySlice); InstallBuiltin(isolate, holder, "splice", Builtins::kArraySplice); InstallBuiltin(isolate, holder, "concat", Builtins::kArrayConcat); return *holder; } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetDefaultReceiver) { ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, callable, 0); if (!callable->IsJSFunction()) { HandleScope scope(isolate); bool threw = false; Handle delegate = Execution::TryGetFunctionDelegate(Handle(callable), &threw); if (threw) return Failure::Exception(); callable = JSFunction::cast(*delegate); } JSFunction* function = JSFunction::cast(callable); SharedFunctionInfo* shared = function->shared(); if (shared->native() || !shared->is_classic_mode()) { return isolate->heap()->undefined_value(); } // Returns undefined for strict or native functions, or // the associated global receiver for "normal" functions. Context* global_context = function->context()->global()->global_context(); return global_context->global()->global_receiver(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MaterializeRegExpLiteral) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0); int index = args.smi_at(1); Handle pattern = args.at(2); Handle flags = args.at(3); // Get the RegExp function from the context in the literals array. // This is the RegExp function from the context in which the // function was created. We do not use the RegExp function from the // current global context because this might be the RegExp function // from another context which we should not have access to. Handle constructor = Handle( JSFunction::GlobalContextFromLiterals(*literals)->regexp_function()); // Compute the regular expression literal. bool has_pending_exception; Handle regexp = RegExpImpl::CreateRegExpLiteral(constructor, pattern, flags, &has_pending_exception); if (has_pending_exception) { ASSERT(isolate->has_pending_exception()); return Failure::Exception(); } literals->set(index, *regexp); return *regexp; } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionGetName) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return f->shared()->name(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionSetName) { NoHandleAllocation ha; ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(JSFunction, f, 0); CONVERT_ARG_CHECKED(String, name, 1); f->shared()->set_name(name); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionNameShouldPrintAsAnonymous) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean( f->shared()->name_should_print_as_anonymous()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionMarkNameShouldPrintAsAnonymous) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); f->shared()->set_name_should_print_as_anonymous(true); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionRemovePrototype) { NoHandleAllocation ha; ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); Object* obj = f->RemovePrototype(); if (obj->IsFailure()) return obj; return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionGetScript) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, fun, 0); Handle script = Handle(fun->shared()->script(), isolate); if (!script->IsScript()) return isolate->heap()->undefined_value(); return *GetScriptWrapper(Handle