// 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 #include "v8.h" #include "accessors.h" #include "allocation-site-scopes.h" #include "api.h" #include "arguments.h" #include "bootstrapper.h" #include "codegen.h" #include "compilation-cache.h" #include "compiler.h" #include "cpu.h" #include "cpu-profiler.h" #include "dateparser-inl.h" #include "debug.h" #include "deoptimizer.h" #include "date.h" #include "execution.h" #include "full-codegen.h" #include "global-handles.h" #include "isolate-inl.h" #include "jsregexp.h" #include "jsregexp-inl.h" #include "json-parser.h" #include "json-stringifier.h" #include "liveedit.h" #include "misc-intrinsics.h" #include "parser.h" #include "platform.h" #include "runtime-profiler.h" #include "runtime.h" #include "scopeinfo.h" #include "smart-pointers.h" #include "string-search.h" #include "stub-cache.h" #include "uri.h" #include "v8conversions.h" #include "v8threads.h" #include "vm-state-inl.h" #ifdef V8_I18N_SUPPORT #include "i18n.h" #include "unicode/brkiter.h" #include "unicode/calendar.h" #include "unicode/coll.h" #include "unicode/curramt.h" #include "unicode/datefmt.h" #include "unicode/dcfmtsym.h" #include "unicode/decimfmt.h" #include "unicode/dtfmtsym.h" #include "unicode/dtptngen.h" #include "unicode/locid.h" #include "unicode/numfmt.h" #include "unicode/numsys.h" #include "unicode/rbbi.h" #include "unicode/smpdtfmt.h" #include "unicode/timezone.h" #include "unicode/uchar.h" #include "unicode/ucol.h" #include "unicode/ucurr.h" #include "unicode/uloc.h" #include "unicode/unum.h" #include "unicode/uversion.h" #endif #ifndef _STLP_VENDOR_CSTD // STLPort doesn't import fpclassify and isless into the std namespace. using std::fpclassify; using std::isless; #endif 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)); 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 internal strings and array indices among keys. int number_of_string_keys = 0; for (int p = 0; p != properties_length; p += 2) { Object* key = constant_properties->get(p); uint32_t element_index = 0; if (key->IsInternalizedString()) { number_of_string_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-internalized-string non-index key makes caching // impossible. // ASSERT to make sure that the if condition after the loop is false. ASSERT(number_of_string_keys != number_of_properties); break; } } // If we only have internalized strings and array indices among keys then we // can use the map cache in the native context. const int kMaxKeys = 10; if ((number_of_string_keys == number_of_properties) && (number_of_string_keys < kMaxKeys)) { // Create the fixed array with the key. Handle keys = isolate->factory()->NewFixedArray(number_of_string_keys); if (number_of_string_keys > 0) { int index = 0; for (int p = 0; p < properties_length; p += 2) { Object* key = constant_properties->get(p); if (key->IsInternalizedString()) { keys->set(index++, key); } } ASSERT(index == number_of_string_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 native 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 native context // because this might be the object function from another context // which we should not have access to. Handle context = Handle(JSFunction::NativeContextFromLiterals(*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, isolate->heap()->GetPretenureMode()); // 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); } // TODO(verwaest): Support tracking representations in the boilerplate. 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; StoreMode mode = value->IsJSObject() ? FORCE_FIELD : ALLOW_AS_CONSTANT; if (key->IsInternalizedString()) { 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, Object::OPTIMAL_REPRESENTATION, mode); } } 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, Object::OPTIMAL_REPRESENTATION, mode); } // 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)) { JSObject::TransitionElementsKind(Handle::cast(object), to_kind); return *object; } return isolate->ThrowIllegalOperation(); } static const int kSmiLiteralMinimumLength = 1024; Handle Runtime::CreateArrayLiteralBoilerplate( Isolate* isolate, Handle literals, Handle elements) { // Create the JSArray. Handle constructor( JSFunction::NativeContextFromLiterals(*literals)->array_function()); Handle object = Handle::cast( isolate->factory()->NewJSObject( constructor, isolate->heap()->GetPretenureMode())); ElementsKind constant_elements_kind = static_cast(Smi::cast(elements->get(0))->value()); Handle constant_elements_values( FixedArrayBase::cast(elements->get(1))); ASSERT(IsFastElementsKind(constant_elements_kind)); Context* native_context = isolate->context()->native_context(); Object* maybe_maps_array = native_context->js_array_maps(); ASSERT(!maybe_maps_array->IsUndefined()); Object* maybe_map = FixedArray::cast(maybe_maps_array)->get( constant_elements_kind); ASSERT(maybe_map->IsMap()); object->set_map(Map::cast(maybe_map)); Handle copied_elements_values; if (IsFastDoubleElementsKind(constant_elements_kind)) { ASSERT(FLAG_smi_only_arrays); copied_elements_values = isolate->factory()->CopyFixedDoubleArray( Handle::cast(constant_elements_values)); } else { ASSERT(IsFastSmiOrObjectElementsKind(constant_elements_kind)); 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() < kSmiLiteralMinimumLength) { ElementsKind elements_kind = object->GetElementsKind(); if (!IsFastObjectElementsKind(elements_kind)) { if (IsFastHoleyElementsKind(elements_kind)) { CHECK(!TransitionElements(object, FAST_HOLEY_ELEMENTS, isolate)->IsFailure()); } else { CHECK(!TransitionElements(object, FAST_ELEMENTS, isolate)->IsFailure()); } } } object->ValidateElements(); return object; } static Handle CreateLiteralBoilerplate( Isolate* isolate, Handle literals, Handle array) { Handle elements = CompileTimeValue::GetElements(array); const bool kHasNoFunctionLiteral = false; switch (CompileTimeValue::GetLiteralType(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 literal_site(literals->get(literals_index), isolate); Handle site; Handle boilerplate; if (*literal_site == isolate->heap()->undefined_value()) { Handle raw_boilerplate = CreateObjectLiteralBoilerplate( isolate, literals, constant_properties, should_have_fast_elements, has_function_literal); RETURN_IF_EMPTY_HANDLE(isolate, raw_boilerplate); boilerplate = Handle::cast(raw_boilerplate); AllocationSiteCreationContext creation_context(isolate); site = creation_context.EnterNewScope(); RETURN_IF_EMPTY_HANDLE(isolate, JSObject::DeepWalk(boilerplate, &creation_context)); creation_context.ExitScope(site, boilerplate); // Update the functions literal and return the boilerplate. literals->set(literals_index, *site); } else { site = Handle::cast(literal_site); boilerplate = Handle(JSObject::cast(site->transition_info()), isolate); } AllocationSiteUsageContext usage_context(isolate, site, true); usage_context.EnterNewScope(); Handle copy = JSObject::DeepCopy(boilerplate, &usage_context); usage_context.ExitScope(site, boilerplate); RETURN_IF_EMPTY_HANDLE(isolate, copy); return *copy; } static Handle GetLiteralAllocationSite( Isolate* isolate, Handle literals, int literals_index, Handle elements) { // Check if boilerplate exists. If not, create it first. Handle literal_site(literals->get(literals_index), isolate); Handle site; if (*literal_site == isolate->heap()->undefined_value()) { ASSERT(*elements != isolate->heap()->empty_fixed_array()); Handle boilerplate = Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements); if (boilerplate.is_null()) return Handle::null(); AllocationSiteCreationContext creation_context(isolate); site = creation_context.EnterNewScope(); if (JSObject::DeepWalk(Handle::cast(boilerplate), &creation_context).is_null()) { return Handle::null(); } creation_context.ExitScope(site, Handle::cast(boilerplate)); literals->set(literals_index, *site); } else { site = Handle::cast(literal_site); } return site; } 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); Handle site = GetLiteralAllocationSite(isolate, literals, literals_index, elements); RETURN_IF_EMPTY_HANDLE(isolate, site); Handle boilerplate(JSObject::cast(site->transition_info())); AllocationSiteUsageContext usage_context(isolate, site, true); usage_context.EnterNewScope(); Handle copy = JSObject::DeepCopy(boilerplate, &usage_context); usage_context.ExitScope(site, boilerplate); RETURN_IF_EMPTY_HANDLE(isolate, copy); return *copy; } 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); Handle site = GetLiteralAllocationSite(isolate, literals, literals_index, elements); RETURN_IF_EMPTY_HANDLE(isolate, site); JSObject* boilerplate = JSObject::cast(site->transition_info()); if (boilerplate->elements()->map() == isolate->heap()->fixed_cow_array_map()) { isolate->counters()->cow_arrays_created_runtime()->Increment(); } if (AllocationSite::GetMode(boilerplate->GetElementsKind()) == TRACK_ALLOCATION_SITE) { return isolate->heap()->CopyJSObject(boilerplate, *site); } return isolate->heap()->CopyJSObject(boilerplate); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateSymbol) { HandleScope scope(isolate); ASSERT(args.length() == 1); Handle name(args[0], isolate); RUNTIME_ASSERT(name->IsString() || name->IsUndefined()); Symbol* symbol; MaybeObject* maybe = isolate->heap()->AllocateSymbol(); if (!maybe->To(&symbol)) return maybe; if (name->IsString()) symbol->set_name(*name); return symbol; } RUNTIME_FUNCTION(MaybeObject*, Runtime_SymbolName) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(Symbol, symbol, 0); return symbol->name(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_CreateJSProxy) { SealHandleScope shs(isolate); ASSERT(args.length() == 2); CONVERT_ARG_CHECKED(JSReceiver, handler, 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) { SealHandleScope shs(isolate); ASSERT(args.length() == 4); CONVERT_ARG_CHECKED(JSReceiver, handler, 0); Object* call_trap = args[1]; RUNTIME_ASSERT(call_trap->IsJSFunction() || call_trap->IsJSFunctionProxy()); CONVERT_ARG_CHECKED(JSFunction, construct_trap, 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) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); Object* obj = args[0]; return isolate->heap()->ToBoolean(obj->IsJSProxy()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsJSFunctionProxy) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); Object* obj = args[0]; return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetHandler) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSProxy, proxy, 0); return proxy->handler(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetCallTrap) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0); return proxy->call_trap(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetConstructTrap) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0); return proxy->construct_trap(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_Fix) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, 0); JSProxy::Fix(proxy); return isolate->heap()->undefined_value(); } void Runtime::FreeArrayBuffer(Isolate* isolate, JSArrayBuffer* phantom_array_buffer) { if (phantom_array_buffer->is_external()) return; size_t allocated_length = NumberToSize( isolate, phantom_array_buffer->byte_length()); isolate->heap()->AdjustAmountOfExternalAllocatedMemory( -static_cast(allocated_length)); CHECK(V8::ArrayBufferAllocator() != NULL); V8::ArrayBufferAllocator()->Free( phantom_array_buffer->backing_store(), allocated_length); } void Runtime::SetupArrayBuffer(Isolate* isolate, Handle array_buffer, bool is_external, void* data, size_t allocated_length) { ASSERT(array_buffer->GetInternalFieldCount() == v8::ArrayBuffer::kInternalFieldCount); for (int i = 0; i < v8::ArrayBuffer::kInternalFieldCount; i++) { array_buffer->SetInternalField(i, Smi::FromInt(0)); } array_buffer->set_backing_store(data); array_buffer->set_flag(Smi::FromInt(0)); array_buffer->set_is_external(is_external); Handle byte_length = isolate->factory()->NewNumberFromSize(allocated_length); CHECK(byte_length->IsSmi() || byte_length->IsHeapNumber()); array_buffer->set_byte_length(*byte_length); array_buffer->set_weak_next(isolate->heap()->array_buffers_list()); isolate->heap()->set_array_buffers_list(*array_buffer); array_buffer->set_weak_first_view(isolate->heap()->undefined_value()); } bool Runtime::SetupArrayBufferAllocatingData( Isolate* isolate, Handle array_buffer, size_t allocated_length, bool initialize) { void* data; CHECK(V8::ArrayBufferAllocator() != NULL); if (allocated_length != 0) { if (initialize) { data = V8::ArrayBufferAllocator()->Allocate(allocated_length); } else { data = V8::ArrayBufferAllocator()->AllocateUninitialized(allocated_length); } if (data == NULL) return false; } else { data = NULL; } SetupArrayBuffer(isolate, array_buffer, false, data, allocated_length); isolate->heap()->AdjustAmountOfExternalAllocatedMemory(allocated_length); return true; } RUNTIME_FUNCTION(MaybeObject*, Runtime_ArrayBufferInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, holder, 0); CONVERT_ARG_HANDLE_CHECKED(Object, byteLength, 1); size_t allocated_length; if (byteLength->IsSmi()) { allocated_length = Smi::cast(*byteLength)->value(); } else { ASSERT(byteLength->IsHeapNumber()); double value = HeapNumber::cast(*byteLength)->value(); ASSERT(value >= 0); if (value > std::numeric_limits::max()) { return isolate->Throw( *isolate->factory()->NewRangeError("invalid_array_buffer_length", HandleVector(NULL, 0))); } allocated_length = static_cast(value); } if (!Runtime::SetupArrayBufferAllocatingData(isolate, holder, allocated_length)) { return isolate->Throw(*isolate->factory()-> NewRangeError("invalid_array_buffer_length", HandleVector(NULL, 0))); } return *holder; } RUNTIME_FUNCTION(MaybeObject*, Runtime_ArrayBufferGetByteLength) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSArrayBuffer, holder, 0); return holder->byte_length(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_ArrayBufferSliceImpl) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, source, 0); CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, target, 1); CONVERT_DOUBLE_ARG_CHECKED(first, 2); size_t start = static_cast(first); size_t target_length = NumberToSize(isolate, target->byte_length()); if (target_length == 0) return isolate->heap()->undefined_value(); ASSERT(NumberToSize(isolate, source->byte_length()) - target_length >= start); uint8_t* source_data = reinterpret_cast(source->backing_store()); uint8_t* target_data = reinterpret_cast(target->backing_store()); CopyBytes(target_data, source_data + start, target_length); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_ArrayBufferIsView) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(Object, object, 0); return object->IsJSArrayBufferView() ? isolate->heap()->true_value() : isolate->heap()->false_value(); } enum TypedArrayId { // arrayIds below should be synchromized with typedarray.js natives. ARRAY_ID_UINT8 = 1, ARRAY_ID_INT8 = 2, ARRAY_ID_UINT16 = 3, ARRAY_ID_INT16 = 4, ARRAY_ID_UINT32 = 5, ARRAY_ID_INT32 = 6, ARRAY_ID_FLOAT32 = 7, ARRAY_ID_FLOAT64 = 8, ARRAY_ID_UINT8C = 9 }; static void ArrayIdToTypeAndSize( int arrayId, ExternalArrayType* array_type, size_t* element_size) { switch (arrayId) { case ARRAY_ID_UINT8: *array_type = kExternalUnsignedByteArray; *element_size = 1; break; case ARRAY_ID_INT8: *array_type = kExternalByteArray; *element_size = 1; break; case ARRAY_ID_UINT16: *array_type = kExternalUnsignedShortArray; *element_size = 2; break; case ARRAY_ID_INT16: *array_type = kExternalShortArray; *element_size = 2; break; case ARRAY_ID_UINT32: *array_type = kExternalUnsignedIntArray; *element_size = 4; break; case ARRAY_ID_INT32: *array_type = kExternalIntArray; *element_size = 4; break; case ARRAY_ID_FLOAT32: *array_type = kExternalFloatArray; *element_size = 4; break; case ARRAY_ID_FLOAT64: *array_type = kExternalDoubleArray; *element_size = 8; break; case ARRAY_ID_UINT8C: *array_type = kExternalPixelArray; *element_size = 1; break; default: UNREACHABLE(); } } RUNTIME_FUNCTION(MaybeObject*, Runtime_TypedArrayInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 5); CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0); CONVERT_SMI_ARG_CHECKED(arrayId, 1); CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 2); CONVERT_ARG_HANDLE_CHECKED(Object, byte_offset_object, 3); CONVERT_ARG_HANDLE_CHECKED(Object, byte_length_object, 4); ASSERT(holder->GetInternalFieldCount() == v8::ArrayBufferView::kInternalFieldCount); for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) { holder->SetInternalField(i, Smi::FromInt(0)); } ExternalArrayType array_type = kExternalByteArray; // Bogus initialization. size_t element_size = 1; // Bogus initialization. ArrayIdToTypeAndSize(arrayId, &array_type, &element_size); holder->set_buffer(*buffer); holder->set_byte_offset(*byte_offset_object); holder->set_byte_length(*byte_length_object); size_t byte_offset = NumberToSize(isolate, *byte_offset_object); size_t byte_length = NumberToSize(isolate, *byte_length_object); ASSERT(byte_length % element_size == 0); size_t length = byte_length / element_size; Handle length_obj = isolate->factory()->NewNumberFromSize(length); holder->set_length(*length_obj); holder->set_weak_next(buffer->weak_first_view()); buffer->set_weak_first_view(*holder); Handle elements = isolate->factory()->NewExternalArray( static_cast(length), array_type, static_cast(buffer->backing_store()) + byte_offset); holder->set_elements(*elements); return isolate->heap()->undefined_value(); } // Initializes a typed array from an array-like object. // If an array-like object happens to be a typed array of the same type, // initializes backing store using memove. // // Returns true if backing store was initialized or false otherwise. RUNTIME_FUNCTION(MaybeObject*, Runtime_TypedArrayInitializeFromArrayLike) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0); CONVERT_SMI_ARG_CHECKED(arrayId, 1); CONVERT_ARG_HANDLE_CHECKED(Object, source, 2); CONVERT_ARG_HANDLE_CHECKED(Object, length_obj, 3); ASSERT(holder->GetInternalFieldCount() == v8::ArrayBufferView::kInternalFieldCount); for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) { holder->SetInternalField(i, Smi::FromInt(0)); } ExternalArrayType array_type = kExternalByteArray; // Bogus initialization. size_t element_size = 1; // Bogus initialization. ArrayIdToTypeAndSize(arrayId, &array_type, &element_size); Handle buffer = isolate->factory()->NewJSArrayBuffer(); size_t length = NumberToSize(isolate, *length_obj); size_t byte_length = length * element_size; if (byte_length < length) { // Overflow return isolate->Throw(*isolate->factory()-> NewRangeError("invalid_array_buffer_length", HandleVector(NULL, 0))); } // NOTE: not initializing backing store. // We assume that the caller of this function will initialize holder // with the loop // for(i = 0; i < length; i++) { holder[i] = source[i]; } // We assume that the caller of this function is always a typed array // constructor. // If source is a typed array, this loop will always run to completion, // so we are sure that the backing store will be initialized. // Otherwise, the indexing operation might throw, so the loop will not // run to completion and the typed array might remain partly initialized. // However we further assume that the caller of this function is a typed array // constructor, and the exception will propagate out of the constructor, // therefore uninitialized memory will not be accessible by a user program. // // TODO(dslomov): revise this once we support subclassing. if (!Runtime::SetupArrayBufferAllocatingData( isolate, buffer, byte_length, false)) { return isolate->Throw(*isolate->factory()-> NewRangeError("invalid_array_buffer_length", HandleVector(NULL, 0))); } holder->set_buffer(*buffer); holder->set_byte_offset(Smi::FromInt(0)); Handle byte_length_obj( isolate->factory()->NewNumberFromSize(byte_length)); holder->set_byte_length(*byte_length_obj); holder->set_length(*length_obj); holder->set_weak_next(buffer->weak_first_view()); buffer->set_weak_first_view(*holder); Handle elements = isolate->factory()->NewExternalArray( static_cast(length), array_type, static_cast(buffer->backing_store())); holder->set_elements(*elements); if (source->IsJSTypedArray()) { Handle typed_array(JSTypedArray::cast(*source)); if (typed_array->type() == holder->type()) { uint8_t* backing_store = static_cast( JSArrayBuffer::cast(typed_array->buffer())->backing_store()); size_t source_byte_offset = NumberToSize(isolate, typed_array->byte_offset()); memcpy( buffer->backing_store(), backing_store + source_byte_offset, byte_length); return *isolate->factory()->true_value(); } else { return *isolate->factory()->false_value(); } } return *isolate->factory()->false_value(); } #define TYPED_ARRAY_GETTER(getter, accessor) \ RUNTIME_FUNCTION(MaybeObject*, Runtime_TypedArrayGet##getter) { \ HandleScope scope(isolate); \ ASSERT(args.length() == 1); \ CONVERT_ARG_HANDLE_CHECKED(Object, holder, 0); \ if (!holder->IsJSTypedArray()) \ return isolate->Throw(*isolate->factory()->NewTypeError( \ "not_typed_array", HandleVector(NULL, 0))); \ Handle typed_array(JSTypedArray::cast(*holder)); \ return typed_array->accessor(); \ } TYPED_ARRAY_GETTER(Buffer, buffer) TYPED_ARRAY_GETTER(ByteLength, byte_length) TYPED_ARRAY_GETTER(ByteOffset, byte_offset) TYPED_ARRAY_GETTER(Length, length) #undef TYPED_ARRAY_GETTER // Return codes for Runtime_TypedArraySetFastCases. // Should be synchronized with typedarray.js natives. enum TypedArraySetResultCodes { // Set from typed array of the same type. // This is processed by TypedArraySetFastCases TYPED_ARRAY_SET_TYPED_ARRAY_SAME_TYPE = 0, // Set from typed array of the different type, overlapping in memory. TYPED_ARRAY_SET_TYPED_ARRAY_OVERLAPPING = 1, // Set from typed array of the different type, non-overlapping. TYPED_ARRAY_SET_TYPED_ARRAY_NONOVERLAPPING = 2, // Set from non-typed array. TYPED_ARRAY_SET_NON_TYPED_ARRAY = 3 }; RUNTIME_FUNCTION(MaybeObject*, Runtime_TypedArraySetFastCases) { HandleScope scope(isolate); CONVERT_ARG_HANDLE_CHECKED(Object, target_obj, 0); CONVERT_ARG_HANDLE_CHECKED(Object, source_obj, 1); CONVERT_ARG_HANDLE_CHECKED(Object, offset_obj, 2); if (!target_obj->IsJSTypedArray()) return isolate->Throw(*isolate->factory()->NewTypeError( "not_typed_array", HandleVector(NULL, 0))); if (!source_obj->IsJSTypedArray()) return Smi::FromInt(TYPED_ARRAY_SET_NON_TYPED_ARRAY); Handle target(JSTypedArray::cast(*target_obj)); Handle source(JSTypedArray::cast(*source_obj)); size_t offset = NumberToSize(isolate, *offset_obj); size_t target_length = NumberToSize(isolate, target->length()); size_t source_length = NumberToSize(isolate, source->length()); size_t target_byte_length = NumberToSize(isolate, target->byte_length()); size_t source_byte_length = NumberToSize(isolate, source->byte_length()); if (offset > target_length || offset + source_length > target_length || offset + source_length < offset) // overflow return isolate->Throw(*isolate->factory()->NewRangeError( "typed_array_set_source_too_large", HandleVector(NULL, 0))); size_t target_offset = NumberToSize(isolate, target->byte_offset()); size_t source_offset = NumberToSize(isolate, source->byte_offset()); uint8_t* target_base = static_cast( JSArrayBuffer::cast(target->buffer())->backing_store()) + target_offset; uint8_t* source_base = static_cast( JSArrayBuffer::cast(source->buffer())->backing_store()) + source_offset; // Typed arrays of the same type: use memmove. if (target->type() == source->type()) { memmove(target_base + offset * target->element_size(), source_base, source_byte_length); return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_SAME_TYPE); } // Typed arrays of different types over the same backing store if ((source_base <= target_base && source_base + source_byte_length > target_base) || (target_base <= source_base && target_base + target_byte_length > source_base)) { // We do not support overlapping ArrayBuffers ASSERT( JSArrayBuffer::cast(target->buffer())->backing_store() == JSArrayBuffer::cast(source->buffer())->backing_store()); return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_OVERLAPPING); } else { // Non-overlapping typed arrays return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_NONOVERLAPPING); } } RUNTIME_FUNCTION(MaybeObject*, Runtime_DataViewInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 4); CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0); CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 1); CONVERT_ARG_HANDLE_CHECKED(Object, byte_offset, 2); CONVERT_ARG_HANDLE_CHECKED(Object, byte_length, 3); ASSERT(holder->GetInternalFieldCount() == v8::ArrayBufferView::kInternalFieldCount); for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) { holder->SetInternalField(i, Smi::FromInt(0)); } holder->set_buffer(*buffer); ASSERT(byte_offset->IsNumber()); ASSERT( NumberToSize(isolate, buffer->byte_length()) >= NumberToSize(isolate, *byte_offset) + NumberToSize(isolate, *byte_length)); holder->set_byte_offset(*byte_offset); ASSERT(byte_length->IsNumber()); holder->set_byte_length(*byte_length); holder->set_weak_next(buffer->weak_first_view()); buffer->set_weak_first_view(*holder); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DataViewGetBuffer) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSDataView, data_view, 0); return data_view->buffer(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DataViewGetByteOffset) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSDataView, data_view, 0); return data_view->byte_offset(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_DataViewGetByteLength) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSDataView, data_view, 0); return data_view->byte_length(); } inline static bool NeedToFlipBytes(bool is_little_endian) { #ifdef V8_TARGET_LITTLE_ENDIAN return !is_little_endian; #else return is_little_endian; #endif } template inline void CopyBytes(uint8_t* target, uint8_t* source) { for (int i = 0; i < n; i++) { *(target++) = *(source++); } } template inline void FlipBytes(uint8_t* target, uint8_t* source) { source = source + (n-1); for (int i = 0; i < n; i++) { *(target++) = *(source--); } } template inline static bool DataViewGetValue( Isolate* isolate, Handle data_view, Handle byte_offset_obj, bool is_little_endian, T* result) { size_t byte_offset = NumberToSize(isolate, *byte_offset_obj); Handle buffer(JSArrayBuffer::cast(data_view->buffer())); size_t data_view_byte_offset = NumberToSize(isolate, data_view->byte_offset()); size_t data_view_byte_length = NumberToSize(isolate, data_view->byte_length()); if (byte_offset + sizeof(T) > data_view_byte_length || byte_offset + sizeof(T) < byte_offset) { // overflow return false; } union Value { T data; uint8_t bytes[sizeof(T)]; }; Value value; size_t buffer_offset = data_view_byte_offset + byte_offset; ASSERT( NumberToSize(isolate, buffer->byte_length()) >= buffer_offset + sizeof(T)); uint8_t* source = static_cast(buffer->backing_store()) + buffer_offset; if (NeedToFlipBytes(is_little_endian)) { FlipBytes(value.bytes, source); } else { CopyBytes(value.bytes, source); } *result = value.data; return true; } template static bool DataViewSetValue( Isolate* isolate, Handle data_view, Handle byte_offset_obj, bool is_little_endian, T data) { size_t byte_offset = NumberToSize(isolate, *byte_offset_obj); Handle buffer(JSArrayBuffer::cast(data_view->buffer())); size_t data_view_byte_offset = NumberToSize(isolate, data_view->byte_offset()); size_t data_view_byte_length = NumberToSize(isolate, data_view->byte_length()); if (byte_offset + sizeof(T) > data_view_byte_length || byte_offset + sizeof(T) < byte_offset) { // overflow return false; } union Value { T data; uint8_t bytes[sizeof(T)]; }; Value value; value.data = data; size_t buffer_offset = data_view_byte_offset + byte_offset; ASSERT( NumberToSize(isolate, buffer->byte_length()) >= buffer_offset + sizeof(T)); uint8_t* target = static_cast(buffer->backing_store()) + buffer_offset; if (NeedToFlipBytes(is_little_endian)) { FlipBytes(target, value.bytes); } else { CopyBytes(target, value.bytes); } return true; } #define DATA_VIEW_GETTER(TypeName, Type, Converter) \ RUNTIME_FUNCTION(MaybeObject*, Runtime_DataViewGet##TypeName) { \ HandleScope scope(isolate); \ ASSERT(args.length() == 3); \ CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0); \ CONVERT_ARG_HANDLE_CHECKED(Object, offset, 1); \ CONVERT_BOOLEAN_ARG_CHECKED(is_little_endian, 2); \ Type result; \ if (DataViewGetValue( \ isolate, holder, offset, is_little_endian, &result)) { \ return isolate->heap()->Converter(result); \ } else { \ return isolate->Throw(*isolate->factory()->NewRangeError( \ "invalid_data_view_accessor_offset", \ HandleVector(NULL, 0))); \ } \ } DATA_VIEW_GETTER(Uint8, uint8_t, NumberFromUint32) DATA_VIEW_GETTER(Int8, int8_t, NumberFromInt32) DATA_VIEW_GETTER(Uint16, uint16_t, NumberFromUint32) DATA_VIEW_GETTER(Int16, int16_t, NumberFromInt32) DATA_VIEW_GETTER(Uint32, uint32_t, NumberFromUint32) DATA_VIEW_GETTER(Int32, int32_t, NumberFromInt32) DATA_VIEW_GETTER(Float32, float, NumberFromDouble) DATA_VIEW_GETTER(Float64, double, NumberFromDouble) #undef DATA_VIEW_GETTER template static T DataViewConvertValue(double value); template <> int8_t DataViewConvertValue(double value) { return static_cast(DoubleToInt32(value)); } template <> int16_t DataViewConvertValue(double value) { return static_cast(DoubleToInt32(value)); } template <> int32_t DataViewConvertValue(double value) { return DoubleToInt32(value); } template <> uint8_t DataViewConvertValue(double value) { return static_cast(DoubleToUint32(value)); } template <> uint16_t DataViewConvertValue(double value) { return static_cast(DoubleToUint32(value)); } template <> uint32_t DataViewConvertValue(double value) { return DoubleToUint32(value); } template <> float DataViewConvertValue(double value) { return static_cast(value); } template <> double DataViewConvertValue(double value) { return value; } #define DATA_VIEW_SETTER(TypeName, Type) \ RUNTIME_FUNCTION(MaybeObject*, Runtime_DataViewSet##TypeName) { \ HandleScope scope(isolate); \ ASSERT(args.length() == 4); \ CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0); \ CONVERT_ARG_HANDLE_CHECKED(Object, offset, 1); \ CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); \ CONVERT_BOOLEAN_ARG_CHECKED(is_little_endian, 3); \ Type v = DataViewConvertValue(value->Number()); \ if (DataViewSetValue( \ isolate, holder, offset, is_little_endian, v)) { \ return isolate->heap()->undefined_value(); \ } else { \ return isolate->Throw(*isolate->factory()->NewRangeError( \ "invalid_data_view_accessor_offset", \ HandleVector(NULL, 0))); \ } \ } DATA_VIEW_SETTER(Uint8, uint8_t) DATA_VIEW_SETTER(Int8, int8_t) DATA_VIEW_SETTER(Uint16, uint16_t) DATA_VIEW_SETTER(Int16, int16_t) DATA_VIEW_SETTER(Uint32, uint32_t) DATA_VIEW_SETTER(Int32, int32_t) DATA_VIEW_SETTER(Float32, float) DATA_VIEW_SETTER(Float64, double) #undef DATA_VIEW_SETTER 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], isolate); Handle table(ObjectHashSet::cast(holder->table())); table = ObjectHashSetAdd(table, key); holder->set_table(*table); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetHas) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0); Handle key(args[1], isolate); 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], isolate); Handle table(ObjectHashSet::cast(holder->table())); table = ObjectHashSetRemove(table, key); holder->set_table(*table); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetGetSize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0); Handle table(ObjectHashSet::cast(holder->table())); return Smi::FromInt(table->NumberOfElements()); } 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); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle table(ObjectHashTable::cast(holder->table())); Handle lookup(table->Lookup(*key), isolate); return lookup->IsTheHole() ? isolate->heap()->undefined_value() : *lookup; } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapHas) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle table(ObjectHashTable::cast(holder->table())); Handle lookup(table->Lookup(*key), isolate); return isolate->heap()->ToBoolean(!lookup->IsTheHole()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapDelete) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle table(ObjectHashTable::cast(holder->table())); Handle lookup(table->Lookup(*key), isolate); Handle new_table = PutIntoObjectHashTable(table, key, isolate->factory()->the_hole_value()); holder->set_table(*new_table); return isolate->heap()->ToBoolean(!lookup->IsTheHole()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapSet) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); Handle table(ObjectHashTable::cast(holder->table())); Handle new_table = PutIntoObjectHashTable(table, key, value); holder->set_table(*new_table); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_MapGetSize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0); Handle table(ObjectHashTable::cast(holder->table())); return Smi::FromInt(table->NumberOfElements()); } static JSWeakCollection* WeakCollectionInitialize(Isolate* isolate, Handle weak_collection) { ASSERT(weak_collection->map()->inobject_properties() == 0); Handle table = isolate->factory()->NewObjectHashTable(0); weak_collection->set_table(*table); weak_collection->set_next(Smi::FromInt(0)); return *weak_collection; } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakCollectionInitialize) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0); return WeakCollectionInitialize(isolate, weak_collection); } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakCollectionGet) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle table( ObjectHashTable::cast(weak_collection->table())); Handle lookup(table->Lookup(*key), isolate); return lookup->IsTheHole() ? isolate->heap()->undefined_value() : *lookup; } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakCollectionHas) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle table( ObjectHashTable::cast(weak_collection->table())); Handle lookup(table->Lookup(*key), isolate); return isolate->heap()->ToBoolean(!lookup->IsTheHole()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakCollectionDelete) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle table(ObjectHashTable::cast( weak_collection->table())); Handle lookup(table->Lookup(*key), isolate); Handle new_table = PutIntoObjectHashTable(table, key, isolate->factory()->the_hole_value()); weak_collection->set_table(*new_table); return isolate->heap()->ToBoolean(!lookup->IsTheHole()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_WeakCollectionSet) { HandleScope scope(isolate); ASSERT(args.length() == 3); CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); Handle value(args[2], isolate); Handle table( ObjectHashTable::cast(weak_collection->table())); Handle new_table = PutIntoObjectHashTable(table, key, value); weak_collection->set_table(*new_table); return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_ClassOf) { SealHandleScope shs(isolate); 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) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0); // We don't expect access checks to be needed on JSProxy objects. ASSERT(!obj->IsAccessCheckNeeded() || obj->IsJSObject()); do { if (obj->IsAccessCheckNeeded() && !isolate->MayNamedAccessWrapper(Handle::cast(obj), isolate->factory()->proto_string(), v8::ACCESS_GET)) { isolate->ReportFailedAccessCheck(JSObject::cast(*obj), v8::ACCESS_GET); RETURN_IF_SCHEDULED_EXCEPTION(isolate); return isolate->heap()->undefined_value(); } obj = handle(obj->GetPrototype(isolate), isolate); } while (obj->IsJSObject() && JSObject::cast(*obj)->map()->is_hidden_prototype()); return *obj; } static inline Object* GetPrototypeSkipHiddenPrototypes(Isolate* isolate, Object* receiver) { Object* current = receiver->GetPrototype(isolate); while (current->IsJSObject() && JSObject::cast(current)->map()->is_hidden_prototype()) { current = current->GetPrototype(isolate); } return current; } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetPrototype) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1); if (FLAG_harmony_observation && obj->map()->is_observed()) { Handle old_value( GetPrototypeSkipHiddenPrototypes(isolate, *obj), isolate); Handle result = JSObject::SetPrototype(obj, prototype, true); RETURN_IF_EMPTY_HANDLE(isolate, result); Handle new_value( GetPrototypeSkipHiddenPrototypes(isolate, *obj), isolate); if (!new_value->SameValue(*old_value)) { JSObject::EnqueueChangeRecord(obj, "prototype", isolate->factory()->proto_string(), old_value); } return *result; } Handle result = JSObject::SetPrototype(obj, prototype, true); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsInPrototypeChain) { SealHandleScope shs(isolate); 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(isolate); if (prototype->IsNull()) return isolate->heap()->false_value(); if (O == prototype) return isolate->heap()->true_value(); V = prototype; } } static bool CheckAccessException(Object* callback, v8::AccessType access_type) { DisallowHeapAllocation no_gc; if (callback->IsAccessorInfo()) { AccessorInfo* info = AccessorInfo::cast(callback); return (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()); } if (callback->IsAccessorPair()) { AccessorPair* info = AccessorPair::cast(callback); return (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 false; } template static bool CheckGenericAccess( Handle receiver, Handle holder, Key key, v8::AccessType access_type, bool (Isolate::*mayAccess)(Handle, Key, v8::AccessType)) { Isolate* isolate = receiver->GetIsolate(); for (Handle current = receiver; true; current = handle(JSObject::cast(current->GetPrototype()), isolate)) { if (current->IsAccessCheckNeeded() && !(isolate->*mayAccess)(current, key, access_type)) { return false; } if (current.is_identical_to(holder)) break; } return true; } enum AccessCheckResult { ACCESS_FORBIDDEN, ACCESS_ALLOWED, ACCESS_ABSENT }; static AccessCheckResult CheckPropertyAccess(Handle obj, Handle name, v8::AccessType access_type) { uint32_t index; if (name->AsArrayIndex(&index)) { // TODO(1095): we should traverse hidden prototype hierachy as well. if (CheckGenericAccess( obj, obj, index, access_type, &Isolate::MayIndexedAccessWrapper)) { return ACCESS_ALLOWED; } obj->GetIsolate()->ReportFailedAccessCheck(*obj, access_type); return ACCESS_FORBIDDEN; } Isolate* isolate = obj->GetIsolate(); LookupResult lookup(isolate); obj->LocalLookup(*name, &lookup, true); if (!lookup.IsProperty()) return ACCESS_ABSENT; Handle holder(lookup.holder(), isolate); if (CheckGenericAccess >( obj, holder, name, access_type, &Isolate::MayNamedAccessWrapper)) { return ACCESS_ALLOWED; } // Access check callback denied the access, but some properties // can have a special permissions which override callbacks descision // (currently see v8::AccessControl). // API callbacks can have per callback access exceptions. switch (lookup.type()) { case CALLBACKS: if (CheckAccessException(lookup.GetCallbackObject(), access_type)) { return ACCESS_ALLOWED; } 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, &lookup); if (lookup.IsProperty() && lookup.IsPropertyCallbacks()) { if (CheckAccessException(lookup.GetCallbackObject(), access_type)) { return ACCESS_ALLOWED; } } break; default: break; } isolate->ReportFailedAccessCheck(*obj, access_type); return ACCESS_FORBIDDEN; } // 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 Handle GetOwnProperty(Isolate* isolate, Handle obj, Handle name) { Heap* heap = isolate->heap(); Factory* factory = isolate->factory(); // Due to some WebKit tests, we want to make sure that we do not log // more than one access failure here. AccessCheckResult access_check_result = CheckPropertyAccess(obj, name, v8::ACCESS_HAS); RETURN_HANDLE_IF_SCHEDULED_EXCEPTION(isolate, Object); switch (access_check_result) { case ACCESS_FORBIDDEN: return factory->false_value(); case ACCESS_ALLOWED: break; case ACCESS_ABSENT: return factory->undefined_value(); } PropertyAttributes attrs = obj->GetLocalPropertyAttribute(*name); if (attrs == ABSENT) { RETURN_HANDLE_IF_SCHEDULED_EXCEPTION(isolate, Object); return factory->undefined_value(); } ASSERT(!isolate->has_scheduled_exception()); AccessorPair* raw_accessors = obj->GetLocalPropertyAccessorPair(*name); Handle accessors(raw_accessors, isolate); Handle elms = isolate->factory()->NewFixedArray(DESCRIPTOR_SIZE); elms->set(ENUMERABLE_INDEX, heap->ToBoolean((attrs & DONT_ENUM) == 0)); elms->set(CONFIGURABLE_INDEX, heap->ToBoolean((attrs & DONT_DELETE) == 0)); elms->set(IS_ACCESSOR_INDEX, heap->ToBoolean(raw_accessors != NULL)); if (raw_accessors == NULL) { elms->set(WRITABLE_INDEX, heap->ToBoolean((attrs & READ_ONLY) == 0)); // GetProperty does access check. Handle value = GetProperty(isolate, obj, name); RETURN_IF_EMPTY_HANDLE_VALUE(isolate, value, Handle::null()); elms->set(VALUE_INDEX, *value); } else { // Access checks are performed for both accessors separately. // When they fail, the respective field is not set in the descriptor. Handle getter(accessors->GetComponent(ACCESSOR_GETTER), isolate); Handle setter(accessors->GetComponent(ACCESSOR_SETTER), isolate); if (!getter->IsMap() && CheckPropertyAccess(obj, name, v8::ACCESS_GET)) { ASSERT(!isolate->has_scheduled_exception()); elms->set(GETTER_INDEX, *getter); } else { RETURN_HANDLE_IF_SCHEDULED_EXCEPTION(isolate, Object); } if (!setter->IsMap() && CheckPropertyAccess(obj, name, v8::ACCESS_SET)) { ASSERT(!isolate->has_scheduled_exception()); elms->set(SETTER_INDEX, *setter); } else { RETURN_HANDLE_IF_SCHEDULED_EXCEPTION(isolate, Object); } } return isolate->factory()->NewJSArrayWithElements(elms); } // 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) { HandleScope scope(isolate); ASSERT(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); Handle result = GetOwnProperty(isolate, obj, name); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_PreventExtensions) { HandleScope scope(isolate); ASSERT(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0); Handle result = JSObject::PreventExtensions(obj); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_IsExtensible) { SealHandleScope shs(isolate); 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); RETURN_IF_EMPTY_HANDLE(isolate, result); 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) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); Object* arg = args[0]; bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo(); return isolate->heap()->ToBoolean(result); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetTemplateField) { SealHandleScope shs(isolate); 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) { SealHandleScope shs(isolate); 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. Map* new_map; MaybeObject* maybe_new_map = old_map->Copy(); if (!maybe_new_map->To(&new_map)) return maybe_new_map; new_map->set_is_access_check_needed(false); object->set_map(new_map); } return isolate->heap()->ToBoolean(needs_access_checks); } RUNTIME_FUNCTION(MaybeObject*, Runtime_EnableAccessChecks) { SealHandleScope shs(isolate); 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. Map* new_map; MaybeObject* maybe_new_map = old_map->Copy(); if (!maybe_new_map->To(&new_map)) return maybe_new_map; new_map->set_is_access_check_needed(true); object->set_map(new_map); } return isolate->heap()->undefined_value(); } // Transform getter or setter into something DefineAccessor can handle. static Handle InstantiateAccessorComponent(Isolate* isolate, Handle component) { if (component->IsUndefined()) return isolate->factory()->null_value(); Handle info = Handle::cast(component); return Utils::OpenHandle(*Utils::ToLocal(info)->GetFunction()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_SetAccessorProperty) { HandleScope scope(isolate); ASSERT(args.length() == 6); CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0); CONVERT_ARG_HANDLE_CHECKED(Name, name, 1); CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2); CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3); CONVERT_SMI_ARG_CHECKED(attribute, 4); CONVERT_SMI_ARG_CHECKED(access_control, 5); JSObject::DefineAccessor(object, name, InstantiateAccessorComponent(isolate, getter), InstantiateAccessorComponent(isolate, setter), static_cast(attribute), static_cast(access_control)); 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) { HandleScope scope(isolate); ASSERT(args.length() == 3); Handle global = Handle( isolate->context()->global_object()); 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(); ASSERT(is_var + is_const + is_function == 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 erratum. LookupResult lookup(isolate); if (FLAG_es52_globals) { global->LocalLookup(*name, &lookup, true); } else { global->Lookup(*name, &lookup); } if (lookup.IsFound()) { // We found an existing property. Unless it was an interceptor // that claims the property is absent, skip this declaration. if (!lookup.IsInterceptor()) 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, true); // 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) { attr |= DONT_DELETE; } bool is_native = DeclareGlobalsNativeFlag::decode(flags); if (is_const || (is_native && is_function)) { attr |= READ_ONLY; } LanguageMode language_mode = DeclareGlobalsLanguageMode::decode(flags); if (!lookup.IsFound() || is_function) { // If the local property exists, check that we can reconfigure it // as required for function declarations. if (lookup.IsFound() && lookup.IsDontDelete()) { if (lookup.IsReadOnly() || lookup.IsDontEnum() || lookup.IsPropertyCallbacks()) { return ThrowRedeclarationError(isolate, "function", 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 native 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 native 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(!JSReceiver::HasLocalProperty(object, 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.IsPropertyCallbacks()) { 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) { HandleScope scope(isolate); // 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); 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. LookupResult lookup(isolate); isolate->context()->global_object()->LocalLookup(*name, &lookup, true); if (lookup.IsInterceptor()) { PropertyAttributes intercepted = lookup.holder()->GetPropertyAttribute(*name); if (intercepted != ABSENT && (intercepted & READ_ONLY) == 0) { // Found an interceptor that's not read only. if (assign) { CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); Handle result = JSObject::SetPropertyForResult( handle(lookup.holder()), &lookup, name, value, attributes, strict_mode_flag); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } else { return isolate->heap()->undefined_value(); } } } if (assign) { CONVERT_ARG_HANDLE_CHECKED(Object, value, 2); Handle global(isolate->context()->global_object()); Handle result = JSReceiver::SetProperty( global, name, value, attributes, strict_mode_flag); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_InitializeConstGlobal) { SealHandleScope shs(isolate); // 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_object(); // 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.IsFound()) { HandleScope handle_scope(isolate); Handle global(isolate->context()->global_object()); RETURN_IF_EMPTY_HANDLE( isolate, JSObject::SetLocalPropertyIgnoreAttributes(global, name, value, attributes)); return *value; } 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_object()); // 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). if (lookup.IsField()) { FixedArray* properties = global->properties(); int index = lookup.GetFieldIndex().field_index(); if (properties->get(index)->IsTheHole() || !lookup.IsReadOnly()) { properties->set(index, *value); } } else if (lookup.IsNormal()) { if (global->GetNormalizedProperty(&lookup)->IsTheHole() || !lookup.IsReadOnly()) { HandleScope scope(isolate); JSObject::SetNormalizedProperty(Handle(global), &lookup, value); } } else { // Ignore re-initialization of constants that have already been // assigned a constant value. ASSERT(lookup.IsReadOnly() && lookup.IsConstant()); } // 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 native 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_object()); // 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 if (lookup.IsField()) { FixedArray* properties = object->properties(); int index = lookup.GetFieldIndex().field_index(); if (properties->get(index)->IsTheHole()) { properties->set(index, *value); } } else if (lookup.IsNormal()) { if (object->GetNormalizedProperty(&lookup)->IsTheHole()) { JSObject::SetNormalizedProperty(object, &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(index >= 0); RUNTIME_ASSERT(index <= subject->length()); isolate->counters()->regexp_entry_runtime()->Increment(); Handle result = RegExpImpl::Exec(regexp, subject, index, last_match_info); RETURN_IF_EMPTY_HANDLE(isolate, result); return *result; } RUNTIME_FUNCTION(MaybeObject*, Runtime_RegExpConstructResult) { SealHandleScope shs(isolate); 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()->AllocateFixedArray(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; } { DisallowHeapAllocation no_gc; HandleScope scope(isolate); reinterpret_cast(new_object)-> set_map(isolate->native_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) { HandleScope scope(isolate); DisallowHeapAllocation no_allocation; ASSERT(args.length() == 5); CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0); CONVERT_ARG_HANDLE_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->factory()->query_colon_string(); CONVERT_ARG_HANDLE_CHECKED(Object, global, 2); if (!global->IsTrue()) global = isolate->factory()->false_value(); CONVERT_ARG_HANDLE_CHECKED(Object, ignoreCase, 3); if (!ignoreCase->IsTrue()) ignoreCase = isolate->factory()->false_value(); CONVERT_ARG_HANDLE_CHECKED(Object, multiline, 4); if (!multiline->IsTrue()) multiline = isolate->factory()->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); 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); Handle zero(Smi::FromInt(0), isolate); Factory* factory = isolate->factory(); CHECK_NOT_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes( regexp, factory->source_string(), source, final)); CHECK_NOT_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes( regexp, factory->global_string(), global, final)); CHECK_NOT_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes( regexp, factory->ignore_case_string(), ignoreCase, final)); CHECK_NOT_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes( regexp, factory->multiline_string(), multiline, final)); CHECK_NOT_EMPTY_HANDLE(isolate, JSObject::SetLocalPropertyIgnoreAttributes( regexp, factory->last_index_string(), zero, writable)); 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()->InternalizeUtf8String(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_IsClassicModeFunction) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, callable, 0); if (!callable->IsJSFunction()) { HandleScope scope(isolate); bool threw = false; Handle delegate = Execution::TryGetFunctionDelegate( isolate, Handle(callable), &threw); if (threw) return Failure::Exception(); callable = JSFunction::cast(*delegate); } JSFunction* function = JSFunction::cast(callable); SharedFunctionInfo* shared = function->shared(); return isolate->heap()->ToBoolean(shared->is_classic_mode()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_GetDefaultReceiver) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSReceiver, callable, 0); if (!callable->IsJSFunction()) { HandleScope scope(isolate); bool threw = false; Handle delegate = Execution::TryGetFunctionDelegate( isolate, 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* native_context = function->context()->global_object()->native_context(); return native_context->global_object()->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 native context because this might be the RegExp function // from another context which we should not have access to. Handle constructor = Handle( JSFunction::NativeContextFromLiterals(*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) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return f->shared()->name(); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionSetName) { SealHandleScope shs(isolate); 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) { SealHandleScope shs(isolate); 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) { SealHandleScope shs(isolate); 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_FunctionIsGenerator) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); return isolate->heap()->ToBoolean(f->shared()->is_generator()); } RUNTIME_FUNCTION(MaybeObject*, Runtime_FunctionRemovePrototype) { SealHandleScope shs(isolate); ASSERT(args.length() == 1); CONVERT_ARG_CHECKED(JSFunction, f, 0); f->RemovePrototype(); 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