1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/accessors.h"
11 #include "src/allocation-site-scopes.h"
13 #include "src/arguments.h"
14 #include "src/bailout-reason.h"
15 #include "src/base/cpu.h"
16 #include "src/base/platform/platform.h"
17 #include "src/bootstrapper.h"
18 #include "src/codegen.h"
19 #include "src/compilation-cache.h"
20 #include "src/compiler.h"
21 #include "src/conversions.h"
22 #include "src/cpu-profiler.h"
24 #include "src/dateparser-inl.h"
25 #include "src/debug.h"
26 #include "src/deoptimizer.h"
27 #include "src/execution.h"
28 #include "src/full-codegen.h"
29 #include "src/global-handles.h"
30 #include "src/isolate-inl.h"
31 #include "src/json-parser.h"
32 #include "src/json-stringifier.h"
33 #include "src/jsregexp-inl.h"
34 #include "src/jsregexp.h"
35 #include "src/liveedit.h"
36 #include "src/misc-intrinsics.h"
37 #include "src/parser.h"
38 #include "src/prototype.h"
39 #include "src/runtime.h"
40 #include "src/runtime-profiler.h"
41 #include "src/scopeinfo.h"
42 #include "src/smart-pointers.h"
43 #include "src/string-search.h"
45 #include "src/utils.h"
46 #include "src/v8threads.h"
47 #include "src/vm-state-inl.h"
48 #include "third_party/fdlibm/fdlibm.h"
50 #ifdef V8_I18N_SUPPORT
52 #include "unicode/brkiter.h"
53 #include "unicode/calendar.h"
54 #include "unicode/coll.h"
55 #include "unicode/curramt.h"
56 #include "unicode/datefmt.h"
57 #include "unicode/dcfmtsym.h"
58 #include "unicode/decimfmt.h"
59 #include "unicode/dtfmtsym.h"
60 #include "unicode/dtptngen.h"
61 #include "unicode/locid.h"
62 #include "unicode/numfmt.h"
63 #include "unicode/numsys.h"
64 #include "unicode/rbbi.h"
65 #include "unicode/smpdtfmt.h"
66 #include "unicode/timezone.h"
67 #include "unicode/uchar.h"
68 #include "unicode/ucol.h"
69 #include "unicode/ucurr.h"
70 #include "unicode/uloc.h"
71 #include "unicode/unum.h"
72 #include "unicode/uversion.h"
75 #ifndef _STLP_VENDOR_CSTD
76 // STLPort doesn't import fpclassify and isless into the std namespace.
77 using std::fpclassify;
85 #define RUNTIME_ASSERT(value) \
86 if (!(value)) return isolate->ThrowIllegalOperation();
88 #define RUNTIME_ASSERT_HANDLIFIED(value, T) \
90 isolate->ThrowIllegalOperation(); \
91 return MaybeHandle<T>(); \
94 // Cast the given object to a value of the specified type and store
95 // it in a variable with the given name. If the object is not of the
96 // expected type call IllegalOperation and return.
97 #define CONVERT_ARG_CHECKED(Type, name, index) \
98 RUNTIME_ASSERT(args[index]->Is##Type()); \
99 Type* name = Type::cast(args[index]);
101 #define CONVERT_ARG_HANDLE_CHECKED(Type, name, index) \
102 RUNTIME_ASSERT(args[index]->Is##Type()); \
103 Handle<Type> name = args.at<Type>(index);
105 #define CONVERT_NUMBER_ARG_HANDLE_CHECKED(name, index) \
106 RUNTIME_ASSERT(args[index]->IsNumber()); \
107 Handle<Object> name = args.at<Object>(index);
109 // Cast the given object to a boolean and store it in a variable with
110 // the given name. If the object is not a boolean call IllegalOperation
112 #define CONVERT_BOOLEAN_ARG_CHECKED(name, index) \
113 RUNTIME_ASSERT(args[index]->IsBoolean()); \
114 bool name = args[index]->IsTrue();
116 // Cast the given argument to a Smi and store its value in an int variable
117 // with the given name. If the argument is not a Smi call IllegalOperation
119 #define CONVERT_SMI_ARG_CHECKED(name, index) \
120 RUNTIME_ASSERT(args[index]->IsSmi()); \
121 int name = args.smi_at(index);
123 // Cast the given argument to a double and store it in a variable with
124 // the given name. If the argument is not a number (as opposed to
125 // the number not-a-number) call IllegalOperation and return.
126 #define CONVERT_DOUBLE_ARG_CHECKED(name, index) \
127 RUNTIME_ASSERT(args[index]->IsNumber()); \
128 double name = args.number_at(index);
130 // Call the specified converter on the object *comand store the result in
131 // a variable of the specified type with the given name. If the
132 // object is not a Number call IllegalOperation and return.
133 #define CONVERT_NUMBER_CHECKED(type, name, Type, obj) \
134 RUNTIME_ASSERT(obj->IsNumber()); \
135 type name = NumberTo##Type(obj);
138 // Cast the given argument to PropertyDetails and store its value in a
139 // variable with the given name. If the argument is not a Smi call
140 // IllegalOperation and return.
141 #define CONVERT_PROPERTY_DETAILS_CHECKED(name, index) \
142 RUNTIME_ASSERT(args[index]->IsSmi()); \
143 PropertyDetails name = PropertyDetails(Smi::cast(args[index]));
146 // Assert that the given argument has a valid value for a StrictMode
147 // and store it in a StrictMode variable with the given name.
148 #define CONVERT_STRICT_MODE_ARG_CHECKED(name, index) \
149 RUNTIME_ASSERT(args[index]->IsSmi()); \
150 RUNTIME_ASSERT(args.smi_at(index) == STRICT || \
151 args.smi_at(index) == SLOPPY); \
152 StrictMode name = static_cast<StrictMode>(args.smi_at(index));
155 // Assert that the given argument is a number within the Int32 range
156 // and convert it to int32_t. If the argument is not an Int32 call
157 // IllegalOperation and return.
158 #define CONVERT_INT32_ARG_CHECKED(name, index) \
159 RUNTIME_ASSERT(args[index]->IsNumber()); \
161 RUNTIME_ASSERT(args[index]->ToInt32(&name));
164 static Handle<Map> ComputeObjectLiteralMap(
165 Handle<Context> context,
166 Handle<FixedArray> constant_properties,
167 bool* is_result_from_cache) {
168 Isolate* isolate = context->GetIsolate();
169 int properties_length = constant_properties->length();
170 int number_of_properties = properties_length / 2;
171 // Check that there are only internal strings and array indices among keys.
172 int number_of_string_keys = 0;
173 for (int p = 0; p != properties_length; p += 2) {
174 Object* key = constant_properties->get(p);
175 uint32_t element_index = 0;
176 if (key->IsInternalizedString()) {
177 number_of_string_keys++;
178 } else if (key->ToArrayIndex(&element_index)) {
179 // An index key does not require space in the property backing store.
180 number_of_properties--;
182 // Bail out as a non-internalized-string non-index key makes caching
184 // DCHECK to make sure that the if condition after the loop is false.
185 DCHECK(number_of_string_keys != number_of_properties);
189 // If we only have internalized strings and array indices among keys then we
190 // can use the map cache in the native context.
191 const int kMaxKeys = 10;
192 if ((number_of_string_keys == number_of_properties) &&
193 (number_of_string_keys < kMaxKeys)) {
194 // Create the fixed array with the key.
195 Handle<FixedArray> keys =
196 isolate->factory()->NewFixedArray(number_of_string_keys);
197 if (number_of_string_keys > 0) {
199 for (int p = 0; p < properties_length; p += 2) {
200 Object* key = constant_properties->get(p);
201 if (key->IsInternalizedString()) {
202 keys->set(index++, key);
205 DCHECK(index == number_of_string_keys);
207 *is_result_from_cache = true;
208 return isolate->factory()->ObjectLiteralMapFromCache(context, keys);
210 *is_result_from_cache = false;
211 return Map::Create(isolate, number_of_properties);
215 MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate(
217 Handle<FixedArray> literals,
218 Handle<FixedArray> constant_properties);
221 MUST_USE_RESULT static MaybeHandle<Object> CreateObjectLiteralBoilerplate(
223 Handle<FixedArray> literals,
224 Handle<FixedArray> constant_properties,
225 bool should_have_fast_elements,
226 bool has_function_literal) {
227 // Get the native context from the literals array. This is the
228 // context in which the function was created and we use the object
229 // function from this context to create the object literal. We do
230 // not use the object function from the current native context
231 // because this might be the object function from another context
232 // which we should not have access to.
233 Handle<Context> context =
234 Handle<Context>(JSFunction::NativeContextFromLiterals(*literals));
236 // In case we have function literals, we want the object to be in
237 // slow properties mode for now. We don't go in the map cache because
238 // maps with constant functions can't be shared if the functions are
239 // not the same (which is the common case).
240 bool is_result_from_cache = false;
241 Handle<Map> map = has_function_literal
242 ? Handle<Map>(context->object_function()->initial_map())
243 : ComputeObjectLiteralMap(context,
245 &is_result_from_cache);
247 PretenureFlag pretenure_flag =
248 isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED;
250 Handle<JSObject> boilerplate =
251 isolate->factory()->NewJSObjectFromMap(map, pretenure_flag);
253 // Normalize the elements of the boilerplate to save space if needed.
254 if (!should_have_fast_elements) JSObject::NormalizeElements(boilerplate);
256 // Add the constant properties to the boilerplate.
257 int length = constant_properties->length();
258 bool should_transform =
259 !is_result_from_cache && boilerplate->HasFastProperties();
260 bool should_normalize = should_transform || has_function_literal;
261 if (should_normalize) {
262 // TODO(verwaest): We might not want to ever normalize here.
263 JSObject::NormalizeProperties(
264 boilerplate, KEEP_INOBJECT_PROPERTIES, length / 2);
266 // TODO(verwaest): Support tracking representations in the boilerplate.
267 for (int index = 0; index < length; index +=2) {
268 Handle<Object> key(constant_properties->get(index+0), isolate);
269 Handle<Object> value(constant_properties->get(index+1), isolate);
270 if (value->IsFixedArray()) {
271 // The value contains the constant_properties of a
272 // simple object or array literal.
273 Handle<FixedArray> array = Handle<FixedArray>::cast(value);
274 ASSIGN_RETURN_ON_EXCEPTION(
276 CreateLiteralBoilerplate(isolate, literals, array),
279 MaybeHandle<Object> maybe_result;
280 uint32_t element_index = 0;
281 if (key->IsInternalizedString()) {
282 if (Handle<String>::cast(key)->AsArrayIndex(&element_index)) {
283 // Array index as string (uint32).
284 if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate);
286 JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY);
288 Handle<String> name(String::cast(*key));
289 DCHECK(!name->AsArrayIndex(&element_index));
290 maybe_result = JSObject::SetOwnPropertyIgnoreAttributes(
291 boilerplate, name, value, NONE);
293 } else if (key->ToArrayIndex(&element_index)) {
294 // Array index (uint32).
295 if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate);
297 JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY);
299 // Non-uint32 number.
300 DCHECK(key->IsNumber());
301 double num = key->Number();
303 Vector<char> buffer(arr, arraysize(arr));
304 const char* str = DoubleToCString(num, buffer);
305 Handle<String> name = isolate->factory()->NewStringFromAsciiChecked(str);
306 maybe_result = JSObject::SetOwnPropertyIgnoreAttributes(boilerplate, name,
309 // If setting the property on the boilerplate throws an
310 // exception, the exception is converted to an empty handle in
311 // the handle based operations. In that case, we need to
312 // convert back to an exception.
313 RETURN_ON_EXCEPTION(isolate, maybe_result, Object);
316 // Transform to fast properties if necessary. For object literals with
317 // containing function literals we defer this operation until after all
318 // computed properties have been assigned so that we can generate
319 // constant function properties.
320 if (should_transform && !has_function_literal) {
321 JSObject::MigrateSlowToFast(
322 boilerplate, boilerplate->map()->unused_property_fields());
329 MUST_USE_RESULT static MaybeHandle<Object> TransitionElements(
330 Handle<Object> object,
331 ElementsKind to_kind,
333 HandleScope scope(isolate);
334 if (!object->IsJSObject()) {
335 isolate->ThrowIllegalOperation();
336 return MaybeHandle<Object>();
338 ElementsKind from_kind =
339 Handle<JSObject>::cast(object)->map()->elements_kind();
340 if (Map::IsValidElementsTransition(from_kind, to_kind)) {
341 JSObject::TransitionElementsKind(Handle<JSObject>::cast(object), to_kind);
344 isolate->ThrowIllegalOperation();
345 return MaybeHandle<Object>();
349 MaybeHandle<Object> Runtime::CreateArrayLiteralBoilerplate(
351 Handle<FixedArray> literals,
352 Handle<FixedArray> elements) {
353 // Create the JSArray.
354 Handle<JSFunction> constructor(
355 JSFunction::NativeContextFromLiterals(*literals)->array_function());
357 PretenureFlag pretenure_flag =
358 isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED;
360 Handle<JSArray> object = Handle<JSArray>::cast(
361 isolate->factory()->NewJSObject(constructor, pretenure_flag));
363 ElementsKind constant_elements_kind =
364 static_cast<ElementsKind>(Smi::cast(elements->get(0))->value());
365 Handle<FixedArrayBase> constant_elements_values(
366 FixedArrayBase::cast(elements->get(1)));
368 { DisallowHeapAllocation no_gc;
369 DCHECK(IsFastElementsKind(constant_elements_kind));
370 Context* native_context = isolate->context()->native_context();
371 Object* maps_array = native_context->js_array_maps();
372 DCHECK(!maps_array->IsUndefined());
373 Object* map = FixedArray::cast(maps_array)->get(constant_elements_kind);
374 object->set_map(Map::cast(map));
377 Handle<FixedArrayBase> copied_elements_values;
378 if (IsFastDoubleElementsKind(constant_elements_kind)) {
379 copied_elements_values = isolate->factory()->CopyFixedDoubleArray(
380 Handle<FixedDoubleArray>::cast(constant_elements_values));
382 DCHECK(IsFastSmiOrObjectElementsKind(constant_elements_kind));
384 (constant_elements_values->map() ==
385 isolate->heap()->fixed_cow_array_map());
387 copied_elements_values = constant_elements_values;
389 Handle<FixedArray> fixed_array_values =
390 Handle<FixedArray>::cast(copied_elements_values);
391 for (int i = 0; i < fixed_array_values->length(); i++) {
392 DCHECK(!fixed_array_values->get(i)->IsFixedArray());
396 Handle<FixedArray> fixed_array_values =
397 Handle<FixedArray>::cast(constant_elements_values);
398 Handle<FixedArray> fixed_array_values_copy =
399 isolate->factory()->CopyFixedArray(fixed_array_values);
400 copied_elements_values = fixed_array_values_copy;
401 for (int i = 0; i < fixed_array_values->length(); i++) {
402 if (fixed_array_values->get(i)->IsFixedArray()) {
403 // The value contains the constant_properties of a
404 // simple object or array literal.
405 Handle<FixedArray> fa(FixedArray::cast(fixed_array_values->get(i)));
406 Handle<Object> result;
407 ASSIGN_RETURN_ON_EXCEPTION(
409 CreateLiteralBoilerplate(isolate, literals, fa),
411 fixed_array_values_copy->set(i, *result);
416 object->set_elements(*copied_elements_values);
417 object->set_length(Smi::FromInt(copied_elements_values->length()));
419 JSObject::ValidateElements(object);
424 MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate(
426 Handle<FixedArray> literals,
427 Handle<FixedArray> array) {
428 Handle<FixedArray> elements = CompileTimeValue::GetElements(array);
429 const bool kHasNoFunctionLiteral = false;
430 switch (CompileTimeValue::GetLiteralType(array)) {
431 case CompileTimeValue::OBJECT_LITERAL_FAST_ELEMENTS:
432 return CreateObjectLiteralBoilerplate(isolate,
436 kHasNoFunctionLiteral);
437 case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS:
438 return CreateObjectLiteralBoilerplate(isolate,
442 kHasNoFunctionLiteral);
443 case CompileTimeValue::ARRAY_LITERAL:
444 return Runtime::CreateArrayLiteralBoilerplate(
445 isolate, literals, elements);
448 return MaybeHandle<Object>();
453 RUNTIME_FUNCTION(Runtime_CreateObjectLiteral) {
454 HandleScope scope(isolate);
455 DCHECK(args.length() == 4);
456 CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
457 CONVERT_SMI_ARG_CHECKED(literals_index, 1);
458 CONVERT_ARG_HANDLE_CHECKED(FixedArray, constant_properties, 2);
459 CONVERT_SMI_ARG_CHECKED(flags, 3);
460 bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0;
461 bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0;
463 RUNTIME_ASSERT(literals_index >= 0 && literals_index < literals->length());
465 // Check if boilerplate exists. If not, create it first.
466 Handle<Object> literal_site(literals->get(literals_index), isolate);
467 Handle<AllocationSite> site;
468 Handle<JSObject> boilerplate;
469 if (*literal_site == isolate->heap()->undefined_value()) {
470 Handle<Object> raw_boilerplate;
471 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
472 isolate, raw_boilerplate,
473 CreateObjectLiteralBoilerplate(
477 should_have_fast_elements,
478 has_function_literal));
479 boilerplate = Handle<JSObject>::cast(raw_boilerplate);
481 AllocationSiteCreationContext creation_context(isolate);
482 site = creation_context.EnterNewScope();
483 RETURN_FAILURE_ON_EXCEPTION(
485 JSObject::DeepWalk(boilerplate, &creation_context));
486 creation_context.ExitScope(site, boilerplate);
488 // Update the functions literal and return the boilerplate.
489 literals->set(literals_index, *site);
491 site = Handle<AllocationSite>::cast(literal_site);
492 boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()),
496 AllocationSiteUsageContext usage_context(isolate, site, true);
497 usage_context.EnterNewScope();
498 MaybeHandle<Object> maybe_copy = JSObject::DeepCopy(
499 boilerplate, &usage_context);
500 usage_context.ExitScope(site, boilerplate);
502 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, copy, maybe_copy);
507 MUST_USE_RESULT static MaybeHandle<AllocationSite> GetLiteralAllocationSite(
509 Handle<FixedArray> literals,
511 Handle<FixedArray> elements) {
512 // Check if boilerplate exists. If not, create it first.
513 Handle<Object> literal_site(literals->get(literals_index), isolate);
514 Handle<AllocationSite> site;
515 if (*literal_site == isolate->heap()->undefined_value()) {
516 DCHECK(*elements != isolate->heap()->empty_fixed_array());
517 Handle<Object> boilerplate;
518 ASSIGN_RETURN_ON_EXCEPTION(
519 isolate, boilerplate,
520 Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements),
523 AllocationSiteCreationContext creation_context(isolate);
524 site = creation_context.EnterNewScope();
525 if (JSObject::DeepWalk(Handle<JSObject>::cast(boilerplate),
526 &creation_context).is_null()) {
527 return Handle<AllocationSite>::null();
529 creation_context.ExitScope(site, Handle<JSObject>::cast(boilerplate));
531 literals->set(literals_index, *site);
533 site = Handle<AllocationSite>::cast(literal_site);
540 static MaybeHandle<JSObject> CreateArrayLiteralImpl(Isolate* isolate,
541 Handle<FixedArray> literals,
543 Handle<FixedArray> elements,
545 RUNTIME_ASSERT_HANDLIFIED(literals_index >= 0 &&
546 literals_index < literals->length(), JSObject);
547 Handle<AllocationSite> site;
548 ASSIGN_RETURN_ON_EXCEPTION(
550 GetLiteralAllocationSite(isolate, literals, literals_index, elements),
553 bool enable_mementos = (flags & ArrayLiteral::kDisableMementos) == 0;
554 Handle<JSObject> boilerplate(JSObject::cast(site->transition_info()));
555 AllocationSiteUsageContext usage_context(isolate, site, enable_mementos);
556 usage_context.EnterNewScope();
557 JSObject::DeepCopyHints hints = (flags & ArrayLiteral::kShallowElements) == 0
559 : JSObject::kObjectIsShallow;
560 MaybeHandle<JSObject> copy = JSObject::DeepCopy(boilerplate, &usage_context,
562 usage_context.ExitScope(site, boilerplate);
567 RUNTIME_FUNCTION(Runtime_CreateArrayLiteral) {
568 HandleScope scope(isolate);
569 DCHECK(args.length() == 4);
570 CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
571 CONVERT_SMI_ARG_CHECKED(literals_index, 1);
572 CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2);
573 CONVERT_SMI_ARG_CHECKED(flags, 3);
575 Handle<JSObject> result;
576 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
577 CreateArrayLiteralImpl(isolate, literals, literals_index, elements,
583 RUNTIME_FUNCTION(Runtime_CreateArrayLiteralStubBailout) {
584 HandleScope scope(isolate);
585 DCHECK(args.length() == 3);
586 CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
587 CONVERT_SMI_ARG_CHECKED(literals_index, 1);
588 CONVERT_ARG_HANDLE_CHECKED(FixedArray, elements, 2);
590 Handle<JSObject> result;
591 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
592 CreateArrayLiteralImpl(isolate, literals, literals_index, elements,
593 ArrayLiteral::kShallowElements));
598 RUNTIME_FUNCTION(Runtime_CreateSymbol) {
599 HandleScope scope(isolate);
600 DCHECK(args.length() == 1);
601 CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
602 RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
603 Handle<Symbol> symbol = isolate->factory()->NewSymbol();
604 if (name->IsString()) symbol->set_name(*name);
609 RUNTIME_FUNCTION(Runtime_CreatePrivateSymbol) {
610 HandleScope scope(isolate);
611 DCHECK(args.length() == 1);
612 CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
613 RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
614 Handle<Symbol> symbol = isolate->factory()->NewPrivateSymbol();
615 if (name->IsString()) symbol->set_name(*name);
620 RUNTIME_FUNCTION(Runtime_CreatePrivateOwnSymbol) {
621 HandleScope scope(isolate);
622 DCHECK(args.length() == 1);
623 CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
624 RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
625 Handle<Symbol> symbol = isolate->factory()->NewPrivateOwnSymbol();
626 if (name->IsString()) symbol->set_name(*name);
631 RUNTIME_FUNCTION(Runtime_CreateGlobalPrivateOwnSymbol) {
632 HandleScope scope(isolate);
633 DCHECK(args.length() == 1);
634 CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
635 Handle<JSObject> registry = isolate->GetSymbolRegistry();
636 Handle<String> part = isolate->factory()->private_intern_string();
637 Handle<Object> privates;
638 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
639 isolate, privates, Object::GetPropertyOrElement(registry, part));
640 Handle<Object> symbol;
641 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
642 isolate, symbol, Object::GetPropertyOrElement(privates, name));
643 if (!symbol->IsSymbol()) {
644 DCHECK(symbol->IsUndefined());
645 symbol = isolate->factory()->NewPrivateSymbol();
646 Handle<Symbol>::cast(symbol)->set_name(*name);
647 Handle<Symbol>::cast(symbol)->set_is_own(true);
648 JSObject::SetProperty(Handle<JSObject>::cast(privates), name, symbol,
655 RUNTIME_FUNCTION(Runtime_NewSymbolWrapper) {
656 HandleScope scope(isolate);
657 DCHECK(args.length() == 1);
658 CONVERT_ARG_HANDLE_CHECKED(Symbol, symbol, 0);
659 return *Object::ToObject(isolate, symbol).ToHandleChecked();
663 RUNTIME_FUNCTION(Runtime_SymbolDescription) {
664 SealHandleScope shs(isolate);
665 DCHECK(args.length() == 1);
666 CONVERT_ARG_CHECKED(Symbol, symbol, 0);
667 return symbol->name();
671 RUNTIME_FUNCTION(Runtime_SymbolRegistry) {
672 HandleScope scope(isolate);
673 DCHECK(args.length() == 0);
674 return *isolate->GetSymbolRegistry();
678 RUNTIME_FUNCTION(Runtime_SymbolIsPrivate) {
679 SealHandleScope shs(isolate);
680 DCHECK(args.length() == 1);
681 CONVERT_ARG_CHECKED(Symbol, symbol, 0);
682 return isolate->heap()->ToBoolean(symbol->is_private());
686 RUNTIME_FUNCTION(Runtime_CreateJSProxy) {
687 HandleScope scope(isolate);
688 DCHECK(args.length() == 2);
689 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, handler, 0);
690 CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
691 if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value();
692 return *isolate->factory()->NewJSProxy(handler, prototype);
696 RUNTIME_FUNCTION(Runtime_CreateJSFunctionProxy) {
697 HandleScope scope(isolate);
698 DCHECK(args.length() == 4);
699 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, handler, 0);
700 CONVERT_ARG_HANDLE_CHECKED(Object, call_trap, 1);
701 RUNTIME_ASSERT(call_trap->IsJSFunction() || call_trap->IsJSFunctionProxy());
702 CONVERT_ARG_HANDLE_CHECKED(JSFunction, construct_trap, 2);
703 CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 3);
704 if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value();
705 return *isolate->factory()->NewJSFunctionProxy(
706 handler, call_trap, construct_trap, prototype);
710 RUNTIME_FUNCTION(Runtime_IsJSProxy) {
711 SealHandleScope shs(isolate);
712 DCHECK(args.length() == 1);
713 CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
714 return isolate->heap()->ToBoolean(obj->IsJSProxy());
718 RUNTIME_FUNCTION(Runtime_IsJSFunctionProxy) {
719 SealHandleScope shs(isolate);
720 DCHECK(args.length() == 1);
721 CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
722 return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy());
726 RUNTIME_FUNCTION(Runtime_GetHandler) {
727 SealHandleScope shs(isolate);
728 DCHECK(args.length() == 1);
729 CONVERT_ARG_CHECKED(JSProxy, proxy, 0);
730 return proxy->handler();
734 RUNTIME_FUNCTION(Runtime_GetCallTrap) {
735 SealHandleScope shs(isolate);
736 DCHECK(args.length() == 1);
737 CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0);
738 return proxy->call_trap();
742 RUNTIME_FUNCTION(Runtime_GetConstructTrap) {
743 SealHandleScope shs(isolate);
744 DCHECK(args.length() == 1);
745 CONVERT_ARG_CHECKED(JSFunctionProxy, proxy, 0);
746 return proxy->construct_trap();
750 RUNTIME_FUNCTION(Runtime_Fix) {
751 HandleScope scope(isolate);
752 DCHECK(args.length() == 1);
753 CONVERT_ARG_HANDLE_CHECKED(JSProxy, proxy, 0);
755 return isolate->heap()->undefined_value();
759 void Runtime::FreeArrayBuffer(Isolate* isolate,
760 JSArrayBuffer* phantom_array_buffer) {
761 if (phantom_array_buffer->should_be_freed()) {
762 DCHECK(phantom_array_buffer->is_external());
763 free(phantom_array_buffer->backing_store());
765 if (phantom_array_buffer->is_external()) return;
767 size_t allocated_length = NumberToSize(
768 isolate, phantom_array_buffer->byte_length());
770 reinterpret_cast<v8::Isolate*>(isolate)
771 ->AdjustAmountOfExternalAllocatedMemory(
772 -static_cast<int64_t>(allocated_length));
773 CHECK(V8::ArrayBufferAllocator() != NULL);
774 V8::ArrayBufferAllocator()->Free(
775 phantom_array_buffer->backing_store(),
780 void Runtime::SetupArrayBuffer(Isolate* isolate,
781 Handle<JSArrayBuffer> array_buffer,
784 size_t allocated_length) {
785 DCHECK(array_buffer->GetInternalFieldCount() ==
786 v8::ArrayBuffer::kInternalFieldCount);
787 for (int i = 0; i < v8::ArrayBuffer::kInternalFieldCount; i++) {
788 array_buffer->SetInternalField(i, Smi::FromInt(0));
790 array_buffer->set_backing_store(data);
791 array_buffer->set_flag(Smi::FromInt(0));
792 array_buffer->set_is_external(is_external);
794 Handle<Object> byte_length =
795 isolate->factory()->NewNumberFromSize(allocated_length);
796 CHECK(byte_length->IsSmi() || byte_length->IsHeapNumber());
797 array_buffer->set_byte_length(*byte_length);
799 array_buffer->set_weak_next(isolate->heap()->array_buffers_list());
800 isolate->heap()->set_array_buffers_list(*array_buffer);
801 array_buffer->set_weak_first_view(isolate->heap()->undefined_value());
805 bool Runtime::SetupArrayBufferAllocatingData(
807 Handle<JSArrayBuffer> array_buffer,
808 size_t allocated_length,
811 CHECK(V8::ArrayBufferAllocator() != NULL);
812 if (allocated_length != 0) {
814 data = V8::ArrayBufferAllocator()->Allocate(allocated_length);
817 V8::ArrayBufferAllocator()->AllocateUninitialized(allocated_length);
819 if (data == NULL) return false;
824 SetupArrayBuffer(isolate, array_buffer, false, data, allocated_length);
826 reinterpret_cast<v8::Isolate*>(isolate)
827 ->AdjustAmountOfExternalAllocatedMemory(allocated_length);
833 void Runtime::NeuterArrayBuffer(Handle<JSArrayBuffer> array_buffer) {
834 Isolate* isolate = array_buffer->GetIsolate();
835 for (Handle<Object> view_obj(array_buffer->weak_first_view(), isolate);
836 !view_obj->IsUndefined();) {
837 Handle<JSArrayBufferView> view(JSArrayBufferView::cast(*view_obj));
838 if (view->IsJSTypedArray()) {
839 JSTypedArray::cast(*view)->Neuter();
840 } else if (view->IsJSDataView()) {
841 JSDataView::cast(*view)->Neuter();
845 view_obj = handle(view->weak_next(), isolate);
847 array_buffer->Neuter();
851 RUNTIME_FUNCTION(Runtime_ArrayBufferInitialize) {
852 HandleScope scope(isolate);
853 DCHECK(args.length() == 2);
854 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, holder, 0);
855 CONVERT_NUMBER_ARG_HANDLE_CHECKED(byteLength, 1);
856 if (!holder->byte_length()->IsUndefined()) {
857 // ArrayBuffer is already initialized; probably a fuzz test.
860 size_t allocated_length = 0;
861 if (!TryNumberToSize(isolate, *byteLength, &allocated_length)) {
862 THROW_NEW_ERROR_RETURN_FAILURE(
863 isolate, NewRangeError("invalid_array_buffer_length",
864 HandleVector<Object>(NULL, 0)));
866 if (!Runtime::SetupArrayBufferAllocatingData(isolate,
867 holder, allocated_length)) {
868 THROW_NEW_ERROR_RETURN_FAILURE(
869 isolate, NewRangeError("invalid_array_buffer_length",
870 HandleVector<Object>(NULL, 0)));
876 RUNTIME_FUNCTION(Runtime_ArrayBufferGetByteLength) {
877 SealHandleScope shs(isolate);
878 DCHECK(args.length() == 1);
879 CONVERT_ARG_CHECKED(JSArrayBuffer, holder, 0);
880 return holder->byte_length();
884 RUNTIME_FUNCTION(Runtime_ArrayBufferSliceImpl) {
885 HandleScope scope(isolate);
886 DCHECK(args.length() == 3);
887 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, source, 0);
888 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, target, 1);
889 CONVERT_NUMBER_ARG_HANDLE_CHECKED(first, 2);
890 RUNTIME_ASSERT(!source.is_identical_to(target));
892 RUNTIME_ASSERT(TryNumberToSize(isolate, *first, &start));
893 size_t target_length = NumberToSize(isolate, target->byte_length());
895 if (target_length == 0) return isolate->heap()->undefined_value();
897 size_t source_byte_length = NumberToSize(isolate, source->byte_length());
898 RUNTIME_ASSERT(start <= source_byte_length);
899 RUNTIME_ASSERT(source_byte_length - start >= target_length);
900 uint8_t* source_data = reinterpret_cast<uint8_t*>(source->backing_store());
901 uint8_t* target_data = reinterpret_cast<uint8_t*>(target->backing_store());
902 CopyBytes(target_data, source_data + start, target_length);
903 return isolate->heap()->undefined_value();
907 RUNTIME_FUNCTION(Runtime_ArrayBufferIsView) {
908 HandleScope scope(isolate);
909 DCHECK(args.length() == 1);
910 CONVERT_ARG_CHECKED(Object, object, 0);
911 return isolate->heap()->ToBoolean(object->IsJSArrayBufferView());
915 RUNTIME_FUNCTION(Runtime_ArrayBufferNeuter) {
916 HandleScope scope(isolate);
917 DCHECK(args.length() == 1);
918 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, array_buffer, 0);
919 if (array_buffer->backing_store() == NULL) {
920 CHECK(Smi::FromInt(0) == array_buffer->byte_length());
921 return isolate->heap()->undefined_value();
923 DCHECK(!array_buffer->is_external());
924 void* backing_store = array_buffer->backing_store();
925 size_t byte_length = NumberToSize(isolate, array_buffer->byte_length());
926 array_buffer->set_is_external(true);
927 Runtime::NeuterArrayBuffer(array_buffer);
928 V8::ArrayBufferAllocator()->Free(backing_store, byte_length);
929 return isolate->heap()->undefined_value();
933 void Runtime::ArrayIdToTypeAndSize(
935 ExternalArrayType* array_type,
936 ElementsKind* external_elements_kind,
937 ElementsKind* fixed_elements_kind,
938 size_t* element_size) {
940 #define ARRAY_ID_CASE(Type, type, TYPE, ctype, size) \
941 case ARRAY_ID_##TYPE: \
942 *array_type = kExternal##Type##Array; \
943 *external_elements_kind = EXTERNAL_##TYPE##_ELEMENTS; \
944 *fixed_elements_kind = TYPE##_ELEMENTS; \
945 *element_size = size; \
948 TYPED_ARRAYS(ARRAY_ID_CASE)
957 RUNTIME_FUNCTION(Runtime_TypedArrayInitialize) {
958 HandleScope scope(isolate);
959 DCHECK(args.length() == 5);
960 CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0);
961 CONVERT_SMI_ARG_CHECKED(arrayId, 1);
962 CONVERT_ARG_HANDLE_CHECKED(Object, maybe_buffer, 2);
963 CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_offset_object, 3);
964 CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_length_object, 4);
966 RUNTIME_ASSERT(arrayId >= Runtime::ARRAY_ID_FIRST &&
967 arrayId <= Runtime::ARRAY_ID_LAST);
969 ExternalArrayType array_type = kExternalInt8Array; // Bogus initialization.
970 size_t element_size = 1; // Bogus initialization.
971 ElementsKind external_elements_kind =
972 EXTERNAL_INT8_ELEMENTS; // Bogus initialization.
973 ElementsKind fixed_elements_kind = INT8_ELEMENTS; // Bogus initialization.
974 Runtime::ArrayIdToTypeAndSize(arrayId,
976 &external_elements_kind,
977 &fixed_elements_kind,
979 RUNTIME_ASSERT(holder->map()->elements_kind() == fixed_elements_kind);
981 size_t byte_offset = 0;
982 size_t byte_length = 0;
983 RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_offset_object, &byte_offset));
984 RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_length_object, &byte_length));
986 if (maybe_buffer->IsJSArrayBuffer()) {
987 Handle<JSArrayBuffer> buffer = Handle<JSArrayBuffer>::cast(maybe_buffer);
988 size_t array_buffer_byte_length =
989 NumberToSize(isolate, buffer->byte_length());
990 RUNTIME_ASSERT(byte_offset <= array_buffer_byte_length);
991 RUNTIME_ASSERT(array_buffer_byte_length - byte_offset >= byte_length);
993 RUNTIME_ASSERT(maybe_buffer->IsNull());
996 RUNTIME_ASSERT(byte_length % element_size == 0);
997 size_t length = byte_length / element_size;
999 if (length > static_cast<unsigned>(Smi::kMaxValue)) {
1000 THROW_NEW_ERROR_RETURN_FAILURE(
1001 isolate, NewRangeError("invalid_typed_array_length",
1002 HandleVector<Object>(NULL, 0)));
1005 // All checks are done, now we can modify objects.
1007 DCHECK(holder->GetInternalFieldCount() ==
1008 v8::ArrayBufferView::kInternalFieldCount);
1009 for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) {
1010 holder->SetInternalField(i, Smi::FromInt(0));
1012 Handle<Object> length_obj = isolate->factory()->NewNumberFromSize(length);
1013 holder->set_length(*length_obj);
1014 holder->set_byte_offset(*byte_offset_object);
1015 holder->set_byte_length(*byte_length_object);
1017 if (!maybe_buffer->IsNull()) {
1018 Handle<JSArrayBuffer> buffer = Handle<JSArrayBuffer>::cast(maybe_buffer);
1019 holder->set_buffer(*buffer);
1020 holder->set_weak_next(buffer->weak_first_view());
1021 buffer->set_weak_first_view(*holder);
1023 Handle<ExternalArray> elements =
1024 isolate->factory()->NewExternalArray(
1025 static_cast<int>(length), array_type,
1026 static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1028 JSObject::GetElementsTransitionMap(holder, external_elements_kind);
1029 JSObject::SetMapAndElements(holder, map, elements);
1030 DCHECK(IsExternalArrayElementsKind(holder->map()->elements_kind()));
1032 holder->set_buffer(Smi::FromInt(0));
1033 holder->set_weak_next(isolate->heap()->undefined_value());
1034 Handle<FixedTypedArrayBase> elements =
1035 isolate->factory()->NewFixedTypedArray(
1036 static_cast<int>(length), array_type);
1037 holder->set_elements(*elements);
1039 return isolate->heap()->undefined_value();
1043 // Initializes a typed array from an array-like object.
1044 // If an array-like object happens to be a typed array of the same type,
1045 // initializes backing store using memove.
1047 // Returns true if backing store was initialized or false otherwise.
1048 RUNTIME_FUNCTION(Runtime_TypedArrayInitializeFromArrayLike) {
1049 HandleScope scope(isolate);
1050 DCHECK(args.length() == 4);
1051 CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0);
1052 CONVERT_SMI_ARG_CHECKED(arrayId, 1);
1053 CONVERT_ARG_HANDLE_CHECKED(Object, source, 2);
1054 CONVERT_NUMBER_ARG_HANDLE_CHECKED(length_obj, 3);
1056 RUNTIME_ASSERT(arrayId >= Runtime::ARRAY_ID_FIRST &&
1057 arrayId <= Runtime::ARRAY_ID_LAST);
1059 ExternalArrayType array_type = kExternalInt8Array; // Bogus initialization.
1060 size_t element_size = 1; // Bogus initialization.
1061 ElementsKind external_elements_kind =
1062 EXTERNAL_INT8_ELEMENTS; // Bogus intialization.
1063 ElementsKind fixed_elements_kind = INT8_ELEMENTS; // Bogus initialization.
1064 Runtime::ArrayIdToTypeAndSize(arrayId,
1066 &external_elements_kind,
1067 &fixed_elements_kind,
1070 RUNTIME_ASSERT(holder->map()->elements_kind() == fixed_elements_kind);
1072 Handle<JSArrayBuffer> buffer = isolate->factory()->NewJSArrayBuffer();
1073 if (source->IsJSTypedArray() &&
1074 JSTypedArray::cast(*source)->type() == array_type) {
1075 length_obj = Handle<Object>(JSTypedArray::cast(*source)->length(), isolate);
1078 RUNTIME_ASSERT(TryNumberToSize(isolate, *length_obj, &length));
1080 if ((length > static_cast<unsigned>(Smi::kMaxValue)) ||
1081 (length > (kMaxInt / element_size))) {
1082 THROW_NEW_ERROR_RETURN_FAILURE(
1083 isolate, NewRangeError("invalid_typed_array_length",
1084 HandleVector<Object>(NULL, 0)));
1086 size_t byte_length = length * element_size;
1088 DCHECK(holder->GetInternalFieldCount() ==
1089 v8::ArrayBufferView::kInternalFieldCount);
1090 for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) {
1091 holder->SetInternalField(i, Smi::FromInt(0));
1094 // NOTE: not initializing backing store.
1095 // We assume that the caller of this function will initialize holder
1097 // for(i = 0; i < length; i++) { holder[i] = source[i]; }
1098 // We assume that the caller of this function is always a typed array
1100 // If source is a typed array, this loop will always run to completion,
1101 // so we are sure that the backing store will be initialized.
1102 // Otherwise, the indexing operation might throw, so the loop will not
1103 // run to completion and the typed array might remain partly initialized.
1104 // However we further assume that the caller of this function is a typed array
1105 // constructor, and the exception will propagate out of the constructor,
1106 // therefore uninitialized memory will not be accessible by a user program.
1108 // TODO(dslomov): revise this once we support subclassing.
1110 if (!Runtime::SetupArrayBufferAllocatingData(
1111 isolate, buffer, byte_length, false)) {
1112 THROW_NEW_ERROR_RETURN_FAILURE(
1113 isolate, NewRangeError("invalid_array_buffer_length",
1114 HandleVector<Object>(NULL, 0)));
1117 holder->set_buffer(*buffer);
1118 holder->set_byte_offset(Smi::FromInt(0));
1119 Handle<Object> byte_length_obj(
1120 isolate->factory()->NewNumberFromSize(byte_length));
1121 holder->set_byte_length(*byte_length_obj);
1122 holder->set_length(*length_obj);
1123 holder->set_weak_next(buffer->weak_first_view());
1124 buffer->set_weak_first_view(*holder);
1126 Handle<ExternalArray> elements =
1127 isolate->factory()->NewExternalArray(
1128 static_cast<int>(length), array_type,
1129 static_cast<uint8_t*>(buffer->backing_store()));
1130 Handle<Map> map = JSObject::GetElementsTransitionMap(
1131 holder, external_elements_kind);
1132 JSObject::SetMapAndElements(holder, map, elements);
1134 if (source->IsJSTypedArray()) {
1135 Handle<JSTypedArray> typed_array(JSTypedArray::cast(*source));
1137 if (typed_array->type() == holder->type()) {
1138 uint8_t* backing_store =
1139 static_cast<uint8_t*>(
1140 typed_array->GetBuffer()->backing_store());
1141 size_t source_byte_offset =
1142 NumberToSize(isolate, typed_array->byte_offset());
1144 buffer->backing_store(),
1145 backing_store + source_byte_offset,
1147 return isolate->heap()->true_value();
1151 return isolate->heap()->false_value();
1155 #define BUFFER_VIEW_GETTER(Type, getter, accessor) \
1156 RUNTIME_FUNCTION(Runtime_##Type##Get##getter) { \
1157 HandleScope scope(isolate); \
1158 DCHECK(args.length() == 1); \
1159 CONVERT_ARG_HANDLE_CHECKED(JS##Type, holder, 0); \
1160 return holder->accessor(); \
1163 BUFFER_VIEW_GETTER(ArrayBufferView, ByteLength, byte_length)
1164 BUFFER_VIEW_GETTER(ArrayBufferView, ByteOffset, byte_offset)
1165 BUFFER_VIEW_GETTER(TypedArray, Length, length)
1166 BUFFER_VIEW_GETTER(DataView, Buffer, buffer)
1168 #undef BUFFER_VIEW_GETTER
1170 RUNTIME_FUNCTION(Runtime_TypedArrayGetBuffer) {
1171 HandleScope scope(isolate);
1172 DCHECK(args.length() == 1);
1173 CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, holder, 0);
1174 return *holder->GetBuffer();
1178 // Return codes for Runtime_TypedArraySetFastCases.
1179 // Should be synchronized with typedarray.js natives.
1180 enum TypedArraySetResultCodes {
1181 // Set from typed array of the same type.
1182 // This is processed by TypedArraySetFastCases
1183 TYPED_ARRAY_SET_TYPED_ARRAY_SAME_TYPE = 0,
1184 // Set from typed array of the different type, overlapping in memory.
1185 TYPED_ARRAY_SET_TYPED_ARRAY_OVERLAPPING = 1,
1186 // Set from typed array of the different type, non-overlapping.
1187 TYPED_ARRAY_SET_TYPED_ARRAY_NONOVERLAPPING = 2,
1188 // Set from non-typed array.
1189 TYPED_ARRAY_SET_NON_TYPED_ARRAY = 3
1193 RUNTIME_FUNCTION(Runtime_TypedArraySetFastCases) {
1194 HandleScope scope(isolate);
1195 DCHECK(args.length() == 3);
1196 if (!args[0]->IsJSTypedArray()) {
1197 THROW_NEW_ERROR_RETURN_FAILURE(
1199 NewTypeError("not_typed_array", HandleVector<Object>(NULL, 0)));
1202 if (!args[1]->IsJSTypedArray())
1203 return Smi::FromInt(TYPED_ARRAY_SET_NON_TYPED_ARRAY);
1205 CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, target_obj, 0);
1206 CONVERT_ARG_HANDLE_CHECKED(JSTypedArray, source_obj, 1);
1207 CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset_obj, 2);
1209 Handle<JSTypedArray> target(JSTypedArray::cast(*target_obj));
1210 Handle<JSTypedArray> source(JSTypedArray::cast(*source_obj));
1212 RUNTIME_ASSERT(TryNumberToSize(isolate, *offset_obj, &offset));
1213 size_t target_length = NumberToSize(isolate, target->length());
1214 size_t source_length = NumberToSize(isolate, source->length());
1215 size_t target_byte_length = NumberToSize(isolate, target->byte_length());
1216 size_t source_byte_length = NumberToSize(isolate, source->byte_length());
1217 if (offset > target_length || offset + source_length > target_length ||
1218 offset + source_length < offset) { // overflow
1219 THROW_NEW_ERROR_RETURN_FAILURE(
1220 isolate, NewRangeError("typed_array_set_source_too_large",
1221 HandleVector<Object>(NULL, 0)));
1224 size_t target_offset = NumberToSize(isolate, target->byte_offset());
1225 size_t source_offset = NumberToSize(isolate, source->byte_offset());
1226 uint8_t* target_base =
1227 static_cast<uint8_t*>(
1228 target->GetBuffer()->backing_store()) + target_offset;
1229 uint8_t* source_base =
1230 static_cast<uint8_t*>(
1231 source->GetBuffer()->backing_store()) + source_offset;
1233 // Typed arrays of the same type: use memmove.
1234 if (target->type() == source->type()) {
1235 memmove(target_base + offset * target->element_size(),
1236 source_base, source_byte_length);
1237 return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_SAME_TYPE);
1240 // Typed arrays of different types over the same backing store
1241 if ((source_base <= target_base &&
1242 source_base + source_byte_length > target_base) ||
1243 (target_base <= source_base &&
1244 target_base + target_byte_length > source_base)) {
1245 // We do not support overlapping ArrayBuffers
1247 target->GetBuffer()->backing_store() ==
1248 source->GetBuffer()->backing_store());
1249 return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_OVERLAPPING);
1250 } else { // Non-overlapping typed arrays
1251 return Smi::FromInt(TYPED_ARRAY_SET_TYPED_ARRAY_NONOVERLAPPING);
1256 RUNTIME_FUNCTION(Runtime_TypedArrayMaxSizeInHeap) {
1257 DCHECK(args.length() == 0);
1259 FLAG_typed_array_max_size_in_heap + FixedTypedArrayBase::kDataOffset);
1260 return Smi::FromInt(FLAG_typed_array_max_size_in_heap);
1264 RUNTIME_FUNCTION(Runtime_DataViewInitialize) {
1265 HandleScope scope(isolate);
1266 DCHECK(args.length() == 4);
1267 CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0);
1268 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 1);
1269 CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_offset, 2);
1270 CONVERT_NUMBER_ARG_HANDLE_CHECKED(byte_length, 3);
1272 DCHECK(holder->GetInternalFieldCount() ==
1273 v8::ArrayBufferView::kInternalFieldCount);
1274 for (int i = 0; i < v8::ArrayBufferView::kInternalFieldCount; i++) {
1275 holder->SetInternalField(i, Smi::FromInt(0));
1277 size_t buffer_length = 0;
1281 TryNumberToSize(isolate, buffer->byte_length(), &buffer_length));
1282 RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_offset, &offset));
1283 RUNTIME_ASSERT(TryNumberToSize(isolate, *byte_length, &length));
1285 // TODO(jkummerow): When we have a "safe numerics" helper class, use it here.
1286 // Entire range [offset, offset + length] must be in bounds.
1287 RUNTIME_ASSERT(offset <= buffer_length);
1288 RUNTIME_ASSERT(offset + length <= buffer_length);
1290 RUNTIME_ASSERT(offset + length >= offset);
1292 holder->set_buffer(*buffer);
1293 holder->set_byte_offset(*byte_offset);
1294 holder->set_byte_length(*byte_length);
1296 holder->set_weak_next(buffer->weak_first_view());
1297 buffer->set_weak_first_view(*holder);
1299 return isolate->heap()->undefined_value();
1303 inline static bool NeedToFlipBytes(bool is_little_endian) {
1304 #ifdef V8_TARGET_LITTLE_ENDIAN
1305 return !is_little_endian;
1307 return is_little_endian;
1313 inline void CopyBytes(uint8_t* target, uint8_t* source) {
1314 for (int i = 0; i < n; i++) {
1315 *(target++) = *(source++);
1321 inline void FlipBytes(uint8_t* target, uint8_t* source) {
1322 source = source + (n-1);
1323 for (int i = 0; i < n; i++) {
1324 *(target++) = *(source--);
1329 template<typename T>
1330 inline static bool DataViewGetValue(
1332 Handle<JSDataView> data_view,
1333 Handle<Object> byte_offset_obj,
1334 bool is_little_endian,
1336 size_t byte_offset = 0;
1337 if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
1340 Handle<JSArrayBuffer> buffer(JSArrayBuffer::cast(data_view->buffer()));
1342 size_t data_view_byte_offset =
1343 NumberToSize(isolate, data_view->byte_offset());
1344 size_t data_view_byte_length =
1345 NumberToSize(isolate, data_view->byte_length());
1346 if (byte_offset + sizeof(T) > data_view_byte_length ||
1347 byte_offset + sizeof(T) < byte_offset) { // overflow
1353 uint8_t bytes[sizeof(T)];
1357 size_t buffer_offset = data_view_byte_offset + byte_offset;
1359 NumberToSize(isolate, buffer->byte_length())
1360 >= buffer_offset + sizeof(T));
1362 static_cast<uint8_t*>(buffer->backing_store()) + buffer_offset;
1363 if (NeedToFlipBytes(is_little_endian)) {
1364 FlipBytes<sizeof(T)>(value.bytes, source);
1366 CopyBytes<sizeof(T)>(value.bytes, source);
1368 *result = value.data;
1373 template<typename T>
1374 static bool DataViewSetValue(
1376 Handle<JSDataView> data_view,
1377 Handle<Object> byte_offset_obj,
1378 bool is_little_endian,
1380 size_t byte_offset = 0;
1381 if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
1384 Handle<JSArrayBuffer> buffer(JSArrayBuffer::cast(data_view->buffer()));
1386 size_t data_view_byte_offset =
1387 NumberToSize(isolate, data_view->byte_offset());
1388 size_t data_view_byte_length =
1389 NumberToSize(isolate, data_view->byte_length());
1390 if (byte_offset + sizeof(T) > data_view_byte_length ||
1391 byte_offset + sizeof(T) < byte_offset) { // overflow
1397 uint8_t bytes[sizeof(T)];
1402 size_t buffer_offset = data_view_byte_offset + byte_offset;
1404 NumberToSize(isolate, buffer->byte_length())
1405 >= buffer_offset + sizeof(T));
1407 static_cast<uint8_t*>(buffer->backing_store()) + buffer_offset;
1408 if (NeedToFlipBytes(is_little_endian)) {
1409 FlipBytes<sizeof(T)>(target, value.bytes);
1411 CopyBytes<sizeof(T)>(target, value.bytes);
1417 #define DATA_VIEW_GETTER(TypeName, Type, Converter) \
1418 RUNTIME_FUNCTION(Runtime_DataViewGet##TypeName) { \
1419 HandleScope scope(isolate); \
1420 DCHECK(args.length() == 3); \
1421 CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0); \
1422 CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1); \
1423 CONVERT_BOOLEAN_ARG_CHECKED(is_little_endian, 2); \
1425 if (DataViewGetValue(isolate, holder, offset, is_little_endian, \
1427 return *isolate->factory()->Converter(result); \
1429 THROW_NEW_ERROR_RETURN_FAILURE( \
1430 isolate, NewRangeError("invalid_data_view_accessor_offset", \
1431 HandleVector<Object>(NULL, 0))); \
1435 DATA_VIEW_GETTER(Uint8, uint8_t, NewNumberFromUint)
1436 DATA_VIEW_GETTER(Int8, int8_t, NewNumberFromInt)
1437 DATA_VIEW_GETTER(Uint16, uint16_t, NewNumberFromUint)
1438 DATA_VIEW_GETTER(Int16, int16_t, NewNumberFromInt)
1439 DATA_VIEW_GETTER(Uint32, uint32_t, NewNumberFromUint)
1440 DATA_VIEW_GETTER(Int32, int32_t, NewNumberFromInt)
1441 DATA_VIEW_GETTER(Float32, float, NewNumber)
1442 DATA_VIEW_GETTER(Float64, double, NewNumber)
1444 #undef DATA_VIEW_GETTER
1447 template <typename T>
1448 static T DataViewConvertValue(double value);
1452 int8_t DataViewConvertValue<int8_t>(double value) {
1453 return static_cast<int8_t>(DoubleToInt32(value));
1458 int16_t DataViewConvertValue<int16_t>(double value) {
1459 return static_cast<int16_t>(DoubleToInt32(value));
1464 int32_t DataViewConvertValue<int32_t>(double value) {
1465 return DoubleToInt32(value);
1470 uint8_t DataViewConvertValue<uint8_t>(double value) {
1471 return static_cast<uint8_t>(DoubleToUint32(value));
1476 uint16_t DataViewConvertValue<uint16_t>(double value) {
1477 return static_cast<uint16_t>(DoubleToUint32(value));
1482 uint32_t DataViewConvertValue<uint32_t>(double value) {
1483 return DoubleToUint32(value);
1488 float DataViewConvertValue<float>(double value) {
1489 return static_cast<float>(value);
1494 double DataViewConvertValue<double>(double value) {
1499 #define DATA_VIEW_SETTER(TypeName, Type) \
1500 RUNTIME_FUNCTION(Runtime_DataViewSet##TypeName) { \
1501 HandleScope scope(isolate); \
1502 DCHECK(args.length() == 4); \
1503 CONVERT_ARG_HANDLE_CHECKED(JSDataView, holder, 0); \
1504 CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1); \
1505 CONVERT_NUMBER_ARG_HANDLE_CHECKED(value, 2); \
1506 CONVERT_BOOLEAN_ARG_CHECKED(is_little_endian, 3); \
1507 Type v = DataViewConvertValue<Type>(value->Number()); \
1508 if (DataViewSetValue(isolate, holder, offset, is_little_endian, v)) { \
1509 return isolate->heap()->undefined_value(); \
1511 THROW_NEW_ERROR_RETURN_FAILURE( \
1512 isolate, NewRangeError("invalid_data_view_accessor_offset", \
1513 HandleVector<Object>(NULL, 0))); \
1517 DATA_VIEW_SETTER(Uint8, uint8_t)
1518 DATA_VIEW_SETTER(Int8, int8_t)
1519 DATA_VIEW_SETTER(Uint16, uint16_t)
1520 DATA_VIEW_SETTER(Int16, int16_t)
1521 DATA_VIEW_SETTER(Uint32, uint32_t)
1522 DATA_VIEW_SETTER(Int32, int32_t)
1523 DATA_VIEW_SETTER(Float32, float)
1524 DATA_VIEW_SETTER(Float64, double)
1526 #undef DATA_VIEW_SETTER
1529 RUNTIME_FUNCTION(Runtime_SetInitialize) {
1530 HandleScope scope(isolate);
1531 DCHECK(args.length() == 1);
1532 CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1533 Handle<OrderedHashSet> table = isolate->factory()->NewOrderedHashSet();
1534 holder->set_table(*table);
1539 RUNTIME_FUNCTION(Runtime_SetAdd) {
1540 HandleScope scope(isolate);
1541 DCHECK(args.length() == 2);
1542 CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1543 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1544 Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1545 table = OrderedHashSet::Add(table, key);
1546 holder->set_table(*table);
1551 RUNTIME_FUNCTION(Runtime_SetHas) {
1552 HandleScope scope(isolate);
1553 DCHECK(args.length() == 2);
1554 CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1555 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1556 Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1557 return isolate->heap()->ToBoolean(table->Contains(key));
1561 RUNTIME_FUNCTION(Runtime_SetDelete) {
1562 HandleScope scope(isolate);
1563 DCHECK(args.length() == 2);
1564 CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1565 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1566 Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1567 bool was_present = false;
1568 table = OrderedHashSet::Remove(table, key, &was_present);
1569 holder->set_table(*table);
1570 return isolate->heap()->ToBoolean(was_present);
1574 RUNTIME_FUNCTION(Runtime_SetClear) {
1575 HandleScope scope(isolate);
1576 DCHECK(args.length() == 1);
1577 CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1578 Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1579 table = OrderedHashSet::Clear(table);
1580 holder->set_table(*table);
1581 return isolate->heap()->undefined_value();
1585 RUNTIME_FUNCTION(Runtime_SetGetSize) {
1586 HandleScope scope(isolate);
1587 DCHECK(args.length() == 1);
1588 CONVERT_ARG_HANDLE_CHECKED(JSSet, holder, 0);
1589 Handle<OrderedHashSet> table(OrderedHashSet::cast(holder->table()));
1590 return Smi::FromInt(table->NumberOfElements());
1594 RUNTIME_FUNCTION(Runtime_SetIteratorInitialize) {
1595 HandleScope scope(isolate);
1596 DCHECK(args.length() == 3);
1597 CONVERT_ARG_HANDLE_CHECKED(JSSetIterator, holder, 0);
1598 CONVERT_ARG_HANDLE_CHECKED(JSSet, set, 1);
1599 CONVERT_SMI_ARG_CHECKED(kind, 2)
1600 RUNTIME_ASSERT(kind == JSSetIterator::kKindValues ||
1601 kind == JSSetIterator::kKindEntries);
1602 Handle<OrderedHashSet> table(OrderedHashSet::cast(set->table()));
1603 holder->set_table(*table);
1604 holder->set_index(Smi::FromInt(0));
1605 holder->set_kind(Smi::FromInt(kind));
1606 return isolate->heap()->undefined_value();
1610 RUNTIME_FUNCTION(Runtime_SetIteratorNext) {
1611 SealHandleScope shs(isolate);
1612 DCHECK(args.length() == 2);
1613 CONVERT_ARG_CHECKED(JSSetIterator, holder, 0);
1614 CONVERT_ARG_CHECKED(JSArray, value_array, 1);
1615 return holder->Next(value_array);
1619 RUNTIME_FUNCTION(Runtime_MapInitialize) {
1620 HandleScope scope(isolate);
1621 DCHECK(args.length() == 1);
1622 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1623 Handle<OrderedHashMap> table = isolate->factory()->NewOrderedHashMap();
1624 holder->set_table(*table);
1629 RUNTIME_FUNCTION(Runtime_MapGet) {
1630 HandleScope scope(isolate);
1631 DCHECK(args.length() == 2);
1632 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1633 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1634 Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1635 Handle<Object> lookup(table->Lookup(key), isolate);
1636 return lookup->IsTheHole() ? isolate->heap()->undefined_value() : *lookup;
1640 RUNTIME_FUNCTION(Runtime_MapHas) {
1641 HandleScope scope(isolate);
1642 DCHECK(args.length() == 2);
1643 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1644 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1645 Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1646 Handle<Object> lookup(table->Lookup(key), isolate);
1647 return isolate->heap()->ToBoolean(!lookup->IsTheHole());
1651 RUNTIME_FUNCTION(Runtime_MapDelete) {
1652 HandleScope scope(isolate);
1653 DCHECK(args.length() == 2);
1654 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1655 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1656 Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1657 bool was_present = false;
1658 Handle<OrderedHashMap> new_table =
1659 OrderedHashMap::Remove(table, key, &was_present);
1660 holder->set_table(*new_table);
1661 return isolate->heap()->ToBoolean(was_present);
1665 RUNTIME_FUNCTION(Runtime_MapClear) {
1666 HandleScope scope(isolate);
1667 DCHECK(args.length() == 1);
1668 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1669 Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1670 table = OrderedHashMap::Clear(table);
1671 holder->set_table(*table);
1672 return isolate->heap()->undefined_value();
1676 RUNTIME_FUNCTION(Runtime_MapSet) {
1677 HandleScope scope(isolate);
1678 DCHECK(args.length() == 3);
1679 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1680 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1681 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
1682 Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1683 Handle<OrderedHashMap> new_table = OrderedHashMap::Put(table, key, value);
1684 holder->set_table(*new_table);
1689 RUNTIME_FUNCTION(Runtime_MapGetSize) {
1690 HandleScope scope(isolate);
1691 DCHECK(args.length() == 1);
1692 CONVERT_ARG_HANDLE_CHECKED(JSMap, holder, 0);
1693 Handle<OrderedHashMap> table(OrderedHashMap::cast(holder->table()));
1694 return Smi::FromInt(table->NumberOfElements());
1698 RUNTIME_FUNCTION(Runtime_MapIteratorInitialize) {
1699 HandleScope scope(isolate);
1700 DCHECK(args.length() == 3);
1701 CONVERT_ARG_HANDLE_CHECKED(JSMapIterator, holder, 0);
1702 CONVERT_ARG_HANDLE_CHECKED(JSMap, map, 1);
1703 CONVERT_SMI_ARG_CHECKED(kind, 2)
1704 RUNTIME_ASSERT(kind == JSMapIterator::kKindKeys
1705 || kind == JSMapIterator::kKindValues
1706 || kind == JSMapIterator::kKindEntries);
1707 Handle<OrderedHashMap> table(OrderedHashMap::cast(map->table()));
1708 holder->set_table(*table);
1709 holder->set_index(Smi::FromInt(0));
1710 holder->set_kind(Smi::FromInt(kind));
1711 return isolate->heap()->undefined_value();
1715 RUNTIME_FUNCTION(Runtime_GetWeakMapEntries) {
1716 HandleScope scope(isolate);
1717 DCHECK(args.length() == 1);
1718 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, holder, 0);
1719 Handle<ObjectHashTable> table(ObjectHashTable::cast(holder->table()));
1720 Handle<FixedArray> entries =
1721 isolate->factory()->NewFixedArray(table->NumberOfElements() * 2);
1723 DisallowHeapAllocation no_gc;
1724 int number_of_non_hole_elements = 0;
1725 for (int i = 0; i < table->Capacity(); i++) {
1726 Handle<Object> key(table->KeyAt(i), isolate);
1727 if (table->IsKey(*key)) {
1728 entries->set(number_of_non_hole_elements++, *key);
1729 Object* value = table->Lookup(key);
1730 entries->set(number_of_non_hole_elements++, value);
1733 DCHECK_EQ(table->NumberOfElements() * 2, number_of_non_hole_elements);
1735 return *isolate->factory()->NewJSArrayWithElements(entries);
1739 RUNTIME_FUNCTION(Runtime_MapIteratorNext) {
1740 SealHandleScope shs(isolate);
1741 DCHECK(args.length() == 2);
1742 CONVERT_ARG_CHECKED(JSMapIterator, holder, 0);
1743 CONVERT_ARG_CHECKED(JSArray, value_array, 1);
1744 return holder->Next(value_array);
1748 static Handle<JSWeakCollection> WeakCollectionInitialize(
1750 Handle<JSWeakCollection> weak_collection) {
1751 DCHECK(weak_collection->map()->inobject_properties() == 0);
1752 Handle<ObjectHashTable> table = ObjectHashTable::New(isolate, 0);
1753 weak_collection->set_table(*table);
1754 return weak_collection;
1758 RUNTIME_FUNCTION(Runtime_WeakCollectionInitialize) {
1759 HandleScope scope(isolate);
1760 DCHECK(args.length() == 1);
1761 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1762 return *WeakCollectionInitialize(isolate, weak_collection);
1766 RUNTIME_FUNCTION(Runtime_WeakCollectionGet) {
1767 HandleScope scope(isolate);
1768 DCHECK(args.length() == 2);
1769 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1770 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1771 RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1772 Handle<ObjectHashTable> table(
1773 ObjectHashTable::cast(weak_collection->table()));
1774 RUNTIME_ASSERT(table->IsKey(*key));
1775 Handle<Object> lookup(table->Lookup(key), isolate);
1776 return lookup->IsTheHole() ? isolate->heap()->undefined_value() : *lookup;
1780 RUNTIME_FUNCTION(Runtime_WeakCollectionHas) {
1781 HandleScope scope(isolate);
1782 DCHECK(args.length() == 2);
1783 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1784 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1785 RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1786 Handle<ObjectHashTable> table(
1787 ObjectHashTable::cast(weak_collection->table()));
1788 RUNTIME_ASSERT(table->IsKey(*key));
1789 Handle<Object> lookup(table->Lookup(key), isolate);
1790 return isolate->heap()->ToBoolean(!lookup->IsTheHole());
1794 RUNTIME_FUNCTION(Runtime_WeakCollectionDelete) {
1795 HandleScope scope(isolate);
1796 DCHECK(args.length() == 2);
1797 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1798 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1799 RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1800 Handle<ObjectHashTable> table(ObjectHashTable::cast(
1801 weak_collection->table()));
1802 RUNTIME_ASSERT(table->IsKey(*key));
1803 bool was_present = false;
1804 Handle<ObjectHashTable> new_table =
1805 ObjectHashTable::Remove(table, key, &was_present);
1806 weak_collection->set_table(*new_table);
1807 return isolate->heap()->ToBoolean(was_present);
1811 RUNTIME_FUNCTION(Runtime_WeakCollectionSet) {
1812 HandleScope scope(isolate);
1813 DCHECK(args.length() == 3);
1814 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, weak_collection, 0);
1815 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
1816 RUNTIME_ASSERT(key->IsJSReceiver() || key->IsSymbol());
1817 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
1818 Handle<ObjectHashTable> table(
1819 ObjectHashTable::cast(weak_collection->table()));
1820 RUNTIME_ASSERT(table->IsKey(*key));
1821 Handle<ObjectHashTable> new_table = ObjectHashTable::Put(table, key, value);
1822 weak_collection->set_table(*new_table);
1823 return *weak_collection;
1827 RUNTIME_FUNCTION(Runtime_GetWeakSetValues) {
1828 HandleScope scope(isolate);
1829 DCHECK(args.length() == 1);
1830 CONVERT_ARG_HANDLE_CHECKED(JSWeakCollection, holder, 0);
1831 Handle<ObjectHashTable> table(ObjectHashTable::cast(holder->table()));
1832 Handle<FixedArray> values =
1833 isolate->factory()->NewFixedArray(table->NumberOfElements());
1835 DisallowHeapAllocation no_gc;
1836 int number_of_non_hole_elements = 0;
1837 for (int i = 0; i < table->Capacity(); i++) {
1838 Handle<Object> key(table->KeyAt(i), isolate);
1839 if (table->IsKey(*key)) {
1840 values->set(number_of_non_hole_elements++, *key);
1843 DCHECK_EQ(table->NumberOfElements(), number_of_non_hole_elements);
1845 return *isolate->factory()->NewJSArrayWithElements(values);
1849 RUNTIME_FUNCTION(Runtime_GetPrototype) {
1850 HandleScope scope(isolate);
1851 DCHECK(args.length() == 1);
1852 CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
1853 // We don't expect access checks to be needed on JSProxy objects.
1854 DCHECK(!obj->IsAccessCheckNeeded() || obj->IsJSObject());
1855 PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER);
1857 if (PrototypeIterator::GetCurrent(iter)->IsAccessCheckNeeded() &&
1858 !isolate->MayNamedAccess(
1859 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)),
1860 isolate->factory()->proto_string(), v8::ACCESS_GET)) {
1861 isolate->ReportFailedAccessCheck(
1862 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)),
1864 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
1865 return isolate->heap()->undefined_value();
1867 iter.AdvanceIgnoringProxies();
1868 if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) {
1869 return *PrototypeIterator::GetCurrent(iter);
1871 } while (!iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN));
1872 return *PrototypeIterator::GetCurrent(iter);
1876 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1877 Isolate* isolate, Handle<Object> receiver) {
1878 PrototypeIterator iter(isolate, receiver);
1879 while (!iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN)) {
1880 if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) {
1881 return PrototypeIterator::GetCurrent(iter);
1885 return PrototypeIterator::GetCurrent(iter);
1889 RUNTIME_FUNCTION(Runtime_InternalSetPrototype) {
1890 HandleScope scope(isolate);
1891 DCHECK(args.length() == 2);
1892 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
1893 CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
1894 DCHECK(!obj->IsAccessCheckNeeded());
1895 DCHECK(!obj->map()->is_observed());
1896 Handle<Object> result;
1897 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1898 isolate, result, JSObject::SetPrototype(obj, prototype, false));
1903 RUNTIME_FUNCTION(Runtime_SetPrototype) {
1904 HandleScope scope(isolate);
1905 DCHECK(args.length() == 2);
1906 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
1907 CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
1908 if (obj->IsAccessCheckNeeded() &&
1909 !isolate->MayNamedAccess(
1910 obj, isolate->factory()->proto_string(), v8::ACCESS_SET)) {
1911 isolate->ReportFailedAccessCheck(obj, v8::ACCESS_SET);
1912 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
1913 return isolate->heap()->undefined_value();
1915 if (obj->map()->is_observed()) {
1916 Handle<Object> old_value = GetPrototypeSkipHiddenPrototypes(isolate, obj);
1917 Handle<Object> result;
1918 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1920 JSObject::SetPrototype(obj, prototype, true));
1922 Handle<Object> new_value = GetPrototypeSkipHiddenPrototypes(isolate, obj);
1923 if (!new_value->SameValue(*old_value)) {
1924 JSObject::EnqueueChangeRecord(obj, "setPrototype",
1925 isolate->factory()->proto_string(),
1930 Handle<Object> result;
1931 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1933 JSObject::SetPrototype(obj, prototype, true));
1938 RUNTIME_FUNCTION(Runtime_IsInPrototypeChain) {
1939 HandleScope shs(isolate);
1940 DCHECK(args.length() == 2);
1941 // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8).
1942 CONVERT_ARG_HANDLE_CHECKED(Object, O, 0);
1943 CONVERT_ARG_HANDLE_CHECKED(Object, V, 1);
1944 PrototypeIterator iter(isolate, V, PrototypeIterator::START_AT_RECEIVER);
1946 iter.AdvanceIgnoringProxies();
1947 if (iter.IsAtEnd()) return isolate->heap()->false_value();
1948 if (iter.IsAtEnd(O)) return isolate->heap()->true_value();
1953 // Enumerator used as indices into the array returned from GetOwnProperty
1954 enum PropertyDescriptorIndices {
1966 MUST_USE_RESULT static MaybeHandle<Object> GetOwnProperty(Isolate* isolate,
1967 Handle<JSObject> obj,
1968 Handle<Name> name) {
1969 Heap* heap = isolate->heap();
1970 Factory* factory = isolate->factory();
1972 PropertyAttributes attrs;
1974 Handle<Object> value;
1975 MaybeHandle<AccessorPair> maybe_accessors;
1976 // TODO(verwaest): Unify once indexed properties can be handled by the
1978 if (name->AsArrayIndex(&index)) {
1980 Maybe<PropertyAttributes> maybe =
1981 JSReceiver::GetOwnElementAttribute(obj, index);
1982 if (!maybe.has_value) return MaybeHandle<Object>();
1983 attrs = maybe.value;
1984 if (attrs == ABSENT) return factory->undefined_value();
1986 // Get AccessorPair if present.
1987 maybe_accessors = JSObject::GetOwnElementAccessorPair(obj, index);
1989 // Get value if not an AccessorPair.
1990 if (maybe_accessors.is_null()) {
1991 ASSIGN_RETURN_ON_EXCEPTION(isolate, value,
1992 Runtime::GetElementOrCharAt(isolate, obj, index), Object);
1996 LookupIterator it(obj, name, LookupIterator::HIDDEN);
1997 Maybe<PropertyAttributes> maybe = JSObject::GetPropertyAttributes(&it);
1998 if (!maybe.has_value) return MaybeHandle<Object>();
1999 attrs = maybe.value;
2000 if (attrs == ABSENT) return factory->undefined_value();
2002 // Get AccessorPair if present.
2003 if (it.state() == LookupIterator::ACCESSOR &&
2004 it.GetAccessors()->IsAccessorPair()) {
2005 maybe_accessors = Handle<AccessorPair>::cast(it.GetAccessors());
2008 // Get value if not an AccessorPair.
2009 if (maybe_accessors.is_null()) {
2010 ASSIGN_RETURN_ON_EXCEPTION(
2011 isolate, value, Object::GetProperty(&it), Object);
2014 DCHECK(!isolate->has_pending_exception());
2015 Handle<FixedArray> elms = factory->NewFixedArray(DESCRIPTOR_SIZE);
2016 elms->set(ENUMERABLE_INDEX, heap->ToBoolean((attrs & DONT_ENUM) == 0));
2017 elms->set(CONFIGURABLE_INDEX, heap->ToBoolean((attrs & DONT_DELETE) == 0));
2018 elms->set(IS_ACCESSOR_INDEX, heap->ToBoolean(!maybe_accessors.is_null()));
2020 Handle<AccessorPair> accessors;
2021 if (maybe_accessors.ToHandle(&accessors)) {
2022 Handle<Object> getter(accessors->GetComponent(ACCESSOR_GETTER), isolate);
2023 Handle<Object> setter(accessors->GetComponent(ACCESSOR_SETTER), isolate);
2024 elms->set(GETTER_INDEX, *getter);
2025 elms->set(SETTER_INDEX, *setter);
2027 elms->set(WRITABLE_INDEX, heap->ToBoolean((attrs & READ_ONLY) == 0));
2028 elms->set(VALUE_INDEX, *value);
2031 return factory->NewJSArrayWithElements(elms);
2035 // Returns an array with the property description:
2036 // if args[1] is not a property on args[0]
2037 // returns undefined
2038 // if args[1] is a data property on args[0]
2039 // [false, value, Writeable, Enumerable, Configurable]
2040 // if args[1] is an accessor on args[0]
2041 // [true, GetFunction, SetFunction, Enumerable, Configurable]
2042 RUNTIME_FUNCTION(Runtime_GetOwnProperty) {
2043 HandleScope scope(isolate);
2044 DCHECK(args.length() == 2);
2045 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
2046 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
2047 Handle<Object> result;
2048 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2049 isolate, result, GetOwnProperty(isolate, obj, name));
2054 RUNTIME_FUNCTION(Runtime_PreventExtensions) {
2055 HandleScope scope(isolate);
2056 DCHECK(args.length() == 1);
2057 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
2058 Handle<Object> result;
2059 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2060 isolate, result, JSObject::PreventExtensions(obj));
2065 RUNTIME_FUNCTION(Runtime_ToMethod) {
2066 HandleScope scope(isolate);
2067 DCHECK(args.length() == 2);
2068 CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
2069 CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1);
2070 Handle<JSFunction> clone = JSFunction::CloneClosure(fun);
2071 Handle<Symbol> home_object_symbol(isolate->heap()->home_object_symbol());
2072 JSObject::SetOwnPropertyIgnoreAttributes(clone, home_object_symbol,
2073 home_object, DONT_ENUM).Assert();
2078 RUNTIME_FUNCTION(Runtime_HomeObjectSymbol) {
2079 DCHECK(args.length() == 0);
2080 return isolate->heap()->home_object_symbol();
2084 RUNTIME_FUNCTION(Runtime_LoadFromSuper) {
2085 HandleScope scope(isolate);
2086 DCHECK(args.length() == 3);
2087 CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 0);
2088 CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 1);
2089 CONVERT_ARG_HANDLE_CHECKED(Name, name, 2);
2091 if (home_object->IsAccessCheckNeeded() &&
2092 !isolate->MayNamedAccess(home_object, name, v8::ACCESS_GET)) {
2093 isolate->ReportFailedAccessCheck(home_object, v8::ACCESS_GET);
2094 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
2097 PrototypeIterator iter(isolate, home_object);
2098 Handle<Object> proto = PrototypeIterator::GetCurrent(iter);
2099 if (!proto->IsJSReceiver()) return isolate->heap()->undefined_value();
2101 LookupIterator it(receiver, name, Handle<JSReceiver>::cast(proto));
2102 Handle<Object> result;
2103 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, Object::GetProperty(&it));
2108 RUNTIME_FUNCTION(Runtime_IsExtensible) {
2109 SealHandleScope shs(isolate);
2110 DCHECK(args.length() == 1);
2111 CONVERT_ARG_CHECKED(JSObject, obj, 0);
2112 if (obj->IsJSGlobalProxy()) {
2113 PrototypeIterator iter(isolate, obj);
2114 if (iter.IsAtEnd()) return isolate->heap()->false_value();
2115 DCHECK(iter.GetCurrent()->IsJSGlobalObject());
2116 obj = JSObject::cast(iter.GetCurrent());
2118 return isolate->heap()->ToBoolean(obj->map()->is_extensible());
2122 RUNTIME_FUNCTION(Runtime_RegExpCompile) {
2123 HandleScope scope(isolate);
2124 DCHECK(args.length() == 3);
2125 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, re, 0);
2126 CONVERT_ARG_HANDLE_CHECKED(String, pattern, 1);
2127 CONVERT_ARG_HANDLE_CHECKED(String, flags, 2);
2128 Handle<Object> result;
2129 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2130 isolate, result, RegExpImpl::Compile(re, pattern, flags));
2135 RUNTIME_FUNCTION(Runtime_CreateApiFunction) {
2136 HandleScope scope(isolate);
2137 DCHECK(args.length() == 2);
2138 CONVERT_ARG_HANDLE_CHECKED(FunctionTemplateInfo, data, 0);
2139 CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
2140 return *isolate->factory()->CreateApiFunction(data, prototype);
2144 RUNTIME_FUNCTION(Runtime_IsTemplate) {
2145 SealHandleScope shs(isolate);
2146 DCHECK(args.length() == 1);
2147 CONVERT_ARG_HANDLE_CHECKED(Object, arg, 0);
2148 bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo();
2149 return isolate->heap()->ToBoolean(result);
2153 RUNTIME_FUNCTION(Runtime_GetTemplateField) {
2154 SealHandleScope shs(isolate);
2155 DCHECK(args.length() == 2);
2156 CONVERT_ARG_CHECKED(HeapObject, templ, 0);
2157 CONVERT_SMI_ARG_CHECKED(index, 1);
2158 int offset = index * kPointerSize + HeapObject::kHeaderSize;
2159 InstanceType type = templ->map()->instance_type();
2160 RUNTIME_ASSERT(type == FUNCTION_TEMPLATE_INFO_TYPE ||
2161 type == OBJECT_TEMPLATE_INFO_TYPE);
2162 RUNTIME_ASSERT(offset > 0);
2163 if (type == FUNCTION_TEMPLATE_INFO_TYPE) {
2164 RUNTIME_ASSERT(offset < FunctionTemplateInfo::kSize);
2166 RUNTIME_ASSERT(offset < ObjectTemplateInfo::kSize);
2168 return *HeapObject::RawField(templ, offset);
2172 RUNTIME_FUNCTION(Runtime_DisableAccessChecks) {
2173 HandleScope scope(isolate);
2174 DCHECK(args.length() == 1);
2175 CONVERT_ARG_HANDLE_CHECKED(HeapObject, object, 0);
2176 Handle<Map> old_map(object->map());
2177 bool needs_access_checks = old_map->is_access_check_needed();
2178 if (needs_access_checks) {
2179 // Copy map so it won't interfere constructor's initial map.
2180 Handle<Map> new_map = Map::Copy(old_map);
2181 new_map->set_is_access_check_needed(false);
2182 JSObject::MigrateToMap(Handle<JSObject>::cast(object), new_map);
2184 return isolate->heap()->ToBoolean(needs_access_checks);
2188 RUNTIME_FUNCTION(Runtime_EnableAccessChecks) {
2189 HandleScope scope(isolate);
2190 DCHECK(args.length() == 1);
2191 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
2192 Handle<Map> old_map(object->map());
2193 RUNTIME_ASSERT(!old_map->is_access_check_needed());
2194 // Copy map so it won't interfere constructor's initial map.
2195 Handle<Map> new_map = Map::Copy(old_map);
2196 new_map->set_is_access_check_needed(true);
2197 JSObject::MigrateToMap(object, new_map);
2198 return isolate->heap()->undefined_value();
2202 static Object* ThrowRedeclarationError(Isolate* isolate, Handle<String> name) {
2203 HandleScope scope(isolate);
2204 Handle<Object> args[1] = { name };
2205 THROW_NEW_ERROR_RETURN_FAILURE(
2206 isolate, NewTypeError("var_redeclaration", HandleVector(args, 1)));
2210 // May throw a RedeclarationError.
2211 static Object* DeclareGlobals(Isolate* isolate, Handle<GlobalObject> global,
2212 Handle<String> name, Handle<Object> value,
2213 PropertyAttributes attr, bool is_var,
2214 bool is_const, bool is_function) {
2215 // Do the lookup own properties only, see ES5 erratum.
2216 LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
2217 Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
2218 if (!maybe.has_value) return isolate->heap()->exception();
2221 PropertyAttributes old_attributes = maybe.value;
2222 // The name was declared before; check for conflicting re-declarations.
2223 if (is_const) return ThrowRedeclarationError(isolate, name);
2225 // Skip var re-declarations.
2226 if (is_var) return isolate->heap()->undefined_value();
2228 DCHECK(is_function);
2229 if ((old_attributes & DONT_DELETE) != 0) {
2230 // Only allow reconfiguring globals to functions in user code (no
2231 // natives, which are marked as read-only).
2232 DCHECK((attr & READ_ONLY) == 0);
2234 // Check whether we can reconfigure the existing property into a
2236 PropertyDetails old_details = it.property_details();
2237 // TODO(verwaest): CALLBACKS invalidly includes ExecutableAccessInfo,
2238 // which are actually data properties, not accessor properties.
2239 if (old_details.IsReadOnly() || old_details.IsDontEnum() ||
2240 old_details.type() == CALLBACKS) {
2241 return ThrowRedeclarationError(isolate, name);
2243 // If the existing property is not configurable, keep its attributes. Do
2244 attr = old_attributes;
2248 // Define or redefine own property.
2249 RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2250 global, name, value, attr));
2252 return isolate->heap()->undefined_value();
2256 RUNTIME_FUNCTION(Runtime_DeclareGlobals) {
2257 HandleScope scope(isolate);
2258 DCHECK(args.length() == 3);
2259 Handle<GlobalObject> global(isolate->global_object());
2261 CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
2262 CONVERT_ARG_HANDLE_CHECKED(FixedArray, pairs, 1);
2263 CONVERT_SMI_ARG_CHECKED(flags, 2);
2265 // Traverse the name/value pairs and set the properties.
2266 int length = pairs->length();
2267 for (int i = 0; i < length; i += 2) {
2268 HandleScope scope(isolate);
2269 Handle<String> name(String::cast(pairs->get(i)));
2270 Handle<Object> initial_value(pairs->get(i + 1), isolate);
2272 // We have to declare a global const property. To capture we only
2273 // assign to it when evaluating the assignment for "const x =
2274 // <expr>" the initial value is the hole.
2275 bool is_var = initial_value->IsUndefined();
2276 bool is_const = initial_value->IsTheHole();
2277 bool is_function = initial_value->IsSharedFunctionInfo();
2278 DCHECK(is_var + is_const + is_function == 1);
2280 Handle<Object> value;
2282 // Copy the function and update its context. Use it as value.
2283 Handle<SharedFunctionInfo> shared =
2284 Handle<SharedFunctionInfo>::cast(initial_value);
2285 Handle<JSFunction> function =
2286 isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
2290 value = isolate->factory()->undefined_value();
2293 // Compute the property attributes. According to ECMA-262,
2294 // the property must be non-configurable except in eval.
2295 bool is_native = DeclareGlobalsNativeFlag::decode(flags);
2296 bool is_eval = DeclareGlobalsEvalFlag::decode(flags);
2298 if (is_const) attr |= READ_ONLY;
2299 if (is_function && is_native) attr |= READ_ONLY;
2300 if (!is_const && !is_eval) attr |= DONT_DELETE;
2302 Object* result = DeclareGlobals(isolate, global, name, value,
2303 static_cast<PropertyAttributes>(attr),
2304 is_var, is_const, is_function);
2305 if (isolate->has_pending_exception()) return result;
2308 return isolate->heap()->undefined_value();
2312 RUNTIME_FUNCTION(Runtime_InitializeVarGlobal) {
2313 HandleScope scope(isolate);
2315 // args[1] == language_mode
2316 // args[2] == value (optional)
2318 // Determine if we need to assign to the variable if it already
2319 // exists (based on the number of arguments).
2320 RUNTIME_ASSERT(args.length() == 3);
2322 CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
2323 CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 1);
2324 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
2326 Handle<GlobalObject> global(isolate->context()->global_object());
2327 Handle<Object> result;
2328 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2329 isolate, result, Object::SetProperty(global, name, value, strict_mode));
2334 RUNTIME_FUNCTION(Runtime_InitializeConstGlobal) {
2335 HandleScope handle_scope(isolate);
2336 // All constants are declared with an initial value. The name
2337 // of the constant is the first argument and the initial value
2339 RUNTIME_ASSERT(args.length() == 2);
2340 CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
2341 CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
2343 Handle<GlobalObject> global = isolate->global_object();
2345 // Lookup the property as own on the global object.
2346 LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
2347 Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
2348 DCHECK(maybe.has_value);
2349 PropertyAttributes old_attributes = maybe.value;
2351 PropertyAttributes attr =
2352 static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
2353 // Set the value if the property is either missing, or the property attributes
2354 // allow setting the value without invoking an accessor.
2356 // Ignore if we can't reconfigure the value.
2357 if ((old_attributes & DONT_DELETE) != 0) {
2358 if ((old_attributes & READ_ONLY) != 0 ||
2359 it.state() == LookupIterator::ACCESSOR) {
2362 attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
2366 RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2367 global, name, value, attr));
2373 RUNTIME_FUNCTION(Runtime_DeclareLookupSlot) {
2374 HandleScope scope(isolate);
2375 DCHECK(args.length() == 4);
2377 // Declarations are always made in a function, native, or global context. In
2378 // the case of eval code, the context passed is the context of the caller,
2379 // which may be some nested context and not the declaration context.
2380 CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 0);
2381 Handle<Context> context(context_arg->declaration_context());
2382 CONVERT_ARG_HANDLE_CHECKED(String, name, 1);
2383 CONVERT_SMI_ARG_CHECKED(attr_arg, 2);
2384 PropertyAttributes attr = static_cast<PropertyAttributes>(attr_arg);
2385 RUNTIME_ASSERT(attr == READ_ONLY || attr == NONE);
2386 CONVERT_ARG_HANDLE_CHECKED(Object, initial_value, 3);
2388 // TODO(verwaest): Unify the encoding indicating "var" with DeclareGlobals.
2389 bool is_var = *initial_value == NULL;
2390 bool is_const = initial_value->IsTheHole();
2391 bool is_function = initial_value->IsJSFunction();
2392 DCHECK(is_var + is_const + is_function == 1);
2395 PropertyAttributes attributes;
2396 ContextLookupFlags flags = DONT_FOLLOW_CHAINS;
2397 BindingFlags binding_flags;
2398 Handle<Object> holder =
2399 context->Lookup(name, flags, &index, &attributes, &binding_flags);
2401 Handle<JSObject> object;
2402 Handle<Object> value =
2403 is_function ? initial_value
2404 : Handle<Object>::cast(isolate->factory()->undefined_value());
2406 // TODO(verwaest): This case should probably not be covered by this function,
2407 // but by DeclareGlobals instead.
2408 if ((attributes != ABSENT && holder->IsJSGlobalObject()) ||
2409 (context_arg->has_extension() &&
2410 context_arg->extension()->IsJSGlobalObject())) {
2411 return DeclareGlobals(isolate, Handle<JSGlobalObject>::cast(holder), name,
2412 value, attr, is_var, is_const, is_function);
2415 if (attributes != ABSENT) {
2416 // The name was declared before; check for conflicting re-declarations.
2417 if (is_const || (attributes & READ_ONLY) != 0) {
2418 return ThrowRedeclarationError(isolate, name);
2421 // Skip var re-declarations.
2422 if (is_var) return isolate->heap()->undefined_value();
2424 DCHECK(is_function);
2426 DCHECK(holder.is_identical_to(context));
2427 context->set(index, *initial_value);
2428 return isolate->heap()->undefined_value();
2431 object = Handle<JSObject>::cast(holder);
2433 } else if (context->has_extension()) {
2434 object = handle(JSObject::cast(context->extension()));
2435 DCHECK(object->IsJSContextExtensionObject() || object->IsJSGlobalObject());
2437 DCHECK(context->IsFunctionContext());
2439 isolate->factory()->NewJSObject(isolate->context_extension_function());
2440 context->set_extension(*object);
2443 RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2444 object, name, value, attr));
2446 return isolate->heap()->undefined_value();
2450 RUNTIME_FUNCTION(Runtime_InitializeLegacyConstLookupSlot) {
2451 HandleScope scope(isolate);
2452 DCHECK(args.length() == 3);
2454 CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
2455 DCHECK(!value->IsTheHole());
2456 // Initializations are always done in a function or native context.
2457 CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 1);
2458 Handle<Context> context(context_arg->declaration_context());
2459 CONVERT_ARG_HANDLE_CHECKED(String, name, 2);
2462 PropertyAttributes attributes;
2463 ContextLookupFlags flags = DONT_FOLLOW_CHAINS;
2464 BindingFlags binding_flags;
2465 Handle<Object> holder =
2466 context->Lookup(name, flags, &index, &attributes, &binding_flags);
2469 DCHECK(holder->IsContext());
2470 // Property was found in a context. Perform the assignment if the constant
2471 // was uninitialized.
2472 Handle<Context> context = Handle<Context>::cast(holder);
2473 DCHECK((attributes & READ_ONLY) != 0);
2474 if (context->get(index)->IsTheHole()) context->set(index, *value);
2478 PropertyAttributes attr =
2479 static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
2481 // Strict mode handling not needed (legacy const is disallowed in strict
2484 // The declared const was configurable, and may have been deleted in the
2485 // meanwhile. If so, re-introduce the variable in the context extension.
2486 DCHECK(context_arg->has_extension());
2487 if (attributes == ABSENT) {
2488 holder = handle(context_arg->extension(), isolate);
2490 // For JSContextExtensionObjects, the initializer can be run multiple times
2491 // if in a for loop: for (var i = 0; i < 2; i++) { const x = i; }. Only the
2492 // first assignment should go through. For JSGlobalObjects, additionally any
2493 // code can run in between that modifies the declared property.
2494 DCHECK(holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject());
2496 LookupIterator it(holder, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
2497 Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
2498 if (!maybe.has_value) return isolate->heap()->exception();
2499 PropertyAttributes old_attributes = maybe.value;
2501 // Ignore if we can't reconfigure the value.
2502 if ((old_attributes & DONT_DELETE) != 0) {
2503 if ((old_attributes & READ_ONLY) != 0 ||
2504 it.state() == LookupIterator::ACCESSOR) {
2507 attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
2511 RETURN_FAILURE_ON_EXCEPTION(
2512 isolate, JSObject::SetOwnPropertyIgnoreAttributes(
2513 Handle<JSObject>::cast(holder), name, value, attr));
2519 RUNTIME_FUNCTION(Runtime_OptimizeObjectForAddingMultipleProperties) {
2520 HandleScope scope(isolate);
2521 DCHECK(args.length() == 2);
2522 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
2523 CONVERT_SMI_ARG_CHECKED(properties, 1);
2524 // Conservative upper limit to prevent fuzz tests from going OOM.
2525 RUNTIME_ASSERT(properties <= 100000);
2526 if (object->HasFastProperties() && !object->IsJSGlobalProxy()) {
2527 JSObject::NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties);
2533 RUNTIME_FUNCTION(Runtime_RegExpExecRT) {
2534 HandleScope scope(isolate);
2535 DCHECK(args.length() == 4);
2536 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0);
2537 CONVERT_ARG_HANDLE_CHECKED(String, subject, 1);
2538 CONVERT_INT32_ARG_CHECKED(index, 2);
2539 CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 3);
2540 // Due to the way the JS calls are constructed this must be less than the
2541 // length of a string, i.e. it is always a Smi. We check anyway for security.
2542 RUNTIME_ASSERT(index >= 0);
2543 RUNTIME_ASSERT(index <= subject->length());
2544 isolate->counters()->regexp_entry_runtime()->Increment();
2545 Handle<Object> result;
2546 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2548 RegExpImpl::Exec(regexp, subject, index, last_match_info));
2553 RUNTIME_FUNCTION(Runtime_RegExpConstructResult) {
2554 HandleScope handle_scope(isolate);
2555 DCHECK(args.length() == 3);
2556 CONVERT_SMI_ARG_CHECKED(size, 0);
2557 RUNTIME_ASSERT(size >= 0 && size <= FixedArray::kMaxLength);
2558 CONVERT_ARG_HANDLE_CHECKED(Object, index, 1);
2559 CONVERT_ARG_HANDLE_CHECKED(Object, input, 2);
2560 Handle<FixedArray> elements = isolate->factory()->NewFixedArray(size);
2561 Handle<Map> regexp_map(isolate->native_context()->regexp_result_map());
2562 Handle<JSObject> object =
2563 isolate->factory()->NewJSObjectFromMap(regexp_map, NOT_TENURED, false);
2564 Handle<JSArray> array = Handle<JSArray>::cast(object);
2565 array->set_elements(*elements);
2566 array->set_length(Smi::FromInt(size));
2567 // Write in-object properties after the length of the array.
2568 array->InObjectPropertyAtPut(JSRegExpResult::kIndexIndex, *index);
2569 array->InObjectPropertyAtPut(JSRegExpResult::kInputIndex, *input);
2574 RUNTIME_FUNCTION(Runtime_RegExpInitializeObject) {
2575 HandleScope scope(isolate);
2576 DCHECK(args.length() == 6);
2577 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0);
2578 CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
2579 // If source is the empty string we set it to "(?:)" instead as
2580 // suggested by ECMA-262, 5th, section 15.10.4.1.
2581 if (source->length() == 0) source = isolate->factory()->query_colon_string();
2583 CONVERT_ARG_HANDLE_CHECKED(Object, global, 2);
2584 if (!global->IsTrue()) global = isolate->factory()->false_value();
2586 CONVERT_ARG_HANDLE_CHECKED(Object, ignoreCase, 3);
2587 if (!ignoreCase->IsTrue()) ignoreCase = isolate->factory()->false_value();
2589 CONVERT_ARG_HANDLE_CHECKED(Object, multiline, 4);
2590 if (!multiline->IsTrue()) multiline = isolate->factory()->false_value();
2592 CONVERT_ARG_HANDLE_CHECKED(Object, sticky, 5);
2593 if (!sticky->IsTrue()) sticky = isolate->factory()->false_value();
2595 Map* map = regexp->map();
2596 Object* constructor = map->constructor();
2597 if (!FLAG_harmony_regexps &&
2598 constructor->IsJSFunction() &&
2599 JSFunction::cast(constructor)->initial_map() == map) {
2600 // If we still have the original map, set in-object properties directly.
2601 regexp->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex, *source);
2602 // Both true and false are immovable immortal objects so no need for write
2604 regexp->InObjectPropertyAtPut(
2605 JSRegExp::kGlobalFieldIndex, *global, SKIP_WRITE_BARRIER);
2606 regexp->InObjectPropertyAtPut(
2607 JSRegExp::kIgnoreCaseFieldIndex, *ignoreCase, SKIP_WRITE_BARRIER);
2608 regexp->InObjectPropertyAtPut(
2609 JSRegExp::kMultilineFieldIndex, *multiline, SKIP_WRITE_BARRIER);
2610 regexp->InObjectPropertyAtPut(
2611 JSRegExp::kLastIndexFieldIndex, Smi::FromInt(0), SKIP_WRITE_BARRIER);
2615 // Map has changed, so use generic, but slower, method. We also end here if
2616 // the --harmony-regexp flag is set, because the initial map does not have
2617 // space for the 'sticky' flag, since it is from the snapshot, but must work
2618 // both with and without --harmony-regexp. When sticky comes out from under
2619 // the flag, we will be able to use the fast initial map.
2620 PropertyAttributes final =
2621 static_cast<PropertyAttributes>(READ_ONLY | DONT_ENUM | DONT_DELETE);
2622 PropertyAttributes writable =
2623 static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
2624 Handle<Object> zero(Smi::FromInt(0), isolate);
2625 Factory* factory = isolate->factory();
2626 JSObject::SetOwnPropertyIgnoreAttributes(
2627 regexp, factory->source_string(), source, final).Check();
2628 JSObject::SetOwnPropertyIgnoreAttributes(
2629 regexp, factory->global_string(), global, final).Check();
2630 JSObject::SetOwnPropertyIgnoreAttributes(
2631 regexp, factory->ignore_case_string(), ignoreCase, final).Check();
2632 JSObject::SetOwnPropertyIgnoreAttributes(
2633 regexp, factory->multiline_string(), multiline, final).Check();
2634 if (FLAG_harmony_regexps) {
2635 JSObject::SetOwnPropertyIgnoreAttributes(
2636 regexp, factory->sticky_string(), sticky, final).Check();
2638 JSObject::SetOwnPropertyIgnoreAttributes(
2639 regexp, factory->last_index_string(), zero, writable).Check();
2644 RUNTIME_FUNCTION(Runtime_FinishArrayPrototypeSetup) {
2645 HandleScope scope(isolate);
2646 DCHECK(args.length() == 1);
2647 CONVERT_ARG_HANDLE_CHECKED(JSArray, prototype, 0);
2648 Object* length = prototype->length();
2649 RUNTIME_ASSERT(length->IsSmi() && Smi::cast(length)->value() == 0);
2650 RUNTIME_ASSERT(prototype->HasFastSmiOrObjectElements());
2651 // This is necessary to enable fast checks for absence of elements
2652 // on Array.prototype and below.
2653 prototype->set_elements(isolate->heap()->empty_fixed_array());
2654 return Smi::FromInt(0);
2658 static void InstallBuiltin(Isolate* isolate,
2659 Handle<JSObject> holder,
2661 Builtins::Name builtin_name) {
2662 Handle<String> key = isolate->factory()->InternalizeUtf8String(name);
2663 Handle<Code> code(isolate->builtins()->builtin(builtin_name));
2664 Handle<JSFunction> optimized =
2665 isolate->factory()->NewFunctionWithoutPrototype(key, code);
2666 optimized->shared()->DontAdaptArguments();
2667 JSObject::AddProperty(holder, key, optimized, NONE);
2671 RUNTIME_FUNCTION(Runtime_SpecialArrayFunctions) {
2672 HandleScope scope(isolate);
2673 DCHECK(args.length() == 0);
2674 Handle<JSObject> holder =
2675 isolate->factory()->NewJSObject(isolate->object_function());
2677 InstallBuiltin(isolate, holder, "pop", Builtins::kArrayPop);
2678 InstallBuiltin(isolate, holder, "push", Builtins::kArrayPush);
2679 InstallBuiltin(isolate, holder, "shift", Builtins::kArrayShift);
2680 InstallBuiltin(isolate, holder, "unshift", Builtins::kArrayUnshift);
2681 InstallBuiltin(isolate, holder, "slice", Builtins::kArraySlice);
2682 InstallBuiltin(isolate, holder, "splice", Builtins::kArraySplice);
2683 InstallBuiltin(isolate, holder, "concat", Builtins::kArrayConcat);
2689 RUNTIME_FUNCTION(Runtime_IsSloppyModeFunction) {
2690 SealHandleScope shs(isolate);
2691 DCHECK(args.length() == 1);
2692 CONVERT_ARG_CHECKED(JSReceiver, callable, 0);
2693 if (!callable->IsJSFunction()) {
2694 HandleScope scope(isolate);
2695 Handle<Object> delegate;
2696 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2698 Execution::TryGetFunctionDelegate(
2699 isolate, Handle<JSReceiver>(callable)));
2700 callable = JSFunction::cast(*delegate);
2702 JSFunction* function = JSFunction::cast(callable);
2703 SharedFunctionInfo* shared = function->shared();
2704 return isolate->heap()->ToBoolean(shared->strict_mode() == SLOPPY);
2708 RUNTIME_FUNCTION(Runtime_GetDefaultReceiver) {
2709 SealHandleScope shs(isolate);
2710 DCHECK(args.length() == 1);
2711 CONVERT_ARG_CHECKED(JSReceiver, callable, 0);
2713 if (!callable->IsJSFunction()) {
2714 HandleScope scope(isolate);
2715 Handle<Object> delegate;
2716 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2718 Execution::TryGetFunctionDelegate(
2719 isolate, Handle<JSReceiver>(callable)));
2720 callable = JSFunction::cast(*delegate);
2722 JSFunction* function = JSFunction::cast(callable);
2724 SharedFunctionInfo* shared = function->shared();
2725 if (shared->native() || shared->strict_mode() == STRICT) {
2726 return isolate->heap()->undefined_value();
2728 // Returns undefined for strict or native functions, or
2729 // the associated global receiver for "normal" functions.
2731 return function->global_proxy();
2735 RUNTIME_FUNCTION(Runtime_MaterializeRegExpLiteral) {
2736 HandleScope scope(isolate);
2737 DCHECK(args.length() == 4);
2738 CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 0);
2739 CONVERT_SMI_ARG_CHECKED(index, 1);
2740 CONVERT_ARG_HANDLE_CHECKED(String, pattern, 2);
2741 CONVERT_ARG_HANDLE_CHECKED(String, flags, 3);
2743 // Get the RegExp function from the context in the literals array.
2744 // This is the RegExp function from the context in which the
2745 // function was created. We do not use the RegExp function from the
2746 // current native context because this might be the RegExp function
2747 // from another context which we should not have access to.
2748 Handle<JSFunction> constructor =
2750 JSFunction::NativeContextFromLiterals(*literals)->regexp_function());
2751 // Compute the regular expression literal.
2752 Handle<Object> regexp;
2753 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2755 RegExpImpl::CreateRegExpLiteral(constructor, pattern, flags));
2756 literals->set(index, *regexp);
2761 RUNTIME_FUNCTION(Runtime_FunctionGetName) {
2762 SealHandleScope shs(isolate);
2763 DCHECK(args.length() == 1);
2765 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2766 return f->shared()->name();
2770 RUNTIME_FUNCTION(Runtime_FunctionSetName) {
2771 SealHandleScope shs(isolate);
2772 DCHECK(args.length() == 2);
2774 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2775 CONVERT_ARG_CHECKED(String, name, 1);
2776 f->shared()->set_name(name);
2777 return isolate->heap()->undefined_value();
2781 RUNTIME_FUNCTION(Runtime_FunctionNameShouldPrintAsAnonymous) {
2782 SealHandleScope shs(isolate);
2783 DCHECK(args.length() == 1);
2784 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2785 return isolate->heap()->ToBoolean(
2786 f->shared()->name_should_print_as_anonymous());
2790 RUNTIME_FUNCTION(Runtime_FunctionMarkNameShouldPrintAsAnonymous) {
2791 SealHandleScope shs(isolate);
2792 DCHECK(args.length() == 1);
2793 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2794 f->shared()->set_name_should_print_as_anonymous(true);
2795 return isolate->heap()->undefined_value();
2799 RUNTIME_FUNCTION(Runtime_FunctionIsGenerator) {
2800 SealHandleScope shs(isolate);
2801 DCHECK(args.length() == 1);
2802 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2803 return isolate->heap()->ToBoolean(f->shared()->is_generator());
2807 RUNTIME_FUNCTION(Runtime_FunctionIsArrow) {
2808 SealHandleScope shs(isolate);
2809 DCHECK(args.length() == 1);
2810 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2811 return isolate->heap()->ToBoolean(f->shared()->is_arrow());
2815 RUNTIME_FUNCTION(Runtime_FunctionIsConciseMethod) {
2816 SealHandleScope shs(isolate);
2817 DCHECK(args.length() == 1);
2818 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2819 return isolate->heap()->ToBoolean(f->shared()->is_concise_method());
2823 RUNTIME_FUNCTION(Runtime_FunctionRemovePrototype) {
2824 SealHandleScope shs(isolate);
2825 DCHECK(args.length() == 1);
2827 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2828 RUNTIME_ASSERT(f->RemovePrototype());
2830 return isolate->heap()->undefined_value();
2834 RUNTIME_FUNCTION(Runtime_FunctionGetScript) {
2835 HandleScope scope(isolate);
2836 DCHECK(args.length() == 1);
2838 CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2839 Handle<Object> script = Handle<Object>(fun->shared()->script(), isolate);
2840 if (!script->IsScript()) return isolate->heap()->undefined_value();
2842 return *Script::GetWrapper(Handle<Script>::cast(script));
2846 RUNTIME_FUNCTION(Runtime_FunctionGetSourceCode) {
2847 HandleScope scope(isolate);
2848 DCHECK(args.length() == 1);
2850 CONVERT_ARG_HANDLE_CHECKED(JSFunction, f, 0);
2851 Handle<SharedFunctionInfo> shared(f->shared());
2852 return *shared->GetSourceCode();
2856 RUNTIME_FUNCTION(Runtime_FunctionGetScriptSourcePosition) {
2857 SealHandleScope shs(isolate);
2858 DCHECK(args.length() == 1);
2860 CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2861 int pos = fun->shared()->start_position();
2862 return Smi::FromInt(pos);
2866 RUNTIME_FUNCTION(Runtime_FunctionGetPositionForOffset) {
2867 SealHandleScope shs(isolate);
2868 DCHECK(args.length() == 2);
2870 CONVERT_ARG_CHECKED(Code, code, 0);
2871 CONVERT_NUMBER_CHECKED(int, offset, Int32, args[1]);
2873 RUNTIME_ASSERT(0 <= offset && offset < code->Size());
2875 Address pc = code->address() + offset;
2876 return Smi::FromInt(code->SourcePosition(pc));
2880 RUNTIME_FUNCTION(Runtime_FunctionSetInstanceClassName) {
2881 SealHandleScope shs(isolate);
2882 DCHECK(args.length() == 2);
2884 CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2885 CONVERT_ARG_CHECKED(String, name, 1);
2886 fun->SetInstanceClassName(name);
2887 return isolate->heap()->undefined_value();
2891 RUNTIME_FUNCTION(Runtime_FunctionSetLength) {
2892 SealHandleScope shs(isolate);
2893 DCHECK(args.length() == 2);
2895 CONVERT_ARG_CHECKED(JSFunction, fun, 0);
2896 CONVERT_SMI_ARG_CHECKED(length, 1);
2897 RUNTIME_ASSERT((length & 0xC0000000) == 0xC0000000 ||
2898 (length & 0xC0000000) == 0x0);
2899 fun->shared()->set_length(length);
2900 return isolate->heap()->undefined_value();
2904 RUNTIME_FUNCTION(Runtime_FunctionSetPrototype) {
2905 HandleScope scope(isolate);
2906 DCHECK(args.length() == 2);
2908 CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
2909 CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
2910 RUNTIME_ASSERT(fun->should_have_prototype());
2911 Accessors::FunctionSetPrototype(fun, value);
2912 return args[0]; // return TOS
2916 RUNTIME_FUNCTION(Runtime_FunctionIsAPIFunction) {
2917 SealHandleScope shs(isolate);
2918 DCHECK(args.length() == 1);
2920 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2921 return isolate->heap()->ToBoolean(f->shared()->IsApiFunction());
2925 RUNTIME_FUNCTION(Runtime_FunctionIsBuiltin) {
2926 SealHandleScope shs(isolate);
2927 DCHECK(args.length() == 1);
2929 CONVERT_ARG_CHECKED(JSFunction, f, 0);
2930 return isolate->heap()->ToBoolean(f->IsBuiltin());
2934 RUNTIME_FUNCTION(Runtime_SetCode) {
2935 HandleScope scope(isolate);
2936 DCHECK(args.length() == 2);
2938 CONVERT_ARG_HANDLE_CHECKED(JSFunction, target, 0);
2939 CONVERT_ARG_HANDLE_CHECKED(JSFunction, source, 1);
2941 Handle<SharedFunctionInfo> target_shared(target->shared());
2942 Handle<SharedFunctionInfo> source_shared(source->shared());
2943 RUNTIME_ASSERT(!source_shared->bound());
2945 if (!Compiler::EnsureCompiled(source, KEEP_EXCEPTION)) {
2946 return isolate->heap()->exception();
2949 // Mark both, the source and the target, as un-flushable because the
2950 // shared unoptimized code makes them impossible to enqueue in a list.
2951 DCHECK(target_shared->code()->gc_metadata() == NULL);
2952 DCHECK(source_shared->code()->gc_metadata() == NULL);
2953 target_shared->set_dont_flush(true);
2954 source_shared->set_dont_flush(true);
2956 // Set the code, scope info, formal parameter count, and the length
2957 // of the target shared function info.
2958 target_shared->ReplaceCode(source_shared->code());
2959 target_shared->set_scope_info(source_shared->scope_info());
2960 target_shared->set_length(source_shared->length());
2961 target_shared->set_feedback_vector(source_shared->feedback_vector());
2962 target_shared->set_formal_parameter_count(
2963 source_shared->formal_parameter_count());
2964 target_shared->set_script(source_shared->script());
2965 target_shared->set_start_position_and_type(
2966 source_shared->start_position_and_type());
2967 target_shared->set_end_position(source_shared->end_position());
2968 bool was_native = target_shared->native();
2969 target_shared->set_compiler_hints(source_shared->compiler_hints());
2970 target_shared->set_native(was_native);
2971 target_shared->set_profiler_ticks(source_shared->profiler_ticks());
2973 // Set the code of the target function.
2974 target->ReplaceCode(source_shared->code());
2975 DCHECK(target->next_function_link()->IsUndefined());
2977 // Make sure we get a fresh copy of the literal vector to avoid cross
2978 // context contamination.
2979 Handle<Context> context(source->context());
2980 int number_of_literals = source->NumberOfLiterals();
2981 Handle<FixedArray> literals =
2982 isolate->factory()->NewFixedArray(number_of_literals, TENURED);
2983 if (number_of_literals > 0) {
2984 literals->set(JSFunction::kLiteralNativeContextIndex,
2985 context->native_context());
2987 target->set_context(*context);
2988 target->set_literals(*literals);
2990 if (isolate->logger()->is_logging_code_events() ||
2991 isolate->cpu_profiler()->is_profiling()) {
2992 isolate->logger()->LogExistingFunction(
2993 source_shared, Handle<Code>(source_shared->code()));
3000 RUNTIME_FUNCTION(Runtime_CreateJSGeneratorObject) {
3001 HandleScope scope(isolate);
3002 DCHECK(args.length() == 0);
3004 JavaScriptFrameIterator it(isolate);
3005 JavaScriptFrame* frame = it.frame();
3006 Handle<JSFunction> function(frame->function());
3007 RUNTIME_ASSERT(function->shared()->is_generator());
3009 Handle<JSGeneratorObject> generator;
3010 if (frame->IsConstructor()) {
3011 generator = handle(JSGeneratorObject::cast(frame->receiver()));
3013 generator = isolate->factory()->NewJSGeneratorObject(function);
3015 generator->set_function(*function);
3016 generator->set_context(Context::cast(frame->context()));
3017 generator->set_receiver(frame->receiver());
3018 generator->set_continuation(0);
3019 generator->set_operand_stack(isolate->heap()->empty_fixed_array());
3020 generator->set_stack_handler_index(-1);
3026 RUNTIME_FUNCTION(Runtime_SuspendJSGeneratorObject) {
3027 HandleScope handle_scope(isolate);
3028 DCHECK(args.length() == 1);
3029 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator_object, 0);
3031 JavaScriptFrameIterator stack_iterator(isolate);
3032 JavaScriptFrame* frame = stack_iterator.frame();
3033 RUNTIME_ASSERT(frame->function()->shared()->is_generator());
3034 DCHECK_EQ(frame->function(), generator_object->function());
3036 // The caller should have saved the context and continuation already.
3037 DCHECK_EQ(generator_object->context(), Context::cast(frame->context()));
3038 DCHECK_LT(0, generator_object->continuation());
3040 // We expect there to be at least two values on the operand stack: the return
3041 // value of the yield expression, and the argument to this runtime call.
3042 // Neither of those should be saved.
3043 int operands_count = frame->ComputeOperandsCount();
3044 DCHECK_GE(operands_count, 2);
3045 operands_count -= 2;
3047 if (operands_count == 0) {
3048 // Although it's semantically harmless to call this function with an
3049 // operands_count of zero, it is also unnecessary.
3050 DCHECK_EQ(generator_object->operand_stack(),
3051 isolate->heap()->empty_fixed_array());
3052 DCHECK_EQ(generator_object->stack_handler_index(), -1);
3053 // If there are no operands on the stack, there shouldn't be a handler
3055 DCHECK(!frame->HasHandler());
3057 int stack_handler_index = -1;
3058 Handle<FixedArray> operand_stack =
3059 isolate->factory()->NewFixedArray(operands_count);
3060 frame->SaveOperandStack(*operand_stack, &stack_handler_index);
3061 generator_object->set_operand_stack(*operand_stack);
3062 generator_object->set_stack_handler_index(stack_handler_index);
3065 return isolate->heap()->undefined_value();
3069 // Note that this function is the slow path for resuming generators. It is only
3070 // called if the suspended activation had operands on the stack, stack handlers
3071 // needing rewinding, or if the resume should throw an exception. The fast path
3072 // is handled directly in FullCodeGenerator::EmitGeneratorResume(), which is
3073 // inlined into GeneratorNext and GeneratorThrow. EmitGeneratorResumeResume is
3074 // called in any case, as it needs to reconstruct the stack frame and make space
3075 // for arguments and operands.
3076 RUNTIME_FUNCTION(Runtime_ResumeJSGeneratorObject) {
3077 SealHandleScope shs(isolate);
3078 DCHECK(args.length() == 3);
3079 CONVERT_ARG_CHECKED(JSGeneratorObject, generator_object, 0);
3080 CONVERT_ARG_CHECKED(Object, value, 1);
3081 CONVERT_SMI_ARG_CHECKED(resume_mode_int, 2);
3082 JavaScriptFrameIterator stack_iterator(isolate);
3083 JavaScriptFrame* frame = stack_iterator.frame();
3085 DCHECK_EQ(frame->function(), generator_object->function());
3086 DCHECK(frame->function()->is_compiled());
3088 STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting < 0);
3089 STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed == 0);
3091 Address pc = generator_object->function()->code()->instruction_start();
3092 int offset = generator_object->continuation();
3094 frame->set_pc(pc + offset);
3095 if (FLAG_enable_ool_constant_pool) {
3096 frame->set_constant_pool(
3097 generator_object->function()->code()->constant_pool());
3099 generator_object->set_continuation(JSGeneratorObject::kGeneratorExecuting);
3101 FixedArray* operand_stack = generator_object->operand_stack();
3102 int operands_count = operand_stack->length();
3103 if (operands_count != 0) {
3104 frame->RestoreOperandStack(operand_stack,
3105 generator_object->stack_handler_index());
3106 generator_object->set_operand_stack(isolate->heap()->empty_fixed_array());
3107 generator_object->set_stack_handler_index(-1);
3110 JSGeneratorObject::ResumeMode resume_mode =
3111 static_cast<JSGeneratorObject::ResumeMode>(resume_mode_int);
3112 switch (resume_mode) {
3113 case JSGeneratorObject::NEXT:
3115 case JSGeneratorObject::THROW:
3116 return isolate->Throw(value);
3120 return isolate->ThrowIllegalOperation();
3124 RUNTIME_FUNCTION(Runtime_ThrowGeneratorStateError) {
3125 HandleScope scope(isolate);
3126 DCHECK(args.length() == 1);
3127 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
3128 int continuation = generator->continuation();
3129 const char* message = continuation == JSGeneratorObject::kGeneratorClosed ?
3130 "generator_finished" : "generator_running";
3131 Vector< Handle<Object> > argv = HandleVector<Object>(NULL, 0);
3132 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewError(message, argv));
3136 RUNTIME_FUNCTION(Runtime_ObjectFreeze) {
3137 HandleScope scope(isolate);
3138 DCHECK(args.length() == 1);
3139 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
3141 // %ObjectFreeze is a fast path and these cases are handled elsewhere.
3142 RUNTIME_ASSERT(!object->HasSloppyArgumentsElements() &&
3143 !object->map()->is_observed() &&
3144 !object->IsJSProxy());
3146 Handle<Object> result;
3147 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSObject::Freeze(object));
3152 RUNTIME_FUNCTION(Runtime_StringCharCodeAtRT) {
3153 HandleScope handle_scope(isolate);
3154 DCHECK(args.length() == 2);
3156 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
3157 CONVERT_NUMBER_CHECKED(uint32_t, i, Uint32, args[1]);
3159 // Flatten the string. If someone wants to get a char at an index
3160 // in a cons string, it is likely that more indices will be
3162 subject = String::Flatten(subject);
3164 if (i >= static_cast<uint32_t>(subject->length())) {
3165 return isolate->heap()->nan_value();
3168 return Smi::FromInt(subject->Get(i));
3172 RUNTIME_FUNCTION(Runtime_CharFromCode) {
3173 HandleScope handlescope(isolate);
3174 DCHECK(args.length() == 1);
3175 if (args[0]->IsNumber()) {
3176 CONVERT_NUMBER_CHECKED(uint32_t, code, Uint32, args[0]);
3178 return *isolate->factory()->LookupSingleCharacterStringFromCode(code);
3180 return isolate->heap()->empty_string();
3184 class FixedArrayBuilder {
3186 explicit FixedArrayBuilder(Isolate* isolate, int initial_capacity)
3187 : array_(isolate->factory()->NewFixedArrayWithHoles(initial_capacity)),
3189 has_non_smi_elements_(false) {
3190 // Require a non-zero initial size. Ensures that doubling the size to
3191 // extend the array will work.
3192 DCHECK(initial_capacity > 0);
3195 explicit FixedArrayBuilder(Handle<FixedArray> backing_store)
3196 : array_(backing_store),
3198 has_non_smi_elements_(false) {
3199 // Require a non-zero initial size. Ensures that doubling the size to
3200 // extend the array will work.
3201 DCHECK(backing_store->length() > 0);
3204 bool HasCapacity(int elements) {
3205 int length = array_->length();
3206 int required_length = length_ + elements;
3207 return (length >= required_length);
3210 void EnsureCapacity(int elements) {
3211 int length = array_->length();
3212 int required_length = length_ + elements;
3213 if (length < required_length) {
3214 int new_length = length;
3217 } while (new_length < required_length);
3218 Handle<FixedArray> extended_array =
3219 array_->GetIsolate()->factory()->NewFixedArrayWithHoles(new_length);
3220 array_->CopyTo(0, *extended_array, 0, length_);
3221 array_ = extended_array;
3225 void Add(Object* value) {
3226 DCHECK(!value->IsSmi());
3227 DCHECK(length_ < capacity());
3228 array_->set(length_, value);
3230 has_non_smi_elements_ = true;
3233 void Add(Smi* value) {
3234 DCHECK(value->IsSmi());
3235 DCHECK(length_ < capacity());
3236 array_->set(length_, value);
3240 Handle<FixedArray> array() {
3249 return array_->length();
3252 Handle<JSArray> ToJSArray(Handle<JSArray> target_array) {
3253 JSArray::SetContent(target_array, array_);
3254 target_array->set_length(Smi::FromInt(length_));
3255 return target_array;
3260 Handle<FixedArray> array_;
3262 bool has_non_smi_elements_;
3266 // Forward declarations.
3267 const int kStringBuilderConcatHelperLengthBits = 11;
3268 const int kStringBuilderConcatHelperPositionBits = 19;
3270 template <typename schar>
3271 static inline void StringBuilderConcatHelper(String*,
3276 typedef BitField<int, 0, kStringBuilderConcatHelperLengthBits>
3277 StringBuilderSubstringLength;
3278 typedef BitField<int,
3279 kStringBuilderConcatHelperLengthBits,
3280 kStringBuilderConcatHelperPositionBits>
3281 StringBuilderSubstringPosition;
3284 class ReplacementStringBuilder {
3286 ReplacementStringBuilder(Heap* heap, Handle<String> subject,
3287 int estimated_part_count)
3289 array_builder_(heap->isolate(), estimated_part_count),
3291 character_count_(0),
3292 is_one_byte_(subject->IsOneByteRepresentation()) {
3293 // Require a non-zero initial size. Ensures that doubling the size to
3294 // extend the array will work.
3295 DCHECK(estimated_part_count > 0);
3298 static inline void AddSubjectSlice(FixedArrayBuilder* builder,
3302 int length = to - from;
3304 if (StringBuilderSubstringLength::is_valid(length) &&
3305 StringBuilderSubstringPosition::is_valid(from)) {
3306 int encoded_slice = StringBuilderSubstringLength::encode(length) |
3307 StringBuilderSubstringPosition::encode(from);
3308 builder->Add(Smi::FromInt(encoded_slice));
3310 // Otherwise encode as two smis.
3311 builder->Add(Smi::FromInt(-length));
3312 builder->Add(Smi::FromInt(from));
3317 void EnsureCapacity(int elements) {
3318 array_builder_.EnsureCapacity(elements);
3322 void AddSubjectSlice(int from, int to) {
3323 AddSubjectSlice(&array_builder_, from, to);
3324 IncrementCharacterCount(to - from);
3328 void AddString(Handle<String> string) {
3329 int length = string->length();
3331 AddElement(*string);
3332 if (!string->IsOneByteRepresentation()) {
3333 is_one_byte_ = false;
3335 IncrementCharacterCount(length);
3339 MaybeHandle<String> ToString() {
3340 Isolate* isolate = heap_->isolate();
3341 if (array_builder_.length() == 0) {
3342 return isolate->factory()->empty_string();
3345 Handle<String> joined_string;
3347 Handle<SeqOneByteString> seq;
3348 ASSIGN_RETURN_ON_EXCEPTION(
3350 isolate->factory()->NewRawOneByteString(character_count_),
3353 DisallowHeapAllocation no_gc;
3354 uint8_t* char_buffer = seq->GetChars();
3355 StringBuilderConcatHelper(*subject_,
3357 *array_builder_.array(),
3358 array_builder_.length());
3359 joined_string = Handle<String>::cast(seq);
3362 Handle<SeqTwoByteString> seq;
3363 ASSIGN_RETURN_ON_EXCEPTION(
3365 isolate->factory()->NewRawTwoByteString(character_count_),
3368 DisallowHeapAllocation no_gc;
3369 uc16* char_buffer = seq->GetChars();
3370 StringBuilderConcatHelper(*subject_,
3372 *array_builder_.array(),
3373 array_builder_.length());
3374 joined_string = Handle<String>::cast(seq);
3376 return joined_string;
3380 void IncrementCharacterCount(int by) {
3381 if (character_count_ > String::kMaxLength - by) {
3382 STATIC_ASSERT(String::kMaxLength < kMaxInt);
3383 character_count_ = kMaxInt;
3385 character_count_ += by;
3390 void AddElement(Object* element) {
3391 DCHECK(element->IsSmi() || element->IsString());
3392 DCHECK(array_builder_.capacity() > array_builder_.length());
3393 array_builder_.Add(element);
3397 FixedArrayBuilder array_builder_;
3398 Handle<String> subject_;
3399 int character_count_;
3404 class CompiledReplacement {
3406 explicit CompiledReplacement(Zone* zone)
3407 : parts_(1, zone), replacement_substrings_(0, zone), zone_(zone) {}
3409 // Return whether the replacement is simple.
3410 bool Compile(Handle<String> replacement,
3412 int subject_length);
3414 // Use Apply only if Compile returned false.
3415 void Apply(ReplacementStringBuilder* builder,
3420 // Number of distinct parts of the replacement pattern.
3422 return parts_.length();
3425 Zone* zone() const { return zone_; }
3432 REPLACEMENT_SUBSTRING,
3435 NUMBER_OF_PART_TYPES
3438 struct ReplacementPart {
3439 static inline ReplacementPart SubjectMatch() {
3440 return ReplacementPart(SUBJECT_CAPTURE, 0);
3442 static inline ReplacementPart SubjectCapture(int capture_index) {
3443 return ReplacementPart(SUBJECT_CAPTURE, capture_index);
3445 static inline ReplacementPart SubjectPrefix() {
3446 return ReplacementPart(SUBJECT_PREFIX, 0);
3448 static inline ReplacementPart SubjectSuffix(int subject_length) {
3449 return ReplacementPart(SUBJECT_SUFFIX, subject_length);
3451 static inline ReplacementPart ReplacementString() {
3452 return ReplacementPart(REPLACEMENT_STRING, 0);
3454 static inline ReplacementPart ReplacementSubString(int from, int to) {
3457 return ReplacementPart(-from, to);
3460 // If tag <= 0 then it is the negation of a start index of a substring of
3461 // the replacement pattern, otherwise it's a value from PartType.
3462 ReplacementPart(int tag, int data)
3463 : tag(tag), data(data) {
3464 // Must be non-positive or a PartType value.
3465 DCHECK(tag < NUMBER_OF_PART_TYPES);
3467 // Either a value of PartType or a non-positive number that is
3468 // the negation of an index into the replacement string.
3470 // The data value's interpretation depends on the value of tag:
3471 // tag == SUBJECT_PREFIX ||
3472 // tag == SUBJECT_SUFFIX: data is unused.
3473 // tag == SUBJECT_CAPTURE: data is the number of the capture.
3474 // tag == REPLACEMENT_SUBSTRING ||
3475 // tag == REPLACEMENT_STRING: data is index into array of substrings
3476 // of the replacement string.
3477 // tag <= 0: Temporary representation of the substring of the replacement
3478 // string ranging over -tag .. data.
3479 // Is replaced by REPLACEMENT_{SUB,}STRING when we create the
3480 // substring objects.
3484 template<typename Char>
3485 bool ParseReplacementPattern(ZoneList<ReplacementPart>* parts,
3486 Vector<Char> characters,
3490 int length = characters.length();
3492 for (int i = 0; i < length; i++) {
3493 Char c = characters[i];
3495 int next_index = i + 1;
3496 if (next_index == length) { // No next character!
3499 Char c2 = characters[next_index];
3503 // There is a substring before. Include the first "$".
3504 parts->Add(ReplacementPart::ReplacementSubString(last, next_index),
3506 last = next_index + 1; // Continue after the second "$".
3508 // Let the next substring start with the second "$".
3515 parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3517 parts->Add(ReplacementPart::SubjectPrefix(), zone);
3523 parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3525 parts->Add(ReplacementPart::SubjectSuffix(subject_length), zone);
3531 parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3533 parts->Add(ReplacementPart::SubjectMatch(), zone);
3547 int capture_ref = c2 - '0';
3548 if (capture_ref > capture_count) {
3552 int second_digit_index = next_index + 1;
3553 if (second_digit_index < length) {
3554 // Peek ahead to see if we have two digits.
3555 Char c3 = characters[second_digit_index];
3556 if ('0' <= c3 && c3 <= '9') { // Double digits.
3557 int double_digit_ref = capture_ref * 10 + c3 - '0';
3558 if (double_digit_ref <= capture_count) {
3559 next_index = second_digit_index;
3560 capture_ref = double_digit_ref;
3564 if (capture_ref > 0) {
3566 parts->Add(ReplacementPart::ReplacementSubString(last, i), zone);
3568 DCHECK(capture_ref <= capture_count);
3569 parts->Add(ReplacementPart::SubjectCapture(capture_ref), zone);
3570 last = next_index + 1;
3581 if (length > last) {
3583 // Replacement is simple. Do not use Apply to do the replacement.
3586 parts->Add(ReplacementPart::ReplacementSubString(last, length), zone);
3592 ZoneList<ReplacementPart> parts_;
3593 ZoneList<Handle<String> > replacement_substrings_;
3598 bool CompiledReplacement::Compile(Handle<String> replacement,
3600 int subject_length) {
3602 DisallowHeapAllocation no_gc;
3603 String::FlatContent content = replacement->GetFlatContent();
3604 DCHECK(content.IsFlat());
3605 bool simple = false;
3606 if (content.IsOneByte()) {
3607 simple = ParseReplacementPattern(&parts_,
3608 content.ToOneByteVector(),
3613 DCHECK(content.IsTwoByte());
3614 simple = ParseReplacementPattern(&parts_,
3615 content.ToUC16Vector(),
3620 if (simple) return true;
3623 Isolate* isolate = replacement->GetIsolate();
3624 // Find substrings of replacement string and create them as String objects.
3625 int substring_index = 0;
3626 for (int i = 0, n = parts_.length(); i < n; i++) {
3627 int tag = parts_[i].tag;
3628 if (tag <= 0) { // A replacement string slice.
3630 int to = parts_[i].data;
3631 replacement_substrings_.Add(
3632 isolate->factory()->NewSubString(replacement, from, to), zone());
3633 parts_[i].tag = REPLACEMENT_SUBSTRING;
3634 parts_[i].data = substring_index;
3636 } else if (tag == REPLACEMENT_STRING) {
3637 replacement_substrings_.Add(replacement, zone());
3638 parts_[i].data = substring_index;
3646 void CompiledReplacement::Apply(ReplacementStringBuilder* builder,
3650 DCHECK_LT(0, parts_.length());
3651 for (int i = 0, n = parts_.length(); i < n; i++) {
3652 ReplacementPart part = parts_[i];
3654 case SUBJECT_PREFIX:
3655 if (match_from > 0) builder->AddSubjectSlice(0, match_from);
3657 case SUBJECT_SUFFIX: {
3658 int subject_length = part.data;
3659 if (match_to < subject_length) {
3660 builder->AddSubjectSlice(match_to, subject_length);
3664 case SUBJECT_CAPTURE: {
3665 int capture = part.data;
3666 int from = match[capture * 2];
3667 int to = match[capture * 2 + 1];
3668 if (from >= 0 && to > from) {
3669 builder->AddSubjectSlice(from, to);
3673 case REPLACEMENT_SUBSTRING:
3674 case REPLACEMENT_STRING:
3675 builder->AddString(replacement_substrings_[part.data]);
3684 void FindOneByteStringIndices(Vector<const uint8_t> subject, char pattern,
3685 ZoneList<int>* indices, unsigned int limit,
3688 // Collect indices of pattern in subject using memchr.
3689 // Stop after finding at most limit values.
3690 const uint8_t* subject_start = subject.start();
3691 const uint8_t* subject_end = subject_start + subject.length();
3692 const uint8_t* pos = subject_start;
3694 pos = reinterpret_cast<const uint8_t*>(
3695 memchr(pos, pattern, subject_end - pos));
3696 if (pos == NULL) return;
3697 indices->Add(static_cast<int>(pos - subject_start), zone);
3704 void FindTwoByteStringIndices(const Vector<const uc16> subject,
3706 ZoneList<int>* indices,
3710 const uc16* subject_start = subject.start();
3711 const uc16* subject_end = subject_start + subject.length();
3712 for (const uc16* pos = subject_start; pos < subject_end && limit > 0; pos++) {
3713 if (*pos == pattern) {
3714 indices->Add(static_cast<int>(pos - subject_start), zone);
3721 template <typename SubjectChar, typename PatternChar>
3722 void FindStringIndices(Isolate* isolate,
3723 Vector<const SubjectChar> subject,
3724 Vector<const PatternChar> pattern,
3725 ZoneList<int>* indices,
3729 // Collect indices of pattern in subject.
3730 // Stop after finding at most limit values.
3731 int pattern_length = pattern.length();
3733 StringSearch<PatternChar, SubjectChar> search(isolate, pattern);
3735 index = search.Search(subject, index);
3736 if (index < 0) return;
3737 indices->Add(index, zone);
3738 index += pattern_length;
3744 void FindStringIndicesDispatch(Isolate* isolate,
3747 ZoneList<int>* indices,
3751 DisallowHeapAllocation no_gc;
3752 String::FlatContent subject_content = subject->GetFlatContent();
3753 String::FlatContent pattern_content = pattern->GetFlatContent();
3754 DCHECK(subject_content.IsFlat());
3755 DCHECK(pattern_content.IsFlat());
3756 if (subject_content.IsOneByte()) {
3757 Vector<const uint8_t> subject_vector = subject_content.ToOneByteVector();
3758 if (pattern_content.IsOneByte()) {
3759 Vector<const uint8_t> pattern_vector =
3760 pattern_content.ToOneByteVector();
3761 if (pattern_vector.length() == 1) {
3762 FindOneByteStringIndices(subject_vector, pattern_vector[0], indices,
3765 FindStringIndices(isolate,
3773 FindStringIndices(isolate,
3775 pattern_content.ToUC16Vector(),
3781 Vector<const uc16> subject_vector = subject_content.ToUC16Vector();
3782 if (pattern_content.IsOneByte()) {
3783 Vector<const uint8_t> pattern_vector =
3784 pattern_content.ToOneByteVector();
3785 if (pattern_vector.length() == 1) {
3786 FindTwoByteStringIndices(subject_vector,
3792 FindStringIndices(isolate,
3800 Vector<const uc16> pattern_vector = pattern_content.ToUC16Vector();
3801 if (pattern_vector.length() == 1) {
3802 FindTwoByteStringIndices(subject_vector,
3808 FindStringIndices(isolate,
3821 template<typename ResultSeqString>
3822 MUST_USE_RESULT static Object* StringReplaceGlobalAtomRegExpWithString(
3824 Handle<String> subject,
3825 Handle<JSRegExp> pattern_regexp,
3826 Handle<String> replacement,
3827 Handle<JSArray> last_match_info) {
3828 DCHECK(subject->IsFlat());
3829 DCHECK(replacement->IsFlat());
3831 ZoneScope zone_scope(isolate->runtime_zone());
3832 ZoneList<int> indices(8, zone_scope.zone());
3833 DCHECK_EQ(JSRegExp::ATOM, pattern_regexp->TypeTag());
3835 String::cast(pattern_regexp->DataAt(JSRegExp::kAtomPatternIndex));
3836 int subject_len = subject->length();
3837 int pattern_len = pattern->length();
3838 int replacement_len = replacement->length();
3840 FindStringIndicesDispatch(
3841 isolate, *subject, pattern, &indices, 0xffffffff, zone_scope.zone());
3843 int matches = indices.length();
3844 if (matches == 0) return *subject;
3846 // Detect integer overflow.
3847 int64_t result_len_64 =
3848 (static_cast<int64_t>(replacement_len) -
3849 static_cast<int64_t>(pattern_len)) *
3850 static_cast<int64_t>(matches) +
3851 static_cast<int64_t>(subject_len);
3853 if (result_len_64 > static_cast<int64_t>(String::kMaxLength)) {
3854 STATIC_ASSERT(String::kMaxLength < kMaxInt);
3855 result_len = kMaxInt; // Provoke exception.
3857 result_len = static_cast<int>(result_len_64);
3860 int subject_pos = 0;
3863 MaybeHandle<SeqString> maybe_res;
3864 if (ResultSeqString::kHasOneByteEncoding) {
3865 maybe_res = isolate->factory()->NewRawOneByteString(result_len);
3867 maybe_res = isolate->factory()->NewRawTwoByteString(result_len);
3869 Handle<SeqString> untyped_res;
3870 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, untyped_res, maybe_res);
3871 Handle<ResultSeqString> result = Handle<ResultSeqString>::cast(untyped_res);
3873 for (int i = 0; i < matches; i++) {
3874 // Copy non-matched subject content.
3875 if (subject_pos < indices.at(i)) {
3876 String::WriteToFlat(*subject,
3877 result->GetChars() + result_pos,
3880 result_pos += indices.at(i) - subject_pos;
3884 if (replacement_len > 0) {
3885 String::WriteToFlat(*replacement,
3886 result->GetChars() + result_pos,
3889 result_pos += replacement_len;
3892 subject_pos = indices.at(i) + pattern_len;
3894 // Add remaining subject content at the end.
3895 if (subject_pos < subject_len) {
3896 String::WriteToFlat(*subject,
3897 result->GetChars() + result_pos,
3902 int32_t match_indices[] = { indices.at(matches - 1),
3903 indices.at(matches - 1) + pattern_len };
3904 RegExpImpl::SetLastMatchInfo(last_match_info, subject, 0, match_indices);
3910 MUST_USE_RESULT static Object* StringReplaceGlobalRegExpWithString(
3912 Handle<String> subject,
3913 Handle<JSRegExp> regexp,
3914 Handle<String> replacement,
3915 Handle<JSArray> last_match_info) {
3916 DCHECK(subject->IsFlat());
3917 DCHECK(replacement->IsFlat());
3919 int capture_count = regexp->CaptureCount();
3920 int subject_length = subject->length();
3922 // CompiledReplacement uses zone allocation.
3923 ZoneScope zone_scope(isolate->runtime_zone());
3924 CompiledReplacement compiled_replacement(zone_scope.zone());
3925 bool simple_replace = compiled_replacement.Compile(replacement,
3929 // Shortcut for simple non-regexp global replacements
3930 if (regexp->TypeTag() == JSRegExp::ATOM && simple_replace) {
3931 if (subject->HasOnlyOneByteChars() &&
3932 replacement->HasOnlyOneByteChars()) {
3933 return StringReplaceGlobalAtomRegExpWithString<SeqOneByteString>(
3934 isolate, subject, regexp, replacement, last_match_info);
3936 return StringReplaceGlobalAtomRegExpWithString<SeqTwoByteString>(
3937 isolate, subject, regexp, replacement, last_match_info);
3941 RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
3942 if (global_cache.HasException()) return isolate->heap()->exception();
3944 int32_t* current_match = global_cache.FetchNext();
3945 if (current_match == NULL) {
3946 if (global_cache.HasException()) return isolate->heap()->exception();
3950 // Guessing the number of parts that the final result string is built
3951 // from. Global regexps can match any number of times, so we guess
3953 int expected_parts = (compiled_replacement.parts() + 1) * 4 + 1;
3954 ReplacementStringBuilder builder(isolate->heap(),
3958 // Number of parts added by compiled replacement plus preceeding
3959 // string and possibly suffix after last match. It is possible for
3960 // all components to use two elements when encoded as two smis.
3961 const int parts_added_per_loop = 2 * (compiled_replacement.parts() + 2);
3966 builder.EnsureCapacity(parts_added_per_loop);
3968 int start = current_match[0];
3969 int end = current_match[1];
3972 builder.AddSubjectSlice(prev, start);
3975 if (simple_replace) {
3976 builder.AddString(replacement);
3978 compiled_replacement.Apply(&builder,
3985 current_match = global_cache.FetchNext();
3986 } while (current_match != NULL);
3988 if (global_cache.HasException()) return isolate->heap()->exception();
3990 if (prev < subject_length) {
3991 builder.EnsureCapacity(2);
3992 builder.AddSubjectSlice(prev, subject_length);
3995 RegExpImpl::SetLastMatchInfo(last_match_info,
3998 global_cache.LastSuccessfulMatch());
4000 Handle<String> result;
4001 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, builder.ToString());
4006 template <typename ResultSeqString>
4007 MUST_USE_RESULT static Object* StringReplaceGlobalRegExpWithEmptyString(
4009 Handle<String> subject,
4010 Handle<JSRegExp> regexp,
4011 Handle<JSArray> last_match_info) {
4012 DCHECK(subject->IsFlat());
4014 // Shortcut for simple non-regexp global replacements
4015 if (regexp->TypeTag() == JSRegExp::ATOM) {
4016 Handle<String> empty_string = isolate->factory()->empty_string();
4017 if (subject->IsOneByteRepresentation()) {
4018 return StringReplaceGlobalAtomRegExpWithString<SeqOneByteString>(
4019 isolate, subject, regexp, empty_string, last_match_info);
4021 return StringReplaceGlobalAtomRegExpWithString<SeqTwoByteString>(
4022 isolate, subject, regexp, empty_string, last_match_info);
4026 RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
4027 if (global_cache.HasException()) return isolate->heap()->exception();
4029 int32_t* current_match = global_cache.FetchNext();
4030 if (current_match == NULL) {
4031 if (global_cache.HasException()) return isolate->heap()->exception();
4035 int start = current_match[0];
4036 int end = current_match[1];
4037 int capture_count = regexp->CaptureCount();
4038 int subject_length = subject->length();
4040 int new_length = subject_length - (end - start);
4041 if (new_length == 0) return isolate->heap()->empty_string();
4043 Handle<ResultSeqString> answer;
4044 if (ResultSeqString::kHasOneByteEncoding) {
4045 answer = Handle<ResultSeqString>::cast(
4046 isolate->factory()->NewRawOneByteString(new_length).ToHandleChecked());
4048 answer = Handle<ResultSeqString>::cast(
4049 isolate->factory()->NewRawTwoByteString(new_length).ToHandleChecked());
4056 start = current_match[0];
4057 end = current_match[1];
4059 // Add substring subject[prev;start] to answer string.
4060 String::WriteToFlat(*subject, answer->GetChars() + position, prev, start);
4061 position += start - prev;
4065 current_match = global_cache.FetchNext();
4066 } while (current_match != NULL);
4068 if (global_cache.HasException()) return isolate->heap()->exception();
4070 RegExpImpl::SetLastMatchInfo(last_match_info,
4073 global_cache.LastSuccessfulMatch());
4075 if (prev < subject_length) {
4076 // Add substring subject[prev;length] to answer string.
4077 String::WriteToFlat(
4078 *subject, answer->GetChars() + position, prev, subject_length);
4079 position += subject_length - prev;
4082 if (position == 0) return isolate->heap()->empty_string();
4084 // Shorten string and fill
4085 int string_size = ResultSeqString::SizeFor(position);
4086 int allocated_string_size = ResultSeqString::SizeFor(new_length);
4087 int delta = allocated_string_size - string_size;
4089 answer->set_length(position);
4090 if (delta == 0) return *answer;
4092 Address end_of_string = answer->address() + string_size;
4093 Heap* heap = isolate->heap();
4095 // The trimming is performed on a newly allocated object, which is on a
4096 // fresly allocated page or on an already swept page. Hence, the sweeper
4097 // thread can not get confused with the filler creation. No synchronization
4099 heap->CreateFillerObjectAt(end_of_string, delta);
4100 heap->AdjustLiveBytes(answer->address(), -delta, Heap::FROM_MUTATOR);
4105 RUNTIME_FUNCTION(Runtime_StringReplaceGlobalRegExpWithString) {
4106 HandleScope scope(isolate);
4107 DCHECK(args.length() == 4);
4109 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
4110 CONVERT_ARG_HANDLE_CHECKED(String, replacement, 2);
4111 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 1);
4112 CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 3);
4114 RUNTIME_ASSERT(regexp->GetFlags().is_global());
4115 RUNTIME_ASSERT(last_match_info->HasFastObjectElements());
4117 subject = String::Flatten(subject);
4119 if (replacement->length() == 0) {
4120 if (subject->HasOnlyOneByteChars()) {
4121 return StringReplaceGlobalRegExpWithEmptyString<SeqOneByteString>(
4122 isolate, subject, regexp, last_match_info);
4124 return StringReplaceGlobalRegExpWithEmptyString<SeqTwoByteString>(
4125 isolate, subject, regexp, last_match_info);
4129 replacement = String::Flatten(replacement);
4131 return StringReplaceGlobalRegExpWithString(
4132 isolate, subject, regexp, replacement, last_match_info);
4136 // This may return an empty MaybeHandle if an exception is thrown or
4137 // we abort due to reaching the recursion limit.
4138 MaybeHandle<String> StringReplaceOneCharWithString(Isolate* isolate,
4139 Handle<String> subject,
4140 Handle<String> search,
4141 Handle<String> replace,
4143 int recursion_limit) {
4144 StackLimitCheck stackLimitCheck(isolate);
4145 if (stackLimitCheck.HasOverflowed() || (recursion_limit == 0)) {
4146 return MaybeHandle<String>();
4149 if (subject->IsConsString()) {
4150 ConsString* cons = ConsString::cast(*subject);
4151 Handle<String> first = Handle<String>(cons->first());
4152 Handle<String> second = Handle<String>(cons->second());
4153 Handle<String> new_first;
4154 if (!StringReplaceOneCharWithString(
4155 isolate, first, search, replace, found, recursion_limit)
4156 .ToHandle(&new_first)) {
4157 return MaybeHandle<String>();
4159 if (*found) return isolate->factory()->NewConsString(new_first, second);
4161 Handle<String> new_second;
4162 if (!StringReplaceOneCharWithString(
4163 isolate, second, search, replace, found, recursion_limit)
4164 .ToHandle(&new_second)) {
4165 return MaybeHandle<String>();
4167 if (*found) return isolate->factory()->NewConsString(first, new_second);
4171 int index = Runtime::StringMatch(isolate, subject, search, 0);
4172 if (index == -1) return subject;
4174 Handle<String> first = isolate->factory()->NewSubString(subject, 0, index);
4175 Handle<String> cons1;
4176 ASSIGN_RETURN_ON_EXCEPTION(
4178 isolate->factory()->NewConsString(first, replace),
4180 Handle<String> second =
4181 isolate->factory()->NewSubString(subject, index + 1, subject->length());
4182 return isolate->factory()->NewConsString(cons1, second);
4187 RUNTIME_FUNCTION(Runtime_StringReplaceOneCharWithString) {
4188 HandleScope scope(isolate);
4189 DCHECK(args.length() == 3);
4190 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
4191 CONVERT_ARG_HANDLE_CHECKED(String, search, 1);
4192 CONVERT_ARG_HANDLE_CHECKED(String, replace, 2);
4194 // If the cons string tree is too deep, we simply abort the recursion and
4195 // retry with a flattened subject string.
4196 const int kRecursionLimit = 0x1000;
4198 Handle<String> result;
4199 if (StringReplaceOneCharWithString(
4200 isolate, subject, search, replace, &found, kRecursionLimit)
4201 .ToHandle(&result)) {
4204 if (isolate->has_pending_exception()) return isolate->heap()->exception();
4206 subject = String::Flatten(subject);
4207 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
4209 StringReplaceOneCharWithString(
4210 isolate, subject, search, replace, &found, kRecursionLimit));
4215 // Perform string match of pattern on subject, starting at start index.
4216 // Caller must ensure that 0 <= start_index <= sub->length(),
4217 // and should check that pat->length() + start_index <= sub->length().
4218 int Runtime::StringMatch(Isolate* isolate,
4222 DCHECK(0 <= start_index);
4223 DCHECK(start_index <= sub->length());
4225 int pattern_length = pat->length();
4226 if (pattern_length == 0) return start_index;
4228 int subject_length = sub->length();
4229 if (start_index + pattern_length > subject_length) return -1;
4231 sub = String::Flatten(sub);
4232 pat = String::Flatten(pat);
4234 DisallowHeapAllocation no_gc; // ensure vectors stay valid
4235 // Extract flattened substrings of cons strings before getting encoding.
4236 String::FlatContent seq_sub = sub->GetFlatContent();
4237 String::FlatContent seq_pat = pat->GetFlatContent();
4239 // dispatch on type of strings
4240 if (seq_pat.IsOneByte()) {
4241 Vector<const uint8_t> pat_vector = seq_pat.ToOneByteVector();
4242 if (seq_sub.IsOneByte()) {
4243 return SearchString(isolate,
4244 seq_sub.ToOneByteVector(),
4248 return SearchString(isolate,
4249 seq_sub.ToUC16Vector(),
4253 Vector<const uc16> pat_vector = seq_pat.ToUC16Vector();
4254 if (seq_sub.IsOneByte()) {
4255 return SearchString(isolate,
4256 seq_sub.ToOneByteVector(),
4260 return SearchString(isolate,
4261 seq_sub.ToUC16Vector(),
4267 RUNTIME_FUNCTION(Runtime_StringIndexOf) {
4268 HandleScope scope(isolate);
4269 DCHECK(args.length() == 3);
4271 CONVERT_ARG_HANDLE_CHECKED(String, sub, 0);
4272 CONVERT_ARG_HANDLE_CHECKED(String, pat, 1);
4273 CONVERT_ARG_HANDLE_CHECKED(Object, index, 2);
4275 uint32_t start_index;
4276 if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
4278 RUNTIME_ASSERT(start_index <= static_cast<uint32_t>(sub->length()));
4279 int position = Runtime::StringMatch(isolate, sub, pat, start_index);
4280 return Smi::FromInt(position);
4284 template <typename schar, typename pchar>
4285 static int StringMatchBackwards(Vector<const schar> subject,
4286 Vector<const pchar> pattern,
4288 int pattern_length = pattern.length();
4289 DCHECK(pattern_length >= 1);
4290 DCHECK(idx + pattern_length <= subject.length());
4292 if (sizeof(schar) == 1 && sizeof(pchar) > 1) {
4293 for (int i = 0; i < pattern_length; i++) {
4294 uc16 c = pattern[i];
4295 if (c > String::kMaxOneByteCharCode) {
4301 pchar pattern_first_char = pattern[0];
4302 for (int i = idx; i >= 0; i--) {
4303 if (subject[i] != pattern_first_char) continue;
4305 while (j < pattern_length) {
4306 if (pattern[j] != subject[i+j]) {
4311 if (j == pattern_length) {
4319 RUNTIME_FUNCTION(Runtime_StringLastIndexOf) {
4320 HandleScope scope(isolate);
4321 DCHECK(args.length() == 3);
4323 CONVERT_ARG_HANDLE_CHECKED(String, sub, 0);
4324 CONVERT_ARG_HANDLE_CHECKED(String, pat, 1);
4325 CONVERT_ARG_HANDLE_CHECKED(Object, index, 2);
4327 uint32_t start_index;
4328 if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
4330 uint32_t pat_length = pat->length();
4331 uint32_t sub_length = sub->length();
4333 if (start_index + pat_length > sub_length) {
4334 start_index = sub_length - pat_length;
4337 if (pat_length == 0) {
4338 return Smi::FromInt(start_index);
4341 sub = String::Flatten(sub);
4342 pat = String::Flatten(pat);
4345 DisallowHeapAllocation no_gc; // ensure vectors stay valid
4347 String::FlatContent sub_content = sub->GetFlatContent();
4348 String::FlatContent pat_content = pat->GetFlatContent();
4350 if (pat_content.IsOneByte()) {
4351 Vector<const uint8_t> pat_vector = pat_content.ToOneByteVector();
4352 if (sub_content.IsOneByte()) {
4353 position = StringMatchBackwards(sub_content.ToOneByteVector(),
4357 position = StringMatchBackwards(sub_content.ToUC16Vector(),
4362 Vector<const uc16> pat_vector = pat_content.ToUC16Vector();
4363 if (sub_content.IsOneByte()) {
4364 position = StringMatchBackwards(sub_content.ToOneByteVector(),
4368 position = StringMatchBackwards(sub_content.ToUC16Vector(),
4374 return Smi::FromInt(position);
4378 RUNTIME_FUNCTION(Runtime_StringLocaleCompare) {
4379 HandleScope handle_scope(isolate);
4380 DCHECK(args.length() == 2);
4382 CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
4383 CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
4385 if (str1.is_identical_to(str2)) return Smi::FromInt(0); // Equal.
4386 int str1_length = str1->length();
4387 int str2_length = str2->length();
4389 // Decide trivial cases without flattening.
4390 if (str1_length == 0) {
4391 if (str2_length == 0) return Smi::FromInt(0); // Equal.
4392 return Smi::FromInt(-str2_length);
4394 if (str2_length == 0) return Smi::FromInt(str1_length);
4397 int end = str1_length < str2_length ? str1_length : str2_length;
4399 // No need to flatten if we are going to find the answer on the first
4400 // character. At this point we know there is at least one character
4401 // in each string, due to the trivial case handling above.
4402 int d = str1->Get(0) - str2->Get(0);
4403 if (d != 0) return Smi::FromInt(d);
4405 str1 = String::Flatten(str1);
4406 str2 = String::Flatten(str2);
4408 DisallowHeapAllocation no_gc;
4409 String::FlatContent flat1 = str1->GetFlatContent();
4410 String::FlatContent flat2 = str2->GetFlatContent();
4412 for (int i = 0; i < end; i++) {
4413 if (flat1.Get(i) != flat2.Get(i)) {
4414 return Smi::FromInt(flat1.Get(i) - flat2.Get(i));
4418 return Smi::FromInt(str1_length - str2_length);
4422 RUNTIME_FUNCTION(Runtime_SubString) {
4423 HandleScope scope(isolate);
4424 DCHECK(args.length() == 3);
4426 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
4428 // We have a fast integer-only case here to avoid a conversion to double in
4429 // the common case where from and to are Smis.
4430 if (args[1]->IsSmi() && args[2]->IsSmi()) {
4431 CONVERT_SMI_ARG_CHECKED(from_number, 1);
4432 CONVERT_SMI_ARG_CHECKED(to_number, 2);
4433 start = from_number;
4436 CONVERT_DOUBLE_ARG_CHECKED(from_number, 1);
4437 CONVERT_DOUBLE_ARG_CHECKED(to_number, 2);
4438 start = FastD2IChecked(from_number);
4439 end = FastD2IChecked(to_number);
4441 RUNTIME_ASSERT(end >= start);
4442 RUNTIME_ASSERT(start >= 0);
4443 RUNTIME_ASSERT(end <= string->length());
4444 isolate->counters()->sub_string_runtime()->Increment();
4446 return *isolate->factory()->NewSubString(string, start, end);
4450 RUNTIME_FUNCTION(Runtime_InternalizeString) {
4451 HandleScope handles(isolate);
4452 RUNTIME_ASSERT(args.length() == 1);
4453 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
4454 return *isolate->factory()->InternalizeString(string);
4458 RUNTIME_FUNCTION(Runtime_StringMatch) {
4459 HandleScope handles(isolate);
4460 DCHECK(args.length() == 3);
4462 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
4463 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 1);
4464 CONVERT_ARG_HANDLE_CHECKED(JSArray, regexp_info, 2);
4466 RUNTIME_ASSERT(regexp_info->HasFastObjectElements());
4468 RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
4469 if (global_cache.HasException()) return isolate->heap()->exception();
4471 int capture_count = regexp->CaptureCount();
4473 ZoneScope zone_scope(isolate->runtime_zone());
4474 ZoneList<int> offsets(8, zone_scope.zone());
4477 int32_t* match = global_cache.FetchNext();
4478 if (match == NULL) break;
4479 offsets.Add(match[0], zone_scope.zone()); // start
4480 offsets.Add(match[1], zone_scope.zone()); // end
4483 if (global_cache.HasException()) return isolate->heap()->exception();
4485 if (offsets.length() == 0) {
4486 // Not a single match.
4487 return isolate->heap()->null_value();
4490 RegExpImpl::SetLastMatchInfo(regexp_info,
4493 global_cache.LastSuccessfulMatch());
4495 int matches = offsets.length() / 2;
4496 Handle<FixedArray> elements = isolate->factory()->NewFixedArray(matches);
4497 Handle<String> substring =
4498 isolate->factory()->NewSubString(subject, offsets.at(0), offsets.at(1));
4499 elements->set(0, *substring);
4500 for (int i = 1; i < matches; i++) {
4501 HandleScope temp_scope(isolate);
4502 int from = offsets.at(i * 2);
4503 int to = offsets.at(i * 2 + 1);
4504 Handle<String> substring =
4505 isolate->factory()->NewProperSubString(subject, from, to);
4506 elements->set(i, *substring);
4508 Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(elements);
4509 result->set_length(Smi::FromInt(matches));
4514 // Only called from Runtime_RegExpExecMultiple so it doesn't need to maintain
4515 // separate last match info. See comment on that function.
4516 template<bool has_capture>
4517 static Object* SearchRegExpMultiple(
4519 Handle<String> subject,
4520 Handle<JSRegExp> regexp,
4521 Handle<JSArray> last_match_array,
4522 Handle<JSArray> result_array) {
4523 DCHECK(subject->IsFlat());
4524 DCHECK_NE(has_capture, regexp->CaptureCount() == 0);
4526 int capture_count = regexp->CaptureCount();
4527 int subject_length = subject->length();
4529 static const int kMinLengthToCache = 0x1000;
4531 if (subject_length > kMinLengthToCache) {
4532 Handle<Object> cached_answer(RegExpResultsCache::Lookup(
4536 RegExpResultsCache::REGEXP_MULTIPLE_INDICES), isolate);
4537 if (*cached_answer != Smi::FromInt(0)) {
4538 Handle<FixedArray> cached_fixed_array =
4539 Handle<FixedArray>(FixedArray::cast(*cached_answer));
4540 // The cache FixedArray is a COW-array and can therefore be reused.
4541 JSArray::SetContent(result_array, cached_fixed_array);
4542 // The actual length of the result array is stored in the last element of
4543 // the backing store (the backing FixedArray may have a larger capacity).
4544 Object* cached_fixed_array_last_element =
4545 cached_fixed_array->get(cached_fixed_array->length() - 1);
4546 Smi* js_array_length = Smi::cast(cached_fixed_array_last_element);
4547 result_array->set_length(js_array_length);
4548 RegExpImpl::SetLastMatchInfo(
4549 last_match_array, subject, capture_count, NULL);
4550 return *result_array;
4554 RegExpImpl::GlobalCache global_cache(regexp, subject, true, isolate);
4555 if (global_cache.HasException()) return isolate->heap()->exception();
4557 // Ensured in Runtime_RegExpExecMultiple.
4558 DCHECK(result_array->HasFastObjectElements());
4559 Handle<FixedArray> result_elements(
4560 FixedArray::cast(result_array->elements()));
4561 if (result_elements->length() < 16) {
4562 result_elements = isolate->factory()->NewFixedArrayWithHoles(16);
4565 FixedArrayBuilder builder(result_elements);
4567 // Position to search from.
4568 int match_start = -1;
4572 // Two smis before and after the match, for very long strings.
4573 static const int kMaxBuilderEntriesPerRegExpMatch = 5;
4576 int32_t* current_match = global_cache.FetchNext();
4577 if (current_match == NULL) break;
4578 match_start = current_match[0];
4579 builder.EnsureCapacity(kMaxBuilderEntriesPerRegExpMatch);
4580 if (match_end < match_start) {
4581 ReplacementStringBuilder::AddSubjectSlice(&builder,
4585 match_end = current_match[1];
4587 // Avoid accumulating new handles inside loop.
4588 HandleScope temp_scope(isolate);
4589 Handle<String> match;
4591 match = isolate->factory()->NewProperSubString(subject,
4595 match = isolate->factory()->NewSubString(subject,
4602 // Arguments array to replace function is match, captures, index and
4603 // subject, i.e., 3 + capture count in total.
4604 Handle<FixedArray> elements =
4605 isolate->factory()->NewFixedArray(3 + capture_count);
4607 elements->set(0, *match);
4608 for (int i = 1; i <= capture_count; i++) {
4609 int start = current_match[i * 2];
4611 int end = current_match[i * 2 + 1];
4612 DCHECK(start <= end);
4613 Handle<String> substring =
4614 isolate->factory()->NewSubString(subject, start, end);
4615 elements->set(i, *substring);
4617 DCHECK(current_match[i * 2 + 1] < 0);
4618 elements->set(i, isolate->heap()->undefined_value());
4621 elements->set(capture_count + 1, Smi::FromInt(match_start));
4622 elements->set(capture_count + 2, *subject);
4623 builder.Add(*isolate->factory()->NewJSArrayWithElements(elements));
4625 builder.Add(*match);
4630 if (global_cache.HasException()) return isolate->heap()->exception();
4632 if (match_start >= 0) {
4633 // Finished matching, with at least one match.
4634 if (match_end < subject_length) {
4635 ReplacementStringBuilder::AddSubjectSlice(&builder,
4640 RegExpImpl::SetLastMatchInfo(
4641 last_match_array, subject, capture_count, NULL);
4643 if (subject_length > kMinLengthToCache) {
4644 // Store the length of the result array into the last element of the
4645 // backing FixedArray.
4646 builder.EnsureCapacity(1);
4647 Handle<FixedArray> fixed_array = builder.array();
4648 fixed_array->set(fixed_array->length() - 1,
4649 Smi::FromInt(builder.length()));
4650 // Cache the result and turn the FixedArray into a COW array.
4651 RegExpResultsCache::Enter(isolate,
4653 handle(regexp->data(), isolate),
4655 RegExpResultsCache::REGEXP_MULTIPLE_INDICES);
4657 return *builder.ToJSArray(result_array);
4659 return isolate->heap()->null_value(); // No matches at all.
4664 // This is only called for StringReplaceGlobalRegExpWithFunction. This sets
4665 // lastMatchInfoOverride to maintain the last match info, so we don't need to
4666 // set any other last match array info.
4667 RUNTIME_FUNCTION(Runtime_RegExpExecMultiple) {
4668 HandleScope handles(isolate);
4669 DCHECK(args.length() == 4);
4671 CONVERT_ARG_HANDLE_CHECKED(String, subject, 1);
4672 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 0);
4673 CONVERT_ARG_HANDLE_CHECKED(JSArray, last_match_info, 2);
4674 CONVERT_ARG_HANDLE_CHECKED(JSArray, result_array, 3);
4675 RUNTIME_ASSERT(last_match_info->HasFastObjectElements());
4676 RUNTIME_ASSERT(result_array->HasFastObjectElements());
4678 subject = String::Flatten(subject);
4679 RUNTIME_ASSERT(regexp->GetFlags().is_global());
4681 if (regexp->CaptureCount() == 0) {
4682 return SearchRegExpMultiple<false>(
4683 isolate, subject, regexp, last_match_info, result_array);
4685 return SearchRegExpMultiple<true>(
4686 isolate, subject, regexp, last_match_info, result_array);
4691 RUNTIME_FUNCTION(Runtime_NumberToRadixString) {
4692 HandleScope scope(isolate);
4693 DCHECK(args.length() == 2);
4694 CONVERT_SMI_ARG_CHECKED(radix, 1);
4695 RUNTIME_ASSERT(2 <= radix && radix <= 36);
4697 // Fast case where the result is a one character string.
4698 if (args[0]->IsSmi()) {
4699 int value = args.smi_at(0);
4700 if (value >= 0 && value < radix) {
4701 // Character array used for conversion.
4702 static const char kCharTable[] = "0123456789abcdefghijklmnopqrstuvwxyz";
4703 return *isolate->factory()->
4704 LookupSingleCharacterStringFromCode(kCharTable[value]);
4709 CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4710 if (std::isnan(value)) {
4711 return isolate->heap()->nan_string();
4713 if (std::isinf(value)) {
4715 return isolate->heap()->minus_infinity_string();
4717 return isolate->heap()->infinity_string();
4719 char* str = DoubleToRadixCString(value, radix);
4720 Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4726 RUNTIME_FUNCTION(Runtime_NumberToFixed) {
4727 HandleScope scope(isolate);
4728 DCHECK(args.length() == 2);
4730 CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4731 CONVERT_DOUBLE_ARG_CHECKED(f_number, 1);
4732 int f = FastD2IChecked(f_number);
4733 // See DoubleToFixedCString for these constants:
4734 RUNTIME_ASSERT(f >= 0 && f <= 20);
4735 RUNTIME_ASSERT(!Double(value).IsSpecial());
4736 char* str = DoubleToFixedCString(value, f);
4737 Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4743 RUNTIME_FUNCTION(Runtime_NumberToExponential) {
4744 HandleScope scope(isolate);
4745 DCHECK(args.length() == 2);
4747 CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4748 CONVERT_DOUBLE_ARG_CHECKED(f_number, 1);
4749 int f = FastD2IChecked(f_number);
4750 RUNTIME_ASSERT(f >= -1 && f <= 20);
4751 RUNTIME_ASSERT(!Double(value).IsSpecial());
4752 char* str = DoubleToExponentialCString(value, f);
4753 Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4759 RUNTIME_FUNCTION(Runtime_NumberToPrecision) {
4760 HandleScope scope(isolate);
4761 DCHECK(args.length() == 2);
4763 CONVERT_DOUBLE_ARG_CHECKED(value, 0);
4764 CONVERT_DOUBLE_ARG_CHECKED(f_number, 1);
4765 int f = FastD2IChecked(f_number);
4766 RUNTIME_ASSERT(f >= 1 && f <= 21);
4767 RUNTIME_ASSERT(!Double(value).IsSpecial());
4768 char* str = DoubleToPrecisionCString(value, f);
4769 Handle<String> result = isolate->factory()->NewStringFromAsciiChecked(str);
4775 RUNTIME_FUNCTION(Runtime_IsValidSmi) {
4776 SealHandleScope shs(isolate);
4777 DCHECK(args.length() == 1);
4779 CONVERT_NUMBER_CHECKED(int32_t, number, Int32, args[0]);
4780 return isolate->heap()->ToBoolean(Smi::IsValid(number));
4784 // Returns a single character string where first character equals
4785 // string->Get(index).
4786 static Handle<Object> GetCharAt(Handle<String> string, uint32_t index) {
4787 if (index < static_cast<uint32_t>(string->length())) {
4788 Factory* factory = string->GetIsolate()->factory();
4789 return factory->LookupSingleCharacterStringFromCode(
4790 String::Flatten(string)->Get(index));
4792 return Execution::CharAt(string, index);
4796 MaybeHandle<Object> Runtime::GetElementOrCharAt(Isolate* isolate,
4797 Handle<Object> object,
4799 // Handle [] indexing on Strings
4800 if (object->IsString()) {
4801 Handle<Object> result = GetCharAt(Handle<String>::cast(object), index);
4802 if (!result->IsUndefined()) return result;
4805 // Handle [] indexing on String objects
4806 if (object->IsStringObjectWithCharacterAt(index)) {
4807 Handle<JSValue> js_value = Handle<JSValue>::cast(object);
4808 Handle<Object> result =
4809 GetCharAt(Handle<String>(String::cast(js_value->value())), index);
4810 if (!result->IsUndefined()) return result;
4813 Handle<Object> result;
4814 if (object->IsString() || object->IsNumber() || object->IsBoolean()) {
4815 PrototypeIterator iter(isolate, object);
4816 return Object::GetElement(isolate, PrototypeIterator::GetCurrent(iter),
4819 return Object::GetElement(isolate, object, index);
4825 static MaybeHandle<Name> ToName(Isolate* isolate, Handle<Object> key) {
4826 if (key->IsName()) {
4827 return Handle<Name>::cast(key);
4829 Handle<Object> converted;
4830 ASSIGN_RETURN_ON_EXCEPTION(
4831 isolate, converted, Execution::ToString(isolate, key), Name);
4832 return Handle<Name>::cast(converted);
4837 MaybeHandle<Object> Runtime::HasObjectProperty(Isolate* isolate,
4838 Handle<JSReceiver> object,
4839 Handle<Object> key) {
4841 // Check if the given key is an array index.
4843 if (key->ToArrayIndex(&index)) {
4844 maybe = JSReceiver::HasElement(object, index);
4846 // Convert the key to a name - possibly by calling back into JavaScript.
4848 ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object);
4850 maybe = JSReceiver::HasProperty(object, name);
4853 if (!maybe.has_value) return MaybeHandle<Object>();
4854 return isolate->factory()->ToBoolean(maybe.value);
4858 MaybeHandle<Object> Runtime::GetObjectProperty(Isolate* isolate,
4859 Handle<Object> object,
4860 Handle<Object> key) {
4861 if (object->IsUndefined() || object->IsNull()) {
4862 Handle<Object> args[2] = { key, object };
4863 THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_load",
4864 HandleVector(args, 2)),
4868 // Check if the given key is an array index.
4870 if (key->ToArrayIndex(&index)) {
4871 return GetElementOrCharAt(isolate, object, index);
4874 // Convert the key to a name - possibly by calling back into JavaScript.
4876 ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object);
4878 // Check if the name is trivially convertible to an index and get
4879 // the element if so.
4880 if (name->AsArrayIndex(&index)) {
4881 return GetElementOrCharAt(isolate, object, index);
4883 return Object::GetProperty(object, name);
4888 RUNTIME_FUNCTION(Runtime_GetProperty) {
4889 HandleScope scope(isolate);
4890 DCHECK(args.length() == 2);
4892 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
4893 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
4894 Handle<Object> result;
4895 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
4897 Runtime::GetObjectProperty(isolate, object, key));
4902 // KeyedGetProperty is called from KeyedLoadIC::GenerateGeneric.
4903 RUNTIME_FUNCTION(Runtime_KeyedGetProperty) {
4904 HandleScope scope(isolate);
4905 DCHECK(args.length() == 2);
4907 CONVERT_ARG_HANDLE_CHECKED(Object, receiver_obj, 0);
4908 CONVERT_ARG_HANDLE_CHECKED(Object, key_obj, 1);
4910 // Fast cases for getting named properties of the receiver JSObject
4913 // The global proxy objects has to be excluded since LookupOwn on
4914 // the global proxy object can return a valid result even though the
4915 // global proxy object never has properties. This is the case
4916 // because the global proxy object forwards everything to its hidden
4917 // prototype including own lookups.
4919 // Additionally, we need to make sure that we do not cache results
4920 // for objects that require access checks.
4921 if (receiver_obj->IsJSObject()) {
4922 if (!receiver_obj->IsJSGlobalProxy() &&
4923 !receiver_obj->IsAccessCheckNeeded() &&
4924 key_obj->IsName()) {
4925 DisallowHeapAllocation no_allocation;
4926 Handle<JSObject> receiver = Handle<JSObject>::cast(receiver_obj);
4927 Handle<Name> key = Handle<Name>::cast(key_obj);
4928 if (receiver->HasFastProperties()) {
4929 // Attempt to use lookup cache.
4930 Handle<Map> receiver_map(receiver->map(), isolate);
4931 KeyedLookupCache* keyed_lookup_cache = isolate->keyed_lookup_cache();
4932 int index = keyed_lookup_cache->Lookup(receiver_map, key);
4934 // Doubles are not cached, so raw read the value.
4935 return receiver->RawFastPropertyAt(
4936 FieldIndex::ForKeyedLookupCacheIndex(*receiver_map, index));
4938 // Lookup cache miss. Perform lookup and update the cache if
4940 LookupIterator it(receiver, key, LookupIterator::OWN);
4941 if (it.state() == LookupIterator::DATA &&
4942 it.property_details().type() == FIELD) {
4943 FieldIndex field_index = it.GetFieldIndex();
4944 // Do not track double fields in the keyed lookup cache. Reading
4945 // double values requires boxing.
4946 if (!it.representation().IsDouble()) {
4947 keyed_lookup_cache->Update(receiver_map, key,
4948 field_index.GetKeyedLookupCacheIndex());
4950 AllowHeapAllocation allow_allocation;
4951 return *JSObject::FastPropertyAt(receiver, it.representation(),
4955 // Attempt dictionary lookup.
4956 NameDictionary* dictionary = receiver->property_dictionary();
4957 int entry = dictionary->FindEntry(key);
4958 if ((entry != NameDictionary::kNotFound) &&
4959 (dictionary->DetailsAt(entry).type() == NORMAL)) {
4960 Object* value = dictionary->ValueAt(entry);
4961 if (!receiver->IsGlobalObject()) return value;
4962 value = PropertyCell::cast(value)->value();
4963 if (!value->IsTheHole()) return value;
4964 // If value is the hole (meaning, absent) do the general lookup.
4967 } else if (key_obj->IsSmi()) {
4968 // JSObject without a name key. If the key is a Smi, check for a
4969 // definite out-of-bounds access to elements, which is a strong indicator
4970 // that subsequent accesses will also call the runtime. Proactively
4971 // transition elements to FAST_*_ELEMENTS to avoid excessive boxing of
4972 // doubles for those future calls in the case that the elements would
4973 // become FAST_DOUBLE_ELEMENTS.
4974 Handle<JSObject> js_object = Handle<JSObject>::cast(receiver_obj);
4975 ElementsKind elements_kind = js_object->GetElementsKind();
4976 if (IsFastDoubleElementsKind(elements_kind)) {
4977 Handle<Smi> key = Handle<Smi>::cast(key_obj);
4978 if (key->value() >= js_object->elements()->length()) {
4979 if (IsFastHoleyElementsKind(elements_kind)) {
4980 elements_kind = FAST_HOLEY_ELEMENTS;
4982 elements_kind = FAST_ELEMENTS;
4984 RETURN_FAILURE_ON_EXCEPTION(
4985 isolate, TransitionElements(js_object, elements_kind, isolate));
4988 DCHECK(IsFastSmiOrObjectElementsKind(elements_kind) ||
4989 !IsFastElementsKind(elements_kind));
4992 } else if (receiver_obj->IsString() && key_obj->IsSmi()) {
4993 // Fast case for string indexing using [] with a smi index.
4994 Handle<String> str = Handle<String>::cast(receiver_obj);
4995 int index = args.smi_at(1);
4996 if (index >= 0 && index < str->length()) {
4997 return *GetCharAt(str, index);
5001 // Fall back to GetObjectProperty.
5002 Handle<Object> result;
5003 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5005 Runtime::GetObjectProperty(isolate, receiver_obj, key_obj));
5010 static bool IsValidAccessor(Handle<Object> obj) {
5011 return obj->IsUndefined() || obj->IsSpecFunction() || obj->IsNull();
5015 // Transform getter or setter into something DefineAccessor can handle.
5016 static Handle<Object> InstantiateAccessorComponent(Isolate* isolate,
5017 Handle<Object> component) {
5018 if (component->IsUndefined()) return isolate->factory()->undefined_value();
5019 Handle<FunctionTemplateInfo> info =
5020 Handle<FunctionTemplateInfo>::cast(component);
5021 return Utils::OpenHandle(*Utils::ToLocal(info)->GetFunction());
5025 RUNTIME_FUNCTION(Runtime_DefineApiAccessorProperty) {
5026 HandleScope scope(isolate);
5027 DCHECK(args.length() == 5);
5028 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5029 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
5030 CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2);
5031 CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3);
5032 CONVERT_SMI_ARG_CHECKED(attribute, 4);
5033 RUNTIME_ASSERT(getter->IsUndefined() || getter->IsFunctionTemplateInfo());
5034 RUNTIME_ASSERT(setter->IsUndefined() || setter->IsFunctionTemplateInfo());
5035 RUNTIME_ASSERT(PropertyDetails::AttributesField::is_valid(
5036 static_cast<PropertyAttributes>(attribute)));
5037 RETURN_FAILURE_ON_EXCEPTION(
5038 isolate, JSObject::DefineAccessor(
5039 object, name, InstantiateAccessorComponent(isolate, getter),
5040 InstantiateAccessorComponent(isolate, setter),
5041 static_cast<PropertyAttributes>(attribute)));
5042 return isolate->heap()->undefined_value();
5046 // Implements part of 8.12.9 DefineOwnProperty.
5047 // There are 3 cases that lead here:
5048 // Step 4b - define a new accessor property.
5049 // Steps 9c & 12 - replace an existing data property with an accessor property.
5050 // Step 12 - update an existing accessor property with an accessor or generic
5052 RUNTIME_FUNCTION(Runtime_DefineAccessorPropertyUnchecked) {
5053 HandleScope scope(isolate);
5054 DCHECK(args.length() == 5);
5055 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5056 RUNTIME_ASSERT(!obj->IsNull());
5057 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
5058 CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2);
5059 RUNTIME_ASSERT(IsValidAccessor(getter));
5060 CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3);
5061 RUNTIME_ASSERT(IsValidAccessor(setter));
5062 CONVERT_SMI_ARG_CHECKED(unchecked, 4);
5063 RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5064 PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
5066 bool fast = obj->HasFastProperties();
5067 RETURN_FAILURE_ON_EXCEPTION(
5068 isolate, JSObject::DefineAccessor(obj, name, getter, setter, attr));
5069 if (fast) JSObject::MigrateSlowToFast(obj, 0);
5070 return isolate->heap()->undefined_value();
5074 // Implements part of 8.12.9 DefineOwnProperty.
5075 // There are 3 cases that lead here:
5076 // Step 4a - define a new data property.
5077 // Steps 9b & 12 - replace an existing accessor property with a data property.
5078 // Step 12 - update an existing data property with a data or generic
5080 RUNTIME_FUNCTION(Runtime_DefineDataPropertyUnchecked) {
5081 HandleScope scope(isolate);
5082 DCHECK(args.length() == 4);
5083 CONVERT_ARG_HANDLE_CHECKED(JSObject, js_object, 0);
5084 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
5085 CONVERT_ARG_HANDLE_CHECKED(Object, obj_value, 2);
5086 CONVERT_SMI_ARG_CHECKED(unchecked, 3);
5087 RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5088 PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
5090 LookupIterator it(js_object, name, LookupIterator::OWN_SKIP_INTERCEPTOR);
5091 if (it.IsFound() && it.state() == LookupIterator::ACCESS_CHECK) {
5092 if (!isolate->MayNamedAccess(js_object, name, v8::ACCESS_SET)) {
5093 return isolate->heap()->undefined_value();
5098 // Take special care when attributes are different and there is already
5100 if (it.state() == LookupIterator::ACCESSOR) {
5101 // Use IgnoreAttributes version since a readonly property may be
5102 // overridden and SetProperty does not allow this.
5103 Handle<Object> result;
5104 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5106 JSObject::SetOwnPropertyIgnoreAttributes(
5107 js_object, name, obj_value, attr,
5108 JSObject::DONT_FORCE_FIELD));
5112 Handle<Object> result;
5113 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5115 Runtime::DefineObjectProperty(js_object, name, obj_value, attr));
5120 // Return property without being observable by accessors or interceptors.
5121 RUNTIME_FUNCTION(Runtime_GetDataProperty) {
5122 HandleScope scope(isolate);
5123 DCHECK(args.length() == 2);
5124 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5125 CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5126 return *JSObject::GetDataProperty(object, key);
5130 MaybeHandle<Object> Runtime::SetObjectProperty(Isolate* isolate,
5131 Handle<Object> object,
5133 Handle<Object> value,
5134 StrictMode strict_mode) {
5135 if (object->IsUndefined() || object->IsNull()) {
5136 Handle<Object> args[2] = { key, object };
5137 THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_store",
5138 HandleVector(args, 2)),
5142 if (object->IsJSProxy()) {
5143 Handle<Object> name_object;
5144 if (key->IsSymbol()) {
5147 ASSIGN_RETURN_ON_EXCEPTION(
5148 isolate, name_object, Execution::ToString(isolate, key), Object);
5150 Handle<Name> name = Handle<Name>::cast(name_object);
5151 return Object::SetProperty(Handle<JSProxy>::cast(object), name, value,
5155 // Check if the given key is an array index.
5157 if (key->ToArrayIndex(&index)) {
5158 // TODO(verwaest): Support non-JSObject receivers.
5159 if (!object->IsJSObject()) return value;
5160 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
5162 // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
5163 // of a string using [] notation. We need to support this too in
5165 // In the case of a String object we just need to redirect the assignment to
5166 // the underlying string if the index is in range. Since the underlying
5167 // string does nothing with the assignment then we can ignore such
5169 if (js_object->IsStringObjectWithCharacterAt(index)) {
5173 JSObject::ValidateElements(js_object);
5174 if (js_object->HasExternalArrayElements() ||
5175 js_object->HasFixedTypedArrayElements()) {
5176 if (!value->IsNumber() && !value->IsFloat32x4() &&
5177 !value->IsFloat64x2() && !value->IsInt32x4() &&
5178 !value->IsUndefined()) {
5179 ASSIGN_RETURN_ON_EXCEPTION(
5180 isolate, value, Execution::ToNumber(isolate, value), Object);
5184 MaybeHandle<Object> result = JSObject::SetElement(
5185 js_object, index, value, NONE, strict_mode, true, SET_PROPERTY);
5186 JSObject::ValidateElements(js_object);
5188 return result.is_null() ? result : value;
5191 if (key->IsName()) {
5192 Handle<Name> name = Handle<Name>::cast(key);
5193 if (name->AsArrayIndex(&index)) {
5194 // TODO(verwaest): Support non-JSObject receivers.
5195 if (!object->IsJSObject()) return value;
5196 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
5197 if (js_object->HasExternalArrayElements()) {
5198 if (!value->IsNumber() && !value->IsFloat32x4() &&
5199 !value->IsFloat64x2() && !value->IsInt32x4() &&
5200 !value->IsUndefined()) {
5201 ASSIGN_RETURN_ON_EXCEPTION(
5202 isolate, value, Execution::ToNumber(isolate, value), Object);
5205 return JSObject::SetElement(js_object, index, value, NONE, strict_mode,
5206 true, SET_PROPERTY);
5208 if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
5209 return Object::SetProperty(object, name, value, strict_mode);
5213 // Call-back into JavaScript to convert the key to a string.
5214 Handle<Object> converted;
5215 ASSIGN_RETURN_ON_EXCEPTION(
5216 isolate, converted, Execution::ToString(isolate, key), Object);
5217 Handle<String> name = Handle<String>::cast(converted);
5219 if (name->AsArrayIndex(&index)) {
5220 // TODO(verwaest): Support non-JSObject receivers.
5221 if (!object->IsJSObject()) return value;
5222 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
5223 return JSObject::SetElement(js_object, index, value, NONE, strict_mode,
5224 true, SET_PROPERTY);
5226 return Object::SetProperty(object, name, value, strict_mode);
5230 MaybeHandle<Object> Runtime::DefineObjectProperty(Handle<JSObject> js_object,
5232 Handle<Object> value,
5233 PropertyAttributes attr) {
5234 Isolate* isolate = js_object->GetIsolate();
5235 // Check if the given key is an array index.
5237 if (key->ToArrayIndex(&index)) {
5238 // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
5239 // of a string using [] notation. We need to support this too in
5241 // In the case of a String object we just need to redirect the assignment to
5242 // the underlying string if the index is in range. Since the underlying
5243 // string does nothing with the assignment then we can ignore such
5245 if (js_object->IsStringObjectWithCharacterAt(index)) {
5249 return JSObject::SetElement(js_object, index, value, attr,
5250 SLOPPY, false, DEFINE_PROPERTY);
5253 if (key->IsName()) {
5254 Handle<Name> name = Handle<Name>::cast(key);
5255 if (name->AsArrayIndex(&index)) {
5256 return JSObject::SetElement(js_object, index, value, attr,
5257 SLOPPY, false, DEFINE_PROPERTY);
5259 if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
5260 return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value,
5265 // Call-back into JavaScript to convert the key to a string.
5266 Handle<Object> converted;
5267 ASSIGN_RETURN_ON_EXCEPTION(
5268 isolate, converted, Execution::ToString(isolate, key), Object);
5269 Handle<String> name = Handle<String>::cast(converted);
5271 if (name->AsArrayIndex(&index)) {
5272 return JSObject::SetElement(js_object, index, value, attr,
5273 SLOPPY, false, DEFINE_PROPERTY);
5275 return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value,
5281 MaybeHandle<Object> Runtime::DeleteObjectProperty(Isolate* isolate,
5282 Handle<JSReceiver> receiver,
5284 JSReceiver::DeleteMode mode) {
5285 // Check if the given key is an array index.
5287 if (key->ToArrayIndex(&index)) {
5288 // In Firefox/SpiderMonkey, Safari and Opera you can access the
5289 // characters of a string using [] notation. In the case of a
5290 // String object we just need to redirect the deletion to the
5291 // underlying string if the index is in range. Since the
5292 // underlying string does nothing with the deletion, we can ignore
5294 if (receiver->IsStringObjectWithCharacterAt(index)) {
5295 return isolate->factory()->true_value();
5298 return JSReceiver::DeleteElement(receiver, index, mode);
5302 if (key->IsName()) {
5303 name = Handle<Name>::cast(key);
5305 // Call-back into JavaScript to convert the key to a string.
5306 Handle<Object> converted;
5307 ASSIGN_RETURN_ON_EXCEPTION(
5308 isolate, converted, Execution::ToString(isolate, key), Object);
5309 name = Handle<String>::cast(converted);
5312 if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
5313 return JSReceiver::DeleteProperty(receiver, name, mode);
5317 RUNTIME_FUNCTION(Runtime_SetHiddenProperty) {
5318 HandleScope scope(isolate);
5319 RUNTIME_ASSERT(args.length() == 3);
5321 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5322 CONVERT_ARG_HANDLE_CHECKED(String, key, 1);
5323 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5324 RUNTIME_ASSERT(key->IsUniqueName());
5325 return *JSObject::SetHiddenProperty(object, key, value);
5329 RUNTIME_FUNCTION(Runtime_AddNamedProperty) {
5330 HandleScope scope(isolate);
5331 RUNTIME_ASSERT(args.length() == 4);
5333 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5334 CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5335 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5336 CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
5338 (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5339 // Compute attributes.
5340 PropertyAttributes attributes =
5341 static_cast<PropertyAttributes>(unchecked_attributes);
5345 DCHECK(!key->ToArrayIndex(&index));
5346 LookupIterator it(object, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
5347 Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
5348 if (!maybe.has_value) return isolate->heap()->exception();
5349 RUNTIME_ASSERT(!it.IsFound());
5352 Handle<Object> result;
5353 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5355 JSObject::SetOwnPropertyIgnoreAttributes(object, key, value, attributes));
5360 RUNTIME_FUNCTION(Runtime_AddPropertyForTemplate) {
5361 HandleScope scope(isolate);
5362 RUNTIME_ASSERT(args.length() == 4);
5364 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5365 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
5366 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5367 CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
5369 (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5370 // Compute attributes.
5371 PropertyAttributes attributes =
5372 static_cast<PropertyAttributes>(unchecked_attributes);
5376 if (key->IsName()) {
5377 LookupIterator it(object, Handle<Name>::cast(key),
5378 LookupIterator::OWN_SKIP_INTERCEPTOR);
5379 Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
5380 DCHECK(maybe.has_value);
5381 duplicate = it.IsFound();
5384 RUNTIME_ASSERT(key->ToArrayIndex(&index));
5385 Maybe<bool> maybe = JSReceiver::HasOwnElement(object, index);
5386 if (!maybe.has_value) return isolate->heap()->exception();
5387 duplicate = maybe.value;
5390 Handle<Object> args[1] = { key };
5391 THROW_NEW_ERROR_RETURN_FAILURE(
5393 NewTypeError("duplicate_template_property", HandleVector(args, 1)));
5397 Handle<Object> result;
5398 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5400 Runtime::DefineObjectProperty(object, key, value, attributes));
5405 RUNTIME_FUNCTION(Runtime_SetProperty) {
5406 HandleScope scope(isolate);
5407 RUNTIME_ASSERT(args.length() == 4);
5409 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
5410 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
5411 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5412 CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode_arg, 3);
5413 StrictMode strict_mode = strict_mode_arg;
5415 Handle<Object> result;
5416 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5418 Runtime::SetObjectProperty(isolate, object, key, value, strict_mode));
5423 // Adds an element to an array.
5424 // This is used to create an indexed data property into an array.
5425 RUNTIME_FUNCTION(Runtime_AddElement) {
5426 HandleScope scope(isolate);
5427 RUNTIME_ASSERT(args.length() == 4);
5429 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5430 CONVERT_ARG_HANDLE_CHECKED(Object, key, 1);
5431 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5432 CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
5434 (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
5435 // Compute attributes.
5436 PropertyAttributes attributes =
5437 static_cast<PropertyAttributes>(unchecked_attributes);
5440 key->ToArrayIndex(&index);
5442 Handle<Object> result;
5443 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5444 isolate, result, JSObject::SetElement(object, index, value, attributes,
5445 SLOPPY, false, DEFINE_PROPERTY));
5450 RUNTIME_FUNCTION(Runtime_TransitionElementsKind) {
5451 HandleScope scope(isolate);
5452 RUNTIME_ASSERT(args.length() == 2);
5453 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
5454 CONVERT_ARG_HANDLE_CHECKED(Map, map, 1);
5455 JSObject::TransitionElementsKind(array, map->elements_kind());
5460 // Set the native flag on the function.
5461 // This is used to decide if we should transform null and undefined
5462 // into the global object when doing call and apply.
5463 RUNTIME_FUNCTION(Runtime_SetNativeFlag) {
5464 SealHandleScope shs(isolate);
5465 RUNTIME_ASSERT(args.length() == 1);
5467 CONVERT_ARG_CHECKED(Object, object, 0);
5469 if (object->IsJSFunction()) {
5470 JSFunction* func = JSFunction::cast(object);
5471 func->shared()->set_native(true);
5473 return isolate->heap()->undefined_value();
5477 RUNTIME_FUNCTION(Runtime_SetInlineBuiltinFlag) {
5478 SealHandleScope shs(isolate);
5479 RUNTIME_ASSERT(args.length() == 1);
5480 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
5482 if (object->IsJSFunction()) {
5483 JSFunction* func = JSFunction::cast(*object);
5484 func->shared()->set_inline_builtin(true);
5486 return isolate->heap()->undefined_value();
5490 RUNTIME_FUNCTION(Runtime_StoreArrayLiteralElement) {
5491 HandleScope scope(isolate);
5492 RUNTIME_ASSERT(args.length() == 5);
5493 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5494 CONVERT_SMI_ARG_CHECKED(store_index, 1);
5495 CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);
5496 CONVERT_ARG_HANDLE_CHECKED(FixedArray, literals, 3);
5497 CONVERT_SMI_ARG_CHECKED(literal_index, 4);
5499 Object* raw_literal_cell = literals->get(literal_index);
5500 JSArray* boilerplate = NULL;
5501 if (raw_literal_cell->IsAllocationSite()) {
5502 AllocationSite* site = AllocationSite::cast(raw_literal_cell);
5503 boilerplate = JSArray::cast(site->transition_info());
5505 boilerplate = JSArray::cast(raw_literal_cell);
5507 Handle<JSArray> boilerplate_object(boilerplate);
5508 ElementsKind elements_kind = object->GetElementsKind();
5509 DCHECK(IsFastElementsKind(elements_kind));
5510 // Smis should never trigger transitions.
5511 DCHECK(!value->IsSmi());
5513 if (value->IsNumber()) {
5514 DCHECK(IsFastSmiElementsKind(elements_kind));
5515 ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind)
5516 ? FAST_HOLEY_DOUBLE_ELEMENTS
5517 : FAST_DOUBLE_ELEMENTS;
5518 if (IsMoreGeneralElementsKindTransition(
5519 boilerplate_object->GetElementsKind(),
5520 transitioned_kind)) {
5521 JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind);
5523 JSObject::TransitionElementsKind(object, transitioned_kind);
5524 DCHECK(IsFastDoubleElementsKind(object->GetElementsKind()));
5525 FixedDoubleArray* double_array = FixedDoubleArray::cast(object->elements());
5526 HeapNumber* number = HeapNumber::cast(*value);
5527 double_array->set(store_index, number->Number());
5529 if (!IsFastObjectElementsKind(elements_kind)) {
5530 ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind)
5531 ? FAST_HOLEY_ELEMENTS
5533 JSObject::TransitionElementsKind(object, transitioned_kind);
5534 ElementsKind boilerplate_elements_kind =
5535 boilerplate_object->GetElementsKind();
5536 if (IsMoreGeneralElementsKindTransition(boilerplate_elements_kind,
5537 transitioned_kind)) {
5538 JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind);
5541 FixedArray* object_array = FixedArray::cast(object->elements());
5542 object_array->set(store_index, *value);
5548 // Check whether debugger and is about to step into the callback that is passed
5549 // to a built-in function such as Array.forEach.
5550 RUNTIME_FUNCTION(Runtime_DebugCallbackSupportsStepping) {
5551 DCHECK(args.length() == 1);
5552 if (!isolate->debug()->is_active() || !isolate->debug()->StepInActive()) {
5553 return isolate->heap()->false_value();
5555 CONVERT_ARG_CHECKED(Object, callback, 0);
5556 // We do not step into the callback if it's a builtin or not even a function.
5557 return isolate->heap()->ToBoolean(
5558 callback->IsJSFunction() && !JSFunction::cast(callback)->IsBuiltin());
5562 // Set one shot breakpoints for the callback function that is passed to a
5563 // built-in function such as Array.forEach to enable stepping into the callback.
5564 RUNTIME_FUNCTION(Runtime_DebugPrepareStepInIfStepping) {
5565 DCHECK(args.length() == 1);
5566 Debug* debug = isolate->debug();
5567 if (!debug->IsStepping()) return isolate->heap()->undefined_value();
5569 HandleScope scope(isolate);
5570 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
5571 RUNTIME_ASSERT(object->IsJSFunction() || object->IsJSGeneratorObject());
5572 Handle<JSFunction> fun;
5573 if (object->IsJSFunction()) {
5574 fun = Handle<JSFunction>::cast(object);
5576 fun = Handle<JSFunction>(
5577 Handle<JSGeneratorObject>::cast(object)->function(), isolate);
5579 // When leaving the function, step out has been activated, but not performed
5580 // if we do not leave the builtin. To be able to step into the function
5581 // again, we need to clear the step out at this point.
5582 debug->ClearStepOut();
5583 debug->FloodWithOneShot(fun);
5584 return isolate->heap()->undefined_value();
5588 RUNTIME_FUNCTION(Runtime_DebugPushPromise) {
5589 DCHECK(args.length() == 1);
5590 HandleScope scope(isolate);
5591 CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
5592 isolate->PushPromise(promise);
5593 return isolate->heap()->undefined_value();
5597 RUNTIME_FUNCTION(Runtime_DebugPopPromise) {
5598 DCHECK(args.length() == 0);
5599 SealHandleScope shs(isolate);
5600 isolate->PopPromise();
5601 return isolate->heap()->undefined_value();
5605 RUNTIME_FUNCTION(Runtime_DebugPromiseEvent) {
5606 DCHECK(args.length() == 1);
5607 HandleScope scope(isolate);
5608 CONVERT_ARG_HANDLE_CHECKED(JSObject, data, 0);
5609 isolate->debug()->OnPromiseEvent(data);
5610 return isolate->heap()->undefined_value();
5614 RUNTIME_FUNCTION(Runtime_DebugPromiseRejectEvent) {
5615 DCHECK(args.length() == 2);
5616 HandleScope scope(isolate);
5617 CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
5618 CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
5619 isolate->debug()->OnPromiseReject(promise, value);
5620 return isolate->heap()->undefined_value();
5624 RUNTIME_FUNCTION(Runtime_DebugAsyncTaskEvent) {
5625 DCHECK(args.length() == 1);
5626 HandleScope scope(isolate);
5627 CONVERT_ARG_HANDLE_CHECKED(JSObject, data, 0);
5628 isolate->debug()->OnAsyncTaskEvent(data);
5629 return isolate->heap()->undefined_value();
5633 RUNTIME_FUNCTION(Runtime_DeleteProperty) {
5634 HandleScope scope(isolate);
5635 DCHECK(args.length() == 3);
5636 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, object, 0);
5637 CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5638 CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 2);
5639 JSReceiver::DeleteMode delete_mode = strict_mode == STRICT
5640 ? JSReceiver::STRICT_DELETION : JSReceiver::NORMAL_DELETION;
5641 Handle<Object> result;
5642 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5644 JSReceiver::DeleteProperty(object, key, delete_mode));
5649 static Object* HasOwnPropertyImplementation(Isolate* isolate,
5650 Handle<JSObject> object,
5652 Maybe<bool> maybe = JSReceiver::HasOwnProperty(object, key);
5653 if (!maybe.has_value) return isolate->heap()->exception();
5654 if (maybe.value) return isolate->heap()->true_value();
5655 // Handle hidden prototypes. If there's a hidden prototype above this thing
5656 // then we have to check it for properties, because they are supposed to
5657 // look like they are on this object.
5658 PrototypeIterator iter(isolate, object);
5659 if (!iter.IsAtEnd() &&
5660 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter))
5662 ->is_hidden_prototype()) {
5663 // TODO(verwaest): The recursion is not necessary for keys that are array
5664 // indices. Removing this.
5665 return HasOwnPropertyImplementation(
5666 isolate, Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)),
5669 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
5670 return isolate->heap()->false_value();
5674 RUNTIME_FUNCTION(Runtime_HasOwnProperty) {
5675 HandleScope scope(isolate);
5676 DCHECK(args.length() == 2);
5677 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0)
5678 CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5681 const bool key_is_array_index = key->AsArrayIndex(&index);
5683 // Only JS objects can have properties.
5684 if (object->IsJSObject()) {
5685 Handle<JSObject> js_obj = Handle<JSObject>::cast(object);
5686 // Fast case: either the key is a real named property or it is not
5687 // an array index and there are no interceptors or hidden
5689 Maybe<bool> maybe = JSObject::HasRealNamedProperty(js_obj, key);
5690 if (!maybe.has_value) return isolate->heap()->exception();
5691 DCHECK(!isolate->has_pending_exception());
5693 return isolate->heap()->true_value();
5695 Map* map = js_obj->map();
5696 if (!key_is_array_index &&
5697 !map->has_named_interceptor() &&
5698 !HeapObject::cast(map->prototype())->map()->is_hidden_prototype()) {
5699 return isolate->heap()->false_value();
5702 return HasOwnPropertyImplementation(isolate,
5703 Handle<JSObject>(js_obj),
5705 } else if (object->IsString() && key_is_array_index) {
5706 // Well, there is one exception: Handle [] on strings.
5707 Handle<String> string = Handle<String>::cast(object);
5708 if (index < static_cast<uint32_t>(string->length())) {
5709 return isolate->heap()->true_value();
5712 return isolate->heap()->false_value();
5716 RUNTIME_FUNCTION(Runtime_HasProperty) {
5717 HandleScope scope(isolate);
5718 DCHECK(args.length() == 2);
5719 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
5720 CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5722 Maybe<bool> maybe = JSReceiver::HasProperty(receiver, key);
5723 if (!maybe.has_value) return isolate->heap()->exception();
5724 return isolate->heap()->ToBoolean(maybe.value);
5728 RUNTIME_FUNCTION(Runtime_HasElement) {
5729 HandleScope scope(isolate);
5730 DCHECK(args.length() == 2);
5731 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
5732 CONVERT_SMI_ARG_CHECKED(index, 1);
5734 Maybe<bool> maybe = JSReceiver::HasElement(receiver, index);
5735 if (!maybe.has_value) return isolate->heap()->exception();
5736 return isolate->heap()->ToBoolean(maybe.value);
5740 RUNTIME_FUNCTION(Runtime_IsPropertyEnumerable) {
5741 HandleScope scope(isolate);
5742 DCHECK(args.length() == 2);
5744 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
5745 CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
5747 Maybe<PropertyAttributes> maybe =
5748 JSReceiver::GetOwnPropertyAttributes(object, key);
5749 if (!maybe.has_value) return isolate->heap()->exception();
5750 if (maybe.value == ABSENT) maybe.value = DONT_ENUM;
5751 return isolate->heap()->ToBoolean((maybe.value & DONT_ENUM) == 0);
5755 RUNTIME_FUNCTION(Runtime_GetPropertyNames) {
5756 HandleScope scope(isolate);
5757 DCHECK(args.length() == 1);
5758 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, object, 0);
5759 Handle<JSArray> result;
5761 isolate->counters()->for_in()->Increment();
5762 Handle<FixedArray> elements;
5763 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5765 JSReceiver::GetKeys(object, JSReceiver::INCLUDE_PROTOS));
5766 return *isolate->factory()->NewJSArrayWithElements(elements);
5770 // Returns either a FixedArray as Runtime_GetPropertyNames,
5771 // or, if the given object has an enum cache that contains
5772 // all enumerable properties of the object and its prototypes
5773 // have none, the map of the object. This is used to speed up
5774 // the check for deletions during a for-in.
5775 RUNTIME_FUNCTION(Runtime_GetPropertyNamesFast) {
5776 SealHandleScope shs(isolate);
5777 DCHECK(args.length() == 1);
5779 CONVERT_ARG_CHECKED(JSReceiver, raw_object, 0);
5781 if (raw_object->IsSimpleEnum()) return raw_object->map();
5783 HandleScope scope(isolate);
5784 Handle<JSReceiver> object(raw_object);
5785 Handle<FixedArray> content;
5786 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
5788 JSReceiver::GetKeys(object, JSReceiver::INCLUDE_PROTOS));
5790 // Test again, since cache may have been built by preceding call.
5791 if (object->IsSimpleEnum()) return object->map();
5797 // Find the length of the prototype chain that is to be handled as one. If a
5798 // prototype object is hidden it is to be viewed as part of the the object it
5799 // is prototype for.
5800 static int OwnPrototypeChainLength(JSObject* obj) {
5802 for (PrototypeIterator iter(obj->GetIsolate(), obj);
5803 !iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN); iter.Advance()) {
5810 // Return the names of the own named properties.
5812 // args[1]: PropertyAttributes as int
5813 RUNTIME_FUNCTION(Runtime_GetOwnPropertyNames) {
5814 HandleScope scope(isolate);
5815 DCHECK(args.length() == 2);
5816 if (!args[0]->IsJSObject()) {
5817 return isolate->heap()->undefined_value();
5819 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5820 CONVERT_SMI_ARG_CHECKED(filter_value, 1);
5821 PropertyAttributes filter = static_cast<PropertyAttributes>(filter_value);
5823 // Skip the global proxy as it has no properties and always delegates to the
5824 // real global object.
5825 if (obj->IsJSGlobalProxy()) {
5826 // Only collect names if access is permitted.
5827 if (obj->IsAccessCheckNeeded() &&
5828 !isolate->MayNamedAccess(
5829 obj, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) {
5830 isolate->ReportFailedAccessCheck(obj, v8::ACCESS_KEYS);
5831 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
5832 return *isolate->factory()->NewJSArray(0);
5834 PrototypeIterator iter(isolate, obj);
5835 obj = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
5838 // Find the number of objects making up this.
5839 int length = OwnPrototypeChainLength(*obj);
5841 // Find the number of own properties for each of the objects.
5842 ScopedVector<int> own_property_count(length);
5843 int total_property_count = 0;
5845 PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER);
5846 for (int i = 0; i < length; i++) {
5847 DCHECK(!iter.IsAtEnd());
5848 Handle<JSObject> jsproto =
5849 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
5850 // Only collect names if access is permitted.
5851 if (jsproto->IsAccessCheckNeeded() &&
5852 !isolate->MayNamedAccess(jsproto,
5853 isolate->factory()->undefined_value(),
5855 isolate->ReportFailedAccessCheck(jsproto, v8::ACCESS_KEYS);
5856 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
5857 return *isolate->factory()->NewJSArray(0);
5860 n = jsproto->NumberOfOwnProperties(filter);
5861 own_property_count[i] = n;
5862 total_property_count += n;
5867 // Allocate an array with storage for all the property names.
5868 Handle<FixedArray> names =
5869 isolate->factory()->NewFixedArray(total_property_count);
5871 // Get the property names.
5872 int next_copy_index = 0;
5873 int hidden_strings = 0;
5875 PrototypeIterator iter(isolate, obj, PrototypeIterator::START_AT_RECEIVER);
5876 for (int i = 0; i < length; i++) {
5877 DCHECK(!iter.IsAtEnd());
5878 Handle<JSObject> jsproto =
5879 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
5880 jsproto->GetOwnPropertyNames(*names, next_copy_index, filter);
5882 // Names from hidden prototypes may already have been added
5883 // for inherited function template instances. Count the duplicates
5884 // and stub them out; the final copy pass at the end ignores holes.
5885 for (int j = next_copy_index;
5886 j < next_copy_index + own_property_count[i]; j++) {
5887 Object* name_from_hidden_proto = names->get(j);
5888 for (int k = 0; k < next_copy_index; k++) {
5889 if (names->get(k) != isolate->heap()->hidden_string()) {
5890 Object* name = names->get(k);
5891 if (name_from_hidden_proto == name) {
5892 names->set(j, isolate->heap()->hidden_string());
5900 next_copy_index += own_property_count[i];
5902 // Hidden properties only show up if the filter does not skip strings.
5903 if ((filter & STRING) == 0 && JSObject::HasHiddenProperties(jsproto)) {
5910 // Filter out name of hidden properties object and
5911 // hidden prototype duplicates.
5912 if (hidden_strings > 0) {
5913 Handle<FixedArray> old_names = names;
5914 names = isolate->factory()->NewFixedArray(
5915 names->length() - hidden_strings);
5917 for (int i = 0; i < total_property_count; i++) {
5918 Object* name = old_names->get(i);
5919 if (name == isolate->heap()->hidden_string()) {
5923 names->set(dest_pos++, name);
5925 DCHECK_EQ(0, hidden_strings);
5928 return *isolate->factory()->NewJSArrayWithElements(names);
5932 // Return the names of the own indexed properties.
5934 RUNTIME_FUNCTION(Runtime_GetOwnElementNames) {
5935 HandleScope scope(isolate);
5936 DCHECK(args.length() == 1);
5937 if (!args[0]->IsJSObject()) {
5938 return isolate->heap()->undefined_value();
5940 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5942 int n = obj->NumberOfOwnElements(static_cast<PropertyAttributes>(NONE));
5943 Handle<FixedArray> names = isolate->factory()->NewFixedArray(n);
5944 obj->GetOwnElementKeys(*names, static_cast<PropertyAttributes>(NONE));
5945 return *isolate->factory()->NewJSArrayWithElements(names);
5949 // Return information on whether an object has a named or indexed interceptor.
5951 RUNTIME_FUNCTION(Runtime_GetInterceptorInfo) {
5952 HandleScope scope(isolate);
5953 DCHECK(args.length() == 1);
5954 if (!args[0]->IsJSObject()) {
5955 return Smi::FromInt(0);
5957 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5960 if (obj->HasNamedInterceptor()) result |= 2;
5961 if (obj->HasIndexedInterceptor()) result |= 1;
5963 return Smi::FromInt(result);
5967 // Return property names from named interceptor.
5969 RUNTIME_FUNCTION(Runtime_GetNamedInterceptorPropertyNames) {
5970 HandleScope scope(isolate);
5971 DCHECK(args.length() == 1);
5972 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5974 if (obj->HasNamedInterceptor()) {
5975 Handle<JSObject> result;
5976 if (JSObject::GetKeysForNamedInterceptor(obj, obj).ToHandle(&result)) {
5980 return isolate->heap()->undefined_value();
5984 // Return element names from indexed interceptor.
5986 RUNTIME_FUNCTION(Runtime_GetIndexedInterceptorElementNames) {
5987 HandleScope scope(isolate);
5988 DCHECK(args.length() == 1);
5989 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
5991 if (obj->HasIndexedInterceptor()) {
5992 Handle<JSObject> result;
5993 if (JSObject::GetKeysForIndexedInterceptor(obj, obj).ToHandle(&result)) {
5997 return isolate->heap()->undefined_value();
6001 RUNTIME_FUNCTION(Runtime_OwnKeys) {
6002 HandleScope scope(isolate);
6003 DCHECK(args.length() == 1);
6004 CONVERT_ARG_CHECKED(JSObject, raw_object, 0);
6005 Handle<JSObject> object(raw_object);
6007 if (object->IsJSGlobalProxy()) {
6008 // Do access checks before going to the global object.
6009 if (object->IsAccessCheckNeeded() &&
6010 !isolate->MayNamedAccess(
6011 object, isolate->factory()->undefined_value(), v8::ACCESS_KEYS)) {
6012 isolate->ReportFailedAccessCheck(object, v8::ACCESS_KEYS);
6013 RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
6014 return *isolate->factory()->NewJSArray(0);
6017 PrototypeIterator iter(isolate, object);
6018 // If proxy is detached we simply return an empty array.
6019 if (iter.IsAtEnd()) return *isolate->factory()->NewJSArray(0);
6020 object = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
6023 Handle<FixedArray> contents;
6024 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6026 JSReceiver::GetKeys(object, JSReceiver::OWN_ONLY));
6028 // Some fast paths through GetKeysInFixedArrayFor reuse a cached
6029 // property array and since the result is mutable we have to create
6030 // a fresh clone on each invocation.
6031 int length = contents->length();
6032 Handle<FixedArray> copy = isolate->factory()->NewFixedArray(length);
6033 for (int i = 0; i < length; i++) {
6034 Object* entry = contents->get(i);
6035 if (entry->IsString()) {
6036 copy->set(i, entry);
6038 DCHECK(entry->IsNumber());
6039 HandleScope scope(isolate);
6040 Handle<Object> entry_handle(entry, isolate);
6041 Handle<Object> entry_str =
6042 isolate->factory()->NumberToString(entry_handle);
6043 copy->set(i, *entry_str);
6046 return *isolate->factory()->NewJSArrayWithElements(copy);
6050 RUNTIME_FUNCTION(Runtime_GetArgumentsProperty) {
6051 SealHandleScope shs(isolate);
6052 DCHECK(args.length() == 1);
6053 CONVERT_ARG_HANDLE_CHECKED(Object, raw_key, 0);
6055 // Compute the frame holding the arguments.
6056 JavaScriptFrameIterator it(isolate);
6057 it.AdvanceToArgumentsFrame();
6058 JavaScriptFrame* frame = it.frame();
6060 // Get the actual number of provided arguments.
6061 const uint32_t n = frame->ComputeParametersCount();
6063 // Try to convert the key to an index. If successful and within
6064 // index return the the argument from the frame.
6066 if (raw_key->ToArrayIndex(&index) && index < n) {
6067 return frame->GetParameter(index);
6070 HandleScope scope(isolate);
6071 if (raw_key->IsSymbol()) {
6072 Handle<Symbol> symbol = Handle<Symbol>::cast(raw_key);
6073 if (symbol->Equals(isolate->native_context()->iterator_symbol())) {
6074 return isolate->native_context()->array_values_iterator();
6076 // Lookup in the initial Object.prototype object.
6077 Handle<Object> result;
6078 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6080 Object::GetProperty(isolate->initial_object_prototype(),
6081 Handle<Symbol>::cast(raw_key)));
6085 // Convert the key to a string.
6086 Handle<Object> converted;
6087 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6088 isolate, converted, Execution::ToString(isolate, raw_key));
6089 Handle<String> key = Handle<String>::cast(converted);
6091 // Try to convert the string key into an array index.
6092 if (key->AsArrayIndex(&index)) {
6094 return frame->GetParameter(index);
6096 Handle<Object> initial_prototype(isolate->initial_object_prototype());
6097 Handle<Object> result;
6098 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6100 Object::GetElement(isolate, initial_prototype, index));
6105 // Handle special arguments properties.
6106 if (String::Equals(isolate->factory()->length_string(), key)) {
6107 return Smi::FromInt(n);
6109 if (String::Equals(isolate->factory()->callee_string(), key)) {
6110 JSFunction* function = frame->function();
6111 if (function->shared()->strict_mode() == STRICT) {
6112 THROW_NEW_ERROR_RETURN_FAILURE(
6113 isolate, NewTypeError("strict_arguments_callee",
6114 HandleVector<Object>(NULL, 0)));
6119 // Lookup in the initial Object.prototype object.
6120 Handle<Object> result;
6121 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6123 Object::GetProperty(isolate->initial_object_prototype(), key));
6128 RUNTIME_FUNCTION(Runtime_ToFastProperties) {
6129 HandleScope scope(isolate);
6130 DCHECK(args.length() == 1);
6131 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
6132 if (object->IsJSObject() && !object->IsGlobalObject()) {
6133 JSObject::MigrateSlowToFast(Handle<JSObject>::cast(object), 0);
6139 RUNTIME_FUNCTION(Runtime_ToBool) {
6140 SealHandleScope shs(isolate);
6141 DCHECK(args.length() == 1);
6142 CONVERT_ARG_CHECKED(Object, object, 0);
6144 return isolate->heap()->ToBoolean(object->BooleanValue());
6148 // Returns the type string of a value; see ECMA-262, 11.4.3 (p 47).
6149 // Possible optimizations: put the type string into the oddballs.
6150 RUNTIME_FUNCTION(Runtime_Typeof) {
6151 SealHandleScope shs(isolate);
6152 DCHECK(args.length() == 1);
6153 CONVERT_ARG_CHECKED(Object, obj, 0);
6154 if (obj->IsNumber()) return isolate->heap()->number_string();
6155 HeapObject* heap_obj = HeapObject::cast(obj);
6157 // typeof an undetectable object is 'undefined'
6158 if (heap_obj->map()->is_undetectable()) {
6159 return isolate->heap()->undefined_string();
6162 InstanceType instance_type = heap_obj->map()->instance_type();
6163 if (instance_type < FIRST_NONSTRING_TYPE) {
6164 return isolate->heap()->string_string();
6167 switch (instance_type) {
6169 if (heap_obj->IsTrue() || heap_obj->IsFalse()) {
6170 return isolate->heap()->boolean_string();
6172 if (heap_obj->IsNull()) {
6173 return isolate->heap()->object_string();
6175 DCHECK(heap_obj->IsUndefined());
6176 return isolate->heap()->undefined_string();
6178 return isolate->heap()->symbol_string();
6179 case JS_FUNCTION_TYPE:
6180 case JS_FUNCTION_PROXY_TYPE:
6181 return isolate->heap()->function_string();
6183 // For any kind of object not handled above, the spec rule for
6184 // host objects gives that it is okay to return "object"
6185 return isolate->heap()->object_string();
6190 RUNTIME_FUNCTION(Runtime_Booleanize) {
6191 SealHandleScope shs(isolate);
6192 DCHECK(args.length() == 2);
6193 CONVERT_ARG_CHECKED(Object, value_raw, 0);
6194 CONVERT_SMI_ARG_CHECKED(token_raw, 1);
6195 intptr_t value = reinterpret_cast<intptr_t>(value_raw);
6196 Token::Value token = static_cast<Token::Value>(token_raw);
6199 case Token::EQ_STRICT:
6200 return isolate->heap()->ToBoolean(value == 0);
6202 case Token::NE_STRICT:
6203 return isolate->heap()->ToBoolean(value != 0);
6205 return isolate->heap()->ToBoolean(value < 0);
6207 return isolate->heap()->ToBoolean(value > 0);
6209 return isolate->heap()->ToBoolean(value <= 0);
6211 return isolate->heap()->ToBoolean(value >= 0);
6213 // This should only happen during natives fuzzing.
6214 return isolate->heap()->undefined_value();
6219 static bool AreDigits(const uint8_t*s, int from, int to) {
6220 for (int i = from; i < to; i++) {
6221 if (s[i] < '0' || s[i] > '9') return false;
6228 static int ParseDecimalInteger(const uint8_t*s, int from, int to) {
6229 DCHECK(to - from < 10); // Overflow is not possible.
6231 int d = s[from] - '0';
6233 for (int i = from + 1; i < to; i++) {
6234 d = 10 * d + (s[i] - '0');
6241 RUNTIME_FUNCTION(Runtime_StringToNumber) {
6242 HandleScope handle_scope(isolate);
6243 DCHECK(args.length() == 1);
6244 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6245 subject = String::Flatten(subject);
6247 // Fast case: short integer or some sorts of junk values.
6248 if (subject->IsSeqOneByteString()) {
6249 int len = subject->length();
6250 if (len == 0) return Smi::FromInt(0);
6252 DisallowHeapAllocation no_gc;
6253 uint8_t const* data = Handle<SeqOneByteString>::cast(subject)->GetChars();
6254 bool minus = (data[0] == '-');
6255 int start_pos = (minus ? 1 : 0);
6257 if (start_pos == len) {
6258 return isolate->heap()->nan_value();
6259 } else if (data[start_pos] > '9') {
6260 // Fast check for a junk value. A valid string may start from a
6261 // whitespace, a sign ('+' or '-'), the decimal point, a decimal digit
6262 // or the 'I' character ('Infinity'). All of that have codes not greater
6263 // than '9' except 'I' and .
6264 if (data[start_pos] != 'I' && data[start_pos] != 0xa0) {
6265 return isolate->heap()->nan_value();
6267 } else if (len - start_pos < 10 && AreDigits(data, start_pos, len)) {
6268 // The maximal/minimal smi has 10 digits. If the string has less digits
6269 // we know it will fit into the smi-data type.
6270 int d = ParseDecimalInteger(data, start_pos, len);
6272 if (d == 0) return isolate->heap()->minus_zero_value();
6274 } else if (!subject->HasHashCode() &&
6275 len <= String::kMaxArrayIndexSize &&
6276 (len == 1 || data[0] != '0')) {
6277 // String hash is not calculated yet but all the data are present.
6278 // Update the hash field to speed up sequential convertions.
6279 uint32_t hash = StringHasher::MakeArrayIndexHash(d, len);
6281 subject->Hash(); // Force hash calculation.
6282 DCHECK_EQ(static_cast<int>(subject->hash_field()),
6283 static_cast<int>(hash));
6285 subject->set_hash_field(hash);
6287 return Smi::FromInt(d);
6292 int flags = ALLOW_HEX;
6293 if (FLAG_harmony_numeric_literals) {
6294 // The current spec draft has not updated "ToNumber Applied to the String
6295 // Type", https://bugs.ecmascript.org/show_bug.cgi?id=1584
6296 flags |= ALLOW_OCTAL | ALLOW_BINARY;
6299 return *isolate->factory()->NewNumber(StringToDouble(
6300 isolate->unicode_cache(), *subject, flags));
6304 RUNTIME_FUNCTION(Runtime_NewString) {
6305 HandleScope scope(isolate);
6306 DCHECK(args.length() == 2);
6307 CONVERT_INT32_ARG_CHECKED(length, 0);
6308 CONVERT_BOOLEAN_ARG_CHECKED(is_one_byte, 1);
6309 if (length == 0) return isolate->heap()->empty_string();
6310 Handle<String> result;
6312 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6313 isolate, result, isolate->factory()->NewRawOneByteString(length));
6315 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6316 isolate, result, isolate->factory()->NewRawTwoByteString(length));
6322 RUNTIME_FUNCTION(Runtime_TruncateString) {
6323 HandleScope scope(isolate);
6324 DCHECK(args.length() == 2);
6325 CONVERT_ARG_HANDLE_CHECKED(SeqString, string, 0);
6326 CONVERT_INT32_ARG_CHECKED(new_length, 1);
6327 RUNTIME_ASSERT(new_length >= 0);
6328 return *SeqString::Truncate(string, new_length);
6332 RUNTIME_FUNCTION(Runtime_URIEscape) {
6333 HandleScope scope(isolate);
6334 DCHECK(args.length() == 1);
6335 CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
6336 Handle<String> string = String::Flatten(source);
6337 DCHECK(string->IsFlat());
6338 Handle<String> result;
6339 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6341 string->IsOneByteRepresentationUnderneath()
6342 ? URIEscape::Escape<uint8_t>(isolate, source)
6343 : URIEscape::Escape<uc16>(isolate, source));
6348 RUNTIME_FUNCTION(Runtime_URIUnescape) {
6349 HandleScope scope(isolate);
6350 DCHECK(args.length() == 1);
6351 CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
6352 Handle<String> string = String::Flatten(source);
6353 DCHECK(string->IsFlat());
6354 Handle<String> result;
6355 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6357 string->IsOneByteRepresentationUnderneath()
6358 ? URIUnescape::Unescape<uint8_t>(isolate, source)
6359 : URIUnescape::Unescape<uc16>(isolate, source));
6364 RUNTIME_FUNCTION(Runtime_QuoteJSONString) {
6365 HandleScope scope(isolate);
6366 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
6367 DCHECK(args.length() == 1);
6368 Handle<Object> result;
6369 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6370 isolate, result, BasicJsonStringifier::StringifyString(isolate, string));
6375 RUNTIME_FUNCTION(Runtime_BasicJSONStringify) {
6376 HandleScope scope(isolate);
6377 DCHECK(args.length() == 1);
6378 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
6379 BasicJsonStringifier stringifier(isolate);
6380 Handle<Object> result;
6381 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6382 isolate, result, stringifier.Stringify(object));
6387 RUNTIME_FUNCTION(Runtime_StringParseInt) {
6388 HandleScope handle_scope(isolate);
6389 DCHECK(args.length() == 2);
6390 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6391 CONVERT_NUMBER_CHECKED(int, radix, Int32, args[1]);
6392 RUNTIME_ASSERT(radix == 0 || (2 <= radix && radix <= 36));
6394 subject = String::Flatten(subject);
6397 { DisallowHeapAllocation no_gc;
6398 String::FlatContent flat = subject->GetFlatContent();
6400 // ECMA-262 section 15.1.2.3, empty string is NaN
6401 if (flat.IsOneByte()) {
6402 value = StringToInt(
6403 isolate->unicode_cache(), flat.ToOneByteVector(), radix);
6405 value = StringToInt(
6406 isolate->unicode_cache(), flat.ToUC16Vector(), radix);
6410 return *isolate->factory()->NewNumber(value);
6414 RUNTIME_FUNCTION(Runtime_StringParseFloat) {
6415 HandleScope shs(isolate);
6416 DCHECK(args.length() == 1);
6417 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6419 subject = String::Flatten(subject);
6420 double value = StringToDouble(isolate->unicode_cache(), *subject,
6421 ALLOW_TRAILING_JUNK, base::OS::nan_value());
6423 return *isolate->factory()->NewNumber(value);
6427 static inline bool ToUpperOverflows(uc32 character) {
6428 // y with umlauts and the micro sign are the only characters that stop
6429 // fitting into one-byte when converting to uppercase.
6430 static const uc32 yuml_code = 0xff;
6431 static const uc32 micro_code = 0xb5;
6432 return (character == yuml_code || character == micro_code);
6436 template <class Converter>
6437 MUST_USE_RESULT static Object* ConvertCaseHelper(
6442 unibrow::Mapping<Converter, 128>* mapping) {
6443 DisallowHeapAllocation no_gc;
6444 // We try this twice, once with the assumption that the result is no longer
6445 // than the input and, if that assumption breaks, again with the exact
6446 // length. This may not be pretty, but it is nicer than what was here before
6447 // and I hereby claim my vaffel-is.
6449 // NOTE: This assumes that the upper/lower case of an ASCII
6450 // character is also ASCII. This is currently the case, but it
6451 // might break in the future if we implement more context and locale
6452 // dependent upper/lower conversions.
6453 bool has_changed_character = false;
6455 // Convert all characters to upper case, assuming that they will fit
6457 Access<ConsStringIteratorOp> op(
6458 isolate->runtime_state()->string_iterator());
6459 StringCharacterStream stream(string, op.value());
6460 unibrow::uchar chars[Converter::kMaxWidth];
6461 // We can assume that the string is not empty
6462 uc32 current = stream.GetNext();
6463 bool ignore_overflow = Converter::kIsToLower || result->IsSeqTwoByteString();
6464 for (int i = 0; i < result_length;) {
6465 bool has_next = stream.HasMore();
6466 uc32 next = has_next ? stream.GetNext() : 0;
6467 int char_length = mapping->get(current, next, chars);
6468 if (char_length == 0) {
6469 // The case conversion of this character is the character itself.
6470 result->Set(i, current);
6472 } else if (char_length == 1 &&
6473 (ignore_overflow || !ToUpperOverflows(current))) {
6474 // Common case: converting the letter resulted in one character.
6475 DCHECK(static_cast<uc32>(chars[0]) != current);
6476 result->Set(i, chars[0]);
6477 has_changed_character = true;
6479 } else if (result_length == string->length()) {
6480 bool overflows = ToUpperOverflows(current);
6481 // We've assumed that the result would be as long as the
6482 // input but here is a character that converts to several
6483 // characters. No matter, we calculate the exact length
6484 // of the result and try the whole thing again.
6486 // Note that this leaves room for optimization. We could just
6487 // memcpy what we already have to the result string. Also,
6488 // the result string is the last object allocated we could
6489 // "realloc" it and probably, in the vast majority of cases,
6490 // extend the existing string to be able to hold the full
6492 int next_length = 0;
6494 next_length = mapping->get(next, 0, chars);
6495 if (next_length == 0) next_length = 1;
6497 int current_length = i + char_length + next_length;
6498 while (stream.HasMore()) {
6499 current = stream.GetNext();
6500 overflows |= ToUpperOverflows(current);
6501 // NOTE: we use 0 as the next character here because, while
6502 // the next character may affect what a character converts to,
6503 // it does not in any case affect the length of what it convert
6505 int char_length = mapping->get(current, 0, chars);
6506 if (char_length == 0) char_length = 1;
6507 current_length += char_length;
6508 if (current_length > String::kMaxLength) {
6509 AllowHeapAllocation allocate_error_and_return;
6510 THROW_NEW_ERROR_RETURN_FAILURE(isolate,
6511 NewInvalidStringLengthError());
6514 // Try again with the real length. Return signed if we need
6515 // to allocate a two-byte string for to uppercase.
6516 return (overflows && !ignore_overflow) ? Smi::FromInt(-current_length)
6517 : Smi::FromInt(current_length);
6519 for (int j = 0; j < char_length; j++) {
6520 result->Set(i, chars[j]);
6523 has_changed_character = true;
6527 if (has_changed_character) {
6530 // If we didn't actually change anything in doing the conversion
6531 // we simple return the result and let the converted string
6532 // become garbage; there is no reason to keep two identical strings
6541 static const uintptr_t kOneInEveryByte = kUintptrAllBitsSet / 0xFF;
6542 static const uintptr_t kAsciiMask = kOneInEveryByte << 7;
6544 // Given a word and two range boundaries returns a word with high bit
6545 // set in every byte iff the corresponding input byte was strictly in
6546 // the range (m, n). All the other bits in the result are cleared.
6547 // This function is only useful when it can be inlined and the
6548 // boundaries are statically known.
6549 // Requires: all bytes in the input word and the boundaries must be
6550 // ASCII (less than 0x7F).
6551 static inline uintptr_t AsciiRangeMask(uintptr_t w, char m, char n) {
6552 // Use strict inequalities since in edge cases the function could be
6553 // further simplified.
6554 DCHECK(0 < m && m < n);
6555 // Has high bit set in every w byte less than n.
6556 uintptr_t tmp1 = kOneInEveryByte * (0x7F + n) - w;
6557 // Has high bit set in every w byte greater than m.
6558 uintptr_t tmp2 = w + kOneInEveryByte * (0x7F - m);
6559 return (tmp1 & tmp2 & (kOneInEveryByte * 0x80));
6564 static bool CheckFastAsciiConvert(char* dst,
6569 bool expected_changed = false;
6570 for (int i = 0; i < length; i++) {
6571 if (dst[i] == src[i]) continue;
6572 expected_changed = true;
6574 DCHECK('A' <= src[i] && src[i] <= 'Z');
6575 DCHECK(dst[i] == src[i] + ('a' - 'A'));
6577 DCHECK('a' <= src[i] && src[i] <= 'z');
6578 DCHECK(dst[i] == src[i] - ('a' - 'A'));
6581 return (expected_changed == changed);
6586 template<class Converter>
6587 static bool FastAsciiConvert(char* dst,
6590 bool* changed_out) {
6592 char* saved_dst = dst;
6593 const char* saved_src = src;
6595 DisallowHeapAllocation no_gc;
6596 // We rely on the distance between upper and lower case letters
6597 // being a known power of 2.
6598 DCHECK('a' - 'A' == (1 << 5));
6599 // Boundaries for the range of input characters than require conversion.
6600 static const char lo = Converter::kIsToLower ? 'A' - 1 : 'a' - 1;
6601 static const char hi = Converter::kIsToLower ? 'Z' + 1 : 'z' + 1;
6602 bool changed = false;
6603 uintptr_t or_acc = 0;
6604 const char* const limit = src + length;
6606 // dst is newly allocated and always aligned.
6607 DCHECK(IsAligned(reinterpret_cast<intptr_t>(dst), sizeof(uintptr_t)));
6608 // Only attempt processing one word at a time if src is also aligned.
6609 if (IsAligned(reinterpret_cast<intptr_t>(src), sizeof(uintptr_t))) {
6610 // Process the prefix of the input that requires no conversion one aligned
6611 // (machine) word at a time.
6612 while (src <= limit - sizeof(uintptr_t)) {
6613 const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src);
6615 if (AsciiRangeMask(w, lo, hi) != 0) {
6619 *reinterpret_cast<uintptr_t*>(dst) = w;
6620 src += sizeof(uintptr_t);
6621 dst += sizeof(uintptr_t);
6623 // Process the remainder of the input performing conversion when
6624 // required one word at a time.
6625 while (src <= limit - sizeof(uintptr_t)) {
6626 const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src);
6628 uintptr_t m = AsciiRangeMask(w, lo, hi);
6629 // The mask has high (7th) bit set in every byte that needs
6630 // conversion and we know that the distance between cases is
6632 *reinterpret_cast<uintptr_t*>(dst) = w ^ (m >> 2);
6633 src += sizeof(uintptr_t);
6634 dst += sizeof(uintptr_t);
6637 // Process the last few bytes of the input (or the whole input if
6638 // unaligned access is not supported).
6639 while (src < limit) {
6642 if (lo < c && c < hi) {
6651 if ((or_acc & kAsciiMask) != 0) return false;
6653 DCHECK(CheckFastAsciiConvert(
6654 saved_dst, saved_src, length, changed, Converter::kIsToLower));
6656 *changed_out = changed;
6663 template <class Converter>
6664 MUST_USE_RESULT static Object* ConvertCase(
6667 unibrow::Mapping<Converter, 128>* mapping) {
6668 s = String::Flatten(s);
6669 int length = s->length();
6670 // Assume that the string is not empty; we need this assumption later
6671 if (length == 0) return *s;
6673 // Simpler handling of ASCII strings.
6675 // NOTE: This assumes that the upper/lower case of an ASCII
6676 // character is also ASCII. This is currently the case, but it
6677 // might break in the future if we implement more context and locale
6678 // dependent upper/lower conversions.
6679 if (s->IsOneByteRepresentationUnderneath()) {
6680 // Same length as input.
6681 Handle<SeqOneByteString> result =
6682 isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
6683 DisallowHeapAllocation no_gc;
6684 String::FlatContent flat_content = s->GetFlatContent();
6685 DCHECK(flat_content.IsFlat());
6686 bool has_changed_character = false;
6687 bool is_ascii = FastAsciiConvert<Converter>(
6688 reinterpret_cast<char*>(result->GetChars()),
6689 reinterpret_cast<const char*>(flat_content.ToOneByteVector().start()),
6691 &has_changed_character);
6692 // If not ASCII, we discard the result and take the 2 byte path.
6693 if (is_ascii) return has_changed_character ? *result : *s;
6696 Handle<SeqString> result; // Same length as input.
6697 if (s->IsOneByteRepresentation()) {
6698 result = isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
6700 result = isolate->factory()->NewRawTwoByteString(length).ToHandleChecked();
6703 Object* answer = ConvertCaseHelper(isolate, *s, *result, length, mapping);
6704 if (answer->IsException() || answer->IsString()) return answer;
6706 DCHECK(answer->IsSmi());
6707 length = Smi::cast(answer)->value();
6708 if (s->IsOneByteRepresentation() && length > 0) {
6709 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6710 isolate, result, isolate->factory()->NewRawOneByteString(length));
6712 if (length < 0) length = -length;
6713 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
6714 isolate, result, isolate->factory()->NewRawTwoByteString(length));
6716 return ConvertCaseHelper(isolate, *s, *result, length, mapping);
6720 RUNTIME_FUNCTION(Runtime_StringToLowerCase) {
6721 HandleScope scope(isolate);
6722 DCHECK(args.length() == 1);
6723 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
6725 s, isolate, isolate->runtime_state()->to_lower_mapping());
6729 RUNTIME_FUNCTION(Runtime_StringToUpperCase) {
6730 HandleScope scope(isolate);
6731 DCHECK(args.length() == 1);
6732 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
6734 s, isolate, isolate->runtime_state()->to_upper_mapping());
6738 RUNTIME_FUNCTION(Runtime_StringTrim) {
6739 HandleScope scope(isolate);
6740 DCHECK(args.length() == 3);
6742 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
6743 CONVERT_BOOLEAN_ARG_CHECKED(trimLeft, 1);
6744 CONVERT_BOOLEAN_ARG_CHECKED(trimRight, 2);
6746 string = String::Flatten(string);
6747 int length = string->length();
6750 UnicodeCache* unicode_cache = isolate->unicode_cache();
6752 while (left < length &&
6753 unicode_cache->IsWhiteSpaceOrLineTerminator(string->Get(left))) {
6760 while (right > left &&
6761 unicode_cache->IsWhiteSpaceOrLineTerminator(
6762 string->Get(right - 1))) {
6767 return *isolate->factory()->NewSubString(string, left, right);
6771 RUNTIME_FUNCTION(Runtime_StringSplit) {
6772 HandleScope handle_scope(isolate);
6773 DCHECK(args.length() == 3);
6774 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
6775 CONVERT_ARG_HANDLE_CHECKED(String, pattern, 1);
6776 CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[2]);
6777 RUNTIME_ASSERT(limit > 0);
6779 int subject_length = subject->length();
6780 int pattern_length = pattern->length();
6781 RUNTIME_ASSERT(pattern_length > 0);
6783 if (limit == 0xffffffffu) {
6784 Handle<Object> cached_answer(
6785 RegExpResultsCache::Lookup(isolate->heap(),
6788 RegExpResultsCache::STRING_SPLIT_SUBSTRINGS),
6790 if (*cached_answer != Smi::FromInt(0)) {
6791 // The cache FixedArray is a COW-array and can therefore be reused.
6792 Handle<JSArray> result =
6793 isolate->factory()->NewJSArrayWithElements(
6794 Handle<FixedArray>::cast(cached_answer));
6799 // The limit can be very large (0xffffffffu), but since the pattern
6800 // isn't empty, we can never create more parts than ~half the length
6803 subject = String::Flatten(subject);
6804 pattern = String::Flatten(pattern);
6806 static const int kMaxInitialListCapacity = 16;
6808 ZoneScope zone_scope(isolate->runtime_zone());
6810 // Find (up to limit) indices of separator and end-of-string in subject
6811 int initial_capacity = Min<uint32_t>(kMaxInitialListCapacity, limit);
6812 ZoneList<int> indices(initial_capacity, zone_scope.zone());
6814 FindStringIndicesDispatch(isolate, *subject, *pattern,
6815 &indices, limit, zone_scope.zone());
6817 if (static_cast<uint32_t>(indices.length()) < limit) {
6818 indices.Add(subject_length, zone_scope.zone());
6821 // The list indices now contains the end of each part to create.
6823 // Create JSArray of substrings separated by separator.
6824 int part_count = indices.length();
6826 Handle<JSArray> result = isolate->factory()->NewJSArray(part_count);
6827 JSObject::EnsureCanContainHeapObjectElements(result);
6828 result->set_length(Smi::FromInt(part_count));
6830 DCHECK(result->HasFastObjectElements());
6832 if (part_count == 1 && indices.at(0) == subject_length) {
6833 FixedArray::cast(result->elements())->set(0, *subject);
6837 Handle<FixedArray> elements(FixedArray::cast(result->elements()));
6839 for (int i = 0; i < part_count; i++) {
6840 HandleScope local_loop_handle(isolate);
6841 int part_end = indices.at(i);
6842 Handle<String> substring =
6843 isolate->factory()->NewProperSubString(subject, part_start, part_end);
6844 elements->set(i, *substring);
6845 part_start = part_end + pattern_length;
6848 if (limit == 0xffffffffu) {
6849 if (result->HasFastObjectElements()) {
6850 RegExpResultsCache::Enter(isolate,
6854 RegExpResultsCache::STRING_SPLIT_SUBSTRINGS);
6862 // Copies Latin1 characters to the given fixed array looking up
6863 // one-char strings in the cache. Gives up on the first char that is
6864 // not in the cache and fills the remainder with smi zeros. Returns
6865 // the length of the successfully copied prefix.
6866 static int CopyCachedOneByteCharsToArray(Heap* heap, const uint8_t* chars,
6867 FixedArray* elements, int length) {
6868 DisallowHeapAllocation no_gc;
6869 FixedArray* one_byte_cache = heap->single_character_string_cache();
6870 Object* undefined = heap->undefined_value();
6872 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
6873 for (i = 0; i < length; ++i) {
6874 Object* value = one_byte_cache->get(chars[i]);
6875 if (value == undefined) break;
6876 elements->set(i, value, mode);
6879 DCHECK(Smi::FromInt(0) == 0);
6880 memset(elements->data_start() + i, 0, kPointerSize * (length - i));
6883 for (int j = 0; j < length; ++j) {
6884 Object* element = elements->get(j);
6885 DCHECK(element == Smi::FromInt(0) ||
6886 (element->IsString() && String::cast(element)->LooksValid()));
6893 // Converts a String to JSArray.
6894 // For example, "foo" => ["f", "o", "o"].
6895 RUNTIME_FUNCTION(Runtime_StringToArray) {
6896 HandleScope scope(isolate);
6897 DCHECK(args.length() == 2);
6898 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
6899 CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
6901 s = String::Flatten(s);
6902 const int length = static_cast<int>(Min<uint32_t>(s->length(), limit));
6904 Handle<FixedArray> elements;
6906 if (s->IsFlat() && s->IsOneByteRepresentation()) {
6907 // Try using cached chars where possible.
6908 elements = isolate->factory()->NewUninitializedFixedArray(length);
6910 DisallowHeapAllocation no_gc;
6911 String::FlatContent content = s->GetFlatContent();
6912 if (content.IsOneByte()) {
6913 Vector<const uint8_t> chars = content.ToOneByteVector();
6914 // Note, this will initialize all elements (not only the prefix)
6915 // to prevent GC from seeing partially initialized array.
6916 position = CopyCachedOneByteCharsToArray(isolate->heap(), chars.start(),
6919 MemsetPointer(elements->data_start(),
6920 isolate->heap()->undefined_value(),
6924 elements = isolate->factory()->NewFixedArray(length);
6926 for (int i = position; i < length; ++i) {
6927 Handle<Object> str =
6928 isolate->factory()->LookupSingleCharacterStringFromCode(s->Get(i));
6929 elements->set(i, *str);
6933 for (int i = 0; i < length; ++i) {
6934 DCHECK(String::cast(elements->get(i))->length() == 1);
6938 return *isolate->factory()->NewJSArrayWithElements(elements);
6942 RUNTIME_FUNCTION(Runtime_NewStringWrapper) {
6943 HandleScope scope(isolate);
6944 DCHECK(args.length() == 1);
6945 CONVERT_ARG_HANDLE_CHECKED(String, value, 0);
6946 return *Object::ToObject(isolate, value).ToHandleChecked();
6950 bool Runtime::IsUpperCaseChar(RuntimeState* runtime_state, uint16_t ch) {
6951 unibrow::uchar chars[unibrow::ToUppercase::kMaxWidth];
6952 int char_length = runtime_state->to_upper_mapping()->get(ch, 0, chars);
6953 return char_length == 0;
6957 RUNTIME_FUNCTION(Runtime_NumberToStringRT) {
6958 HandleScope scope(isolate);
6959 DCHECK(args.length() == 1);
6960 CONVERT_NUMBER_ARG_HANDLE_CHECKED(number, 0);
6962 return *isolate->factory()->NumberToString(number);
6966 RUNTIME_FUNCTION(Runtime_NumberToStringSkipCache) {
6967 HandleScope scope(isolate);
6968 DCHECK(args.length() == 1);
6969 CONVERT_NUMBER_ARG_HANDLE_CHECKED(number, 0);
6971 return *isolate->factory()->NumberToString(number, false);
6975 RUNTIME_FUNCTION(Runtime_NumberToInteger) {
6976 HandleScope scope(isolate);
6977 DCHECK(args.length() == 1);
6979 CONVERT_DOUBLE_ARG_CHECKED(number, 0);
6980 return *isolate->factory()->NewNumber(DoubleToInteger(number));
6984 RUNTIME_FUNCTION(Runtime_NumberToIntegerMapMinusZero) {
6985 HandleScope scope(isolate);
6986 DCHECK(args.length() == 1);
6988 CONVERT_DOUBLE_ARG_CHECKED(number, 0);
6989 double double_value = DoubleToInteger(number);
6990 // Map both -0 and +0 to +0.
6991 if (double_value == 0) double_value = 0;
6993 return *isolate->factory()->NewNumber(double_value);
6997 RUNTIME_FUNCTION(Runtime_NumberToJSUint32) {
6998 HandleScope scope(isolate);
6999 DCHECK(args.length() == 1);
7001 CONVERT_NUMBER_CHECKED(int32_t, number, Uint32, args[0]);
7002 return *isolate->factory()->NewNumberFromUint(number);
7006 RUNTIME_FUNCTION(Runtime_NumberToJSInt32) {
7007 HandleScope scope(isolate);
7008 DCHECK(args.length() == 1);
7010 CONVERT_DOUBLE_ARG_CHECKED(number, 0);
7011 return *isolate->factory()->NewNumberFromInt(DoubleToInt32(number));
7015 // Converts a Number to a Smi, if possible. Returns NaN if the number is not
7017 RUNTIME_FUNCTION(Runtime_NumberToSmi) {
7018 SealHandleScope shs(isolate);
7019 DCHECK(args.length() == 1);
7020 CONVERT_ARG_CHECKED(Object, obj, 0);
7024 if (obj->IsHeapNumber()) {
7025 double value = HeapNumber::cast(obj)->value();
7026 int int_value = FastD2I(value);
7027 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
7028 return Smi::FromInt(int_value);
7031 return isolate->heap()->nan_value();
7035 RUNTIME_FUNCTION(Runtime_AllocateHeapNumber) {
7036 HandleScope scope(isolate);
7037 DCHECK(args.length() == 0);
7038 return *isolate->factory()->NewHeapNumber(0);
7042 RUNTIME_FUNCTION(Runtime_AllocateFloat32x4) {
7043 HandleScope scope(isolate);
7044 DCHECK(args.length() == 0);
7046 float32x4_value_t zero = {{0, 0, 0, 0}};
7047 return *isolate->factory()->NewFloat32x4(zero);
7051 RUNTIME_FUNCTION(Runtime_AllocateFloat64x2) {
7052 HandleScope scope(isolate);
7053 DCHECK(args.length() == 0);
7055 float64x2_value_t zero = {{0, 0}};
7056 return *isolate->factory()->NewFloat64x2(zero);
7060 RUNTIME_FUNCTION(Runtime_AllocateInt32x4) {
7061 HandleScope scope(isolate);
7062 DCHECK(args.length() == 0);
7064 int32x4_value_t zero = {{0, 0, 0, 0}};
7065 return *isolate->factory()->NewInt32x4(zero);
7069 RUNTIME_FUNCTION(Runtime_NumberAdd) {
7070 HandleScope scope(isolate);
7071 DCHECK(args.length() == 2);
7073 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7074 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7075 return *isolate->factory()->NewNumber(x + y);
7079 RUNTIME_FUNCTION(Runtime_NumberSub) {
7080 HandleScope scope(isolate);
7081 DCHECK(args.length() == 2);
7083 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7084 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7085 return *isolate->factory()->NewNumber(x - y);
7089 RUNTIME_FUNCTION(Runtime_NumberMul) {
7090 HandleScope scope(isolate);
7091 DCHECK(args.length() == 2);
7093 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7094 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7095 return *isolate->factory()->NewNumber(x * y);
7099 RUNTIME_FUNCTION(Runtime_NumberUnaryMinus) {
7100 HandleScope scope(isolate);
7101 DCHECK(args.length() == 1);
7103 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7104 return *isolate->factory()->NewNumber(-x);
7108 RUNTIME_FUNCTION(Runtime_NumberDiv) {
7109 HandleScope scope(isolate);
7110 DCHECK(args.length() == 2);
7112 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7113 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7114 return *isolate->factory()->NewNumber(x / y);
7118 RUNTIME_FUNCTION(Runtime_NumberMod) {
7119 HandleScope scope(isolate);
7120 DCHECK(args.length() == 2);
7122 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7123 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7124 return *isolate->factory()->NewNumber(modulo(x, y));
7128 RUNTIME_FUNCTION(Runtime_NumberImul) {
7129 HandleScope scope(isolate);
7130 DCHECK(args.length() == 2);
7132 // We rely on implementation-defined behavior below, but at least not on
7133 // undefined behavior.
7134 CONVERT_NUMBER_CHECKED(uint32_t, x, Int32, args[0]);
7135 CONVERT_NUMBER_CHECKED(uint32_t, y, Int32, args[1]);
7136 int32_t product = static_cast<int32_t>(x * y);
7137 return *isolate->factory()->NewNumberFromInt(product);
7141 RUNTIME_FUNCTION(Runtime_StringAdd) {
7142 HandleScope scope(isolate);
7143 DCHECK(args.length() == 2);
7144 CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
7145 CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
7146 isolate->counters()->string_add_runtime()->Increment();
7147 Handle<String> result;
7148 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7149 isolate, result, isolate->factory()->NewConsString(str1, str2));
7154 template <typename sinkchar>
7155 static inline void StringBuilderConcatHelper(String* special,
7157 FixedArray* fixed_array,
7159 DisallowHeapAllocation no_gc;
7161 for (int i = 0; i < array_length; i++) {
7162 Object* element = fixed_array->get(i);
7163 if (element->IsSmi()) {
7164 // Smi encoding of position and length.
7165 int encoded_slice = Smi::cast(element)->value();
7168 if (encoded_slice > 0) {
7169 // Position and length encoded in one smi.
7170 pos = StringBuilderSubstringPosition::decode(encoded_slice);
7171 len = StringBuilderSubstringLength::decode(encoded_slice);
7173 // Position and length encoded in two smis.
7174 Object* obj = fixed_array->get(++i);
7175 DCHECK(obj->IsSmi());
7176 pos = Smi::cast(obj)->value();
7177 len = -encoded_slice;
7179 String::WriteToFlat(special,
7185 String* string = String::cast(element);
7186 int element_length = string->length();
7187 String::WriteToFlat(string, sink + position, 0, element_length);
7188 position += element_length;
7194 // Returns the result length of the concatenation.
7195 // On illegal argument, -1 is returned.
7196 static inline int StringBuilderConcatLength(int special_length,
7197 FixedArray* fixed_array,
7200 DisallowHeapAllocation no_gc;
7202 for (int i = 0; i < array_length; i++) {
7204 Object* elt = fixed_array->get(i);
7206 // Smi encoding of position and length.
7207 int smi_value = Smi::cast(elt)->value();
7210 if (smi_value > 0) {
7211 // Position and length encoded in one smi.
7212 pos = StringBuilderSubstringPosition::decode(smi_value);
7213 len = StringBuilderSubstringLength::decode(smi_value);
7215 // Position and length encoded in two smis.
7217 // Get the position and check that it is a positive smi.
7219 if (i >= array_length) return -1;
7220 Object* next_smi = fixed_array->get(i);
7221 if (!next_smi->IsSmi()) return -1;
7222 pos = Smi::cast(next_smi)->value();
7223 if (pos < 0) return -1;
7227 if (pos > special_length || len > special_length - pos) return -1;
7229 } else if (elt->IsString()) {
7230 String* element = String::cast(elt);
7231 int element_length = element->length();
7232 increment = element_length;
7233 if (*one_byte && !element->HasOnlyOneByteChars()) {
7239 if (increment > String::kMaxLength - position) {
7240 return kMaxInt; // Provoke throw on allocation.
7242 position += increment;
7248 RUNTIME_FUNCTION(Runtime_StringBuilderConcat) {
7249 HandleScope scope(isolate);
7250 DCHECK(args.length() == 3);
7251 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
7252 int32_t array_length;
7253 if (!args[1]->ToInt32(&array_length)) {
7254 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7256 CONVERT_ARG_HANDLE_CHECKED(String, special, 2);
7258 size_t actual_array_length = 0;
7260 TryNumberToSize(isolate, array->length(), &actual_array_length));
7261 RUNTIME_ASSERT(array_length >= 0);
7262 RUNTIME_ASSERT(static_cast<size_t>(array_length) <= actual_array_length);
7264 // This assumption is used by the slice encoding in one or two smis.
7265 DCHECK(Smi::kMaxValue >= String::kMaxLength);
7267 RUNTIME_ASSERT(array->HasFastElements());
7268 JSObject::EnsureCanContainHeapObjectElements(array);
7270 int special_length = special->length();
7271 if (!array->HasFastObjectElements()) {
7272 return isolate->Throw(isolate->heap()->illegal_argument_string());
7276 bool one_byte = special->HasOnlyOneByteChars();
7278 { DisallowHeapAllocation no_gc;
7279 FixedArray* fixed_array = FixedArray::cast(array->elements());
7280 if (fixed_array->length() < array_length) {
7281 array_length = fixed_array->length();
7284 if (array_length == 0) {
7285 return isolate->heap()->empty_string();
7286 } else if (array_length == 1) {
7287 Object* first = fixed_array->get(0);
7288 if (first->IsString()) return first;
7290 length = StringBuilderConcatLength(
7291 special_length, fixed_array, array_length, &one_byte);
7295 return isolate->Throw(isolate->heap()->illegal_argument_string());
7299 Handle<SeqOneByteString> answer;
7300 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7302 isolate->factory()->NewRawOneByteString(length));
7303 StringBuilderConcatHelper(*special,
7305 FixedArray::cast(array->elements()),
7309 Handle<SeqTwoByteString> answer;
7310 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7312 isolate->factory()->NewRawTwoByteString(length));
7313 StringBuilderConcatHelper(*special,
7315 FixedArray::cast(array->elements()),
7322 RUNTIME_FUNCTION(Runtime_StringBuilderJoin) {
7323 HandleScope scope(isolate);
7324 DCHECK(args.length() == 3);
7325 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
7326 int32_t array_length;
7327 if (!args[1]->ToInt32(&array_length)) {
7328 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7330 CONVERT_ARG_HANDLE_CHECKED(String, separator, 2);
7331 RUNTIME_ASSERT(array->HasFastObjectElements());
7332 RUNTIME_ASSERT(array_length >= 0);
7334 Handle<FixedArray> fixed_array(FixedArray::cast(array->elements()));
7335 if (fixed_array->length() < array_length) {
7336 array_length = fixed_array->length();
7339 if (array_length == 0) {
7340 return isolate->heap()->empty_string();
7341 } else if (array_length == 1) {
7342 Object* first = fixed_array->get(0);
7343 RUNTIME_ASSERT(first->IsString());
7347 int separator_length = separator->length();
7348 RUNTIME_ASSERT(separator_length > 0);
7349 int max_nof_separators =
7350 (String::kMaxLength + separator_length - 1) / separator_length;
7351 if (max_nof_separators < (array_length - 1)) {
7352 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7354 int length = (array_length - 1) * separator_length;
7355 for (int i = 0; i < array_length; i++) {
7356 Object* element_obj = fixed_array->get(i);
7357 RUNTIME_ASSERT(element_obj->IsString());
7358 String* element = String::cast(element_obj);
7359 int increment = element->length();
7360 if (increment > String::kMaxLength - length) {
7361 STATIC_ASSERT(String::kMaxLength < kMaxInt);
7362 length = kMaxInt; // Provoke exception;
7365 length += increment;
7368 Handle<SeqTwoByteString> answer;
7369 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
7371 isolate->factory()->NewRawTwoByteString(length));
7373 DisallowHeapAllocation no_gc;
7375 uc16* sink = answer->GetChars();
7377 uc16* end = sink + length;
7380 RUNTIME_ASSERT(fixed_array->get(0)->IsString());
7381 String* first = String::cast(fixed_array->get(0));
7382 String* separator_raw = *separator;
7383 int first_length = first->length();
7384 String::WriteToFlat(first, sink, 0, first_length);
7385 sink += first_length;
7387 for (int i = 1; i < array_length; i++) {
7388 DCHECK(sink + separator_length <= end);
7389 String::WriteToFlat(separator_raw, sink, 0, separator_length);
7390 sink += separator_length;
7392 RUNTIME_ASSERT(fixed_array->get(i)->IsString());
7393 String* element = String::cast(fixed_array->get(i));
7394 int element_length = element->length();
7395 DCHECK(sink + element_length <= end);
7396 String::WriteToFlat(element, sink, 0, element_length);
7397 sink += element_length;
7399 DCHECK(sink == end);
7401 // Use %_FastOneByteArrayJoin instead.
7402 DCHECK(!answer->IsOneByteRepresentation());
7406 template <typename Char>
7407 static void JoinSparseArrayWithSeparator(FixedArray* elements,
7408 int elements_length,
7409 uint32_t array_length,
7411 Vector<Char> buffer) {
7412 DisallowHeapAllocation no_gc;
7413 int previous_separator_position = 0;
7414 int separator_length = separator->length();
7416 for (int i = 0; i < elements_length; i += 2) {
7417 int position = NumberToInt32(elements->get(i));
7418 String* string = String::cast(elements->get(i + 1));
7419 int string_length = string->length();
7420 if (string->length() > 0) {
7421 while (previous_separator_position < position) {
7422 String::WriteToFlat<Char>(separator, &buffer[cursor],
7423 0, separator_length);
7424 cursor += separator_length;
7425 previous_separator_position++;
7427 String::WriteToFlat<Char>(string, &buffer[cursor],
7429 cursor += string->length();
7432 if (separator_length > 0) {
7433 // Array length must be representable as a signed 32-bit number,
7434 // otherwise the total string length would have been too large.
7435 DCHECK(array_length <= 0x7fffffff); // Is int32_t.
7436 int last_array_index = static_cast<int>(array_length - 1);
7437 while (previous_separator_position < last_array_index) {
7438 String::WriteToFlat<Char>(separator, &buffer[cursor],
7439 0, separator_length);
7440 cursor += separator_length;
7441 previous_separator_position++;
7444 DCHECK(cursor <= buffer.length());
7448 RUNTIME_FUNCTION(Runtime_SparseJoinWithSeparator) {
7449 HandleScope scope(isolate);
7450 DCHECK(args.length() == 3);
7451 CONVERT_ARG_HANDLE_CHECKED(JSArray, elements_array, 0);
7452 CONVERT_NUMBER_CHECKED(uint32_t, array_length, Uint32, args[1]);
7453 CONVERT_ARG_HANDLE_CHECKED(String, separator, 2);
7454 // elements_array is fast-mode JSarray of alternating positions
7455 // (increasing order) and strings.
7456 RUNTIME_ASSERT(elements_array->HasFastSmiOrObjectElements());
7457 // array_length is length of original array (used to add separators);
7458 // separator is string to put between elements. Assumed to be non-empty.
7459 RUNTIME_ASSERT(array_length > 0);
7461 // Find total length of join result.
7462 int string_length = 0;
7463 bool is_one_byte = separator->IsOneByteRepresentation();
7464 bool overflow = false;
7465 CONVERT_NUMBER_CHECKED(int, elements_length, Int32, elements_array->length());
7466 RUNTIME_ASSERT(elements_length <= elements_array->elements()->length());
7467 RUNTIME_ASSERT((elements_length & 1) == 0); // Even length.
7468 FixedArray* elements = FixedArray::cast(elements_array->elements());
7469 for (int i = 0; i < elements_length; i += 2) {
7470 RUNTIME_ASSERT(elements->get(i)->IsNumber());
7471 CONVERT_NUMBER_CHECKED(uint32_t, position, Uint32, elements->get(i));
7472 RUNTIME_ASSERT(position < array_length);
7473 RUNTIME_ASSERT(elements->get(i + 1)->IsString());
7476 { DisallowHeapAllocation no_gc;
7477 for (int i = 0; i < elements_length; i += 2) {
7478 String* string = String::cast(elements->get(i + 1));
7479 int length = string->length();
7480 if (is_one_byte && !string->IsOneByteRepresentation()) {
7481 is_one_byte = false;
7483 if (length > String::kMaxLength ||
7484 String::kMaxLength - length < string_length) {
7488 string_length += length;
7492 int separator_length = separator->length();
7493 if (!overflow && separator_length > 0) {
7494 if (array_length <= 0x7fffffffu) {
7495 int separator_count = static_cast<int>(array_length) - 1;
7496 int remaining_length = String::kMaxLength - string_length;
7497 if ((remaining_length / separator_length) >= separator_count) {
7498 string_length += separator_length * (array_length - 1);
7500 // Not room for the separators within the maximal string length.
7504 // Nonempty separator and at least 2^31-1 separators necessary
7505 // means that the string is too large to create.
7506 STATIC_ASSERT(String::kMaxLength < 0x7fffffff);
7511 // Throw an exception if the resulting string is too large. See
7512 // https://code.google.com/p/chromium/issues/detail?id=336820
7514 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
7518 Handle<SeqOneByteString> result = isolate->factory()->NewRawOneByteString(
7519 string_length).ToHandleChecked();
7520 JoinSparseArrayWithSeparator<uint8_t>(
7521 FixedArray::cast(elements_array->elements()),
7525 Vector<uint8_t>(result->GetChars(), string_length));
7528 Handle<SeqTwoByteString> result = isolate->factory()->NewRawTwoByteString(
7529 string_length).ToHandleChecked();
7530 JoinSparseArrayWithSeparator<uc16>(
7531 FixedArray::cast(elements_array->elements()),
7535 Vector<uc16>(result->GetChars(), string_length));
7541 RUNTIME_FUNCTION(Runtime_NumberOr) {
7542 HandleScope scope(isolate);
7543 DCHECK(args.length() == 2);
7545 CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7546 CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7547 return *isolate->factory()->NewNumberFromInt(x | y);
7551 RUNTIME_FUNCTION(Runtime_NumberAnd) {
7552 HandleScope scope(isolate);
7553 DCHECK(args.length() == 2);
7555 CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7556 CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7557 return *isolate->factory()->NewNumberFromInt(x & y);
7561 RUNTIME_FUNCTION(Runtime_NumberXor) {
7562 HandleScope scope(isolate);
7563 DCHECK(args.length() == 2);
7565 CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7566 CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7567 return *isolate->factory()->NewNumberFromInt(x ^ y);
7571 RUNTIME_FUNCTION(Runtime_NumberShl) {
7572 HandleScope scope(isolate);
7573 DCHECK(args.length() == 2);
7575 CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7576 CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7577 return *isolate->factory()->NewNumberFromInt(x << (y & 0x1f));
7581 RUNTIME_FUNCTION(Runtime_NumberShr) {
7582 HandleScope scope(isolate);
7583 DCHECK(args.length() == 2);
7585 CONVERT_NUMBER_CHECKED(uint32_t, x, Uint32, args[0]);
7586 CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7587 return *isolate->factory()->NewNumberFromUint(x >> (y & 0x1f));
7591 RUNTIME_FUNCTION(Runtime_NumberSar) {
7592 HandleScope scope(isolate);
7593 DCHECK(args.length() == 2);
7595 CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
7596 CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
7597 return *isolate->factory()->NewNumberFromInt(
7598 ArithmeticShiftRight(x, y & 0x1f));
7602 RUNTIME_FUNCTION(Runtime_NumberEquals) {
7603 SealHandleScope shs(isolate);
7604 DCHECK(args.length() == 2);
7606 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7607 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7608 if (std::isnan(x)) return Smi::FromInt(NOT_EQUAL);
7609 if (std::isnan(y)) return Smi::FromInt(NOT_EQUAL);
7610 if (x == y) return Smi::FromInt(EQUAL);
7612 if ((fpclassify(x) == FP_ZERO) && (fpclassify(y) == FP_ZERO)) {
7613 result = Smi::FromInt(EQUAL);
7615 result = Smi::FromInt(NOT_EQUAL);
7621 RUNTIME_FUNCTION(Runtime_StringEquals) {
7622 HandleScope handle_scope(isolate);
7623 DCHECK(args.length() == 2);
7625 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
7626 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
7628 bool not_equal = !String::Equals(x, y);
7629 // This is slightly convoluted because the value that signifies
7630 // equality is 0 and inequality is 1 so we have to negate the result
7631 // from String::Equals.
7632 DCHECK(not_equal == 0 || not_equal == 1);
7633 STATIC_ASSERT(EQUAL == 0);
7634 STATIC_ASSERT(NOT_EQUAL == 1);
7635 return Smi::FromInt(not_equal);
7639 RUNTIME_FUNCTION(Runtime_NumberCompare) {
7640 SealHandleScope shs(isolate);
7641 DCHECK(args.length() == 3);
7643 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7644 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7645 CONVERT_ARG_HANDLE_CHECKED(Object, uncomparable_result, 2)
7646 if (std::isnan(x) || std::isnan(y)) return *uncomparable_result;
7647 if (x == y) return Smi::FromInt(EQUAL);
7648 if (isless(x, y)) return Smi::FromInt(LESS);
7649 return Smi::FromInt(GREATER);
7653 // Compare two Smis as if they were converted to strings and then
7654 // compared lexicographically.
7655 RUNTIME_FUNCTION(Runtime_SmiLexicographicCompare) {
7656 SealHandleScope shs(isolate);
7657 DCHECK(args.length() == 2);
7658 CONVERT_SMI_ARG_CHECKED(x_value, 0);
7659 CONVERT_SMI_ARG_CHECKED(y_value, 1);
7661 // If the integers are equal so are the string representations.
7662 if (x_value == y_value) return Smi::FromInt(EQUAL);
7664 // If one of the integers is zero the normal integer order is the
7665 // same as the lexicographic order of the string representations.
7666 if (x_value == 0 || y_value == 0)
7667 return Smi::FromInt(x_value < y_value ? LESS : GREATER);
7669 // If only one of the integers is negative the negative number is
7670 // smallest because the char code of '-' is less than the char code
7671 // of any digit. Otherwise, we make both values positive.
7673 // Use unsigned values otherwise the logic is incorrect for -MIN_INT on
7674 // architectures using 32-bit Smis.
7675 uint32_t x_scaled = x_value;
7676 uint32_t y_scaled = y_value;
7677 if (x_value < 0 || y_value < 0) {
7678 if (y_value >= 0) return Smi::FromInt(LESS);
7679 if (x_value >= 0) return Smi::FromInt(GREATER);
7680 x_scaled = -x_value;
7681 y_scaled = -y_value;
7684 static const uint32_t kPowersOf10[] = {
7685 1, 10, 100, 1000, 10*1000, 100*1000,
7686 1000*1000, 10*1000*1000, 100*1000*1000,
7690 // If the integers have the same number of decimal digits they can be
7691 // compared directly as the numeric order is the same as the
7692 // lexicographic order. If one integer has fewer digits, it is scaled
7693 // by some power of 10 to have the same number of digits as the longer
7694 // integer. If the scaled integers are equal it means the shorter
7695 // integer comes first in the lexicographic order.
7697 // From http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
7698 int x_log2 = IntegerLog2(x_scaled);
7699 int x_log10 = ((x_log2 + 1) * 1233) >> 12;
7700 x_log10 -= x_scaled < kPowersOf10[x_log10];
7702 int y_log2 = IntegerLog2(y_scaled);
7703 int y_log10 = ((y_log2 + 1) * 1233) >> 12;
7704 y_log10 -= y_scaled < kPowersOf10[y_log10];
7708 if (x_log10 < y_log10) {
7709 // X has fewer digits. We would like to simply scale up X but that
7710 // might overflow, e.g when comparing 9 with 1_000_000_000, 9 would
7711 // be scaled up to 9_000_000_000. So we scale up by the next
7712 // smallest power and scale down Y to drop one digit. It is OK to
7713 // drop one digit from the longer integer since the final digit is
7714 // past the length of the shorter integer.
7715 x_scaled *= kPowersOf10[y_log10 - x_log10 - 1];
7718 } else if (y_log10 < x_log10) {
7719 y_scaled *= kPowersOf10[x_log10 - y_log10 - 1];
7724 if (x_scaled < y_scaled) return Smi::FromInt(LESS);
7725 if (x_scaled > y_scaled) return Smi::FromInt(GREATER);
7726 return Smi::FromInt(tie);
7730 RUNTIME_FUNCTION(Runtime_StringCompare) {
7731 HandleScope handle_scope(isolate);
7732 DCHECK(args.length() == 2);
7734 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
7735 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
7737 isolate->counters()->string_compare_runtime()->Increment();
7739 // A few fast case tests before we flatten.
7740 if (x.is_identical_to(y)) return Smi::FromInt(EQUAL);
7741 if (y->length() == 0) {
7742 if (x->length() == 0) return Smi::FromInt(EQUAL);
7743 return Smi::FromInt(GREATER);
7744 } else if (x->length() == 0) {
7745 return Smi::FromInt(LESS);
7748 int d = x->Get(0) - y->Get(0);
7749 if (d < 0) return Smi::FromInt(LESS);
7750 else if (d > 0) return Smi::FromInt(GREATER);
7753 x = String::Flatten(x);
7754 y = String::Flatten(y);
7756 DisallowHeapAllocation no_gc;
7757 Object* equal_prefix_result = Smi::FromInt(EQUAL);
7758 int prefix_length = x->length();
7759 if (y->length() < prefix_length) {
7760 prefix_length = y->length();
7761 equal_prefix_result = Smi::FromInt(GREATER);
7762 } else if (y->length() > prefix_length) {
7763 equal_prefix_result = Smi::FromInt(LESS);
7766 String::FlatContent x_content = x->GetFlatContent();
7767 String::FlatContent y_content = y->GetFlatContent();
7768 if (x_content.IsOneByte()) {
7769 Vector<const uint8_t> x_chars = x_content.ToOneByteVector();
7770 if (y_content.IsOneByte()) {
7771 Vector<const uint8_t> y_chars = y_content.ToOneByteVector();
7772 r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7774 Vector<const uc16> y_chars = y_content.ToUC16Vector();
7775 r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7778 Vector<const uc16> x_chars = x_content.ToUC16Vector();
7779 if (y_content.IsOneByte()) {
7780 Vector<const uint8_t> y_chars = y_content.ToOneByteVector();
7781 r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7783 Vector<const uc16> y_chars = y_content.ToUC16Vector();
7784 r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
7789 result = equal_prefix_result;
7791 result = (r < 0) ? Smi::FromInt(LESS) : Smi::FromInt(GREATER);
7797 #define RUNTIME_UNARY_MATH(Name, name) \
7798 RUNTIME_FUNCTION(Runtime_Math##Name) { \
7799 HandleScope scope(isolate); \
7800 DCHECK(args.length() == 1); \
7801 isolate->counters()->math_##name()->Increment(); \
7802 CONVERT_DOUBLE_ARG_CHECKED(x, 0); \
7803 return *isolate->factory()->NewHeapNumber(std::name(x)); \
7806 RUNTIME_UNARY_MATH(Acos, acos)
7807 RUNTIME_UNARY_MATH(Asin, asin)
7808 RUNTIME_UNARY_MATH(Atan, atan)
7809 RUNTIME_UNARY_MATH(LogRT, log)
7810 #undef RUNTIME_UNARY_MATH
7813 RUNTIME_FUNCTION(Runtime_DoubleHi) {
7814 HandleScope scope(isolate);
7815 DCHECK(args.length() == 1);
7816 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7817 uint64_t integer = double_to_uint64(x);
7818 integer = (integer >> 32) & 0xFFFFFFFFu;
7819 return *isolate->factory()->NewNumber(static_cast<int32_t>(integer));
7823 RUNTIME_FUNCTION(Runtime_DoubleLo) {
7824 HandleScope scope(isolate);
7825 DCHECK(args.length() == 1);
7826 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7827 return *isolate->factory()->NewNumber(
7828 static_cast<int32_t>(double_to_uint64(x) & 0xFFFFFFFFu));
7832 RUNTIME_FUNCTION(Runtime_ConstructDouble) {
7833 HandleScope scope(isolate);
7834 DCHECK(args.length() == 2);
7835 CONVERT_NUMBER_CHECKED(uint32_t, hi, Uint32, args[0]);
7836 CONVERT_NUMBER_CHECKED(uint32_t, lo, Uint32, args[1]);
7837 uint64_t result = (static_cast<uint64_t>(hi) << 32) | lo;
7838 return *isolate->factory()->NewNumber(uint64_to_double(result));
7842 RUNTIME_FUNCTION(Runtime_RemPiO2) {
7843 HandleScope handle_scope(isolate);
7844 DCHECK(args.length() == 1);
7845 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7846 Factory* factory = isolate->factory();
7847 double y[2] = {0.0, 0.0};
7848 int n = fdlibm::rempio2(x, y);
7849 Handle<FixedArray> array = factory->NewFixedArray(3);
7850 Handle<HeapNumber> y0 = factory->NewHeapNumber(y[0]);
7851 Handle<HeapNumber> y1 = factory->NewHeapNumber(y[1]);
7852 array->set(0, Smi::FromInt(n));
7855 return *factory->NewJSArrayWithElements(array);
7859 static const double kPiDividedBy4 = 0.78539816339744830962;
7862 RUNTIME_FUNCTION(Runtime_MathAtan2) {
7863 HandleScope scope(isolate);
7864 DCHECK(args.length() == 2);
7865 isolate->counters()->math_atan2()->Increment();
7867 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7868 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7870 if (std::isinf(x) && std::isinf(y)) {
7871 // Make sure that the result in case of two infinite arguments
7872 // is a multiple of Pi / 4. The sign of the result is determined
7873 // by the first argument (x) and the sign of the second argument
7874 // determines the multiplier: one or three.
7875 int multiplier = (x < 0) ? -1 : 1;
7876 if (y < 0) multiplier *= 3;
7877 result = multiplier * kPiDividedBy4;
7879 result = std::atan2(x, y);
7881 return *isolate->factory()->NewNumber(result);
7885 RUNTIME_FUNCTION(Runtime_MathExpRT) {
7886 HandleScope scope(isolate);
7887 DCHECK(args.length() == 1);
7888 isolate->counters()->math_exp()->Increment();
7890 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7891 lazily_initialize_fast_exp();
7892 return *isolate->factory()->NewNumber(fast_exp(x));
7896 RUNTIME_FUNCTION(Runtime_MathFloorRT) {
7897 HandleScope scope(isolate);
7898 DCHECK(args.length() == 1);
7899 isolate->counters()->math_floor()->Increment();
7901 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7902 return *isolate->factory()->NewNumber(Floor(x));
7906 // Slow version of Math.pow. We check for fast paths for special cases.
7907 // Used if VFP3 is not available.
7908 RUNTIME_FUNCTION(Runtime_MathPowSlow) {
7909 HandleScope scope(isolate);
7910 DCHECK(args.length() == 2);
7911 isolate->counters()->math_pow()->Increment();
7913 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7915 // If the second argument is a smi, it is much faster to call the
7916 // custom powi() function than the generic pow().
7917 if (args[1]->IsSmi()) {
7918 int y = args.smi_at(1);
7919 return *isolate->factory()->NewNumber(power_double_int(x, y));
7922 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7923 double result = power_helper(x, y);
7924 if (std::isnan(result)) return isolate->heap()->nan_value();
7925 return *isolate->factory()->NewNumber(result);
7929 // Fast version of Math.pow if we know that y is not an integer and y is not
7930 // -0.5 or 0.5. Used as slow case from full codegen.
7931 RUNTIME_FUNCTION(Runtime_MathPowRT) {
7932 HandleScope scope(isolate);
7933 DCHECK(args.length() == 2);
7934 isolate->counters()->math_pow()->Increment();
7936 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7937 CONVERT_DOUBLE_ARG_CHECKED(y, 1);
7939 return Smi::FromInt(1);
7941 double result = power_double_double(x, y);
7942 if (std::isnan(result)) return isolate->heap()->nan_value();
7943 return *isolate->factory()->NewNumber(result);
7948 RUNTIME_FUNCTION(Runtime_RoundNumber) {
7949 HandleScope scope(isolate);
7950 DCHECK(args.length() == 1);
7951 CONVERT_NUMBER_ARG_HANDLE_CHECKED(input, 0);
7952 isolate->counters()->math_round()->Increment();
7954 if (!input->IsHeapNumber()) {
7955 DCHECK(input->IsSmi());
7959 Handle<HeapNumber> number = Handle<HeapNumber>::cast(input);
7961 double value = number->value();
7962 int exponent = number->get_exponent();
7963 int sign = number->get_sign();
7965 if (exponent < -1) {
7966 // Number in range ]-0.5..0.5[. These always round to +/-zero.
7967 if (sign) return isolate->heap()->minus_zero_value();
7968 return Smi::FromInt(0);
7971 // We compare with kSmiValueSize - 2 because (2^30 - 0.1) has exponent 29 and
7972 // should be rounded to 2^30, which is not smi (for 31-bit smis, similar
7973 // argument holds for 32-bit smis).
7974 if (!sign && exponent < kSmiValueSize - 2) {
7975 return Smi::FromInt(static_cast<int>(value + 0.5));
7978 // If the magnitude is big enough, there's no place for fraction part. If we
7979 // try to add 0.5 to this number, 1.0 will be added instead.
7980 if (exponent >= 52) {
7984 if (sign && value >= -0.5) return isolate->heap()->minus_zero_value();
7986 // Do not call NumberFromDouble() to avoid extra checks.
7987 return *isolate->factory()->NewNumber(Floor(value + 0.5));
7991 RUNTIME_FUNCTION(Runtime_MathSqrtRT) {
7992 HandleScope scope(isolate);
7993 DCHECK(args.length() == 1);
7994 isolate->counters()->math_sqrt()->Increment();
7996 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
7997 return *isolate->factory()->NewNumber(fast_sqrt(x));
8001 RUNTIME_FUNCTION(Runtime_MathFround) {
8002 HandleScope scope(isolate);
8003 DCHECK(args.length() == 1);
8005 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
8006 float xf = DoubleToFloat32(x);
8007 return *isolate->factory()->NewNumber(xf);
8011 RUNTIME_FUNCTION(Runtime_DateMakeDay) {
8012 SealHandleScope shs(isolate);
8013 DCHECK(args.length() == 2);
8015 CONVERT_SMI_ARG_CHECKED(year, 0);
8016 CONVERT_SMI_ARG_CHECKED(month, 1);
8018 int days = isolate->date_cache()->DaysFromYearMonth(year, month);
8019 RUNTIME_ASSERT(Smi::IsValid(days));
8020 return Smi::FromInt(days);
8024 RUNTIME_FUNCTION(Runtime_DateSetValue) {
8025 HandleScope scope(isolate);
8026 DCHECK(args.length() == 3);
8028 CONVERT_ARG_HANDLE_CHECKED(JSDate, date, 0);
8029 CONVERT_DOUBLE_ARG_CHECKED(time, 1);
8030 CONVERT_SMI_ARG_CHECKED(is_utc, 2);
8032 DateCache* date_cache = isolate->date_cache();
8034 Handle<Object> value;;
8035 bool is_value_nan = false;
8036 if (std::isnan(time)) {
8037 value = isolate->factory()->nan_value();
8038 is_value_nan = true;
8039 } else if (!is_utc &&
8040 (time < -DateCache::kMaxTimeBeforeUTCInMs ||
8041 time > DateCache::kMaxTimeBeforeUTCInMs)) {
8042 value = isolate->factory()->nan_value();
8043 is_value_nan = true;
8045 time = is_utc ? time : date_cache->ToUTC(static_cast<int64_t>(time));
8046 if (time < -DateCache::kMaxTimeInMs ||
8047 time > DateCache::kMaxTimeInMs) {
8048 value = isolate->factory()->nan_value();
8049 is_value_nan = true;
8051 value = isolate->factory()->NewNumber(DoubleToInteger(time));
8054 date->SetValue(*value, is_value_nan);
8059 static Handle<JSObject> NewSloppyArguments(Isolate* isolate,
8060 Handle<JSFunction> callee,
8061 Object** parameters,
8062 int argument_count) {
8063 Handle<JSObject> result =
8064 isolate->factory()->NewArgumentsObject(callee, argument_count);
8066 // Allocate the elements if needed.
8067 int parameter_count = callee->shared()->formal_parameter_count();
8068 if (argument_count > 0) {
8069 if (parameter_count > 0) {
8070 int mapped_count = Min(argument_count, parameter_count);
8071 Handle<FixedArray> parameter_map =
8072 isolate->factory()->NewFixedArray(mapped_count + 2, NOT_TENURED);
8073 parameter_map->set_map(
8074 isolate->heap()->sloppy_arguments_elements_map());
8076 Handle<Map> map = Map::Copy(handle(result->map()));
8077 map->set_elements_kind(SLOPPY_ARGUMENTS_ELEMENTS);
8079 result->set_map(*map);
8080 result->set_elements(*parameter_map);
8082 // Store the context and the arguments array at the beginning of the
8084 Handle<Context> context(isolate->context());
8085 Handle<FixedArray> arguments =
8086 isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
8087 parameter_map->set(0, *context);
8088 parameter_map->set(1, *arguments);
8090 // Loop over the actual parameters backwards.
8091 int index = argument_count - 1;
8092 while (index >= mapped_count) {
8093 // These go directly in the arguments array and have no
8094 // corresponding slot in the parameter map.
8095 arguments->set(index, *(parameters - index - 1));
8099 Handle<ScopeInfo> scope_info(callee->shared()->scope_info());
8100 while (index >= 0) {
8101 // Detect duplicate names to the right in the parameter list.
8102 Handle<String> name(scope_info->ParameterName(index));
8103 int context_local_count = scope_info->ContextLocalCount();
8104 bool duplicate = false;
8105 for (int j = index + 1; j < parameter_count; ++j) {
8106 if (scope_info->ParameterName(j) == *name) {
8113 // This goes directly in the arguments array with a hole in the
8115 arguments->set(index, *(parameters - index - 1));
8116 parameter_map->set_the_hole(index + 2);
8118 // The context index goes in the parameter map with a hole in the
8120 int context_index = -1;
8121 for (int j = 0; j < context_local_count; ++j) {
8122 if (scope_info->ContextLocalName(j) == *name) {
8127 DCHECK(context_index >= 0);
8128 arguments->set_the_hole(index);
8129 parameter_map->set(index + 2, Smi::FromInt(
8130 Context::MIN_CONTEXT_SLOTS + context_index));
8136 // If there is no aliasing, the arguments object elements are not
8137 // special in any way.
8138 Handle<FixedArray> elements =
8139 isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
8140 result->set_elements(*elements);
8141 for (int i = 0; i < argument_count; ++i) {
8142 elements->set(i, *(parameters - i - 1));
8150 static Handle<JSObject> NewStrictArguments(Isolate* isolate,
8151 Handle<JSFunction> callee,
8152 Object** parameters,
8153 int argument_count) {
8154 Handle<JSObject> result =
8155 isolate->factory()->NewArgumentsObject(callee, argument_count);
8157 if (argument_count > 0) {
8158 Handle<FixedArray> array =
8159 isolate->factory()->NewUninitializedFixedArray(argument_count);
8160 DisallowHeapAllocation no_gc;
8161 WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc);
8162 for (int i = 0; i < argument_count; i++) {
8163 array->set(i, *--parameters, mode);
8165 result->set_elements(*array);
8171 RUNTIME_FUNCTION(Runtime_NewArguments) {
8172 HandleScope scope(isolate);
8173 DCHECK(args.length() == 1);
8174 CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
8175 JavaScriptFrameIterator it(isolate);
8177 // Find the frame that holds the actual arguments passed to the function.
8178 it.AdvanceToArgumentsFrame();
8179 JavaScriptFrame* frame = it.frame();
8181 // Determine parameter location on the stack and dispatch on language mode.
8182 int argument_count = frame->GetArgumentsLength();
8183 Object** parameters = reinterpret_cast<Object**>(frame->GetParameterSlot(-1));
8184 return callee->shared()->strict_mode() == STRICT
8185 ? *NewStrictArguments(isolate, callee, parameters, argument_count)
8186 : *NewSloppyArguments(isolate, callee, parameters, argument_count);
8190 RUNTIME_FUNCTION(Runtime_NewSloppyArguments) {
8191 HandleScope scope(isolate);
8192 DCHECK(args.length() == 3);
8193 CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
8194 Object** parameters = reinterpret_cast<Object**>(args[1]);
8195 CONVERT_SMI_ARG_CHECKED(argument_count, 2);
8196 return *NewSloppyArguments(isolate, callee, parameters, argument_count);
8200 RUNTIME_FUNCTION(Runtime_NewStrictArguments) {
8201 HandleScope scope(isolate);
8202 DCHECK(args.length() == 3);
8203 CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0)
8204 Object** parameters = reinterpret_cast<Object**>(args[1]);
8205 CONVERT_SMI_ARG_CHECKED(argument_count, 2);
8206 return *NewStrictArguments(isolate, callee, parameters, argument_count);
8210 RUNTIME_FUNCTION(Runtime_NewClosureFromStubFailure) {
8211 HandleScope scope(isolate);
8212 DCHECK(args.length() == 1);
8213 CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0);
8214 Handle<Context> context(isolate->context());
8215 PretenureFlag pretenure_flag = NOT_TENURED;
8216 return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
8221 RUNTIME_FUNCTION(Runtime_NewClosure) {
8222 HandleScope scope(isolate);
8223 DCHECK(args.length() == 3);
8224 CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
8225 CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 1);
8226 CONVERT_BOOLEAN_ARG_CHECKED(pretenure, 2);
8228 // The caller ensures that we pretenure closures that are assigned
8229 // directly to properties.
8230 PretenureFlag pretenure_flag = pretenure ? TENURED : NOT_TENURED;
8231 return *isolate->factory()->NewFunctionFromSharedFunctionInfo(
8232 shared, context, pretenure_flag);
8236 // Find the arguments of the JavaScript function invocation that called
8237 // into C++ code. Collect these in a newly allocated array of handles (possibly
8238 // prefixed by a number of empty handles).
8239 static SmartArrayPointer<Handle<Object> > GetCallerArguments(
8243 // Find frame containing arguments passed to the caller.
8244 JavaScriptFrameIterator it(isolate);
8245 JavaScriptFrame* frame = it.frame();
8246 List<JSFunction*> functions(2);
8247 frame->GetFunctions(&functions);
8248 if (functions.length() > 1) {
8249 int inlined_jsframe_index = functions.length() - 1;
8250 JSFunction* inlined_function = functions[inlined_jsframe_index];
8251 SlotRefValueBuilder slot_refs(
8253 inlined_jsframe_index,
8254 inlined_function->shared()->formal_parameter_count());
8256 int args_count = slot_refs.args_length();
8258 *total_argc = prefix_argc + args_count;
8259 SmartArrayPointer<Handle<Object> > param_data(
8260 NewArray<Handle<Object> >(*total_argc));
8261 slot_refs.Prepare(isolate);
8262 for (int i = 0; i < args_count; i++) {
8263 Handle<Object> val = slot_refs.GetNext(isolate, 0);
8264 param_data[prefix_argc + i] = val;
8266 slot_refs.Finish(isolate);
8270 it.AdvanceToArgumentsFrame();
8272 int args_count = frame->ComputeParametersCount();
8274 *total_argc = prefix_argc + args_count;
8275 SmartArrayPointer<Handle<Object> > param_data(
8276 NewArray<Handle<Object> >(*total_argc));
8277 for (int i = 0; i < args_count; i++) {
8278 Handle<Object> val = Handle<Object>(frame->GetParameter(i), isolate);
8279 param_data[prefix_argc + i] = val;
8286 RUNTIME_FUNCTION(Runtime_FunctionBindArguments) {
8287 HandleScope scope(isolate);
8288 DCHECK(args.length() == 4);
8289 CONVERT_ARG_HANDLE_CHECKED(JSFunction, bound_function, 0);
8290 CONVERT_ARG_HANDLE_CHECKED(Object, bindee, 1);
8291 CONVERT_ARG_HANDLE_CHECKED(Object, this_object, 2);
8292 CONVERT_NUMBER_ARG_HANDLE_CHECKED(new_length, 3);
8294 // TODO(lrn): Create bound function in C++ code from premade shared info.
8295 bound_function->shared()->set_bound(true);
8296 // Get all arguments of calling function (Function.prototype.bind).
8298 SmartArrayPointer<Handle<Object> > arguments =
8299 GetCallerArguments(isolate, 0, &argc);
8300 // Don't count the this-arg.
8302 RUNTIME_ASSERT(arguments[0].is_identical_to(this_object));
8305 RUNTIME_ASSERT(this_object->IsUndefined());
8307 // Initialize array of bindings (function, this, and any existing arguments
8308 // if the function was already bound).
8309 Handle<FixedArray> new_bindings;
8311 if (bindee->IsJSFunction() && JSFunction::cast(*bindee)->shared()->bound()) {
8312 Handle<FixedArray> old_bindings(
8313 JSFunction::cast(*bindee)->function_bindings());
8314 RUNTIME_ASSERT(old_bindings->length() > JSFunction::kBoundFunctionIndex);
8316 isolate->factory()->NewFixedArray(old_bindings->length() + argc);
8317 bindee = Handle<Object>(old_bindings->get(JSFunction::kBoundFunctionIndex),
8320 for (int n = old_bindings->length(); i < n; i++) {
8321 new_bindings->set(i, old_bindings->get(i));
8324 int array_size = JSFunction::kBoundArgumentsStartIndex + argc;
8325 new_bindings = isolate->factory()->NewFixedArray(array_size);
8326 new_bindings->set(JSFunction::kBoundFunctionIndex, *bindee);
8327 new_bindings->set(JSFunction::kBoundThisIndex, *this_object);
8330 // Copy arguments, skipping the first which is "this_arg".
8331 for (int j = 0; j < argc; j++, i++) {
8332 new_bindings->set(i, *arguments[j + 1]);
8334 new_bindings->set_map_no_write_barrier(
8335 isolate->heap()->fixed_cow_array_map());
8336 bound_function->set_function_bindings(*new_bindings);
8338 // Update length. Have to remove the prototype first so that map migration
8339 // is happy about the number of fields.
8340 RUNTIME_ASSERT(bound_function->RemovePrototype());
8341 Handle<Map> bound_function_map(
8342 isolate->native_context()->bound_function_map());
8343 JSObject::MigrateToMap(bound_function, bound_function_map);
8344 Handle<String> length_string = isolate->factory()->length_string();
8345 PropertyAttributes attr =
8346 static_cast<PropertyAttributes>(DONT_DELETE | DONT_ENUM | READ_ONLY);
8347 RETURN_FAILURE_ON_EXCEPTION(
8349 JSObject::SetOwnPropertyIgnoreAttributes(
8350 bound_function, length_string, new_length, attr));
8351 return *bound_function;
8355 RUNTIME_FUNCTION(Runtime_BoundFunctionGetBindings) {
8356 HandleScope handles(isolate);
8357 DCHECK(args.length() == 1);
8358 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, callable, 0);
8359 if (callable->IsJSFunction()) {
8360 Handle<JSFunction> function = Handle<JSFunction>::cast(callable);
8361 if (function->shared()->bound()) {
8362 Handle<FixedArray> bindings(function->function_bindings());
8363 RUNTIME_ASSERT(bindings->map() == isolate->heap()->fixed_cow_array_map());
8364 return *isolate->factory()->NewJSArrayWithElements(bindings);
8367 return isolate->heap()->undefined_value();
8371 RUNTIME_FUNCTION(Runtime_NewObjectFromBound) {
8372 HandleScope scope(isolate);
8373 DCHECK(args.length() == 1);
8374 // First argument is a function to use as a constructor.
8375 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8376 RUNTIME_ASSERT(function->shared()->bound());
8378 // The argument is a bound function. Extract its bound arguments
8380 Handle<FixedArray> bound_args =
8381 Handle<FixedArray>(FixedArray::cast(function->function_bindings()));
8382 int bound_argc = bound_args->length() - JSFunction::kBoundArgumentsStartIndex;
8383 Handle<Object> bound_function(
8384 JSReceiver::cast(bound_args->get(JSFunction::kBoundFunctionIndex)),
8386 DCHECK(!bound_function->IsJSFunction() ||
8387 !Handle<JSFunction>::cast(bound_function)->shared()->bound());
8390 SmartArrayPointer<Handle<Object> > param_data =
8391 GetCallerArguments(isolate, bound_argc, &total_argc);
8392 for (int i = 0; i < bound_argc; i++) {
8393 param_data[i] = Handle<Object>(bound_args->get(
8394 JSFunction::kBoundArgumentsStartIndex + i), isolate);
8397 if (!bound_function->IsJSFunction()) {
8398 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
8399 isolate, bound_function,
8400 Execution::TryGetConstructorDelegate(isolate, bound_function));
8402 DCHECK(bound_function->IsJSFunction());
8404 Handle<Object> result;
8405 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
8407 Execution::New(Handle<JSFunction>::cast(bound_function),
8408 total_argc, param_data.get()));
8413 static Object* Runtime_NewObjectHelper(Isolate* isolate,
8414 Handle<Object> constructor,
8415 Handle<AllocationSite> site) {
8416 // If the constructor isn't a proper function we throw a type error.
8417 if (!constructor->IsJSFunction()) {
8418 Vector< Handle<Object> > arguments = HandleVector(&constructor, 1);
8419 THROW_NEW_ERROR_RETURN_FAILURE(isolate,
8420 NewTypeError("not_constructor", arguments));
8423 Handle<JSFunction> function = Handle<JSFunction>::cast(constructor);
8425 // If function should not have prototype, construction is not allowed. In this
8426 // case generated code bailouts here, since function has no initial_map.
8427 if (!function->should_have_prototype() && !function->shared()->bound()) {
8428 Vector< Handle<Object> > arguments = HandleVector(&constructor, 1);
8429 THROW_NEW_ERROR_RETURN_FAILURE(isolate,
8430 NewTypeError("not_constructor", arguments));
8433 Debug* debug = isolate->debug();
8434 // Handle stepping into constructors if step into is active.
8435 if (debug->StepInActive()) {
8436 debug->HandleStepIn(function, Handle<Object>::null(), 0, true);
8439 if (function->has_initial_map()) {
8440 if (function->initial_map()->instance_type() == JS_FUNCTION_TYPE) {
8441 // The 'Function' function ignores the receiver object when
8442 // called using 'new' and creates a new JSFunction object that
8443 // is returned. The receiver object is only used for error
8444 // reporting if an error occurs when constructing the new
8445 // JSFunction. Factory::NewJSObject() should not be used to
8446 // allocate JSFunctions since it does not properly initialize
8447 // the shared part of the function. Since the receiver is
8448 // ignored anyway, we use the global object as the receiver
8449 // instead of a new JSFunction object. This way, errors are
8450 // reported the same way whether or not 'Function' is called
8452 return isolate->global_proxy();
8456 // The function should be compiled for the optimization hints to be
8458 Compiler::EnsureCompiled(function, CLEAR_EXCEPTION);
8460 Handle<JSObject> result;
8461 if (site.is_null()) {
8462 result = isolate->factory()->NewJSObject(function);
8464 result = isolate->factory()->NewJSObjectWithMemento(function, site);
8467 isolate->counters()->constructed_objects()->Increment();
8468 isolate->counters()->constructed_objects_runtime()->Increment();
8474 RUNTIME_FUNCTION(Runtime_NewObject) {
8475 HandleScope scope(isolate);
8476 DCHECK(args.length() == 1);
8477 CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 0);
8478 return Runtime_NewObjectHelper(isolate,
8480 Handle<AllocationSite>::null());
8484 RUNTIME_FUNCTION(Runtime_NewObjectWithAllocationSite) {
8485 HandleScope scope(isolate);
8486 DCHECK(args.length() == 2);
8487 CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 1);
8488 CONVERT_ARG_HANDLE_CHECKED(Object, feedback, 0);
8489 Handle<AllocationSite> site;
8490 if (feedback->IsAllocationSite()) {
8491 // The feedback can be an AllocationSite or undefined.
8492 site = Handle<AllocationSite>::cast(feedback);
8494 return Runtime_NewObjectHelper(isolate, constructor, site);
8498 RUNTIME_FUNCTION(Runtime_FinalizeInstanceSize) {
8499 HandleScope scope(isolate);
8500 DCHECK(args.length() == 1);
8502 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8503 function->CompleteInobjectSlackTracking();
8505 return isolate->heap()->undefined_value();
8509 RUNTIME_FUNCTION(Runtime_CompileLazy) {
8510 HandleScope scope(isolate);
8511 DCHECK(args.length() == 1);
8512 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8514 if (FLAG_trace_lazy && !function->shared()->is_compiled()) {
8515 PrintF("[unoptimized: ");
8516 function->PrintName();
8521 // Compile the target function.
8522 DCHECK(function->shared()->allows_lazy_compilation());
8525 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, code,
8526 Compiler::GetLazyCode(function));
8527 DCHECK(code->kind() == Code::FUNCTION ||
8528 code->kind() == Code::OPTIMIZED_FUNCTION);
8529 function->ReplaceCode(*code);
8534 RUNTIME_FUNCTION(Runtime_CompileOptimized) {
8535 HandleScope scope(isolate);
8536 DCHECK(args.length() == 2);
8537 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8538 CONVERT_BOOLEAN_ARG_CHECKED(concurrent, 1);
8540 Handle<Code> unoptimized(function->shared()->code());
8541 if (!isolate->use_crankshaft() ||
8542 function->shared()->optimization_disabled() ||
8543 isolate->DebuggerHasBreakPoints()) {
8544 // If the function is not optimizable or debugger is active continue
8545 // using the code from the full compiler.
8546 if (FLAG_trace_opt) {
8547 PrintF("[failed to optimize ");
8548 function->PrintName();
8549 PrintF(": is code optimizable: %s, is debugger enabled: %s]\n",
8550 function->shared()->optimization_disabled() ? "F" : "T",
8551 isolate->DebuggerHasBreakPoints() ? "T" : "F");
8553 function->ReplaceCode(*unoptimized);
8554 return function->code();
8557 Compiler::ConcurrencyMode mode =
8558 concurrent ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT;
8560 if (Compiler::GetOptimizedCode(function, unoptimized, mode).ToHandle(&code)) {
8561 function->ReplaceCode(*code);
8563 function->ReplaceCode(function->shared()->code());
8566 DCHECK(function->code()->kind() == Code::FUNCTION ||
8567 function->code()->kind() == Code::OPTIMIZED_FUNCTION ||
8568 function->IsInOptimizationQueue());
8569 return function->code();
8573 class ActivationsFinder : public ThreadVisitor {
8576 bool has_code_activations_;
8578 explicit ActivationsFinder(Code* code)
8580 has_code_activations_(false) { }
8582 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
8583 JavaScriptFrameIterator it(isolate, top);
8587 void VisitFrames(JavaScriptFrameIterator* it) {
8588 for (; !it->done(); it->Advance()) {
8589 JavaScriptFrame* frame = it->frame();
8590 if (code_->contains(frame->pc())) has_code_activations_ = true;
8596 RUNTIME_FUNCTION(Runtime_NotifyStubFailure) {
8597 HandleScope scope(isolate);
8598 DCHECK(args.length() == 0);
8599 Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate);
8600 DCHECK(AllowHeapAllocation::IsAllowed());
8602 return isolate->heap()->undefined_value();
8606 RUNTIME_FUNCTION(Runtime_NotifyDeoptimized) {
8607 HandleScope scope(isolate);
8608 DCHECK(args.length() == 1);
8609 CONVERT_SMI_ARG_CHECKED(type_arg, 0);
8610 Deoptimizer::BailoutType type =
8611 static_cast<Deoptimizer::BailoutType>(type_arg);
8612 Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate);
8613 DCHECK(AllowHeapAllocation::IsAllowed());
8615 Handle<JSFunction> function = deoptimizer->function();
8616 Handle<Code> optimized_code = deoptimizer->compiled_code();
8618 DCHECK(optimized_code->kind() == Code::OPTIMIZED_FUNCTION);
8619 DCHECK(type == deoptimizer->bailout_type());
8621 // Make sure to materialize objects before causing any allocation.
8622 JavaScriptFrameIterator it(isolate);
8623 deoptimizer->MaterializeHeapObjects(&it);
8626 JavaScriptFrame* frame = it.frame();
8627 RUNTIME_ASSERT(frame->function()->IsJSFunction());
8628 DCHECK(frame->function() == *function);
8630 // Avoid doing too much work when running with --always-opt and keep
8631 // the optimized code around.
8632 if (FLAG_always_opt || type == Deoptimizer::LAZY) {
8633 return isolate->heap()->undefined_value();
8636 // Search for other activations of the same function and code.
8637 ActivationsFinder activations_finder(*optimized_code);
8638 activations_finder.VisitFrames(&it);
8639 isolate->thread_manager()->IterateArchivedThreads(&activations_finder);
8641 if (!activations_finder.has_code_activations_) {
8642 if (function->code() == *optimized_code) {
8643 if (FLAG_trace_deopt) {
8644 PrintF("[removing optimized code for: ");
8645 function->PrintName();
8648 function->ReplaceCode(function->shared()->code());
8649 // Evict optimized code for this function from the cache so that it
8650 // doesn't get used for new closures.
8651 function->shared()->EvictFromOptimizedCodeMap(*optimized_code,
8652 "notify deoptimized");
8655 // TODO(titzer): we should probably do DeoptimizeCodeList(code)
8656 // unconditionally if the code is not already marked for deoptimization.
8657 // If there is an index by shared function info, all the better.
8658 Deoptimizer::DeoptimizeFunction(*function);
8661 return isolate->heap()->undefined_value();
8665 RUNTIME_FUNCTION(Runtime_DeoptimizeFunction) {
8666 HandleScope scope(isolate);
8667 DCHECK(args.length() == 1);
8668 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8669 if (!function->IsOptimized()) return isolate->heap()->undefined_value();
8671 // TODO(turbofan): Deoptimization is not supported yet.
8672 if (function->code()->is_turbofanned() && !FLAG_turbo_deoptimization) {
8673 return isolate->heap()->undefined_value();
8676 Deoptimizer::DeoptimizeFunction(*function);
8678 return isolate->heap()->undefined_value();
8682 RUNTIME_FUNCTION(Runtime_ClearFunctionTypeFeedback) {
8683 HandleScope scope(isolate);
8684 DCHECK(args.length() == 1);
8685 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8686 function->shared()->ClearTypeFeedbackInfo();
8687 Code* unoptimized = function->shared()->code();
8688 if (unoptimized->kind() == Code::FUNCTION) {
8689 unoptimized->ClearInlineCaches();
8691 return isolate->heap()->undefined_value();
8695 RUNTIME_FUNCTION(Runtime_RunningInSimulator) {
8696 SealHandleScope shs(isolate);
8697 DCHECK(args.length() == 0);
8698 #if defined(USE_SIMULATOR)
8699 return isolate->heap()->true_value();
8701 return isolate->heap()->false_value();
8706 RUNTIME_FUNCTION(Runtime_IsConcurrentRecompilationSupported) {
8707 SealHandleScope shs(isolate);
8708 DCHECK(args.length() == 0);
8709 return isolate->heap()->ToBoolean(
8710 isolate->concurrent_recompilation_enabled());
8714 RUNTIME_FUNCTION(Runtime_OptimizeFunctionOnNextCall) {
8715 HandleScope scope(isolate);
8716 RUNTIME_ASSERT(args.length() == 1 || args.length() == 2);
8717 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8718 // The following two assertions are lifted from the DCHECKs inside
8719 // JSFunction::MarkForOptimization().
8720 RUNTIME_ASSERT(!function->shared()->is_generator());
8721 RUNTIME_ASSERT(function->shared()->allows_lazy_compilation() ||
8722 (function->code()->kind() == Code::FUNCTION &&
8723 function->code()->optimizable()));
8725 // If the function is optimized, just return.
8726 if (function->IsOptimized()) return isolate->heap()->undefined_value();
8728 function->MarkForOptimization();
8730 Code* unoptimized = function->shared()->code();
8731 if (args.length() == 2 &&
8732 unoptimized->kind() == Code::FUNCTION) {
8733 CONVERT_ARG_HANDLE_CHECKED(String, type, 1);
8734 if (type->IsOneByteEqualTo(STATIC_CHAR_VECTOR("osr")) && FLAG_use_osr) {
8735 // Start patching from the currently patched loop nesting level.
8736 DCHECK(BackEdgeTable::Verify(isolate, unoptimized));
8737 isolate->runtime_profiler()->AttemptOnStackReplacement(
8738 *function, Code::kMaxLoopNestingMarker);
8739 } else if (type->IsOneByteEqualTo(STATIC_CHAR_VECTOR("concurrent")) &&
8740 isolate->concurrent_recompilation_enabled()) {
8741 function->MarkForConcurrentOptimization();
8745 return isolate->heap()->undefined_value();
8749 RUNTIME_FUNCTION(Runtime_NeverOptimizeFunction) {
8750 HandleScope scope(isolate);
8751 DCHECK(args.length() == 1);
8752 CONVERT_ARG_CHECKED(JSFunction, function, 0);
8753 function->shared()->set_optimization_disabled(true);
8754 return isolate->heap()->undefined_value();
8758 RUNTIME_FUNCTION(Runtime_GetOptimizationStatus) {
8759 HandleScope scope(isolate);
8760 RUNTIME_ASSERT(args.length() == 1 || args.length() == 2);
8761 if (!isolate->use_crankshaft()) {
8762 return Smi::FromInt(4); // 4 == "never".
8764 bool sync_with_compiler_thread = true;
8765 if (args.length() == 2) {
8766 CONVERT_ARG_HANDLE_CHECKED(String, sync, 1);
8767 if (sync->IsOneByteEqualTo(STATIC_CHAR_VECTOR("no sync"))) {
8768 sync_with_compiler_thread = false;
8771 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8772 if (isolate->concurrent_recompilation_enabled() &&
8773 sync_with_compiler_thread) {
8774 while (function->IsInOptimizationQueue()) {
8775 isolate->optimizing_compiler_thread()->InstallOptimizedFunctions();
8776 base::OS::Sleep(50);
8779 if (FLAG_always_opt) {
8780 // We may have always opt, but that is more best-effort than a real
8781 // promise, so we still say "no" if it is not optimized.
8782 return function->IsOptimized() ? Smi::FromInt(3) // 3 == "always".
8783 : Smi::FromInt(2); // 2 == "no".
8785 if (FLAG_deopt_every_n_times) {
8786 return Smi::FromInt(6); // 6 == "maybe deopted".
8788 if (function->IsOptimized() && function->code()->is_turbofanned()) {
8789 return Smi::FromInt(7); // 7 == "TurboFan compiler".
8791 return function->IsOptimized() ? Smi::FromInt(1) // 1 == "yes".
8792 : Smi::FromInt(2); // 2 == "no".
8796 RUNTIME_FUNCTION(Runtime_UnblockConcurrentRecompilation) {
8797 DCHECK(args.length() == 0);
8798 RUNTIME_ASSERT(FLAG_block_concurrent_recompilation);
8799 RUNTIME_ASSERT(isolate->concurrent_recompilation_enabled());
8800 isolate->optimizing_compiler_thread()->Unblock();
8801 return isolate->heap()->undefined_value();
8805 RUNTIME_FUNCTION(Runtime_GetOptimizationCount) {
8806 HandleScope scope(isolate);
8807 DCHECK(args.length() == 1);
8808 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8809 return Smi::FromInt(function->shared()->opt_count());
8813 static bool IsSuitableForOnStackReplacement(Isolate* isolate,
8814 Handle<JSFunction> function,
8815 Handle<Code> current_code) {
8816 // Keep track of whether we've succeeded in optimizing.
8817 if (!isolate->use_crankshaft() || !current_code->optimizable()) return false;
8818 // If we are trying to do OSR when there are already optimized
8819 // activations of the function, it means (a) the function is directly or
8820 // indirectly recursive and (b) an optimized invocation has been
8821 // deoptimized so that we are currently in an unoptimized activation.
8822 // Check for optimized activations of this function.
8823 for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) {
8824 JavaScriptFrame* frame = it.frame();
8825 if (frame->is_optimized() && frame->function() == *function) return false;
8832 RUNTIME_FUNCTION(Runtime_CompileForOnStackReplacement) {
8833 HandleScope scope(isolate);
8834 DCHECK(args.length() == 1);
8835 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8836 Handle<Code> caller_code(function->shared()->code());
8838 // We're not prepared to handle a function with arguments object.
8839 DCHECK(!function->shared()->uses_arguments());
8841 RUNTIME_ASSERT(FLAG_use_osr);
8843 // Passing the PC in the javascript frame from the caller directly is
8844 // not GC safe, so we walk the stack to get it.
8845 JavaScriptFrameIterator it(isolate);
8846 JavaScriptFrame* frame = it.frame();
8847 if (!caller_code->contains(frame->pc())) {
8848 // Code on the stack may not be the code object referenced by the shared
8849 // function info. It may have been replaced to include deoptimization data.
8850 caller_code = Handle<Code>(frame->LookupCode());
8853 uint32_t pc_offset = static_cast<uint32_t>(
8854 frame->pc() - caller_code->instruction_start());
8857 DCHECK_EQ(frame->function(), *function);
8858 DCHECK_EQ(frame->LookupCode(), *caller_code);
8859 DCHECK(caller_code->contains(frame->pc()));
8863 BailoutId ast_id = caller_code->TranslatePcOffsetToAstId(pc_offset);
8864 DCHECK(!ast_id.IsNone());
8866 Compiler::ConcurrencyMode mode =
8867 isolate->concurrent_osr_enabled() &&
8868 (function->shared()->ast_node_count() > 512) ? Compiler::CONCURRENT
8869 : Compiler::NOT_CONCURRENT;
8870 Handle<Code> result = Handle<Code>::null();
8872 OptimizedCompileJob* job = NULL;
8873 if (mode == Compiler::CONCURRENT) {
8874 // Gate the OSR entry with a stack check.
8875 BackEdgeTable::AddStackCheck(caller_code, pc_offset);
8876 // Poll already queued compilation jobs.
8877 OptimizingCompilerThread* thread = isolate->optimizing_compiler_thread();
8878 if (thread->IsQueuedForOSR(function, ast_id)) {
8879 if (FLAG_trace_osr) {
8880 PrintF("[OSR - Still waiting for queued: ");
8881 function->PrintName();
8882 PrintF(" at AST id %d]\n", ast_id.ToInt());
8887 job = thread->FindReadyOSRCandidate(function, ast_id);
8891 if (FLAG_trace_osr) {
8892 PrintF("[OSR - Found ready: ");
8893 function->PrintName();
8894 PrintF(" at AST id %d]\n", ast_id.ToInt());
8896 result = Compiler::GetConcurrentlyOptimizedCode(job);
8897 } else if (IsSuitableForOnStackReplacement(isolate, function, caller_code)) {
8898 if (FLAG_trace_osr) {
8899 PrintF("[OSR - Compiling: ");
8900 function->PrintName();
8901 PrintF(" at AST id %d]\n", ast_id.ToInt());
8903 MaybeHandle<Code> maybe_result = Compiler::GetOptimizedCode(
8904 function, caller_code, mode, ast_id);
8905 if (maybe_result.ToHandle(&result) &&
8906 result.is_identical_to(isolate->builtins()->InOptimizationQueue())) {
8907 // Optimization is queued. Return to check later.
8912 // Revert the patched back edge table, regardless of whether OSR succeeds.
8913 BackEdgeTable::Revert(isolate, *caller_code);
8915 // Check whether we ended up with usable optimized code.
8916 if (!result.is_null() && result->kind() == Code::OPTIMIZED_FUNCTION) {
8917 DeoptimizationInputData* data =
8918 DeoptimizationInputData::cast(result->deoptimization_data());
8920 if (data->OsrPcOffset()->value() >= 0) {
8921 DCHECK(BailoutId(data->OsrAstId()->value()) == ast_id);
8922 if (FLAG_trace_osr) {
8923 PrintF("[OSR - Entry at AST id %d, offset %d in optimized code]\n",
8924 ast_id.ToInt(), data->OsrPcOffset()->value());
8926 // TODO(titzer): this is a massive hack to make the deopt counts
8927 // match. Fix heuristics for reenabling optimizations!
8928 function->shared()->increment_deopt_count();
8930 // TODO(titzer): Do not install code into the function.
8931 function->ReplaceCode(*result);
8937 if (FLAG_trace_osr) {
8938 PrintF("[OSR - Failed: ");
8939 function->PrintName();
8940 PrintF(" at AST id %d]\n", ast_id.ToInt());
8943 if (!function->IsOptimized()) {
8944 function->ReplaceCode(function->shared()->code());
8950 RUNTIME_FUNCTION(Runtime_SetAllocationTimeout) {
8951 SealHandleScope shs(isolate);
8952 DCHECK(args.length() == 2 || args.length() == 3);
8954 CONVERT_SMI_ARG_CHECKED(interval, 0);
8955 CONVERT_SMI_ARG_CHECKED(timeout, 1);
8956 isolate->heap()->set_allocation_timeout(timeout);
8957 FLAG_gc_interval = interval;
8958 if (args.length() == 3) {
8959 // Enable/disable inline allocation if requested.
8960 CONVERT_BOOLEAN_ARG_CHECKED(inline_allocation, 2);
8961 if (inline_allocation) {
8962 isolate->heap()->EnableInlineAllocation();
8964 isolate->heap()->DisableInlineAllocation();
8968 return isolate->heap()->undefined_value();
8972 RUNTIME_FUNCTION(Runtime_CheckIsBootstrapping) {
8973 SealHandleScope shs(isolate);
8974 DCHECK(args.length() == 0);
8975 RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
8976 return isolate->heap()->undefined_value();
8980 RUNTIME_FUNCTION(Runtime_GetRootNaN) {
8981 SealHandleScope shs(isolate);
8982 DCHECK(args.length() == 0);
8983 RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
8984 return isolate->heap()->nan_value();
8988 RUNTIME_FUNCTION(Runtime_Call) {
8989 HandleScope scope(isolate);
8990 DCHECK(args.length() >= 2);
8991 int argc = args.length() - 2;
8992 CONVERT_ARG_CHECKED(JSReceiver, fun, argc + 1);
8993 Object* receiver = args[0];
8995 // If there are too many arguments, allocate argv via malloc.
8996 const int argv_small_size = 10;
8997 Handle<Object> argv_small_buffer[argv_small_size];
8998 SmartArrayPointer<Handle<Object> > argv_large_buffer;
8999 Handle<Object>* argv = argv_small_buffer;
9000 if (argc > argv_small_size) {
9001 argv = new Handle<Object>[argc];
9002 if (argv == NULL) return isolate->StackOverflow();
9003 argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv);
9006 for (int i = 0; i < argc; ++i) {
9007 argv[i] = Handle<Object>(args[1 + i], isolate);
9010 Handle<JSReceiver> hfun(fun);
9011 Handle<Object> hreceiver(receiver, isolate);
9012 Handle<Object> result;
9013 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9015 Execution::Call(isolate, hfun, hreceiver, argc, argv, true));
9020 RUNTIME_FUNCTION(Runtime_Apply) {
9021 HandleScope scope(isolate);
9022 DCHECK(args.length() == 5);
9023 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, fun, 0);
9024 CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 1);
9025 CONVERT_ARG_HANDLE_CHECKED(JSObject, arguments, 2);
9026 CONVERT_INT32_ARG_CHECKED(offset, 3);
9027 CONVERT_INT32_ARG_CHECKED(argc, 4);
9028 RUNTIME_ASSERT(offset >= 0);
9029 // Loose upper bound to allow fuzzing. We'll most likely run out of
9030 // stack space before hitting this limit.
9031 static int kMaxArgc = 1000000;
9032 RUNTIME_ASSERT(argc >= 0 && argc <= kMaxArgc);
9034 // If there are too many arguments, allocate argv via malloc.
9035 const int argv_small_size = 10;
9036 Handle<Object> argv_small_buffer[argv_small_size];
9037 SmartArrayPointer<Handle<Object> > argv_large_buffer;
9038 Handle<Object>* argv = argv_small_buffer;
9039 if (argc > argv_small_size) {
9040 argv = new Handle<Object>[argc];
9041 if (argv == NULL) return isolate->StackOverflow();
9042 argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv);
9045 for (int i = 0; i < argc; ++i) {
9046 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9048 Object::GetElement(isolate, arguments, offset + i));
9051 Handle<Object> result;
9052 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9054 Execution::Call(isolate, fun, receiver, argc, argv, true));
9059 RUNTIME_FUNCTION(Runtime_GetFunctionDelegate) {
9060 HandleScope scope(isolate);
9061 DCHECK(args.length() == 1);
9062 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
9063 RUNTIME_ASSERT(!object->IsJSFunction());
9064 return *Execution::GetFunctionDelegate(isolate, object);
9068 RUNTIME_FUNCTION(Runtime_GetConstructorDelegate) {
9069 HandleScope scope(isolate);
9070 DCHECK(args.length() == 1);
9071 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
9072 RUNTIME_ASSERT(!object->IsJSFunction());
9073 return *Execution::GetConstructorDelegate(isolate, object);
9077 RUNTIME_FUNCTION(Runtime_NewGlobalContext) {
9078 HandleScope scope(isolate);
9079 DCHECK(args.length() == 2);
9081 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
9082 CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
9083 Handle<Context> result =
9084 isolate->factory()->NewGlobalContext(function, scope_info);
9086 DCHECK(function->context() == isolate->context());
9087 DCHECK(function->context()->global_object() == result->global_object());
9088 result->global_object()->set_global_context(*result);
9093 RUNTIME_FUNCTION(Runtime_NewFunctionContext) {
9094 HandleScope scope(isolate);
9095 DCHECK(args.length() == 1);
9097 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
9099 DCHECK(function->context() == isolate->context());
9100 int length = function->shared()->scope_info()->ContextLength();
9101 return *isolate->factory()->NewFunctionContext(length, function);
9105 RUNTIME_FUNCTION(Runtime_PushWithContext) {
9106 HandleScope scope(isolate);
9107 DCHECK(args.length() == 2);
9108 Handle<JSReceiver> extension_object;
9109 if (args[0]->IsJSReceiver()) {
9110 extension_object = args.at<JSReceiver>(0);
9112 // Try to convert the object to a proper JavaScript object.
9113 MaybeHandle<JSReceiver> maybe_object =
9114 Object::ToObject(isolate, args.at<Object>(0));
9115 if (!maybe_object.ToHandle(&extension_object)) {
9116 Handle<Object> handle = args.at<Object>(0);
9117 THROW_NEW_ERROR_RETURN_FAILURE(
9118 isolate, NewTypeError("with_expression", HandleVector(&handle, 1)));
9122 Handle<JSFunction> function;
9123 if (args[1]->IsSmi()) {
9124 // A smi sentinel indicates a context nested inside global code rather
9125 // than some function. There is a canonical empty function that can be
9126 // gotten from the native context.
9127 function = handle(isolate->native_context()->closure());
9129 function = args.at<JSFunction>(1);
9132 Handle<Context> current(isolate->context());
9133 Handle<Context> context = isolate->factory()->NewWithContext(
9134 function, current, extension_object);
9135 isolate->set_context(*context);
9140 RUNTIME_FUNCTION(Runtime_PushCatchContext) {
9141 HandleScope scope(isolate);
9142 DCHECK(args.length() == 3);
9143 CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
9144 CONVERT_ARG_HANDLE_CHECKED(Object, thrown_object, 1);
9145 Handle<JSFunction> function;
9146 if (args[2]->IsSmi()) {
9147 // A smi sentinel indicates a context nested inside global code rather
9148 // than some function. There is a canonical empty function that can be
9149 // gotten from the native context.
9150 function = handle(isolate->native_context()->closure());
9152 function = args.at<JSFunction>(2);
9154 Handle<Context> current(isolate->context());
9155 Handle<Context> context = isolate->factory()->NewCatchContext(
9156 function, current, name, thrown_object);
9157 isolate->set_context(*context);
9162 RUNTIME_FUNCTION(Runtime_PushBlockContext) {
9163 HandleScope scope(isolate);
9164 DCHECK(args.length() == 2);
9165 CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
9166 Handle<JSFunction> function;
9167 if (args[1]->IsSmi()) {
9168 // A smi sentinel indicates a context nested inside global code rather
9169 // than some function. There is a canonical empty function that can be
9170 // gotten from the native context.
9171 function = handle(isolate->native_context()->closure());
9173 function = args.at<JSFunction>(1);
9175 Handle<Context> current(isolate->context());
9176 Handle<Context> context = isolate->factory()->NewBlockContext(
9177 function, current, scope_info);
9178 isolate->set_context(*context);
9183 RUNTIME_FUNCTION(Runtime_IsJSModule) {
9184 SealHandleScope shs(isolate);
9185 DCHECK(args.length() == 1);
9186 CONVERT_ARG_CHECKED(Object, obj, 0);
9187 return isolate->heap()->ToBoolean(obj->IsJSModule());
9191 RUNTIME_FUNCTION(Runtime_PushModuleContext) {
9192 SealHandleScope shs(isolate);
9193 DCHECK(args.length() == 2);
9194 CONVERT_SMI_ARG_CHECKED(index, 0);
9196 if (!args[1]->IsScopeInfo()) {
9197 // Module already initialized. Find hosting context and retrieve context.
9198 Context* host = Context::cast(isolate->context())->global_context();
9199 Context* context = Context::cast(host->get(index));
9200 DCHECK(context->previous() == isolate->context());
9201 isolate->set_context(context);
9205 CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
9207 // Allocate module context.
9208 HandleScope scope(isolate);
9209 Factory* factory = isolate->factory();
9210 Handle<Context> context = factory->NewModuleContext(scope_info);
9211 Handle<JSModule> module = factory->NewJSModule(context, scope_info);
9212 context->set_module(*module);
9213 Context* previous = isolate->context();
9214 context->set_previous(previous);
9215 context->set_closure(previous->closure());
9216 context->set_global_object(previous->global_object());
9217 isolate->set_context(*context);
9219 // Find hosting scope and initialize internal variable holding module there.
9220 previous->global_context()->set(index, *context);
9226 RUNTIME_FUNCTION(Runtime_DeclareModules) {
9227 HandleScope scope(isolate);
9228 DCHECK(args.length() == 1);
9229 CONVERT_ARG_HANDLE_CHECKED(FixedArray, descriptions, 0);
9230 Context* host_context = isolate->context();
9232 for (int i = 0; i < descriptions->length(); ++i) {
9233 Handle<ModuleInfo> description(ModuleInfo::cast(descriptions->get(i)));
9234 int host_index = description->host_index();
9235 Handle<Context> context(Context::cast(host_context->get(host_index)));
9236 Handle<JSModule> module(context->module());
9238 for (int j = 0; j < description->length(); ++j) {
9239 Handle<String> name(description->name(j));
9240 VariableMode mode = description->mode(j);
9241 int index = description->index(j);
9246 case CONST_LEGACY: {
9247 PropertyAttributes attr =
9248 IsImmutableVariableMode(mode) ? FROZEN : SEALED;
9249 Handle<AccessorInfo> info =
9250 Accessors::MakeModuleExport(name, index, attr);
9251 Handle<Object> result =
9252 JSObject::SetAccessor(module, info).ToHandleChecked();
9253 DCHECK(!result->IsUndefined());
9258 Object* referenced_context = Context::cast(host_context)->get(index);
9259 Handle<JSModule> value(Context::cast(referenced_context)->module());
9260 JSObject::SetOwnPropertyIgnoreAttributes(module, name, value, FROZEN)
9267 case DYNAMIC_GLOBAL:
9273 JSObject::PreventExtensions(module).Assert();
9276 DCHECK(!isolate->has_pending_exception());
9277 return isolate->heap()->undefined_value();
9281 RUNTIME_FUNCTION(Runtime_DeleteLookupSlot) {
9282 HandleScope scope(isolate);
9283 DCHECK(args.length() == 2);
9285 CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
9286 CONVERT_ARG_HANDLE_CHECKED(String, name, 1);
9289 PropertyAttributes attributes;
9290 ContextLookupFlags flags = FOLLOW_CHAINS;
9291 BindingFlags binding_flags;
9292 Handle<Object> holder = context->Lookup(name,
9298 // If the slot was not found the result is true.
9299 if (holder.is_null()) {
9300 return isolate->heap()->true_value();
9303 // If the slot was found in a context, it should be DONT_DELETE.
9304 if (holder->IsContext()) {
9305 return isolate->heap()->false_value();
9308 // The slot was found in a JSObject, either a context extension object,
9309 // the global object, or the subject of a with. Try to delete it
9310 // (respecting DONT_DELETE).
9311 Handle<JSObject> object = Handle<JSObject>::cast(holder);
9312 Handle<Object> result;
9313 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9315 JSReceiver::DeleteProperty(object, name));
9320 // A mechanism to return a pair of Object pointers in registers (if possible).
9321 // How this is achieved is calling convention-dependent.
9322 // All currently supported x86 compiles uses calling conventions that are cdecl
9323 // variants where a 64-bit value is returned in two 32-bit registers
9324 // (edx:eax on ia32, r1:r0 on ARM).
9325 // In AMD-64 calling convention a struct of two pointers is returned in rdx:rax.
9326 // In Win64 calling convention, a struct of two pointers is returned in memory,
9327 // allocated by the caller, and passed as a pointer in a hidden first parameter.
9328 #ifdef V8_HOST_ARCH_64_BIT
9335 static inline ObjectPair MakePair(Object* x, Object* y) {
9336 ObjectPair result = {x, y};
9337 // Pointers x and y returned in rax and rdx, in AMD-x64-abi.
9338 // In Win64 they are assigned to a hidden first argument.
9341 #elif V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT
9342 // For x32 a 128-bit struct return is done as rax and rdx from the ObjectPair
9343 // are used in the full codegen and Crankshaft compiler. An alternative is
9344 // using uint64_t and modifying full codegen and Crankshaft compiler.
9353 static inline ObjectPair MakePair(Object* x, Object* y) {
9354 ObjectPair result = {x, 0, y, 0};
9355 // Pointers x and y returned in rax and rdx, in x32-abi.
9359 typedef uint64_t ObjectPair;
9360 static inline ObjectPair MakePair(Object* x, Object* y) {
9361 #if defined(V8_TARGET_LITTLE_ENDIAN)
9362 return reinterpret_cast<uint32_t>(x) |
9363 (reinterpret_cast<ObjectPair>(y) << 32);
9364 #elif defined(V8_TARGET_BIG_ENDIAN)
9365 return reinterpret_cast<uint32_t>(y) |
9366 (reinterpret_cast<ObjectPair>(x) << 32);
9368 #error Unknown endianness
9374 static Object* ComputeReceiverForNonGlobal(Isolate* isolate,
9376 DCHECK(!holder->IsGlobalObject());
9377 Context* top = isolate->context();
9378 // Get the context extension function.
9379 JSFunction* context_extension_function =
9380 top->native_context()->context_extension_function();
9381 // If the holder isn't a context extension object, we just return it
9382 // as the receiver. This allows arguments objects to be used as
9383 // receivers, but only if they are put in the context scope chain
9384 // explicitly via a with-statement.
9385 Object* constructor = holder->map()->constructor();
9386 if (constructor != context_extension_function) return holder;
9387 // Fall back to using the global object as the implicit receiver if
9388 // the property turns out to be a local variable allocated in a
9389 // context extension object - introduced via eval.
9390 return isolate->heap()->undefined_value();
9394 static ObjectPair LoadLookupSlotHelper(Arguments args, Isolate* isolate,
9396 HandleScope scope(isolate);
9397 DCHECK_EQ(2, args.length());
9399 if (!args[0]->IsContext() || !args[1]->IsString()) {
9400 return MakePair(isolate->ThrowIllegalOperation(), NULL);
9402 Handle<Context> context = args.at<Context>(0);
9403 Handle<String> name = args.at<String>(1);
9406 PropertyAttributes attributes;
9407 ContextLookupFlags flags = FOLLOW_CHAINS;
9408 BindingFlags binding_flags;
9409 Handle<Object> holder = context->Lookup(name,
9414 if (isolate->has_pending_exception()) {
9415 return MakePair(isolate->heap()->exception(), NULL);
9418 // If the index is non-negative, the slot has been found in a context.
9420 DCHECK(holder->IsContext());
9421 // If the "property" we were looking for is a local variable, the
9422 // receiver is the global object; see ECMA-262, 3rd., 10.1.6 and 10.2.3.
9423 Handle<Object> receiver = isolate->factory()->undefined_value();
9424 Object* value = Context::cast(*holder)->get(index);
9425 // Check for uninitialized bindings.
9426 switch (binding_flags) {
9427 case MUTABLE_CHECK_INITIALIZED:
9428 case IMMUTABLE_CHECK_INITIALIZED_HARMONY:
9429 if (value->IsTheHole()) {
9430 Handle<Object> error;
9431 MaybeHandle<Object> maybe_error =
9432 isolate->factory()->NewReferenceError("not_defined",
9433 HandleVector(&name, 1));
9434 if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
9435 return MakePair(isolate->heap()->exception(), NULL);
9438 case MUTABLE_IS_INITIALIZED:
9439 case IMMUTABLE_IS_INITIALIZED:
9440 case IMMUTABLE_IS_INITIALIZED_HARMONY:
9441 DCHECK(!value->IsTheHole());
9442 return MakePair(value, *receiver);
9443 case IMMUTABLE_CHECK_INITIALIZED:
9444 if (value->IsTheHole()) {
9445 DCHECK((attributes & READ_ONLY) != 0);
9446 value = isolate->heap()->undefined_value();
9448 return MakePair(value, *receiver);
9449 case MISSING_BINDING:
9451 return MakePair(NULL, NULL);
9455 // Otherwise, if the slot was found the holder is a context extension
9456 // object, subject of a with, or a global object. We read the named
9457 // property from it.
9458 if (!holder.is_null()) {
9459 Handle<JSReceiver> object = Handle<JSReceiver>::cast(holder);
9461 if (!object->IsJSProxy()) {
9462 Maybe<bool> maybe = JSReceiver::HasProperty(object, name);
9463 DCHECK(maybe.has_value);
9464 DCHECK(maybe.value);
9467 // GetProperty below can cause GC.
9468 Handle<Object> receiver_handle(
9469 object->IsGlobalObject()
9470 ? Object::cast(isolate->heap()->undefined_value())
9471 : object->IsJSProxy() ? static_cast<Object*>(*object)
9472 : ComputeReceiverForNonGlobal(isolate, JSObject::cast(*object)),
9475 // No need to unhole the value here. This is taken care of by the
9476 // GetProperty function.
9477 Handle<Object> value;
9478 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
9480 Object::GetProperty(object, name),
9481 MakePair(isolate->heap()->exception(), NULL));
9482 return MakePair(*value, *receiver_handle);
9486 // The property doesn't exist - throw exception.
9487 Handle<Object> error;
9488 MaybeHandle<Object> maybe_error = isolate->factory()->NewReferenceError(
9489 "not_defined", HandleVector(&name, 1));
9490 if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
9491 return MakePair(isolate->heap()->exception(), NULL);
9493 // The property doesn't exist - return undefined.
9494 return MakePair(isolate->heap()->undefined_value(),
9495 isolate->heap()->undefined_value());
9500 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlot) {
9501 return LoadLookupSlotHelper(args, isolate, true);
9505 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlotNoReferenceError) {
9506 return LoadLookupSlotHelper(args, isolate, false);
9510 RUNTIME_FUNCTION(Runtime_StoreLookupSlot) {
9511 HandleScope scope(isolate);
9512 DCHECK(args.length() == 4);
9514 CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
9515 CONVERT_ARG_HANDLE_CHECKED(Context, context, 1);
9516 CONVERT_ARG_HANDLE_CHECKED(String, name, 2);
9517 CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 3);
9520 PropertyAttributes attributes;
9521 ContextLookupFlags flags = FOLLOW_CHAINS;
9522 BindingFlags binding_flags;
9523 Handle<Object> holder = context->Lookup(name,
9528 // In case of JSProxy, an exception might have been thrown.
9529 if (isolate->has_pending_exception()) return isolate->heap()->exception();
9531 // The property was found in a context slot.
9533 if ((attributes & READ_ONLY) == 0) {
9534 Handle<Context>::cast(holder)->set(index, *value);
9535 } else if (strict_mode == STRICT) {
9536 // Setting read only property in strict mode.
9537 THROW_NEW_ERROR_RETURN_FAILURE(
9539 NewTypeError("strict_cannot_assign", HandleVector(&name, 1)));
9544 // Slow case: The property is not in a context slot. It is either in a
9545 // context extension object, a property of the subject of a with, or a
9546 // property of the global object.
9547 Handle<JSReceiver> object;
9548 if (attributes != ABSENT) {
9549 // The property exists on the holder.
9550 object = Handle<JSReceiver>::cast(holder);
9551 } else if (strict_mode == STRICT) {
9552 // If absent in strict mode: throw.
9553 THROW_NEW_ERROR_RETURN_FAILURE(
9554 isolate, NewReferenceError("not_defined", HandleVector(&name, 1)));
9556 // If absent in sloppy mode: add the property to the global object.
9557 object = Handle<JSReceiver>(context->global_object());
9560 RETURN_FAILURE_ON_EXCEPTION(
9561 isolate, Object::SetProperty(object, name, value, strict_mode));
9567 RUNTIME_FUNCTION(Runtime_Throw) {
9568 HandleScope scope(isolate);
9569 DCHECK(args.length() == 1);
9571 return isolate->Throw(args[0]);
9575 RUNTIME_FUNCTION(Runtime_ReThrow) {
9576 HandleScope scope(isolate);
9577 DCHECK(args.length() == 1);
9579 return isolate->ReThrow(args[0]);
9583 RUNTIME_FUNCTION(Runtime_PromoteScheduledException) {
9584 SealHandleScope shs(isolate);
9585 DCHECK(args.length() == 0);
9586 return isolate->PromoteScheduledException();
9590 RUNTIME_FUNCTION(Runtime_ThrowReferenceError) {
9591 HandleScope scope(isolate);
9592 DCHECK(args.length() == 1);
9593 CONVERT_ARG_HANDLE_CHECKED(Object, name, 0);
9594 THROW_NEW_ERROR_RETURN_FAILURE(
9595 isolate, NewReferenceError("not_defined", HandleVector(&name, 1)));
9599 RUNTIME_FUNCTION(Runtime_ThrowNonMethodError) {
9600 HandleScope scope(isolate);
9601 DCHECK(args.length() == 0);
9602 THROW_NEW_ERROR_RETURN_FAILURE(
9603 isolate, NewReferenceError("non_method", HandleVector<Object>(NULL, 0)));
9607 RUNTIME_FUNCTION(Runtime_ThrowUnsupportedSuperError) {
9608 HandleScope scope(isolate);
9609 DCHECK(args.length() == 0);
9610 THROW_NEW_ERROR_RETURN_FAILURE(
9612 NewReferenceError("unsupported_super", HandleVector<Object>(NULL, 0)));
9616 RUNTIME_FUNCTION(Runtime_ThrowNotDateError) {
9617 HandleScope scope(isolate);
9618 DCHECK(args.length() == 0);
9619 THROW_NEW_ERROR_RETURN_FAILURE(
9620 isolate, NewTypeError("not_date_object", HandleVector<Object>(NULL, 0)));
9624 RUNTIME_FUNCTION(Runtime_StackGuard) {
9625 SealHandleScope shs(isolate);
9626 DCHECK(args.length() == 0);
9628 // First check if this is a real stack overflow.
9629 StackLimitCheck check(isolate);
9630 if (check.JsHasOverflowed()) {
9631 return isolate->StackOverflow();
9634 return isolate->stack_guard()->HandleInterrupts();
9638 RUNTIME_FUNCTION(Runtime_TryInstallOptimizedCode) {
9639 HandleScope scope(isolate);
9640 DCHECK(args.length() == 1);
9641 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
9643 // First check if this is a real stack overflow.
9644 StackLimitCheck check(isolate);
9645 if (check.JsHasOverflowed()) {
9646 SealHandleScope shs(isolate);
9647 return isolate->StackOverflow();
9650 isolate->optimizing_compiler_thread()->InstallOptimizedFunctions();
9651 return (function->IsOptimized()) ? function->code()
9652 : function->shared()->code();
9656 RUNTIME_FUNCTION(Runtime_Interrupt) {
9657 SealHandleScope shs(isolate);
9658 DCHECK(args.length() == 0);
9659 return isolate->stack_guard()->HandleInterrupts();
9663 static int StackSize(Isolate* isolate) {
9665 for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) n++;
9670 static void PrintTransition(Isolate* isolate, Object* result) {
9672 { const int nmax = 80;
9673 int n = StackSize(isolate);
9675 PrintF("%4d:%*s", n, n, "");
9677 PrintF("%4d:%*s", n, nmax, "...");
9680 if (result == NULL) {
9681 JavaScriptFrame::PrintTop(isolate, stdout, true, false);
9686 result->ShortPrint();
9692 RUNTIME_FUNCTION(Runtime_TraceEnter) {
9693 SealHandleScope shs(isolate);
9694 DCHECK(args.length() == 0);
9695 PrintTransition(isolate, NULL);
9696 return isolate->heap()->undefined_value();
9700 RUNTIME_FUNCTION(Runtime_TraceExit) {
9701 SealHandleScope shs(isolate);
9702 DCHECK(args.length() == 1);
9703 CONVERT_ARG_CHECKED(Object, obj, 0);
9704 PrintTransition(isolate, obj);
9705 return obj; // return TOS
9709 RUNTIME_FUNCTION(Runtime_DebugPrint) {
9710 SealHandleScope shs(isolate);
9711 DCHECK(args.length() == 1);
9713 OFStream os(stdout);
9715 if (args[0]->IsString()) {
9716 // If we have a string, assume it's a code "marker"
9717 // and print some interesting cpu debugging info.
9718 JavaScriptFrameIterator it(isolate);
9719 JavaScriptFrame* frame = it.frame();
9720 os << "fp = " << frame->fp() << ", sp = " << frame->sp()
9721 << ", caller_sp = " << frame->caller_sp() << ": ";
9723 os << "DebugPrint: ";
9726 if (args[0]->IsHeapObject()) {
9728 HeapObject::cast(args[0])->map()->Print(os);
9731 // ShortPrint is available in release mode. Print is not.
9732 os << Brief(args[0]);
9736 return args[0]; // return TOS
9740 RUNTIME_FUNCTION(Runtime_DebugTrace) {
9741 SealHandleScope shs(isolate);
9742 DCHECK(args.length() == 0);
9743 isolate->PrintStack(stdout);
9744 return isolate->heap()->undefined_value();
9748 RUNTIME_FUNCTION(Runtime_DateCurrentTime) {
9749 HandleScope scope(isolate);
9750 DCHECK(args.length() == 0);
9751 if (FLAG_log_timer_events) LOG(isolate, CurrentTimeEvent());
9753 // According to ECMA-262, section 15.9.1, page 117, the precision of
9754 // the number in a Date object representing a particular instant in
9755 // time is milliseconds. Therefore, we floor the result of getting
9758 if (FLAG_verify_predictable) {
9759 millis = 1388534400000.0; // Jan 1 2014 00:00:00 GMT+0000
9760 millis += Floor(isolate->heap()->synthetic_time());
9762 millis = Floor(base::OS::TimeCurrentMillis());
9764 return *isolate->factory()->NewNumber(millis);
9768 RUNTIME_FUNCTION(Runtime_DateParseString) {
9769 HandleScope scope(isolate);
9770 DCHECK(args.length() == 2);
9771 CONVERT_ARG_HANDLE_CHECKED(String, str, 0);
9772 CONVERT_ARG_HANDLE_CHECKED(JSArray, output, 1);
9774 RUNTIME_ASSERT(output->HasFastElements());
9775 JSObject::EnsureCanContainHeapObjectElements(output);
9776 RUNTIME_ASSERT(output->HasFastObjectElements());
9777 Handle<FixedArray> output_array(FixedArray::cast(output->elements()));
9778 RUNTIME_ASSERT(output_array->length() >= DateParser::OUTPUT_SIZE);
9780 str = String::Flatten(str);
9781 DisallowHeapAllocation no_gc;
9784 String::FlatContent str_content = str->GetFlatContent();
9785 if (str_content.IsOneByte()) {
9786 result = DateParser::Parse(str_content.ToOneByteVector(),
9788 isolate->unicode_cache());
9790 DCHECK(str_content.IsTwoByte());
9791 result = DateParser::Parse(str_content.ToUC16Vector(),
9793 isolate->unicode_cache());
9799 return isolate->heap()->null_value();
9804 RUNTIME_FUNCTION(Runtime_DateLocalTimezone) {
9805 HandleScope scope(isolate);
9806 DCHECK(args.length() == 1);
9808 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
9809 RUNTIME_ASSERT(x >= -DateCache::kMaxTimeBeforeUTCInMs &&
9810 x <= DateCache::kMaxTimeBeforeUTCInMs);
9812 isolate->date_cache()->LocalTimezone(static_cast<int64_t>(x));
9813 Handle<String> result = isolate->factory()->NewStringFromUtf8(
9814 CStrVector(zone)).ToHandleChecked();
9819 RUNTIME_FUNCTION(Runtime_DateToUTC) {
9820 HandleScope scope(isolate);
9821 DCHECK(args.length() == 1);
9823 CONVERT_DOUBLE_ARG_CHECKED(x, 0);
9824 RUNTIME_ASSERT(x >= -DateCache::kMaxTimeBeforeUTCInMs &&
9825 x <= DateCache::kMaxTimeBeforeUTCInMs);
9826 int64_t time = isolate->date_cache()->ToUTC(static_cast<int64_t>(x));
9828 return *isolate->factory()->NewNumber(static_cast<double>(time));
9832 RUNTIME_FUNCTION(Runtime_DateCacheVersion) {
9833 HandleScope hs(isolate);
9834 DCHECK(args.length() == 0);
9835 if (!isolate->eternal_handles()->Exists(EternalHandles::DATE_CACHE_VERSION)) {
9836 Handle<FixedArray> date_cache_version =
9837 isolate->factory()->NewFixedArray(1, TENURED);
9838 date_cache_version->set(0, Smi::FromInt(0));
9839 isolate->eternal_handles()->CreateSingleton(
9840 isolate, *date_cache_version, EternalHandles::DATE_CACHE_VERSION);
9842 Handle<FixedArray> date_cache_version =
9843 Handle<FixedArray>::cast(isolate->eternal_handles()->GetSingleton(
9844 EternalHandles::DATE_CACHE_VERSION));
9845 // Return result as a JS array.
9846 Handle<JSObject> result =
9847 isolate->factory()->NewJSObject(isolate->array_function());
9848 JSArray::SetContent(Handle<JSArray>::cast(result), date_cache_version);
9853 RUNTIME_FUNCTION(Runtime_GlobalProxy) {
9854 SealHandleScope shs(isolate);
9855 DCHECK(args.length() == 1);
9856 CONVERT_ARG_CHECKED(Object, global, 0);
9857 if (!global->IsJSGlobalObject()) return isolate->heap()->null_value();
9858 return JSGlobalObject::cast(global)->global_proxy();
9862 RUNTIME_FUNCTION(Runtime_IsAttachedGlobal) {
9863 SealHandleScope shs(isolate);
9864 DCHECK(args.length() == 1);
9865 CONVERT_ARG_CHECKED(Object, global, 0);
9866 if (!global->IsJSGlobalObject()) return isolate->heap()->false_value();
9867 return isolate->heap()->ToBoolean(
9868 !JSGlobalObject::cast(global)->IsDetached());
9872 RUNTIME_FUNCTION(Runtime_ParseJson) {
9873 HandleScope scope(isolate);
9874 DCHECK(args.length() == 1);
9875 CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
9877 source = String::Flatten(source);
9878 // Optimized fast case where we only have Latin1 characters.
9879 Handle<Object> result;
9880 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9882 source->IsSeqOneByteString() ? JsonParser<true>::Parse(source)
9883 : JsonParser<false>::Parse(source));
9888 bool CodeGenerationFromStringsAllowed(Isolate* isolate,
9889 Handle<Context> context) {
9890 DCHECK(context->allow_code_gen_from_strings()->IsFalse());
9891 // Check with callback if set.
9892 AllowCodeGenerationFromStringsCallback callback =
9893 isolate->allow_code_gen_callback();
9894 if (callback == NULL) {
9895 // No callback set and code generation disallowed.
9898 // Callback set. Let it decide if code generation is allowed.
9899 VMState<EXTERNAL> state(isolate);
9900 return callback(v8::Utils::ToLocal(context));
9905 RUNTIME_FUNCTION(Runtime_CompileString) {
9906 HandleScope scope(isolate);
9907 DCHECK(args.length() == 2);
9908 CONVERT_ARG_HANDLE_CHECKED(String, source, 0);
9909 CONVERT_BOOLEAN_ARG_CHECKED(function_literal_only, 1);
9911 // Extract native context.
9912 Handle<Context> context(isolate->native_context());
9914 // Check if native context allows code generation from
9915 // strings. Throw an exception if it doesn't.
9916 if (context->allow_code_gen_from_strings()->IsFalse() &&
9917 !CodeGenerationFromStringsAllowed(isolate, context)) {
9918 Handle<Object> error_message =
9919 context->ErrorMessageForCodeGenerationFromStrings();
9920 THROW_NEW_ERROR_RETURN_FAILURE(
9921 isolate, NewEvalError("code_gen_from_strings",
9922 HandleVector<Object>(&error_message, 1)));
9925 // Compile source string in the native context.
9926 ParseRestriction restriction = function_literal_only
9927 ? ONLY_SINGLE_FUNCTION_LITERAL : NO_PARSE_RESTRICTION;
9928 Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate);
9929 Handle<JSFunction> fun;
9930 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
9932 Compiler::GetFunctionFromEval(
9934 context, SLOPPY, restriction, RelocInfo::kNoPosition));
9939 static ObjectPair CompileGlobalEval(Isolate* isolate,
9940 Handle<String> source,
9941 Handle<SharedFunctionInfo> outer_info,
9942 Handle<Object> receiver,
9943 StrictMode strict_mode,
9944 int scope_position) {
9945 Handle<Context> context = Handle<Context>(isolate->context());
9946 Handle<Context> native_context = Handle<Context>(context->native_context());
9948 // Check if native context allows code generation from
9949 // strings. Throw an exception if it doesn't.
9950 if (native_context->allow_code_gen_from_strings()->IsFalse() &&
9951 !CodeGenerationFromStringsAllowed(isolate, native_context)) {
9952 Handle<Object> error_message =
9953 native_context->ErrorMessageForCodeGenerationFromStrings();
9954 Handle<Object> error;
9955 MaybeHandle<Object> maybe_error = isolate->factory()->NewEvalError(
9956 "code_gen_from_strings", HandleVector<Object>(&error_message, 1));
9957 if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
9958 return MakePair(isolate->heap()->exception(), NULL);
9961 // Deal with a normal eval call with a string argument. Compile it
9962 // and return the compiled function bound in the local context.
9963 static const ParseRestriction restriction = NO_PARSE_RESTRICTION;
9964 Handle<JSFunction> compiled;
9965 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
9967 Compiler::GetFunctionFromEval(
9969 context, strict_mode, restriction, scope_position),
9970 MakePair(isolate->heap()->exception(), NULL));
9971 return MakePair(*compiled, *receiver);
9975 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ResolvePossiblyDirectEval) {
9976 HandleScope scope(isolate);
9977 DCHECK(args.length() == 6);
9979 Handle<Object> callee = args.at<Object>(0);
9981 // If "eval" didn't refer to the original GlobalEval, it's not a
9982 // direct call to eval.
9983 // (And even if it is, but the first argument isn't a string, just let
9984 // execution default to an indirect call to eval, which will also return
9985 // the first argument without doing anything).
9986 if (*callee != isolate->native_context()->global_eval_fun() ||
9987 !args[1]->IsString()) {
9988 return MakePair(*callee, isolate->heap()->undefined_value());
9991 DCHECK(args[4]->IsSmi());
9992 DCHECK(args.smi_at(4) == SLOPPY || args.smi_at(4) == STRICT);
9993 StrictMode strict_mode = static_cast<StrictMode>(args.smi_at(4));
9994 DCHECK(args[5]->IsSmi());
9995 Handle<SharedFunctionInfo> outer_info(args.at<JSFunction>(2)->shared(),
9997 return CompileGlobalEval(isolate,
10000 args.at<Object>(3),
10006 RUNTIME_FUNCTION(Runtime_AllocateInNewSpace) {
10007 HandleScope scope(isolate);
10008 DCHECK(args.length() == 1);
10009 CONVERT_SMI_ARG_CHECKED(size, 0);
10010 RUNTIME_ASSERT(IsAligned(size, kPointerSize));
10011 RUNTIME_ASSERT(size > 0);
10012 RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize);
10013 return *isolate->factory()->NewFillerObject(size, false, NEW_SPACE);
10017 RUNTIME_FUNCTION(Runtime_AllocateInTargetSpace) {
10018 HandleScope scope(isolate);
10019 DCHECK(args.length() == 2);
10020 CONVERT_SMI_ARG_CHECKED(size, 0);
10021 CONVERT_SMI_ARG_CHECKED(flags, 1);
10022 RUNTIME_ASSERT(IsAligned(size, kPointerSize));
10023 RUNTIME_ASSERT(size > 0);
10024 RUNTIME_ASSERT(size <= Page::kMaxRegularHeapObjectSize);
10025 bool double_align = AllocateDoubleAlignFlag::decode(flags);
10026 AllocationSpace space = AllocateTargetSpace::decode(flags);
10027 return *isolate->factory()->NewFillerObject(size, double_align, space);
10031 // Push an object unto an array of objects if it is not already in the
10032 // array. Returns true if the element was pushed on the stack and
10033 // false otherwise.
10034 RUNTIME_FUNCTION(Runtime_PushIfAbsent) {
10035 HandleScope scope(isolate);
10036 DCHECK(args.length() == 2);
10037 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
10038 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, element, 1);
10039 RUNTIME_ASSERT(array->HasFastSmiOrObjectElements());
10040 int length = Smi::cast(array->length())->value();
10041 FixedArray* elements = FixedArray::cast(array->elements());
10042 for (int i = 0; i < length; i++) {
10043 if (elements->get(i) == *element) return isolate->heap()->false_value();
10046 // Strict not needed. Used for cycle detection in Array join implementation.
10047 RETURN_FAILURE_ON_EXCEPTION(
10049 JSObject::SetFastElement(array, length, element, SLOPPY, true));
10050 return isolate->heap()->true_value();
10055 * A simple visitor visits every element of Array's.
10056 * The backend storage can be a fixed array for fast elements case,
10057 * or a dictionary for sparse array. Since Dictionary is a subtype
10058 * of FixedArray, the class can be used by both fast and slow cases.
10059 * The second parameter of the constructor, fast_elements, specifies
10060 * whether the storage is a FixedArray or Dictionary.
10062 * An index limit is used to deal with the situation that a result array
10063 * length overflows 32-bit non-negative integer.
10065 class ArrayConcatVisitor {
10067 ArrayConcatVisitor(Isolate* isolate,
10068 Handle<FixedArray> storage,
10069 bool fast_elements) :
10071 storage_(Handle<FixedArray>::cast(
10072 isolate->global_handles()->Create(*storage))),
10074 fast_elements_(fast_elements),
10075 exceeds_array_limit_(false) { }
10077 ~ArrayConcatVisitor() {
10081 void visit(uint32_t i, Handle<Object> elm) {
10082 if (i > JSObject::kMaxElementCount - index_offset_) {
10083 exceeds_array_limit_ = true;
10086 uint32_t index = index_offset_ + i;
10088 if (fast_elements_) {
10089 if (index < static_cast<uint32_t>(storage_->length())) {
10090 storage_->set(index, *elm);
10093 // Our initial estimate of length was foiled, possibly by
10094 // getters on the arrays increasing the length of later arrays
10095 // during iteration.
10096 // This shouldn't happen in anything but pathological cases.
10097 SetDictionaryMode();
10098 // Fall-through to dictionary mode.
10100 DCHECK(!fast_elements_);
10101 Handle<SeededNumberDictionary> dict(
10102 SeededNumberDictionary::cast(*storage_));
10103 Handle<SeededNumberDictionary> result =
10104 SeededNumberDictionary::AtNumberPut(dict, index, elm);
10105 if (!result.is_identical_to(dict)) {
10106 // Dictionary needed to grow.
10108 set_storage(*result);
10112 void increase_index_offset(uint32_t delta) {
10113 if (JSObject::kMaxElementCount - index_offset_ < delta) {
10114 index_offset_ = JSObject::kMaxElementCount;
10116 index_offset_ += delta;
10118 // If the initial length estimate was off (see special case in visit()),
10119 // but the array blowing the limit didn't contain elements beyond the
10120 // provided-for index range, go to dictionary mode now.
10121 if (fast_elements_ &&
10123 static_cast<uint32_t>(FixedArrayBase::cast(*storage_)->length())) {
10124 SetDictionaryMode();
10128 bool exceeds_array_limit() {
10129 return exceeds_array_limit_;
10132 Handle<JSArray> ToArray() {
10133 Handle<JSArray> array = isolate_->factory()->NewJSArray(0);
10134 Handle<Object> length =
10135 isolate_->factory()->NewNumber(static_cast<double>(index_offset_));
10136 Handle<Map> map = JSObject::GetElementsTransitionMap(
10138 fast_elements_ ? FAST_HOLEY_ELEMENTS : DICTIONARY_ELEMENTS);
10139 array->set_map(*map);
10140 array->set_length(*length);
10141 array->set_elements(*storage_);
10146 // Convert storage to dictionary mode.
10147 void SetDictionaryMode() {
10148 DCHECK(fast_elements_);
10149 Handle<FixedArray> current_storage(*storage_);
10150 Handle<SeededNumberDictionary> slow_storage(
10151 SeededNumberDictionary::New(isolate_, current_storage->length()));
10152 uint32_t current_length = static_cast<uint32_t>(current_storage->length());
10153 for (uint32_t i = 0; i < current_length; i++) {
10154 HandleScope loop_scope(isolate_);
10155 Handle<Object> element(current_storage->get(i), isolate_);
10156 if (!element->IsTheHole()) {
10157 Handle<SeededNumberDictionary> new_storage =
10158 SeededNumberDictionary::AtNumberPut(slow_storage, i, element);
10159 if (!new_storage.is_identical_to(slow_storage)) {
10160 slow_storage = loop_scope.CloseAndEscape(new_storage);
10165 set_storage(*slow_storage);
10166 fast_elements_ = false;
10169 inline void clear_storage() {
10170 GlobalHandles::Destroy(Handle<Object>::cast(storage_).location());
10173 inline void set_storage(FixedArray* storage) {
10174 storage_ = Handle<FixedArray>::cast(
10175 isolate_->global_handles()->Create(storage));
10179 Handle<FixedArray> storage_; // Always a global handle.
10180 // Index after last seen index. Always less than or equal to
10181 // JSObject::kMaxElementCount.
10182 uint32_t index_offset_;
10183 bool fast_elements_ : 1;
10184 bool exceeds_array_limit_ : 1;
10188 static uint32_t EstimateElementCount(Handle<JSArray> array) {
10189 uint32_t length = static_cast<uint32_t>(array->length()->Number());
10190 int element_count = 0;
10191 switch (array->GetElementsKind()) {
10192 case FAST_SMI_ELEMENTS:
10193 case FAST_HOLEY_SMI_ELEMENTS:
10194 case FAST_ELEMENTS:
10195 case FAST_HOLEY_ELEMENTS: {
10196 // Fast elements can't have lengths that are not representable by
10197 // a 32-bit signed integer.
10198 DCHECK(static_cast<int32_t>(FixedArray::kMaxLength) >= 0);
10199 int fast_length = static_cast<int>(length);
10200 Handle<FixedArray> elements(FixedArray::cast(array->elements()));
10201 for (int i = 0; i < fast_length; i++) {
10202 if (!elements->get(i)->IsTheHole()) element_count++;
10206 case FAST_DOUBLE_ELEMENTS:
10207 case FAST_HOLEY_DOUBLE_ELEMENTS: {
10208 // Fast elements can't have lengths that are not representable by
10209 // a 32-bit signed integer.
10210 DCHECK(static_cast<int32_t>(FixedDoubleArray::kMaxLength) >= 0);
10211 int fast_length = static_cast<int>(length);
10212 if (array->elements()->IsFixedArray()) {
10213 DCHECK(FixedArray::cast(array->elements())->length() == 0);
10216 Handle<FixedDoubleArray> elements(
10217 FixedDoubleArray::cast(array->elements()));
10218 for (int i = 0; i < fast_length; i++) {
10219 if (!elements->is_the_hole(i)) element_count++;
10223 case DICTIONARY_ELEMENTS: {
10224 Handle<SeededNumberDictionary> dictionary(
10225 SeededNumberDictionary::cast(array->elements()));
10226 int capacity = dictionary->Capacity();
10227 for (int i = 0; i < capacity; i++) {
10228 Handle<Object> key(dictionary->KeyAt(i), array->GetIsolate());
10229 if (dictionary->IsKey(*key)) {
10235 case SLOPPY_ARGUMENTS_ELEMENTS:
10236 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
10237 case EXTERNAL_##TYPE##_ELEMENTS: \
10238 case TYPE##_ELEMENTS: \
10240 TYPED_ARRAYS(TYPED_ARRAY_CASE)
10241 #undef TYPED_ARRAY_CASE
10242 // External arrays are always dense.
10245 // As an estimate, we assume that the prototype doesn't contain any
10246 // inherited elements.
10247 return element_count;
10252 template<class ExternalArrayClass, class ElementType>
10253 static void IterateExternalArrayElements(Isolate* isolate,
10254 Handle<JSObject> receiver,
10255 bool elements_are_ints,
10256 bool elements_are_guaranteed_smis,
10257 ArrayConcatVisitor* visitor) {
10258 Handle<ExternalArrayClass> array(
10259 ExternalArrayClass::cast(receiver->elements()));
10260 uint32_t len = static_cast<uint32_t>(array->length());
10262 DCHECK(visitor != NULL);
10263 if (elements_are_ints) {
10264 if (elements_are_guaranteed_smis) {
10265 for (uint32_t j = 0; j < len; j++) {
10266 HandleScope loop_scope(isolate);
10267 Handle<Smi> e(Smi::FromInt(static_cast<int>(array->get_scalar(j))),
10269 visitor->visit(j, e);
10272 for (uint32_t j = 0; j < len; j++) {
10273 HandleScope loop_scope(isolate);
10274 int64_t val = static_cast<int64_t>(array->get_scalar(j));
10275 if (Smi::IsValid(static_cast<intptr_t>(val))) {
10276 Handle<Smi> e(Smi::FromInt(static_cast<int>(val)), isolate);
10277 visitor->visit(j, e);
10280 isolate->factory()->NewNumber(static_cast<ElementType>(val));
10281 visitor->visit(j, e);
10286 for (uint32_t j = 0; j < len; j++) {
10287 HandleScope loop_scope(isolate);
10288 Handle<Object> e = isolate->factory()->NewNumber(array->get_scalar(j));
10289 visitor->visit(j, e);
10295 static void IterateExternalFloat32x4ArrayElements(Isolate* isolate,
10296 Handle<JSObject> receiver,
10297 ArrayConcatVisitor* visitor) {
10298 Handle<ExternalFloat32x4Array> array(
10299 ExternalFloat32x4Array::cast(receiver->elements()));
10300 uint32_t len = static_cast<uint32_t>(array->length());
10302 DCHECK(visitor != NULL);
10303 for (uint32_t j = 0; j < len; j++) {
10304 HandleScope loop_scope(isolate);
10305 Handle<Object> e = isolate->factory()->NewFloat32x4(array->get_scalar(j));
10306 visitor->visit(j, e);
10311 static void IterateExternalFloat64x2ArrayElements(Isolate* isolate,
10312 Handle<JSObject> receiver,
10313 ArrayConcatVisitor* visitor) {
10314 Handle<ExternalFloat64x2Array> array(
10315 ExternalFloat64x2Array::cast(receiver->elements()));
10316 uint32_t len = static_cast<uint32_t>(array->length());
10318 DCHECK(visitor != NULL);
10319 for (uint32_t j = 0; j < len; j++) {
10320 HandleScope loop_scope(isolate);
10321 Handle<Object> e = isolate->factory()->NewFloat64x2(array->get_scalar(j));
10322 visitor->visit(j, e);
10327 static void IterateExternalInt32x4ArrayElements(Isolate* isolate,
10328 Handle<JSObject> receiver,
10329 ArrayConcatVisitor* visitor) {
10330 Handle<ExternalInt32x4Array> array(
10331 ExternalInt32x4Array::cast(receiver->elements()));
10332 uint32_t len = static_cast<uint32_t>(array->length());
10334 DCHECK(visitor != NULL);
10335 for (uint32_t j = 0; j < len; j++) {
10336 HandleScope loop_scope(isolate);
10337 Handle<Object> e = isolate->factory()->NewInt32x4(array->get_scalar(j));
10338 visitor->visit(j, e);
10343 // Used for sorting indices in a List<uint32_t>.
10344 static int compareUInt32(const uint32_t* ap, const uint32_t* bp) {
10347 return (a == b) ? 0 : (a < b) ? -1 : 1;
10351 static void CollectElementIndices(Handle<JSObject> object,
10353 List<uint32_t>* indices) {
10354 Isolate* isolate = object->GetIsolate();
10355 ElementsKind kind = object->GetElementsKind();
10357 case FAST_SMI_ELEMENTS:
10358 case FAST_ELEMENTS:
10359 case FAST_HOLEY_SMI_ELEMENTS:
10360 case FAST_HOLEY_ELEMENTS: {
10361 Handle<FixedArray> elements(FixedArray::cast(object->elements()));
10362 uint32_t length = static_cast<uint32_t>(elements->length());
10363 if (range < length) length = range;
10364 for (uint32_t i = 0; i < length; i++) {
10365 if (!elements->get(i)->IsTheHole()) {
10371 case FAST_HOLEY_DOUBLE_ELEMENTS:
10372 case FAST_DOUBLE_ELEMENTS: {
10373 if (object->elements()->IsFixedArray()) {
10374 DCHECK(object->elements()->length() == 0);
10377 Handle<FixedDoubleArray> elements(
10378 FixedDoubleArray::cast(object->elements()));
10379 uint32_t length = static_cast<uint32_t>(elements->length());
10380 if (range < length) length = range;
10381 for (uint32_t i = 0; i < length; i++) {
10382 if (!elements->is_the_hole(i)) {
10388 case DICTIONARY_ELEMENTS: {
10389 Handle<SeededNumberDictionary> dict(
10390 SeededNumberDictionary::cast(object->elements()));
10391 uint32_t capacity = dict->Capacity();
10392 for (uint32_t j = 0; j < capacity; j++) {
10393 HandleScope loop_scope(isolate);
10394 Handle<Object> k(dict->KeyAt(j), isolate);
10395 if (dict->IsKey(*k)) {
10396 DCHECK(k->IsNumber());
10397 uint32_t index = static_cast<uint32_t>(k->Number());
10398 if (index < range) {
10399 indices->Add(index);
10405 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
10406 case TYPE##_ELEMENTS: \
10407 case EXTERNAL_##TYPE##_ELEMENTS:
10409 TYPED_ARRAYS(TYPED_ARRAY_CASE)
10410 #undef TYPED_ARRAY_CASE
10412 uint32_t length = static_cast<uint32_t>(
10413 FixedArrayBase::cast(object->elements())->length());
10414 if (range <= length) {
10416 // We will add all indices, so we might as well clear it first
10417 // and avoid duplicates.
10420 for (uint32_t i = 0; i < length; i++) {
10423 if (length == range) return; // All indices accounted for already.
10426 case SLOPPY_ARGUMENTS_ELEMENTS: {
10427 MaybeHandle<Object> length_obj =
10428 Object::GetProperty(object, isolate->factory()->length_string());
10429 double length_num = length_obj.ToHandleChecked()->Number();
10430 uint32_t length = static_cast<uint32_t>(DoubleToInt32(length_num));
10431 ElementsAccessor* accessor = object->GetElementsAccessor();
10432 for (uint32_t i = 0; i < length; i++) {
10433 if (accessor->HasElement(object, object, i)) {
10441 PrototypeIterator iter(isolate, object);
10442 if (!iter.IsAtEnd()) {
10443 // The prototype will usually have no inherited element indices,
10444 // but we have to check.
10445 CollectElementIndices(
10446 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter)), range,
10453 * A helper function that visits elements of a JSArray in numerical
10456 * The visitor argument called for each existing element in the array
10457 * with the element index and the element's value.
10458 * Afterwards it increments the base-index of the visitor by the array
10460 * Returns false if any access threw an exception, otherwise true.
10462 static bool IterateElements(Isolate* isolate,
10463 Handle<JSArray> receiver,
10464 ArrayConcatVisitor* visitor) {
10465 uint32_t length = static_cast<uint32_t>(receiver->length()->Number());
10466 switch (receiver->GetElementsKind()) {
10467 case FAST_SMI_ELEMENTS:
10468 case FAST_ELEMENTS:
10469 case FAST_HOLEY_SMI_ELEMENTS:
10470 case FAST_HOLEY_ELEMENTS: {
10471 // Run through the elements FixedArray and use HasElement and GetElement
10472 // to check the prototype for missing elements.
10473 Handle<FixedArray> elements(FixedArray::cast(receiver->elements()));
10474 int fast_length = static_cast<int>(length);
10475 DCHECK(fast_length <= elements->length());
10476 for (int j = 0; j < fast_length; j++) {
10477 HandleScope loop_scope(isolate);
10478 Handle<Object> element_value(elements->get(j), isolate);
10479 if (!element_value->IsTheHole()) {
10480 visitor->visit(j, element_value);
10482 Maybe<bool> maybe = JSReceiver::HasElement(receiver, j);
10483 if (!maybe.has_value) return false;
10485 // Call GetElement on receiver, not its prototype, or getters won't
10486 // have the correct receiver.
10487 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
10488 isolate, element_value,
10489 Object::GetElement(isolate, receiver, j), false);
10490 visitor->visit(j, element_value);
10496 case FAST_HOLEY_DOUBLE_ELEMENTS:
10497 case FAST_DOUBLE_ELEMENTS: {
10498 // Empty array is FixedArray but not FixedDoubleArray.
10499 if (length == 0) break;
10500 // Run through the elements FixedArray and use HasElement and GetElement
10501 // to check the prototype for missing elements.
10502 if (receiver->elements()->IsFixedArray()) {
10503 DCHECK(receiver->elements()->length() == 0);
10506 Handle<FixedDoubleArray> elements(
10507 FixedDoubleArray::cast(receiver->elements()));
10508 int fast_length = static_cast<int>(length);
10509 DCHECK(fast_length <= elements->length());
10510 for (int j = 0; j < fast_length; j++) {
10511 HandleScope loop_scope(isolate);
10512 if (!elements->is_the_hole(j)) {
10513 double double_value = elements->get_scalar(j);
10514 Handle<Object> element_value =
10515 isolate->factory()->NewNumber(double_value);
10516 visitor->visit(j, element_value);
10518 Maybe<bool> maybe = JSReceiver::HasElement(receiver, j);
10519 if (!maybe.has_value) return false;
10521 // Call GetElement on receiver, not its prototype, or getters won't
10522 // have the correct receiver.
10523 Handle<Object> element_value;
10524 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
10525 isolate, element_value,
10526 Object::GetElement(isolate, receiver, j), false);
10527 visitor->visit(j, element_value);
10533 case DICTIONARY_ELEMENTS: {
10534 Handle<SeededNumberDictionary> dict(receiver->element_dictionary());
10535 List<uint32_t> indices(dict->Capacity() / 2);
10536 // Collect all indices in the object and the prototypes less
10537 // than length. This might introduce duplicates in the indices list.
10538 CollectElementIndices(receiver, length, &indices);
10539 indices.Sort(&compareUInt32);
10541 int n = indices.length();
10543 HandleScope loop_scope(isolate);
10544 uint32_t index = indices[j];
10545 Handle<Object> element;
10546 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
10548 Object::GetElement(isolate, receiver, index),
10550 visitor->visit(index, element);
10551 // Skip to next different index (i.e., omit duplicates).
10554 } while (j < n && indices[j] == index);
10558 case EXTERNAL_UINT8_CLAMPED_ELEMENTS: {
10559 Handle<ExternalUint8ClampedArray> pixels(ExternalUint8ClampedArray::cast(
10560 receiver->elements()));
10561 for (uint32_t j = 0; j < length; j++) {
10562 Handle<Smi> e(Smi::FromInt(pixels->get_scalar(j)), isolate);
10563 visitor->visit(j, e);
10567 case EXTERNAL_INT8_ELEMENTS: {
10568 IterateExternalArrayElements<ExternalInt8Array, int8_t>(
10569 isolate, receiver, true, true, visitor);
10572 case EXTERNAL_UINT8_ELEMENTS: {
10573 IterateExternalArrayElements<ExternalUint8Array, uint8_t>(
10574 isolate, receiver, true, true, visitor);
10577 case EXTERNAL_INT16_ELEMENTS: {
10578 IterateExternalArrayElements<ExternalInt16Array, int16_t>(
10579 isolate, receiver, true, true, visitor);
10582 case EXTERNAL_UINT16_ELEMENTS: {
10583 IterateExternalArrayElements<ExternalUint16Array, uint16_t>(
10584 isolate, receiver, true, true, visitor);
10587 case EXTERNAL_INT32_ELEMENTS: {
10588 IterateExternalArrayElements<ExternalInt32Array, int32_t>(
10589 isolate, receiver, true, false, visitor);
10592 case EXTERNAL_UINT32_ELEMENTS: {
10593 IterateExternalArrayElements<ExternalUint32Array, uint32_t>(
10594 isolate, receiver, true, false, visitor);
10597 case EXTERNAL_FLOAT32_ELEMENTS: {
10598 IterateExternalArrayElements<ExternalFloat32Array, float>(
10599 isolate, receiver, false, false, visitor);
10602 case EXTERNAL_FLOAT32x4_ELEMENTS: {
10603 IterateExternalFloat32x4ArrayElements(isolate, receiver, visitor);
10606 case EXTERNAL_FLOAT64x2_ELEMENTS: {
10607 IterateExternalFloat64x2ArrayElements(isolate, receiver, visitor);
10610 case EXTERNAL_INT32x4_ELEMENTS: {
10611 IterateExternalInt32x4ArrayElements(isolate, receiver, visitor);
10614 case EXTERNAL_FLOAT64_ELEMENTS: {
10615 IterateExternalArrayElements<ExternalFloat64Array, double>(
10616 isolate, receiver, false, false, visitor);
10623 visitor->increase_index_offset(length);
10629 * Array::concat implementation.
10630 * See ECMAScript 262, 15.4.4.4.
10631 * TODO(581): Fix non-compliance for very large concatenations and update to
10632 * following the ECMAScript 5 specification.
10634 RUNTIME_FUNCTION(Runtime_ArrayConcat) {
10635 HandleScope handle_scope(isolate);
10636 DCHECK(args.length() == 1);
10638 CONVERT_ARG_HANDLE_CHECKED(JSArray, arguments, 0);
10639 int argument_count = static_cast<int>(arguments->length()->Number());
10640 RUNTIME_ASSERT(arguments->HasFastObjectElements());
10641 Handle<FixedArray> elements(FixedArray::cast(arguments->elements()));
10643 // Pass 1: estimate the length and number of elements of the result.
10644 // The actual length can be larger if any of the arguments have getters
10645 // that mutate other arguments (but will otherwise be precise).
10646 // The number of elements is precise if there are no inherited elements.
10648 ElementsKind kind = FAST_SMI_ELEMENTS;
10650 uint32_t estimate_result_length = 0;
10651 uint32_t estimate_nof_elements = 0;
10652 for (int i = 0; i < argument_count; i++) {
10653 HandleScope loop_scope(isolate);
10654 Handle<Object> obj(elements->get(i), isolate);
10655 uint32_t length_estimate;
10656 uint32_t element_estimate;
10657 if (obj->IsJSArray()) {
10658 Handle<JSArray> array(Handle<JSArray>::cast(obj));
10659 length_estimate = static_cast<uint32_t>(array->length()->Number());
10660 if (length_estimate != 0) {
10661 ElementsKind array_kind =
10662 GetPackedElementsKind(array->map()->elements_kind());
10663 if (IsMoreGeneralElementsKindTransition(kind, array_kind)) {
10667 element_estimate = EstimateElementCount(array);
10669 if (obj->IsHeapObject()) {
10670 if (obj->IsNumber()) {
10671 if (IsMoreGeneralElementsKindTransition(kind, FAST_DOUBLE_ELEMENTS)) {
10672 kind = FAST_DOUBLE_ELEMENTS;
10674 } else if (IsMoreGeneralElementsKindTransition(kind, FAST_ELEMENTS)) {
10675 kind = FAST_ELEMENTS;
10678 length_estimate = 1;
10679 element_estimate = 1;
10681 // Avoid overflows by capping at kMaxElementCount.
10682 if (JSObject::kMaxElementCount - estimate_result_length <
10684 estimate_result_length = JSObject::kMaxElementCount;
10686 estimate_result_length += length_estimate;
10688 if (JSObject::kMaxElementCount - estimate_nof_elements <
10689 element_estimate) {
10690 estimate_nof_elements = JSObject::kMaxElementCount;
10692 estimate_nof_elements += element_estimate;
10696 // If estimated number of elements is more than half of length, a
10697 // fixed array (fast case) is more time and space-efficient than a
10699 bool fast_case = (estimate_nof_elements * 2) >= estimate_result_length;
10701 if (fast_case && kind == FAST_DOUBLE_ELEMENTS) {
10702 Handle<FixedArrayBase> storage =
10703 isolate->factory()->NewFixedDoubleArray(estimate_result_length);
10705 bool failure = false;
10706 if (estimate_result_length > 0) {
10707 Handle<FixedDoubleArray> double_storage =
10708 Handle<FixedDoubleArray>::cast(storage);
10709 for (int i = 0; i < argument_count; i++) {
10710 Handle<Object> obj(elements->get(i), isolate);
10711 if (obj->IsSmi()) {
10712 double_storage->set(j, Smi::cast(*obj)->value());
10714 } else if (obj->IsNumber()) {
10715 double_storage->set(j, obj->Number());
10718 JSArray* array = JSArray::cast(*obj);
10719 uint32_t length = static_cast<uint32_t>(array->length()->Number());
10720 switch (array->map()->elements_kind()) {
10721 case FAST_HOLEY_DOUBLE_ELEMENTS:
10722 case FAST_DOUBLE_ELEMENTS: {
10723 // Empty array is FixedArray but not FixedDoubleArray.
10724 if (length == 0) break;
10725 FixedDoubleArray* elements =
10726 FixedDoubleArray::cast(array->elements());
10727 for (uint32_t i = 0; i < length; i++) {
10728 if (elements->is_the_hole(i)) {
10729 // TODO(jkummerow/verwaest): We could be a bit more clever
10730 // here: Check if there are no elements/getters on the
10731 // prototype chain, and if so, allow creation of a holey
10733 // Same thing below (holey smi case).
10737 double double_value = elements->get_scalar(i);
10738 double_storage->set(j, double_value);
10743 case FAST_HOLEY_SMI_ELEMENTS:
10744 case FAST_SMI_ELEMENTS: {
10745 FixedArray* elements(
10746 FixedArray::cast(array->elements()));
10747 for (uint32_t i = 0; i < length; i++) {
10748 Object* element = elements->get(i);
10749 if (element->IsTheHole()) {
10753 int32_t int_value = Smi::cast(element)->value();
10754 double_storage->set(j, int_value);
10759 case FAST_HOLEY_ELEMENTS:
10760 case FAST_ELEMENTS:
10761 DCHECK_EQ(0, length);
10767 if (failure) break;
10771 Handle<JSArray> array = isolate->factory()->NewJSArray(0);
10772 Smi* length = Smi::FromInt(j);
10774 map = JSObject::GetElementsTransitionMap(array, kind);
10775 array->set_map(*map);
10776 array->set_length(length);
10777 array->set_elements(*storage);
10780 // In case of failure, fall through.
10783 Handle<FixedArray> storage;
10785 // The backing storage array must have non-existing elements to preserve
10786 // holes across concat operations.
10787 storage = isolate->factory()->NewFixedArrayWithHoles(
10788 estimate_result_length);
10790 // TODO(126): move 25% pre-allocation logic into Dictionary::Allocate
10791 uint32_t at_least_space_for = estimate_nof_elements +
10792 (estimate_nof_elements >> 2);
10793 storage = Handle<FixedArray>::cast(
10794 SeededNumberDictionary::New(isolate, at_least_space_for));
10797 ArrayConcatVisitor visitor(isolate, storage, fast_case);
10799 for (int i = 0; i < argument_count; i++) {
10800 Handle<Object> obj(elements->get(i), isolate);
10801 if (obj->IsJSArray()) {
10802 Handle<JSArray> array = Handle<JSArray>::cast(obj);
10803 if (!IterateElements(isolate, array, &visitor)) {
10804 return isolate->heap()->exception();
10807 visitor.visit(0, obj);
10808 visitor.increase_index_offset(1);
10812 if (visitor.exceeds_array_limit()) {
10813 THROW_NEW_ERROR_RETURN_FAILURE(
10815 NewRangeError("invalid_array_length", HandleVector<Object>(NULL, 0)));
10817 return *visitor.ToArray();
10821 // This will not allocate (flatten the string), but it may run
10822 // very slowly for very deeply nested ConsStrings. For debugging use only.
10823 RUNTIME_FUNCTION(Runtime_GlobalPrint) {
10824 SealHandleScope shs(isolate);
10825 DCHECK(args.length() == 1);
10827 CONVERT_ARG_CHECKED(String, string, 0);
10828 ConsStringIteratorOp op;
10829 StringCharacterStream stream(string, &op);
10830 while (stream.HasMore()) {
10831 uint16_t character = stream.GetNext();
10832 PrintF("%c", character);
10838 // Moves all own elements of an object, that are below a limit, to positions
10839 // starting at zero. All undefined values are placed after non-undefined values,
10840 // and are followed by non-existing element. Does not change the length
10842 // Returns the number of non-undefined elements collected.
10843 // Returns -1 if hole removal is not supported by this method.
10844 RUNTIME_FUNCTION(Runtime_RemoveArrayHoles) {
10845 HandleScope scope(isolate);
10846 DCHECK(args.length() == 2);
10847 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
10848 CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
10849 return *JSObject::PrepareElementsForSort(object, limit);
10853 // Move contents of argument 0 (an array) to argument 1 (an array)
10854 RUNTIME_FUNCTION(Runtime_MoveArrayContents) {
10855 HandleScope scope(isolate);
10856 DCHECK(args.length() == 2);
10857 CONVERT_ARG_HANDLE_CHECKED(JSArray, from, 0);
10858 CONVERT_ARG_HANDLE_CHECKED(JSArray, to, 1);
10859 JSObject::ValidateElements(from);
10860 JSObject::ValidateElements(to);
10862 Handle<FixedArrayBase> new_elements(from->elements());
10863 ElementsKind from_kind = from->GetElementsKind();
10864 Handle<Map> new_map = JSObject::GetElementsTransitionMap(to, from_kind);
10865 JSObject::SetMapAndElements(to, new_map, new_elements);
10866 to->set_length(from->length());
10868 JSObject::ResetElements(from);
10869 from->set_length(Smi::FromInt(0));
10871 JSObject::ValidateElements(to);
10876 // How many elements does this object/array have?
10877 RUNTIME_FUNCTION(Runtime_EstimateNumberOfElements) {
10878 HandleScope scope(isolate);
10879 DCHECK(args.length() == 1);
10880 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
10881 Handle<FixedArrayBase> elements(array->elements(), isolate);
10882 SealHandleScope shs(isolate);
10883 if (elements->IsDictionary()) {
10885 Handle<SeededNumberDictionary>::cast(elements)->NumberOfElements();
10886 return Smi::FromInt(result);
10888 DCHECK(array->length()->IsSmi());
10889 // For packed elements, we know the exact number of elements
10890 int length = elements->length();
10891 ElementsKind kind = array->GetElementsKind();
10892 if (IsFastPackedElementsKind(kind)) {
10893 return Smi::FromInt(length);
10895 // For holey elements, take samples from the buffer checking for holes
10896 // to generate the estimate.
10897 const int kNumberOfHoleCheckSamples = 97;
10898 int increment = (length < kNumberOfHoleCheckSamples)
10900 : static_cast<int>(length / kNumberOfHoleCheckSamples);
10901 ElementsAccessor* accessor = array->GetElementsAccessor();
10903 for (int i = 0; i < length; i += increment) {
10904 if (!accessor->HasElement(array, array, i, elements)) {
10908 int estimate = static_cast<int>((kNumberOfHoleCheckSamples - holes) /
10909 kNumberOfHoleCheckSamples * length);
10910 return Smi::FromInt(estimate);
10915 // Returns an array that tells you where in the [0, length) interval an array
10916 // might have elements. Can either return an array of keys (positive integers
10917 // or undefined) or a number representing the positive length of an interval
10918 // starting at index 0.
10919 // Intervals can span over some keys that are not in the object.
10920 RUNTIME_FUNCTION(Runtime_GetArrayKeys) {
10921 HandleScope scope(isolate);
10922 DCHECK(args.length() == 2);
10923 CONVERT_ARG_HANDLE_CHECKED(JSObject, array, 0);
10924 CONVERT_NUMBER_CHECKED(uint32_t, length, Uint32, args[1]);
10925 if (array->elements()->IsDictionary()) {
10926 Handle<FixedArray> keys = isolate->factory()->empty_fixed_array();
10927 for (PrototypeIterator iter(isolate, array,
10928 PrototypeIterator::START_AT_RECEIVER);
10929 !iter.IsAtEnd(); iter.Advance()) {
10930 if (PrototypeIterator::GetCurrent(iter)->IsJSProxy() ||
10931 JSObject::cast(*PrototypeIterator::GetCurrent(iter))
10932 ->HasIndexedInterceptor()) {
10933 // Bail out if we find a proxy or interceptor, likely not worth
10934 // collecting keys in that case.
10935 return *isolate->factory()->NewNumberFromUint(length);
10937 Handle<JSObject> current =
10938 Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
10939 Handle<FixedArray> current_keys =
10940 isolate->factory()->NewFixedArray(current->NumberOfOwnElements(NONE));
10941 current->GetOwnElementKeys(*current_keys, NONE);
10942 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
10943 isolate, keys, FixedArray::UnionOfKeys(keys, current_keys));
10945 // Erase any keys >= length.
10946 // TODO(adamk): Remove this step when the contract of %GetArrayKeys
10947 // is changed to let this happen on the JS side.
10948 for (int i = 0; i < keys->length(); i++) {
10949 if (NumberToUint32(keys->get(i)) >= length) keys->set_undefined(i);
10951 return *isolate->factory()->NewJSArrayWithElements(keys);
10953 RUNTIME_ASSERT(array->HasFastSmiOrObjectElements() ||
10954 array->HasFastDoubleElements());
10955 uint32_t actual_length = static_cast<uint32_t>(array->elements()->length());
10956 return *isolate->factory()->NewNumberFromUint(Min(actual_length, length));
10961 RUNTIME_FUNCTION(Runtime_LookupAccessor) {
10962 HandleScope scope(isolate);
10963 DCHECK(args.length() == 3);
10964 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
10965 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
10966 CONVERT_SMI_ARG_CHECKED(flag, 2);
10967 AccessorComponent component = flag == 0 ? ACCESSOR_GETTER : ACCESSOR_SETTER;
10968 if (!receiver->IsJSObject()) return isolate->heap()->undefined_value();
10969 Handle<Object> result;
10970 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
10972 JSObject::GetAccessor(Handle<JSObject>::cast(receiver), name, component));
10977 RUNTIME_FUNCTION(Runtime_DebugBreak) {
10978 SealHandleScope shs(isolate);
10979 DCHECK(args.length() == 0);
10980 isolate->debug()->HandleDebugBreak();
10981 return isolate->heap()->undefined_value();
10985 // Helper functions for wrapping and unwrapping stack frame ids.
10986 static Smi* WrapFrameId(StackFrame::Id id) {
10987 DCHECK(IsAligned(OffsetFrom(id), static_cast<intptr_t>(4)));
10988 return Smi::FromInt(id >> 2);
10992 static StackFrame::Id UnwrapFrameId(int wrapped) {
10993 return static_cast<StackFrame::Id>(wrapped << 2);
10997 // Adds a JavaScript function as a debug event listener.
10998 // args[0]: debug event listener function to set or null or undefined for
10999 // clearing the event listener function
11000 // args[1]: object supplied during callback
11001 RUNTIME_FUNCTION(Runtime_SetDebugEventListener) {
11002 SealHandleScope shs(isolate);
11003 DCHECK(args.length() == 2);
11004 RUNTIME_ASSERT(args[0]->IsJSFunction() ||
11005 args[0]->IsUndefined() ||
11006 args[0]->IsNull());
11007 CONVERT_ARG_HANDLE_CHECKED(Object, callback, 0);
11008 CONVERT_ARG_HANDLE_CHECKED(Object, data, 1);
11009 isolate->debug()->SetEventListener(callback, data);
11011 return isolate->heap()->undefined_value();
11015 RUNTIME_FUNCTION(Runtime_Break) {
11016 SealHandleScope shs(isolate);
11017 DCHECK(args.length() == 0);
11018 isolate->stack_guard()->RequestDebugBreak();
11019 return isolate->heap()->undefined_value();
11023 static Handle<Object> DebugGetProperty(LookupIterator* it,
11024 bool* has_caught = NULL) {
11025 for (; it->IsFound(); it->Next()) {
11026 switch (it->state()) {
11027 case LookupIterator::NOT_FOUND:
11028 case LookupIterator::TRANSITION:
11030 case LookupIterator::ACCESS_CHECK:
11031 // Ignore access checks.
11033 case LookupIterator::INTERCEPTOR:
11034 case LookupIterator::JSPROXY:
11035 return it->isolate()->factory()->undefined_value();
11036 case LookupIterator::ACCESSOR: {
11037 Handle<Object> accessors = it->GetAccessors();
11038 if (!accessors->IsAccessorInfo()) {
11039 return it->isolate()->factory()->undefined_value();
11041 MaybeHandle<Object> maybe_result = JSObject::GetPropertyWithAccessor(
11042 it->GetReceiver(), it->name(), it->GetHolder<JSObject>(),
11044 Handle<Object> result;
11045 if (!maybe_result.ToHandle(&result)) {
11046 result = handle(it->isolate()->pending_exception(), it->isolate());
11047 it->isolate()->clear_pending_exception();
11048 if (has_caught != NULL) *has_caught = true;
11053 case LookupIterator::DATA:
11054 return it->GetDataValue();
11058 return it->isolate()->factory()->undefined_value();
11062 // Get debugger related details for an object property, in the following format:
11063 // 0: Property value
11064 // 1: Property details
11065 // 2: Property value is exception
11066 // 3: Getter function if defined
11067 // 4: Setter function if defined
11068 // Items 2-4 are only filled if the property has either a getter or a setter.
11069 RUNTIME_FUNCTION(Runtime_DebugGetPropertyDetails) {
11070 HandleScope scope(isolate);
11072 DCHECK(args.length() == 2);
11074 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11075 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
11077 // Make sure to set the current context to the context before the debugger was
11078 // entered (if the debugger is entered). The reason for switching context here
11079 // is that for some property lookups (accessors and interceptors) callbacks
11080 // into the embedding application can occour, and the embedding application
11081 // could have the assumption that its own native context is the current
11082 // context and not some internal debugger context.
11083 SaveContext save(isolate);
11084 if (isolate->debug()->in_debug_scope()) {
11085 isolate->set_context(*isolate->debug()->debugger_entry()->GetContext());
11088 // Check if the name is trivially convertible to an index and get the element
11091 if (name->AsArrayIndex(&index)) {
11092 Handle<FixedArray> details = isolate->factory()->NewFixedArray(2);
11093 Handle<Object> element_or_char;
11094 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
11095 isolate, element_or_char,
11096 Runtime::GetElementOrCharAt(isolate, obj, index));
11097 details->set(0, *element_or_char);
11099 1, PropertyDetails(NONE, NORMAL, Representation::None()).AsSmi());
11100 return *isolate->factory()->NewJSArrayWithElements(details);
11103 LookupIterator it(obj, name, LookupIterator::HIDDEN);
11104 bool has_caught = false;
11105 Handle<Object> value = DebugGetProperty(&it, &has_caught);
11106 if (!it.IsFound()) return isolate->heap()->undefined_value();
11108 Handle<Object> maybe_pair;
11109 if (it.state() == LookupIterator::ACCESSOR) {
11110 maybe_pair = it.GetAccessors();
11113 // If the callback object is a fixed array then it contains JavaScript
11114 // getter and/or setter.
11115 bool has_js_accessors = !maybe_pair.is_null() && maybe_pair->IsAccessorPair();
11116 Handle<FixedArray> details =
11117 isolate->factory()->NewFixedArray(has_js_accessors ? 6 : 3);
11118 details->set(0, *value);
11119 // TODO(verwaest): Get rid of this random way of handling interceptors.
11120 PropertyDetails d = it.state() == LookupIterator::INTERCEPTOR
11121 ? PropertyDetails(NONE, NORMAL, 0)
11122 : it.property_details();
11123 details->set(1, d.AsSmi());
11125 2, isolate->heap()->ToBoolean(it.state() == LookupIterator::INTERCEPTOR));
11126 if (has_js_accessors) {
11127 AccessorPair* accessors = AccessorPair::cast(*maybe_pair);
11128 details->set(3, isolate->heap()->ToBoolean(has_caught));
11129 details->set(4, accessors->GetComponent(ACCESSOR_GETTER));
11130 details->set(5, accessors->GetComponent(ACCESSOR_SETTER));
11133 return *isolate->factory()->NewJSArrayWithElements(details);
11137 RUNTIME_FUNCTION(Runtime_DebugGetProperty) {
11138 HandleScope scope(isolate);
11140 DCHECK(args.length() == 2);
11142 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11143 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
11145 LookupIterator it(obj, name);
11146 return *DebugGetProperty(&it);
11150 // Return the property type calculated from the property details.
11151 // args[0]: smi with property details.
11152 RUNTIME_FUNCTION(Runtime_DebugPropertyTypeFromDetails) {
11153 SealHandleScope shs(isolate);
11154 DCHECK(args.length() == 1);
11155 CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
11156 return Smi::FromInt(static_cast<int>(details.type()));
11160 // Return the property attribute calculated from the property details.
11161 // args[0]: smi with property details.
11162 RUNTIME_FUNCTION(Runtime_DebugPropertyAttributesFromDetails) {
11163 SealHandleScope shs(isolate);
11164 DCHECK(args.length() == 1);
11165 CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
11166 return Smi::FromInt(static_cast<int>(details.attributes()));
11170 // Return the property insertion index calculated from the property details.
11171 // args[0]: smi with property details.
11172 RUNTIME_FUNCTION(Runtime_DebugPropertyIndexFromDetails) {
11173 SealHandleScope shs(isolate);
11174 DCHECK(args.length() == 1);
11175 CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
11176 // TODO(verwaest): Depends on the type of details.
11177 return Smi::FromInt(details.dictionary_index());
11181 // Return property value from named interceptor.
11183 // args[1]: property name
11184 RUNTIME_FUNCTION(Runtime_DebugNamedInterceptorPropertyValue) {
11185 HandleScope scope(isolate);
11186 DCHECK(args.length() == 2);
11187 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11188 RUNTIME_ASSERT(obj->HasNamedInterceptor());
11189 CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);
11191 Handle<Object> result;
11192 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
11193 isolate, result, JSObject::GetProperty(obj, name));
11198 // Return element value from indexed interceptor.
11201 RUNTIME_FUNCTION(Runtime_DebugIndexedInterceptorElementValue) {
11202 HandleScope scope(isolate);
11203 DCHECK(args.length() == 2);
11204 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
11205 RUNTIME_ASSERT(obj->HasIndexedInterceptor());
11206 CONVERT_NUMBER_CHECKED(uint32_t, index, Uint32, args[1]);
11207 Handle<Object> result;
11208 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
11209 isolate, result, JSObject::GetElementWithInterceptor(obj, obj, index));
11214 static bool CheckExecutionState(Isolate* isolate, int break_id) {
11215 return !isolate->debug()->debug_context().is_null() &&
11216 isolate->debug()->break_id() != 0 &&
11217 isolate->debug()->break_id() == break_id;
11221 RUNTIME_FUNCTION(Runtime_CheckExecutionState) {
11222 SealHandleScope shs(isolate);
11223 DCHECK(args.length() == 1);
11224 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
11225 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
11226 return isolate->heap()->true_value();
11230 RUNTIME_FUNCTION(Runtime_GetFrameCount) {
11231 HandleScope scope(isolate);
11232 DCHECK(args.length() == 1);
11233 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
11234 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
11236 // Count all frames which are relevant to debugging stack trace.
11238 StackFrame::Id id = isolate->debug()->break_frame_id();
11239 if (id == StackFrame::NO_ID) {
11240 // If there is no JavaScript stack frame count is 0.
11241 return Smi::FromInt(0);
11244 for (JavaScriptFrameIterator it(isolate, id); !it.done(); it.Advance()) {
11245 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
11246 it.frame()->Summarize(&frames);
11247 for (int i = frames.length() - 1; i >= 0; i--) {
11248 // Omit functions from native scripts.
11249 if (!frames[i].function()->IsFromNativeScript()) n++;
11252 return Smi::FromInt(n);
11256 class FrameInspector {
11258 FrameInspector(JavaScriptFrame* frame,
11259 int inlined_jsframe_index,
11261 : frame_(frame), deoptimized_frame_(NULL), isolate_(isolate) {
11262 // Calculate the deoptimized frame.
11263 if (frame->is_optimized()) {
11264 deoptimized_frame_ = Deoptimizer::DebuggerInspectableFrame(
11265 frame, inlined_jsframe_index, isolate);
11267 has_adapted_arguments_ = frame_->has_adapted_arguments();
11268 is_bottommost_ = inlined_jsframe_index == 0;
11269 is_optimized_ = frame_->is_optimized();
11272 ~FrameInspector() {
11273 // Get rid of the calculated deoptimized frame if any.
11274 if (deoptimized_frame_ != NULL) {
11275 Deoptimizer::DeleteDebuggerInspectableFrame(deoptimized_frame_,
11280 int GetParametersCount() {
11281 return is_optimized_
11282 ? deoptimized_frame_->parameters_count()
11283 : frame_->ComputeParametersCount();
11285 int expression_count() { return deoptimized_frame_->expression_count(); }
11286 Object* GetFunction() {
11287 return is_optimized_
11288 ? deoptimized_frame_->GetFunction()
11289 : frame_->function();
11291 Object* GetParameter(int index) {
11292 return is_optimized_
11293 ? deoptimized_frame_->GetParameter(index)
11294 : frame_->GetParameter(index);
11296 Object* GetExpression(int index) {
11297 return is_optimized_
11298 ? deoptimized_frame_->GetExpression(index)
11299 : frame_->GetExpression(index);
11301 int GetSourcePosition() {
11302 return is_optimized_
11303 ? deoptimized_frame_->GetSourcePosition()
11304 : frame_->LookupCode()->SourcePosition(frame_->pc());
11306 bool IsConstructor() {
11307 return is_optimized_ && !is_bottommost_
11308 ? deoptimized_frame_->HasConstructStub()
11309 : frame_->IsConstructor();
11311 Object* GetContext() {
11312 return is_optimized_ ? deoptimized_frame_->GetContext() : frame_->context();
11315 // To inspect all the provided arguments the frame might need to be
11316 // replaced with the arguments frame.
11317 void SetArgumentsFrame(JavaScriptFrame* frame) {
11318 DCHECK(has_adapted_arguments_);
11320 is_optimized_ = frame_->is_optimized();
11321 DCHECK(!is_optimized_);
11325 JavaScriptFrame* frame_;
11326 DeoptimizedFrameInfo* deoptimized_frame_;
11328 bool is_optimized_;
11329 bool is_bottommost_;
11330 bool has_adapted_arguments_;
11332 DISALLOW_COPY_AND_ASSIGN(FrameInspector);
11336 static const int kFrameDetailsFrameIdIndex = 0;
11337 static const int kFrameDetailsReceiverIndex = 1;
11338 static const int kFrameDetailsFunctionIndex = 2;
11339 static const int kFrameDetailsArgumentCountIndex = 3;
11340 static const int kFrameDetailsLocalCountIndex = 4;
11341 static const int kFrameDetailsSourcePositionIndex = 5;
11342 static const int kFrameDetailsConstructCallIndex = 6;
11343 static const int kFrameDetailsAtReturnIndex = 7;
11344 static const int kFrameDetailsFlagsIndex = 8;
11345 static const int kFrameDetailsFirstDynamicIndex = 9;
11348 static SaveContext* FindSavedContextForFrame(Isolate* isolate,
11349 JavaScriptFrame* frame) {
11350 SaveContext* save = isolate->save_context();
11351 while (save != NULL && !save->IsBelowFrame(frame)) {
11352 save = save->prev();
11354 DCHECK(save != NULL);
11359 // Advances the iterator to the frame that matches the index and returns the
11360 // inlined frame index, or -1 if not found. Skips native JS functions.
11361 static int FindIndexedNonNativeFrame(JavaScriptFrameIterator* it, int index) {
11363 for (; !it->done(); it->Advance()) {
11364 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
11365 it->frame()->Summarize(&frames);
11366 for (int i = frames.length() - 1; i >= 0; i--) {
11367 // Omit functions from native scripts.
11368 if (frames[i].function()->IsFromNativeScript()) continue;
11369 if (++count == index) return i;
11376 // Return an array with frame details
11377 // args[0]: number: break id
11378 // args[1]: number: frame index
11380 // The array returned contains the following information:
11384 // 3: Argument count
11386 // 5: Source position
11387 // 6: Constructor call
11390 // Arguments name, value
11391 // Locals name, value
11392 // Return value if any
11393 RUNTIME_FUNCTION(Runtime_GetFrameDetails) {
11394 HandleScope scope(isolate);
11395 DCHECK(args.length() == 2);
11396 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
11397 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
11399 CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
11400 Heap* heap = isolate->heap();
11402 // Find the relevant frame with the requested index.
11403 StackFrame::Id id = isolate->debug()->break_frame_id();
11404 if (id == StackFrame::NO_ID) {
11405 // If there are no JavaScript stack frames return undefined.
11406 return heap->undefined_value();
11409 JavaScriptFrameIterator it(isolate, id);
11410 // Inlined frame index in optimized frame, starting from outer function.
11411 int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index);
11412 if (inlined_jsframe_index == -1) return heap->undefined_value();
11414 FrameInspector frame_inspector(it.frame(), inlined_jsframe_index, isolate);
11415 bool is_optimized = it.frame()->is_optimized();
11417 // Traverse the saved contexts chain to find the active context for the
11419 SaveContext* save = FindSavedContextForFrame(isolate, it.frame());
11421 // Get the frame id.
11422 Handle<Object> frame_id(WrapFrameId(it.frame()->id()), isolate);
11424 // Find source position in unoptimized code.
11425 int position = frame_inspector.GetSourcePosition();
11427 // Check for constructor frame.
11428 bool constructor = frame_inspector.IsConstructor();
11430 // Get scope info and read from it for local variable information.
11431 Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
11432 Handle<SharedFunctionInfo> shared(function->shared());
11433 Handle<ScopeInfo> scope_info(shared->scope_info());
11434 DCHECK(*scope_info != ScopeInfo::Empty(isolate));
11436 // Get the locals names and values into a temporary array.
11437 int local_count = scope_info->LocalCount();
11438 for (int slot = 0; slot < scope_info->LocalCount(); ++slot) {
11439 // Hide compiler-introduced temporary variables, whether on the stack or on
11441 if (scope_info->LocalIsSynthetic(slot))
11445 Handle<FixedArray> locals =
11446 isolate->factory()->NewFixedArray(local_count * 2);
11448 // Fill in the values of the locals.
11451 for (; i < scope_info->StackLocalCount(); ++i) {
11452 // Use the value from the stack.
11453 if (scope_info->LocalIsSynthetic(i))
11455 locals->set(local * 2, scope_info->LocalName(i));
11456 locals->set(local * 2 + 1, frame_inspector.GetExpression(i));
11459 if (local < local_count) {
11460 // Get the context containing declarations.
11461 Handle<Context> context(
11462 Context::cast(frame_inspector.GetContext())->declaration_context());
11463 for (; i < scope_info->LocalCount(); ++i) {
11464 if (scope_info->LocalIsSynthetic(i))
11466 Handle<String> name(scope_info->LocalName(i));
11468 InitializationFlag init_flag;
11469 MaybeAssignedFlag maybe_assigned_flag;
11470 locals->set(local * 2, *name);
11471 int context_slot_index = ScopeInfo::ContextSlotIndex(
11472 scope_info, name, &mode, &init_flag, &maybe_assigned_flag);
11473 Object* value = context->get(context_slot_index);
11474 locals->set(local * 2 + 1, value);
11479 // Check whether this frame is positioned at return. If not top
11480 // frame or if the frame is optimized it cannot be at a return.
11481 bool at_return = false;
11482 if (!is_optimized && index == 0) {
11483 at_return = isolate->debug()->IsBreakAtReturn(it.frame());
11486 // If positioned just before return find the value to be returned and add it
11487 // to the frame information.
11488 Handle<Object> return_value = isolate->factory()->undefined_value();
11490 StackFrameIterator it2(isolate);
11491 Address internal_frame_sp = NULL;
11492 while (!it2.done()) {
11493 if (it2.frame()->is_internal()) {
11494 internal_frame_sp = it2.frame()->sp();
11496 if (it2.frame()->is_java_script()) {
11497 if (it2.frame()->id() == it.frame()->id()) {
11498 // The internal frame just before the JavaScript frame contains the
11499 // value to return on top. A debug break at return will create an
11500 // internal frame to store the return value (eax/rax/r0) before
11501 // entering the debug break exit frame.
11502 if (internal_frame_sp != NULL) {
11504 Handle<Object>(Memory::Object_at(internal_frame_sp),
11511 // Indicate that the previous frame was not an internal frame.
11512 internal_frame_sp = NULL;
11518 // Now advance to the arguments adapter frame (if any). It contains all
11519 // the provided parameters whereas the function frame always have the number
11520 // of arguments matching the functions parameters. The rest of the
11521 // information (except for what is collected above) is the same.
11522 if ((inlined_jsframe_index == 0) && it.frame()->has_adapted_arguments()) {
11523 it.AdvanceToArgumentsFrame();
11524 frame_inspector.SetArgumentsFrame(it.frame());
11527 // Find the number of arguments to fill. At least fill the number of
11528 // parameters for the function and fill more if more parameters are provided.
11529 int argument_count = scope_info->ParameterCount();
11530 if (argument_count < frame_inspector.GetParametersCount()) {
11531 argument_count = frame_inspector.GetParametersCount();
11534 // Calculate the size of the result.
11535 int details_size = kFrameDetailsFirstDynamicIndex +
11536 2 * (argument_count + local_count) +
11537 (at_return ? 1 : 0);
11538 Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);
11540 // Add the frame id.
11541 details->set(kFrameDetailsFrameIdIndex, *frame_id);
11543 // Add the function (same as in function frame).
11544 details->set(kFrameDetailsFunctionIndex, frame_inspector.GetFunction());
11546 // Add the arguments count.
11547 details->set(kFrameDetailsArgumentCountIndex, Smi::FromInt(argument_count));
11549 // Add the locals count
11550 details->set(kFrameDetailsLocalCountIndex,
11551 Smi::FromInt(local_count));
11553 // Add the source position.
11554 if (position != RelocInfo::kNoPosition) {
11555 details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position));
11557 details->set(kFrameDetailsSourcePositionIndex, heap->undefined_value());
11560 // Add the constructor information.
11561 details->set(kFrameDetailsConstructCallIndex, heap->ToBoolean(constructor));
11563 // Add the at return information.
11564 details->set(kFrameDetailsAtReturnIndex, heap->ToBoolean(at_return));
11566 // Add flags to indicate information on whether this frame is
11567 // bit 0: invoked in the debugger context.
11568 // bit 1: optimized frame.
11569 // bit 2: inlined in optimized frame
11571 if (*save->context() == *isolate->debug()->debug_context()) {
11574 if (is_optimized) {
11576 flags |= inlined_jsframe_index << 2;
11578 details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags));
11580 // Fill the dynamic part.
11581 int details_index = kFrameDetailsFirstDynamicIndex;
11583 // Add arguments name and value.
11584 for (int i = 0; i < argument_count; i++) {
11585 // Name of the argument.
11586 if (i < scope_info->ParameterCount()) {
11587 details->set(details_index++, scope_info->ParameterName(i));
11589 details->set(details_index++, heap->undefined_value());
11592 // Parameter value.
11593 if (i < frame_inspector.GetParametersCount()) {
11594 // Get the value from the stack.
11595 details->set(details_index++, frame_inspector.GetParameter(i));
11597 details->set(details_index++, heap->undefined_value());
11601 // Add locals name and value from the temporary copy from the function frame.
11602 for (int i = 0; i < local_count * 2; i++) {
11603 details->set(details_index++, locals->get(i));
11606 // Add the value being returned.
11608 details->set(details_index++, *return_value);
11611 // Add the receiver (same as in function frame).
11612 // THIS MUST BE DONE LAST SINCE WE MIGHT ADVANCE
11613 // THE FRAME ITERATOR TO WRAP THE RECEIVER.
11614 Handle<Object> receiver(it.frame()->receiver(), isolate);
11615 if (!receiver->IsJSObject() &&
11616 shared->strict_mode() == SLOPPY &&
11617 !function->IsBuiltin()) {
11618 // If the receiver is not a JSObject and the function is not a
11619 // builtin or strict-mode we have hit an optimization where a
11620 // value object is not converted into a wrapped JS objects. To
11621 // hide this optimization from the debugger, we wrap the receiver
11622 // by creating correct wrapper object based on the calling frame's
11625 if (receiver->IsUndefined()) {
11626 receiver = handle(function->global_proxy());
11628 Context* context = Context::cast(it.frame()->context());
11629 Handle<Context> native_context(Context::cast(context->native_context()));
11630 if (!Object::ToObject(isolate, receiver, native_context)
11631 .ToHandle(&receiver)) {
11632 // This only happens if the receiver is forcibly set in %_CallFunction.
11633 return heap->undefined_value();
11637 details->set(kFrameDetailsReceiverIndex, *receiver);
11639 DCHECK_EQ(details_size, details_index);
11640 return *isolate->factory()->NewJSArrayWithElements(details);
11644 static bool ParameterIsShadowedByContextLocal(Handle<ScopeInfo> info,
11645 Handle<String> parameter_name) {
11647 InitializationFlag init_flag;
11648 MaybeAssignedFlag maybe_assigned_flag;
11649 return ScopeInfo::ContextSlotIndex(info, parameter_name, &mode, &init_flag,
11650 &maybe_assigned_flag) != -1;
11654 // Create a plain JSObject which materializes the local scope for the specified
11657 static MaybeHandle<JSObject> MaterializeStackLocalsWithFrameInspector(
11659 Handle<JSObject> target,
11660 Handle<JSFunction> function,
11661 FrameInspector* frame_inspector) {
11662 Handle<SharedFunctionInfo> shared(function->shared());
11663 Handle<ScopeInfo> scope_info(shared->scope_info());
11665 // First fill all parameters.
11666 for (int i = 0; i < scope_info->ParameterCount(); ++i) {
11667 // Do not materialize the parameter if it is shadowed by a context local.
11668 Handle<String> name(scope_info->ParameterName(i));
11669 if (ParameterIsShadowedByContextLocal(scope_info, name)) continue;
11671 HandleScope scope(isolate);
11672 Handle<Object> value(i < frame_inspector->GetParametersCount()
11673 ? frame_inspector->GetParameter(i)
11674 : isolate->heap()->undefined_value(),
11676 DCHECK(!value->IsTheHole());
11678 RETURN_ON_EXCEPTION(
11680 Runtime::SetObjectProperty(isolate, target, name, value, SLOPPY),
11684 // Second fill all stack locals.
11685 for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
11686 if (scope_info->LocalIsSynthetic(i)) continue;
11687 Handle<String> name(scope_info->StackLocalName(i));
11688 Handle<Object> value(frame_inspector->GetExpression(i), isolate);
11689 if (value->IsTheHole()) continue;
11691 RETURN_ON_EXCEPTION(
11693 Runtime::SetObjectProperty(isolate, target, name, value, SLOPPY),
11701 static void UpdateStackLocalsFromMaterializedObject(Isolate* isolate,
11702 Handle<JSObject> target,
11703 Handle<JSFunction> function,
11704 JavaScriptFrame* frame,
11705 int inlined_jsframe_index) {
11706 if (inlined_jsframe_index != 0 || frame->is_optimized()) {
11707 // Optimized frames are not supported.
11708 // TODO(yangguo): make sure all code deoptimized when debugger is active
11709 // and assert that this cannot happen.
11713 Handle<SharedFunctionInfo> shared(function->shared());
11714 Handle<ScopeInfo> scope_info(shared->scope_info());
11717 for (int i = 0; i < scope_info->ParameterCount(); ++i) {
11718 // Shadowed parameters were not materialized.
11719 Handle<String> name(scope_info->ParameterName(i));
11720 if (ParameterIsShadowedByContextLocal(scope_info, name)) continue;
11722 DCHECK(!frame->GetParameter(i)->IsTheHole());
11723 HandleScope scope(isolate);
11724 Handle<Object> value =
11725 Object::GetPropertyOrElement(target, name).ToHandleChecked();
11726 frame->SetParameterValue(i, *value);
11730 for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
11731 if (scope_info->LocalIsSynthetic(i)) continue;
11732 if (frame->GetExpression(i)->IsTheHole()) continue;
11733 HandleScope scope(isolate);
11734 Handle<Object> value = Object::GetPropertyOrElement(
11736 handle(scope_info->StackLocalName(i), isolate)).ToHandleChecked();
11737 frame->SetExpression(i, *value);
11742 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeLocalContext(
11744 Handle<JSObject> target,
11745 Handle<JSFunction> function,
11746 JavaScriptFrame* frame) {
11747 HandleScope scope(isolate);
11748 Handle<SharedFunctionInfo> shared(function->shared());
11749 Handle<ScopeInfo> scope_info(shared->scope_info());
11751 if (!scope_info->HasContext()) return target;
11753 // Third fill all context locals.
11754 Handle<Context> frame_context(Context::cast(frame->context()));
11755 Handle<Context> function_context(frame_context->declaration_context());
11756 if (!ScopeInfo::CopyContextLocalsToScopeObject(
11757 scope_info, function_context, target)) {
11758 return MaybeHandle<JSObject>();
11761 // Finally copy any properties from the function context extension.
11762 // These will be variables introduced by eval.
11763 if (function_context->closure() == *function) {
11764 if (function_context->has_extension() &&
11765 !function_context->IsNativeContext()) {
11766 Handle<JSObject> ext(JSObject::cast(function_context->extension()));
11767 Handle<FixedArray> keys;
11768 ASSIGN_RETURN_ON_EXCEPTION(
11770 JSReceiver::GetKeys(ext, JSReceiver::INCLUDE_PROTOS),
11773 for (int i = 0; i < keys->length(); i++) {
11774 // Names of variables introduced by eval are strings.
11775 DCHECK(keys->get(i)->IsString());
11776 Handle<String> key(String::cast(keys->get(i)));
11777 Handle<Object> value;
11778 ASSIGN_RETURN_ON_EXCEPTION(
11779 isolate, value, Object::GetPropertyOrElement(ext, key), JSObject);
11780 RETURN_ON_EXCEPTION(
11782 Runtime::SetObjectProperty(isolate, target, key, value, SLOPPY),
11792 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeLocalScope(
11794 JavaScriptFrame* frame,
11795 int inlined_jsframe_index) {
11796 FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
11797 Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
11799 Handle<JSObject> local_scope =
11800 isolate->factory()->NewJSObject(isolate->object_function());
11801 ASSIGN_RETURN_ON_EXCEPTION(
11802 isolate, local_scope,
11803 MaterializeStackLocalsWithFrameInspector(
11804 isolate, local_scope, function, &frame_inspector),
11807 return MaterializeLocalContext(isolate, local_scope, function, frame);
11811 // Set the context local variable value.
11812 static bool SetContextLocalValue(Isolate* isolate,
11813 Handle<ScopeInfo> scope_info,
11814 Handle<Context> context,
11815 Handle<String> variable_name,
11816 Handle<Object> new_value) {
11817 for (int i = 0; i < scope_info->ContextLocalCount(); i++) {
11818 Handle<String> next_name(scope_info->ContextLocalName(i));
11819 if (String::Equals(variable_name, next_name)) {
11821 InitializationFlag init_flag;
11822 MaybeAssignedFlag maybe_assigned_flag;
11823 int context_index = ScopeInfo::ContextSlotIndex(
11824 scope_info, next_name, &mode, &init_flag, &maybe_assigned_flag);
11825 context->set(context_index, *new_value);
11834 static bool SetLocalVariableValue(Isolate* isolate,
11835 JavaScriptFrame* frame,
11836 int inlined_jsframe_index,
11837 Handle<String> variable_name,
11838 Handle<Object> new_value) {
11839 if (inlined_jsframe_index != 0 || frame->is_optimized()) {
11840 // Optimized frames are not supported.
11844 Handle<JSFunction> function(frame->function());
11845 Handle<SharedFunctionInfo> shared(function->shared());
11846 Handle<ScopeInfo> scope_info(shared->scope_info());
11848 bool default_result = false;
11851 for (int i = 0; i < scope_info->ParameterCount(); ++i) {
11852 HandleScope scope(isolate);
11853 if (String::Equals(handle(scope_info->ParameterName(i)), variable_name)) {
11854 frame->SetParameterValue(i, *new_value);
11855 // Argument might be shadowed in heap context, don't stop here.
11856 default_result = true;
11861 for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
11862 HandleScope scope(isolate);
11863 if (String::Equals(handle(scope_info->StackLocalName(i)), variable_name)) {
11864 frame->SetExpression(i, *new_value);
11869 if (scope_info->HasContext()) {
11871 Handle<Context> frame_context(Context::cast(frame->context()));
11872 Handle<Context> function_context(frame_context->declaration_context());
11873 if (SetContextLocalValue(
11874 isolate, scope_info, function_context, variable_name, new_value)) {
11878 // Function context extension. These are variables introduced by eval.
11879 if (function_context->closure() == *function) {
11880 if (function_context->has_extension() &&
11881 !function_context->IsNativeContext()) {
11882 Handle<JSObject> ext(JSObject::cast(function_context->extension()));
11884 Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
11885 DCHECK(maybe.has_value);
11887 // We don't expect this to do anything except replacing
11889 Runtime::SetObjectProperty(isolate, ext, variable_name, new_value,
11897 return default_result;
11901 // Create a plain JSObject which materializes the closure content for the
11903 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeClosure(
11905 Handle<Context> context) {
11906 DCHECK(context->IsFunctionContext());
11908 Handle<SharedFunctionInfo> shared(context->closure()->shared());
11909 Handle<ScopeInfo> scope_info(shared->scope_info());
11911 // Allocate and initialize a JSObject with all the content of this function
11913 Handle<JSObject> closure_scope =
11914 isolate->factory()->NewJSObject(isolate->object_function());
11916 // Fill all context locals to the context extension.
11917 if (!ScopeInfo::CopyContextLocalsToScopeObject(
11918 scope_info, context, closure_scope)) {
11919 return MaybeHandle<JSObject>();
11922 // Finally copy any properties from the function context extension. This will
11923 // be variables introduced by eval.
11924 if (context->has_extension()) {
11925 Handle<JSObject> ext(JSObject::cast(context->extension()));
11926 Handle<FixedArray> keys;
11927 ASSIGN_RETURN_ON_EXCEPTION(
11929 JSReceiver::GetKeys(ext, JSReceiver::INCLUDE_PROTOS), JSObject);
11931 for (int i = 0; i < keys->length(); i++) {
11932 HandleScope scope(isolate);
11933 // Names of variables introduced by eval are strings.
11934 DCHECK(keys->get(i)->IsString());
11935 Handle<String> key(String::cast(keys->get(i)));
11936 Handle<Object> value;
11937 ASSIGN_RETURN_ON_EXCEPTION(
11938 isolate, value, Object::GetPropertyOrElement(ext, key), JSObject);
11939 RETURN_ON_EXCEPTION(
11941 Runtime::DefineObjectProperty(closure_scope, key, value, NONE),
11946 return closure_scope;
11950 // This method copies structure of MaterializeClosure method above.
11951 static bool SetClosureVariableValue(Isolate* isolate,
11952 Handle<Context> context,
11953 Handle<String> variable_name,
11954 Handle<Object> new_value) {
11955 DCHECK(context->IsFunctionContext());
11957 Handle<SharedFunctionInfo> shared(context->closure()->shared());
11958 Handle<ScopeInfo> scope_info(shared->scope_info());
11960 // Context locals to the context extension.
11961 if (SetContextLocalValue(
11962 isolate, scope_info, context, variable_name, new_value)) {
11966 // Properties from the function context extension. This will
11967 // be variables introduced by eval.
11968 if (context->has_extension()) {
11969 Handle<JSObject> ext(JSObject::cast(context->extension()));
11970 Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
11971 DCHECK(maybe.has_value);
11973 // We don't expect this to do anything except replacing property value.
11974 Runtime::DefineObjectProperty(
11975 ext, variable_name, new_value, NONE).Assert();
11984 // Create a plain JSObject which materializes the scope for the specified
11986 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeCatchScope(
11988 Handle<Context> context) {
11989 DCHECK(context->IsCatchContext());
11990 Handle<String> name(String::cast(context->extension()));
11991 Handle<Object> thrown_object(context->get(Context::THROWN_OBJECT_INDEX),
11993 Handle<JSObject> catch_scope =
11994 isolate->factory()->NewJSObject(isolate->object_function());
11995 RETURN_ON_EXCEPTION(
11997 Runtime::DefineObjectProperty(catch_scope, name, thrown_object, NONE),
11999 return catch_scope;
12003 static bool SetCatchVariableValue(Isolate* isolate,
12004 Handle<Context> context,
12005 Handle<String> variable_name,
12006 Handle<Object> new_value) {
12007 DCHECK(context->IsCatchContext());
12008 Handle<String> name(String::cast(context->extension()));
12009 if (!String::Equals(name, variable_name)) {
12012 context->set(Context::THROWN_OBJECT_INDEX, *new_value);
12017 // Create a plain JSObject which materializes the block scope for the specified
12019 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeBlockScope(
12021 Handle<Context> context) {
12022 DCHECK(context->IsBlockContext());
12023 Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension()));
12025 // Allocate and initialize a JSObject with all the arguments, stack locals
12026 // heap locals and extension properties of the debugged function.
12027 Handle<JSObject> block_scope =
12028 isolate->factory()->NewJSObject(isolate->object_function());
12030 // Fill all context locals.
12031 if (!ScopeInfo::CopyContextLocalsToScopeObject(
12032 scope_info, context, block_scope)) {
12033 return MaybeHandle<JSObject>();
12036 return block_scope;
12040 // Create a plain JSObject which materializes the module scope for the specified
12042 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeModuleScope(
12044 Handle<Context> context) {
12045 DCHECK(context->IsModuleContext());
12046 Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension()));
12048 // Allocate and initialize a JSObject with all the members of the debugged
12050 Handle<JSObject> module_scope =
12051 isolate->factory()->NewJSObject(isolate->object_function());
12053 // Fill all context locals.
12054 if (!ScopeInfo::CopyContextLocalsToScopeObject(
12055 scope_info, context, module_scope)) {
12056 return MaybeHandle<JSObject>();
12059 return module_scope;
12063 // Iterate over the actual scopes visible from a stack frame or from a closure.
12064 // The iteration proceeds from the innermost visible nested scope outwards.
12065 // All scopes are backed by an actual context except the local scope,
12066 // which is inserted "artificially" in the context chain.
12067 class ScopeIterator {
12070 ScopeTypeGlobal = 0,
12079 ScopeIterator(Isolate* isolate,
12080 JavaScriptFrame* frame,
12081 int inlined_jsframe_index,
12082 bool ignore_nested_scopes = false)
12083 : isolate_(isolate),
12085 inlined_jsframe_index_(inlined_jsframe_index),
12086 function_(frame->function()),
12087 context_(Context::cast(frame->context())),
12088 nested_scope_chain_(4),
12091 // Catch the case when the debugger stops in an internal function.
12092 Handle<SharedFunctionInfo> shared_info(function_->shared());
12093 Handle<ScopeInfo> scope_info(shared_info->scope_info());
12094 if (shared_info->script() == isolate->heap()->undefined_value()) {
12095 while (context_->closure() == *function_) {
12096 context_ = Handle<Context>(context_->previous(), isolate_);
12101 // Get the debug info (create it if it does not exist).
12102 if (!isolate->debug()->EnsureDebugInfo(shared_info, function_)) {
12103 // Return if ensuring debug info failed.
12107 // Currently it takes too much time to find nested scopes due to script
12108 // parsing. Sometimes we want to run the ScopeIterator as fast as possible
12109 // (for example, while collecting async call stacks on every
12110 // addEventListener call), even if we drop some nested scopes.
12111 // Later we may optimize getting the nested scopes (cache the result?)
12112 // and include nested scopes into the "fast" iteration case as well.
12113 if (!ignore_nested_scopes) {
12114 Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared_info);
12116 // Find the break point where execution has stopped.
12117 BreakLocationIterator break_location_iterator(debug_info,
12118 ALL_BREAK_LOCATIONS);
12119 // pc points to the instruction after the current one, possibly a break
12120 // location as well. So the "- 1" to exclude it from the search.
12121 break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
12123 // Within the return sequence at the moment it is not possible to
12124 // get a source position which is consistent with the current scope chain.
12125 // Thus all nested with, catch and block contexts are skipped and we only
12126 // provide the function scope.
12127 ignore_nested_scopes = break_location_iterator.IsExit();
12130 if (ignore_nested_scopes) {
12131 if (scope_info->HasContext()) {
12132 context_ = Handle<Context>(context_->declaration_context(), isolate_);
12134 while (context_->closure() == *function_) {
12135 context_ = Handle<Context>(context_->previous(), isolate_);
12138 if (scope_info->scope_type() == FUNCTION_SCOPE) {
12139 nested_scope_chain_.Add(scope_info);
12142 // Reparse the code and analyze the scopes.
12143 Handle<Script> script(Script::cast(shared_info->script()));
12144 Scope* scope = NULL;
12146 // Check whether we are in global, eval or function code.
12147 Handle<ScopeInfo> scope_info(shared_info->scope_info());
12148 if (scope_info->scope_type() != FUNCTION_SCOPE) {
12149 // Global or eval code.
12150 CompilationInfoWithZone info(script);
12151 if (scope_info->scope_type() == GLOBAL_SCOPE) {
12152 info.MarkAsGlobal();
12154 DCHECK(scope_info->scope_type() == EVAL_SCOPE);
12156 info.SetContext(Handle<Context>(function_->context()));
12158 if (Parser::Parse(&info) && Scope::Analyze(&info)) {
12159 scope = info.function()->scope();
12161 RetrieveScopeChain(scope, shared_info);
12164 CompilationInfoWithZone info(shared_info);
12165 if (Parser::Parse(&info) && Scope::Analyze(&info)) {
12166 scope = info.function()->scope();
12168 RetrieveScopeChain(scope, shared_info);
12173 ScopeIterator(Isolate* isolate,
12174 Handle<JSFunction> function)
12175 : isolate_(isolate),
12177 inlined_jsframe_index_(0),
12178 function_(function),
12179 context_(function->context()),
12181 if (function->IsBuiltin()) {
12182 context_ = Handle<Context>();
12189 return context_.is_null();
12192 bool Failed() { return failed_; }
12194 // Move to the next scope.
12197 ScopeType scope_type = Type();
12198 if (scope_type == ScopeTypeGlobal) {
12199 // The global scope is always the last in the chain.
12200 DCHECK(context_->IsNativeContext());
12201 context_ = Handle<Context>();
12204 if (nested_scope_chain_.is_empty()) {
12205 context_ = Handle<Context>(context_->previous(), isolate_);
12207 if (nested_scope_chain_.last()->HasContext()) {
12208 DCHECK(context_->previous() != NULL);
12209 context_ = Handle<Context>(context_->previous(), isolate_);
12211 nested_scope_chain_.RemoveLast();
12215 // Return the type of the current scope.
12218 if (!nested_scope_chain_.is_empty()) {
12219 Handle<ScopeInfo> scope_info = nested_scope_chain_.last();
12220 switch (scope_info->scope_type()) {
12221 case FUNCTION_SCOPE:
12222 DCHECK(context_->IsFunctionContext() ||
12223 !scope_info->HasContext());
12224 return ScopeTypeLocal;
12226 DCHECK(context_->IsModuleContext());
12227 return ScopeTypeModule;
12229 DCHECK(context_->IsNativeContext());
12230 return ScopeTypeGlobal;
12232 DCHECK(context_->IsWithContext());
12233 return ScopeTypeWith;
12235 DCHECK(context_->IsCatchContext());
12236 return ScopeTypeCatch;
12238 DCHECK(!scope_info->HasContext() ||
12239 context_->IsBlockContext());
12240 return ScopeTypeBlock;
12245 if (context_->IsNativeContext()) {
12246 DCHECK(context_->global_object()->IsGlobalObject());
12247 return ScopeTypeGlobal;
12249 if (context_->IsFunctionContext()) {
12250 return ScopeTypeClosure;
12252 if (context_->IsCatchContext()) {
12253 return ScopeTypeCatch;
12255 if (context_->IsBlockContext()) {
12256 return ScopeTypeBlock;
12258 if (context_->IsModuleContext()) {
12259 return ScopeTypeModule;
12261 DCHECK(context_->IsWithContext());
12262 return ScopeTypeWith;
12265 // Return the JavaScript object with the content of the current scope.
12266 MaybeHandle<JSObject> ScopeObject() {
12269 case ScopeIterator::ScopeTypeGlobal:
12270 return Handle<JSObject>(CurrentContext()->global_object());
12271 case ScopeIterator::ScopeTypeLocal:
12272 // Materialize the content of the local scope into a JSObject.
12273 DCHECK(nested_scope_chain_.length() == 1);
12274 return MaterializeLocalScope(isolate_, frame_, inlined_jsframe_index_);
12275 case ScopeIterator::ScopeTypeWith:
12276 // Return the with object.
12277 return Handle<JSObject>(JSObject::cast(CurrentContext()->extension()));
12278 case ScopeIterator::ScopeTypeCatch:
12279 return MaterializeCatchScope(isolate_, CurrentContext());
12280 case ScopeIterator::ScopeTypeClosure:
12281 // Materialize the content of the closure scope into a JSObject.
12282 return MaterializeClosure(isolate_, CurrentContext());
12283 case ScopeIterator::ScopeTypeBlock:
12284 return MaterializeBlockScope(isolate_, CurrentContext());
12285 case ScopeIterator::ScopeTypeModule:
12286 return MaterializeModuleScope(isolate_, CurrentContext());
12289 return Handle<JSObject>();
12292 bool SetVariableValue(Handle<String> variable_name,
12293 Handle<Object> new_value) {
12296 case ScopeIterator::ScopeTypeGlobal:
12298 case ScopeIterator::ScopeTypeLocal:
12299 return SetLocalVariableValue(isolate_, frame_, inlined_jsframe_index_,
12300 variable_name, new_value);
12301 case ScopeIterator::ScopeTypeWith:
12303 case ScopeIterator::ScopeTypeCatch:
12304 return SetCatchVariableValue(isolate_, CurrentContext(),
12305 variable_name, new_value);
12306 case ScopeIterator::ScopeTypeClosure:
12307 return SetClosureVariableValue(isolate_, CurrentContext(),
12308 variable_name, new_value);
12309 case ScopeIterator::ScopeTypeBlock:
12310 // TODO(2399): should we implement it?
12312 case ScopeIterator::ScopeTypeModule:
12313 // TODO(2399): should we implement it?
12319 Handle<ScopeInfo> CurrentScopeInfo() {
12321 if (!nested_scope_chain_.is_empty()) {
12322 return nested_scope_chain_.last();
12323 } else if (context_->IsBlockContext()) {
12324 return Handle<ScopeInfo>(ScopeInfo::cast(context_->extension()));
12325 } else if (context_->IsFunctionContext()) {
12326 return Handle<ScopeInfo>(context_->closure()->shared()->scope_info());
12328 return Handle<ScopeInfo>::null();
12331 // Return the context for this scope. For the local context there might not
12332 // be an actual context.
12333 Handle<Context> CurrentContext() {
12335 if (Type() == ScopeTypeGlobal ||
12336 nested_scope_chain_.is_empty()) {
12338 } else if (nested_scope_chain_.last()->HasContext()) {
12341 return Handle<Context>();
12346 // Debug print of the content of the current scope.
12347 void DebugPrint() {
12348 OFStream os(stdout);
12351 case ScopeIterator::ScopeTypeGlobal:
12353 CurrentContext()->Print(os);
12356 case ScopeIterator::ScopeTypeLocal: {
12358 function_->shared()->scope_info()->Print();
12359 if (!CurrentContext().is_null()) {
12360 CurrentContext()->Print(os);
12361 if (CurrentContext()->has_extension()) {
12362 Handle<Object> extension(CurrentContext()->extension(), isolate_);
12363 if (extension->IsJSContextExtensionObject()) {
12364 extension->Print(os);
12371 case ScopeIterator::ScopeTypeWith:
12373 CurrentContext()->extension()->Print(os);
12376 case ScopeIterator::ScopeTypeCatch:
12378 CurrentContext()->extension()->Print(os);
12379 CurrentContext()->get(Context::THROWN_OBJECT_INDEX)->Print(os);
12382 case ScopeIterator::ScopeTypeClosure:
12383 os << "Closure:\n";
12384 CurrentContext()->Print(os);
12385 if (CurrentContext()->has_extension()) {
12386 Handle<Object> extension(CurrentContext()->extension(), isolate_);
12387 if (extension->IsJSContextExtensionObject()) {
12388 extension->Print(os);
12402 JavaScriptFrame* frame_;
12403 int inlined_jsframe_index_;
12404 Handle<JSFunction> function_;
12405 Handle<Context> context_;
12406 List<Handle<ScopeInfo> > nested_scope_chain_;
12409 void RetrieveScopeChain(Scope* scope,
12410 Handle<SharedFunctionInfo> shared_info) {
12411 if (scope != NULL) {
12412 int source_position = shared_info->code()->SourcePosition(frame_->pc());
12413 scope->GetNestedScopeChain(&nested_scope_chain_, source_position);
12415 // A failed reparse indicates that the preparser has diverged from the
12416 // parser or that the preparse data given to the initial parse has been
12417 // faulty. We fail in debug mode but in release mode we only provide the
12418 // information we get from the context chain but nothing about
12419 // completely stack allocated scopes or stack allocated locals.
12420 // Or it could be due to stack overflow.
12421 DCHECK(isolate_->has_pending_exception());
12426 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeIterator);
12430 RUNTIME_FUNCTION(Runtime_GetScopeCount) {
12431 HandleScope scope(isolate);
12432 DCHECK(args.length() == 2);
12433 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12434 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12436 CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12438 // Get the frame where the debugging is performed.
12439 StackFrame::Id id = UnwrapFrameId(wrapped_id);
12440 JavaScriptFrameIterator it(isolate, id);
12441 JavaScriptFrame* frame = it.frame();
12443 // Count the visible scopes.
12445 for (ScopeIterator it(isolate, frame, 0);
12451 return Smi::FromInt(n);
12455 // Returns the list of step-in positions (text offset) in a function of the
12456 // stack frame in a range from the current debug break position to the end
12457 // of the corresponding statement.
12458 RUNTIME_FUNCTION(Runtime_GetStepInPositions) {
12459 HandleScope scope(isolate);
12460 DCHECK(args.length() == 2);
12461 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12462 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12464 CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12466 // Get the frame where the debugging is performed.
12467 StackFrame::Id id = UnwrapFrameId(wrapped_id);
12468 JavaScriptFrameIterator frame_it(isolate, id);
12469 RUNTIME_ASSERT(!frame_it.done());
12471 JavaScriptFrame* frame = frame_it.frame();
12473 Handle<JSFunction> fun =
12474 Handle<JSFunction>(frame->function());
12475 Handle<SharedFunctionInfo> shared =
12476 Handle<SharedFunctionInfo>(fun->shared());
12478 if (!isolate->debug()->EnsureDebugInfo(shared, fun)) {
12479 return isolate->heap()->undefined_value();
12482 Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared);
12485 Handle<JSArray> array(isolate->factory()->NewJSArray(10));
12486 // Find the break point where execution has stopped.
12487 BreakLocationIterator break_location_iterator(debug_info,
12488 ALL_BREAK_LOCATIONS);
12490 break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
12491 int current_statement_pos = break_location_iterator.statement_position();
12493 while (!break_location_iterator.Done()) {
12495 if (break_location_iterator.pc() > frame->pc()) {
12498 StackFrame::Id break_frame_id = isolate->debug()->break_frame_id();
12499 // The break point is near our pc. Could be a step-in possibility,
12500 // that is currently taken by active debugger call.
12501 if (break_frame_id == StackFrame::NO_ID) {
12502 // We are not stepping.
12505 JavaScriptFrameIterator additional_frame_it(isolate, break_frame_id);
12506 // If our frame is a top frame and we are stepping, we can do step-in
12508 accept = additional_frame_it.frame()->id() == id;
12512 if (break_location_iterator.IsStepInLocation(isolate)) {
12513 Smi* position_value = Smi::FromInt(break_location_iterator.position());
12514 RETURN_FAILURE_ON_EXCEPTION(
12516 JSObject::SetElement(array, len,
12517 Handle<Object>(position_value, isolate),
12522 // Advance iterator.
12523 break_location_iterator.Next();
12524 if (current_statement_pos !=
12525 break_location_iterator.statement_position()) {
12533 static const int kScopeDetailsTypeIndex = 0;
12534 static const int kScopeDetailsObjectIndex = 1;
12535 static const int kScopeDetailsSize = 2;
12538 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeScopeDetails(
12540 ScopeIterator* it) {
12541 // Calculate the size of the result.
12542 int details_size = kScopeDetailsSize;
12543 Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);
12545 // Fill in scope details.
12546 details->set(kScopeDetailsTypeIndex, Smi::FromInt(it->Type()));
12547 Handle<JSObject> scope_object;
12548 ASSIGN_RETURN_ON_EXCEPTION(
12549 isolate, scope_object, it->ScopeObject(), JSObject);
12550 details->set(kScopeDetailsObjectIndex, *scope_object);
12552 return isolate->factory()->NewJSArrayWithElements(details);
12556 // Return an array with scope details
12557 // args[0]: number: break id
12558 // args[1]: number: frame index
12559 // args[2]: number: inlined frame index
12560 // args[3]: number: scope index
12562 // The array returned contains the following information:
12565 RUNTIME_FUNCTION(Runtime_GetScopeDetails) {
12566 HandleScope scope(isolate);
12567 DCHECK(args.length() == 4);
12568 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12569 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12571 CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12572 CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
12573 CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
12575 // Get the frame where the debugging is performed.
12576 StackFrame::Id id = UnwrapFrameId(wrapped_id);
12577 JavaScriptFrameIterator frame_it(isolate, id);
12578 JavaScriptFrame* frame = frame_it.frame();
12580 // Find the requested scope.
12582 ScopeIterator it(isolate, frame, inlined_jsframe_index);
12583 for (; !it.Done() && n < index; it.Next()) {
12587 return isolate->heap()->undefined_value();
12589 Handle<JSObject> details;
12590 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
12591 isolate, details, MaterializeScopeDetails(isolate, &it));
12596 // Return an array of scope details
12597 // args[0]: number: break id
12598 // args[1]: number: frame index
12599 // args[2]: number: inlined frame index
12600 // args[3]: boolean: ignore nested scopes
12602 // The array returned contains arrays with the following information:
12605 RUNTIME_FUNCTION(Runtime_GetAllScopesDetails) {
12606 HandleScope scope(isolate);
12607 DCHECK(args.length() == 3 || args.length() == 4);
12608 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12609 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12611 CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12612 CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
12614 bool ignore_nested_scopes = false;
12615 if (args.length() == 4) {
12616 CONVERT_BOOLEAN_ARG_CHECKED(flag, 3);
12617 ignore_nested_scopes = flag;
12620 // Get the frame where the debugging is performed.
12621 StackFrame::Id id = UnwrapFrameId(wrapped_id);
12622 JavaScriptFrameIterator frame_it(isolate, id);
12623 JavaScriptFrame* frame = frame_it.frame();
12625 List<Handle<JSObject> > result(4);
12626 ScopeIterator it(isolate, frame, inlined_jsframe_index, ignore_nested_scopes);
12627 for (; !it.Done(); it.Next()) {
12628 Handle<JSObject> details;
12629 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
12630 isolate, details, MaterializeScopeDetails(isolate, &it));
12631 result.Add(details);
12634 Handle<FixedArray> array = isolate->factory()->NewFixedArray(result.length());
12635 for (int i = 0; i < result.length(); ++i) {
12636 array->set(i, *result[i]);
12638 return *isolate->factory()->NewJSArrayWithElements(array);
12642 RUNTIME_FUNCTION(Runtime_GetFunctionScopeCount) {
12643 HandleScope scope(isolate);
12644 DCHECK(args.length() == 1);
12646 // Check arguments.
12647 CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12649 // Count the visible scopes.
12651 for (ScopeIterator it(isolate, fun); !it.Done(); it.Next()) {
12655 return Smi::FromInt(n);
12659 RUNTIME_FUNCTION(Runtime_GetFunctionScopeDetails) {
12660 HandleScope scope(isolate);
12661 DCHECK(args.length() == 2);
12663 // Check arguments.
12664 CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12665 CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
12667 // Find the requested scope.
12669 ScopeIterator it(isolate, fun);
12670 for (; !it.Done() && n < index; it.Next()) {
12674 return isolate->heap()->undefined_value();
12677 Handle<JSObject> details;
12678 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
12679 isolate, details, MaterializeScopeDetails(isolate, &it));
12684 static bool SetScopeVariableValue(ScopeIterator* it, int index,
12685 Handle<String> variable_name,
12686 Handle<Object> new_value) {
12687 for (int n = 0; !it->Done() && n < index; it->Next()) {
12693 return it->SetVariableValue(variable_name, new_value);
12697 // Change variable value in closure or local scope
12698 // args[0]: number or JsFunction: break id or function
12699 // args[1]: number: frame index (when arg[0] is break id)
12700 // args[2]: number: inlined frame index (when arg[0] is break id)
12701 // args[3]: number: scope index
12702 // args[4]: string: variable name
12703 // args[5]: object: new value
12705 // Return true if success and false otherwise
12706 RUNTIME_FUNCTION(Runtime_SetScopeVariableValue) {
12707 HandleScope scope(isolate);
12708 DCHECK(args.length() == 6);
12710 // Check arguments.
12711 CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
12712 CONVERT_ARG_HANDLE_CHECKED(String, variable_name, 4);
12713 CONVERT_ARG_HANDLE_CHECKED(Object, new_value, 5);
12716 if (args[0]->IsNumber()) {
12717 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12718 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12720 CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
12721 CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
12723 // Get the frame where the debugging is performed.
12724 StackFrame::Id id = UnwrapFrameId(wrapped_id);
12725 JavaScriptFrameIterator frame_it(isolate, id);
12726 JavaScriptFrame* frame = frame_it.frame();
12728 ScopeIterator it(isolate, frame, inlined_jsframe_index);
12729 res = SetScopeVariableValue(&it, index, variable_name, new_value);
12731 CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12732 ScopeIterator it(isolate, fun);
12733 res = SetScopeVariableValue(&it, index, variable_name, new_value);
12736 return isolate->heap()->ToBoolean(res);
12740 RUNTIME_FUNCTION(Runtime_DebugPrintScopes) {
12741 HandleScope scope(isolate);
12742 DCHECK(args.length() == 0);
12745 // Print the scopes for the top frame.
12746 StackFrameLocator locator(isolate);
12747 JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
12748 for (ScopeIterator it(isolate, frame, 0);
12754 return isolate->heap()->undefined_value();
12758 RUNTIME_FUNCTION(Runtime_GetThreadCount) {
12759 HandleScope scope(isolate);
12760 DCHECK(args.length() == 1);
12761 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12762 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12764 // Count all archived V8 threads.
12766 for (ThreadState* thread =
12767 isolate->thread_manager()->FirstThreadStateInUse();
12769 thread = thread->Next()) {
12773 // Total number of threads is current thread and archived threads.
12774 return Smi::FromInt(n + 1);
12778 static const int kThreadDetailsCurrentThreadIndex = 0;
12779 static const int kThreadDetailsThreadIdIndex = 1;
12780 static const int kThreadDetailsSize = 2;
12782 // Return an array with thread details
12783 // args[0]: number: break id
12784 // args[1]: number: thread index
12786 // The array returned contains the following information:
12787 // 0: Is current thread?
12789 RUNTIME_FUNCTION(Runtime_GetThreadDetails) {
12790 HandleScope scope(isolate);
12791 DCHECK(args.length() == 2);
12792 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12793 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12795 CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
12797 // Allocate array for result.
12798 Handle<FixedArray> details =
12799 isolate->factory()->NewFixedArray(kThreadDetailsSize);
12801 // Thread index 0 is current thread.
12803 // Fill the details.
12804 details->set(kThreadDetailsCurrentThreadIndex,
12805 isolate->heap()->true_value());
12806 details->set(kThreadDetailsThreadIdIndex,
12807 Smi::FromInt(ThreadId::Current().ToInteger()));
12809 // Find the thread with the requested index.
12811 ThreadState* thread =
12812 isolate->thread_manager()->FirstThreadStateInUse();
12813 while (index != n && thread != NULL) {
12814 thread = thread->Next();
12817 if (thread == NULL) {
12818 return isolate->heap()->undefined_value();
12821 // Fill the details.
12822 details->set(kThreadDetailsCurrentThreadIndex,
12823 isolate->heap()->false_value());
12824 details->set(kThreadDetailsThreadIdIndex,
12825 Smi::FromInt(thread->id().ToInteger()));
12828 // Convert to JS array and return.
12829 return *isolate->factory()->NewJSArrayWithElements(details);
12833 // Sets the disable break state
12834 // args[0]: disable break state
12835 RUNTIME_FUNCTION(Runtime_SetDisableBreak) {
12836 HandleScope scope(isolate);
12837 DCHECK(args.length() == 1);
12838 CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 0);
12839 isolate->debug()->set_disable_break(disable_break);
12840 return isolate->heap()->undefined_value();
12844 static bool IsPositionAlignmentCodeCorrect(int alignment) {
12845 return alignment == STATEMENT_ALIGNED || alignment == BREAK_POSITION_ALIGNED;
12849 RUNTIME_FUNCTION(Runtime_GetBreakLocations) {
12850 HandleScope scope(isolate);
12851 DCHECK(args.length() == 2);
12853 CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
12854 CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[1]);
12856 if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
12857 return isolate->ThrowIllegalOperation();
12859 BreakPositionAlignment alignment =
12860 static_cast<BreakPositionAlignment>(statement_aligned_code);
12862 Handle<SharedFunctionInfo> shared(fun->shared());
12863 // Find the number of break points
12864 Handle<Object> break_locations =
12865 Debug::GetSourceBreakLocations(shared, alignment);
12866 if (break_locations->IsUndefined()) return isolate->heap()->undefined_value();
12867 // Return array as JS array
12868 return *isolate->factory()->NewJSArrayWithElements(
12869 Handle<FixedArray>::cast(break_locations));
12873 // Set a break point in a function.
12874 // args[0]: function
12875 // args[1]: number: break source position (within the function source)
12876 // args[2]: number: break point object
12877 RUNTIME_FUNCTION(Runtime_SetFunctionBreakPoint) {
12878 HandleScope scope(isolate);
12879 DCHECK(args.length() == 3);
12880 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
12881 CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
12882 RUNTIME_ASSERT(source_position >= function->shared()->start_position() &&
12883 source_position <= function->shared()->end_position());
12884 CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 2);
12886 // Set break point.
12887 RUNTIME_ASSERT(isolate->debug()->SetBreakPoint(
12888 function, break_point_object_arg, &source_position));
12890 return Smi::FromInt(source_position);
12894 // Changes the state of a break point in a script and returns source position
12895 // where break point was set. NOTE: Regarding performance see the NOTE for
12896 // GetScriptFromScriptData.
12897 // args[0]: script to set break point in
12898 // args[1]: number: break source position (within the script source)
12899 // args[2]: number, breakpoint position alignment
12900 // args[3]: number: break point object
12901 RUNTIME_FUNCTION(Runtime_SetScriptBreakPoint) {
12902 HandleScope scope(isolate);
12903 DCHECK(args.length() == 4);
12904 CONVERT_ARG_HANDLE_CHECKED(JSValue, wrapper, 0);
12905 CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
12906 RUNTIME_ASSERT(source_position >= 0);
12907 CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[2]);
12908 CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 3);
12910 if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
12911 return isolate->ThrowIllegalOperation();
12913 BreakPositionAlignment alignment =
12914 static_cast<BreakPositionAlignment>(statement_aligned_code);
12916 // Get the script from the script wrapper.
12917 RUNTIME_ASSERT(wrapper->value()->IsScript());
12918 Handle<Script> script(Script::cast(wrapper->value()));
12920 // Set break point.
12921 if (!isolate->debug()->SetBreakPointForScript(script, break_point_object_arg,
12924 return isolate->heap()->undefined_value();
12927 return Smi::FromInt(source_position);
12931 // Clear a break point
12932 // args[0]: number: break point object
12933 RUNTIME_FUNCTION(Runtime_ClearBreakPoint) {
12934 HandleScope scope(isolate);
12935 DCHECK(args.length() == 1);
12936 CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 0);
12938 // Clear break point.
12939 isolate->debug()->ClearBreakPoint(break_point_object_arg);
12941 return isolate->heap()->undefined_value();
12945 // Change the state of break on exceptions.
12946 // args[0]: Enum value indicating whether to affect caught/uncaught exceptions.
12947 // args[1]: Boolean indicating on/off.
12948 RUNTIME_FUNCTION(Runtime_ChangeBreakOnException) {
12949 HandleScope scope(isolate);
12950 DCHECK(args.length() == 2);
12951 CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
12952 CONVERT_BOOLEAN_ARG_CHECKED(enable, 1);
12954 // If the number doesn't match an enum value, the ChangeBreakOnException
12955 // function will default to affecting caught exceptions.
12956 ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
12957 // Update break point state.
12958 isolate->debug()->ChangeBreakOnException(type, enable);
12959 return isolate->heap()->undefined_value();
12963 // Returns the state of break on exceptions
12964 // args[0]: boolean indicating uncaught exceptions
12965 RUNTIME_FUNCTION(Runtime_IsBreakOnException) {
12966 HandleScope scope(isolate);
12967 DCHECK(args.length() == 1);
12968 CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
12970 ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
12971 bool result = isolate->debug()->IsBreakOnException(type);
12972 return Smi::FromInt(result);
12976 // Prepare for stepping
12977 // args[0]: break id for checking execution state
12978 // args[1]: step action from the enumeration StepAction
12979 // args[2]: number of times to perform the step, for step out it is the number
12980 // of frames to step down.
12981 RUNTIME_FUNCTION(Runtime_PrepareStep) {
12982 HandleScope scope(isolate);
12983 DCHECK(args.length() == 4);
12984 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
12985 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
12987 if (!args[1]->IsNumber() || !args[2]->IsNumber()) {
12988 return isolate->Throw(isolate->heap()->illegal_argument_string());
12991 CONVERT_NUMBER_CHECKED(int, wrapped_frame_id, Int32, args[3]);
12993 StackFrame::Id frame_id;
12994 if (wrapped_frame_id == 0) {
12995 frame_id = StackFrame::NO_ID;
12997 frame_id = UnwrapFrameId(wrapped_frame_id);
13000 // Get the step action and check validity.
13001 StepAction step_action = static_cast<StepAction>(NumberToInt32(args[1]));
13002 if (step_action != StepIn &&
13003 step_action != StepNext &&
13004 step_action != StepOut &&
13005 step_action != StepInMin &&
13006 step_action != StepMin) {
13007 return isolate->Throw(isolate->heap()->illegal_argument_string());
13010 if (frame_id != StackFrame::NO_ID && step_action != StepNext &&
13011 step_action != StepMin && step_action != StepOut) {
13012 return isolate->ThrowIllegalOperation();
13015 // Get the number of steps.
13016 int step_count = NumberToInt32(args[2]);
13017 if (step_count < 1) {
13018 return isolate->Throw(isolate->heap()->illegal_argument_string());
13021 // Clear all current stepping setup.
13022 isolate->debug()->ClearStepping();
13025 isolate->debug()->PrepareStep(static_cast<StepAction>(step_action),
13028 return isolate->heap()->undefined_value();
13032 // Clear all stepping set by PrepareStep.
13033 RUNTIME_FUNCTION(Runtime_ClearStepping) {
13034 HandleScope scope(isolate);
13035 DCHECK(args.length() == 0);
13036 isolate->debug()->ClearStepping();
13037 return isolate->heap()->undefined_value();
13041 // Helper function to find or create the arguments object for
13042 // Runtime_DebugEvaluate.
13043 MUST_USE_RESULT static MaybeHandle<JSObject> MaterializeArgumentsObject(
13045 Handle<JSObject> target,
13046 Handle<JSFunction> function) {
13047 // Do not materialize the arguments object for eval or top-level code.
13048 // Skip if "arguments" is already taken.
13049 if (!function->shared()->is_function()) return target;
13050 Maybe<bool> maybe = JSReceiver::HasOwnProperty(
13051 target, isolate->factory()->arguments_string());
13052 if (!maybe.has_value) return MaybeHandle<JSObject>();
13053 if (maybe.value) return target;
13055 // FunctionGetArguments can't throw an exception.
13056 Handle<JSObject> arguments = Handle<JSObject>::cast(
13057 Accessors::FunctionGetArguments(function));
13058 Handle<String> arguments_str = isolate->factory()->arguments_string();
13059 RETURN_ON_EXCEPTION(
13061 Runtime::DefineObjectProperty(target, arguments_str, arguments, NONE),
13067 // Compile and evaluate source for the given context.
13068 static MaybeHandle<Object> DebugEvaluate(Isolate* isolate,
13069 Handle<SharedFunctionInfo> outer_info,
13070 Handle<Context> context,
13071 Handle<Object> context_extension,
13072 Handle<Object> receiver,
13073 Handle<String> source) {
13074 if (context_extension->IsJSObject()) {
13075 Handle<JSObject> extension = Handle<JSObject>::cast(context_extension);
13076 Handle<JSFunction> closure(context->closure(), isolate);
13077 context = isolate->factory()->NewWithContext(closure, context, extension);
13080 Handle<JSFunction> eval_fun;
13081 ASSIGN_RETURN_ON_EXCEPTION(
13083 Compiler::GetFunctionFromEval(source,
13087 NO_PARSE_RESTRICTION,
13088 RelocInfo::kNoPosition),
13091 Handle<Object> result;
13092 ASSIGN_RETURN_ON_EXCEPTION(
13094 Execution::Call(isolate, eval_fun, receiver, 0, NULL),
13097 // Skip the global proxy as it has no properties and always delegates to the
13098 // real global object.
13099 if (result->IsJSGlobalProxy()) {
13100 PrototypeIterator iter(isolate, result);
13101 // TODO(verwaest): This will crash when the global proxy is detached.
13102 result = Handle<JSObject>::cast(PrototypeIterator::GetCurrent(iter));
13105 // Clear the oneshot breakpoints so that the debugger does not step further.
13106 isolate->debug()->ClearStepping();
13111 static Handle<JSObject> NewJSObjectWithNullProto(Isolate* isolate) {
13112 Handle<JSObject> result =
13113 isolate->factory()->NewJSObject(isolate->object_function());
13114 Handle<Map> new_map = Map::Copy(Handle<Map>(result->map()));
13115 new_map->set_prototype(*isolate->factory()->null_value());
13116 JSObject::MigrateToMap(result, new_map);
13121 // Evaluate a piece of JavaScript in the context of a stack frame for
13122 // debugging. Things that need special attention are:
13123 // - Parameters and stack-allocated locals need to be materialized. Altered
13124 // values need to be written back to the stack afterwards.
13125 // - The arguments object needs to materialized.
13126 RUNTIME_FUNCTION(Runtime_DebugEvaluate) {
13127 HandleScope scope(isolate);
13129 // Check the execution state and decode arguments frame and source to be
13131 DCHECK(args.length() == 6);
13132 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
13133 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
13135 CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
13136 CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
13137 CONVERT_ARG_HANDLE_CHECKED(String, source, 3);
13138 CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 4);
13139 CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 5);
13141 // Handle the processing of break.
13142 DisableBreak disable_break_scope(isolate->debug(), disable_break);
13144 // Get the frame where the debugging is performed.
13145 StackFrame::Id id = UnwrapFrameId(wrapped_id);
13146 JavaScriptFrameIterator it(isolate, id);
13147 JavaScriptFrame* frame = it.frame();
13148 FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
13149 Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
13150 Handle<SharedFunctionInfo> outer_info(function->shared());
13152 // Traverse the saved contexts chain to find the active context for the
13154 SaveContext* save = FindSavedContextForFrame(isolate, frame);
13156 SaveContext savex(isolate);
13157 isolate->set_context(*(save->context()));
13159 // Evaluate on the context of the frame.
13160 Handle<Context> context(Context::cast(frame_inspector.GetContext()));
13161 DCHECK(!context.is_null());
13163 // Materialize stack locals and the arguments object.
13164 Handle<JSObject> materialized = NewJSObjectWithNullProto(isolate);
13166 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13167 isolate, materialized,
13168 MaterializeStackLocalsWithFrameInspector(
13169 isolate, materialized, function, &frame_inspector));
13171 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13172 isolate, materialized,
13173 MaterializeArgumentsObject(isolate, materialized, function));
13175 // Add the materialized object in a with-scope to shadow the stack locals.
13176 context = isolate->factory()->NewWithContext(function, context, materialized);
13178 Handle<Object> receiver(frame->receiver(), isolate);
13179 Handle<Object> result;
13180 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13182 DebugEvaluate(isolate, outer_info,
13183 context, context_extension, receiver, source));
13185 // Write back potential changes to materialized stack locals to the stack.
13186 UpdateStackLocalsFromMaterializedObject(
13187 isolate, materialized, function, frame, inlined_jsframe_index);
13193 RUNTIME_FUNCTION(Runtime_DebugEvaluateGlobal) {
13194 HandleScope scope(isolate);
13196 // Check the execution state and decode arguments frame and source to be
13198 DCHECK(args.length() == 4);
13199 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
13200 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
13202 CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
13203 CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 2);
13204 CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 3);
13206 // Handle the processing of break.
13207 DisableBreak disable_break_scope(isolate->debug(), disable_break);
13209 // Enter the top context from before the debugger was invoked.
13210 SaveContext save(isolate);
13211 SaveContext* top = &save;
13212 while (top != NULL && *top->context() == *isolate->debug()->debug_context()) {
13216 isolate->set_context(*top->context());
13219 // Get the native context now set to the top context from before the
13220 // debugger was invoked.
13221 Handle<Context> context = isolate->native_context();
13222 Handle<JSObject> receiver(context->global_proxy());
13223 Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate);
13224 Handle<Object> result;
13225 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13227 DebugEvaluate(isolate, outer_info,
13228 context, context_extension, receiver, source));
13233 RUNTIME_FUNCTION(Runtime_DebugGetLoadedScripts) {
13234 HandleScope scope(isolate);
13235 DCHECK(args.length() == 0);
13237 // Fill the script objects.
13238 Handle<FixedArray> instances = isolate->debug()->GetLoadedScripts();
13240 // Convert the script objects to proper JS objects.
13241 for (int i = 0; i < instances->length(); i++) {
13242 Handle<Script> script = Handle<Script>(Script::cast(instances->get(i)));
13243 // Get the script wrapper in a local handle before calling GetScriptWrapper,
13245 // instances->set(i, *GetScriptWrapper(script))
13246 // is unsafe as GetScriptWrapper might call GC and the C++ compiler might
13247 // already have dereferenced the instances handle.
13248 Handle<JSObject> wrapper = Script::GetWrapper(script);
13249 instances->set(i, *wrapper);
13252 // Return result as a JS array.
13253 Handle<JSObject> result =
13254 isolate->factory()->NewJSObject(isolate->array_function());
13255 JSArray::SetContent(Handle<JSArray>::cast(result), instances);
13260 // Helper function used by Runtime_DebugReferencedBy below.
13261 static int DebugReferencedBy(HeapIterator* iterator,
13263 Object* instance_filter, int max_references,
13264 FixedArray* instances, int instances_size,
13265 JSFunction* arguments_function) {
13266 Isolate* isolate = target->GetIsolate();
13267 SealHandleScope shs(isolate);
13268 DisallowHeapAllocation no_allocation;
13270 // Iterate the heap.
13272 JSObject* last = NULL;
13273 HeapObject* heap_obj = NULL;
13274 while (((heap_obj = iterator->next()) != NULL) &&
13275 (max_references == 0 || count < max_references)) {
13276 // Only look at all JSObjects.
13277 if (heap_obj->IsJSObject()) {
13278 // Skip context extension objects and argument arrays as these are
13279 // checked in the context of functions using them.
13280 JSObject* obj = JSObject::cast(heap_obj);
13281 if (obj->IsJSContextExtensionObject() ||
13282 obj->map()->constructor() == arguments_function) {
13286 // Check if the JS object has a reference to the object looked for.
13287 if (obj->ReferencesObject(target)) {
13288 // Check instance filter if supplied. This is normally used to avoid
13289 // references from mirror objects (see Runtime_IsInPrototypeChain).
13290 if (!instance_filter->IsUndefined()) {
13291 for (PrototypeIterator iter(isolate, obj); !iter.IsAtEnd();
13293 if (iter.GetCurrent() == instance_filter) {
13294 obj = NULL; // Don't add this object.
13301 // Valid reference found add to instance array if supplied an update
13303 if (instances != NULL && count < instances_size) {
13304 instances->set(count, obj);
13313 // Check for circular reference only. This can happen when the object is only
13314 // referenced from mirrors and has a circular reference in which case the
13315 // object is not really alive and would have been garbage collected if not
13316 // referenced from the mirror.
13317 if (count == 1 && last == target) {
13321 // Return the number of referencing objects found.
13326 // Scan the heap for objects with direct references to an object
13327 // args[0]: the object to find references to
13328 // args[1]: constructor function for instances to exclude (Mirror)
13329 // args[2]: the the maximum number of objects to return
13330 RUNTIME_FUNCTION(Runtime_DebugReferencedBy) {
13331 HandleScope scope(isolate);
13332 DCHECK(args.length() == 3);
13334 // Check parameters.
13335 CONVERT_ARG_HANDLE_CHECKED(JSObject, target, 0);
13336 CONVERT_ARG_HANDLE_CHECKED(Object, instance_filter, 1);
13337 RUNTIME_ASSERT(instance_filter->IsUndefined() ||
13338 instance_filter->IsJSObject());
13339 CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]);
13340 RUNTIME_ASSERT(max_references >= 0);
13343 // Get the constructor function for context extension and arguments array.
13344 Handle<JSFunction> arguments_function(
13345 JSFunction::cast(isolate->sloppy_arguments_map()->constructor()));
13347 // Get the number of referencing objects.
13349 // First perform a full GC in order to avoid dead objects and to make the heap
13351 Heap* heap = isolate->heap();
13352 heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy");
13354 HeapIterator heap_iterator(heap);
13355 count = DebugReferencedBy(&heap_iterator,
13356 *target, *instance_filter, max_references,
13357 NULL, 0, *arguments_function);
13360 // Allocate an array to hold the result.
13361 Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count);
13363 // Fill the referencing objects.
13365 HeapIterator heap_iterator(heap);
13366 count = DebugReferencedBy(&heap_iterator,
13367 *target, *instance_filter, max_references,
13368 *instances, count, *arguments_function);
13371 // Return result as JS array.
13372 Handle<JSFunction> constructor = isolate->array_function();
13374 Handle<JSObject> result = isolate->factory()->NewJSObject(constructor);
13375 JSArray::SetContent(Handle<JSArray>::cast(result), instances);
13380 // Helper function used by Runtime_DebugConstructedBy below.
13381 static int DebugConstructedBy(HeapIterator* iterator,
13382 JSFunction* constructor,
13383 int max_references,
13384 FixedArray* instances,
13385 int instances_size) {
13386 DisallowHeapAllocation no_allocation;
13388 // Iterate the heap.
13390 HeapObject* heap_obj = NULL;
13391 while (((heap_obj = iterator->next()) != NULL) &&
13392 (max_references == 0 || count < max_references)) {
13393 // Only look at all JSObjects.
13394 if (heap_obj->IsJSObject()) {
13395 JSObject* obj = JSObject::cast(heap_obj);
13396 if (obj->map()->constructor() == constructor) {
13397 // Valid reference found add to instance array if supplied an update
13399 if (instances != NULL && count < instances_size) {
13400 instances->set(count, obj);
13407 // Return the number of referencing objects found.
13412 // Scan the heap for objects constructed by a specific function.
13413 // args[0]: the constructor to find instances of
13414 // args[1]: the the maximum number of objects to return
13415 RUNTIME_FUNCTION(Runtime_DebugConstructedBy) {
13416 HandleScope scope(isolate);
13417 DCHECK(args.length() == 2);
13420 // Check parameters.
13421 CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, 0);
13422 CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]);
13423 RUNTIME_ASSERT(max_references >= 0);
13425 // Get the number of referencing objects.
13427 // First perform a full GC in order to avoid dead objects and to make the heap
13429 Heap* heap = isolate->heap();
13430 heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy");
13432 HeapIterator heap_iterator(heap);
13433 count = DebugConstructedBy(&heap_iterator,
13440 // Allocate an array to hold the result.
13441 Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count);
13443 // Fill the referencing objects.
13445 HeapIterator heap_iterator2(heap);
13446 count = DebugConstructedBy(&heap_iterator2,
13453 // Return result as JS array.
13454 Handle<JSFunction> array_function = isolate->array_function();
13455 Handle<JSObject> result = isolate->factory()->NewJSObject(array_function);
13456 JSArray::SetContent(Handle<JSArray>::cast(result), instances);
13461 // Find the effective prototype object as returned by __proto__.
13462 // args[0]: the object to find the prototype for.
13463 RUNTIME_FUNCTION(Runtime_DebugGetPrototype) {
13464 HandleScope shs(isolate);
13465 DCHECK(args.length() == 1);
13466 CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
13467 return *GetPrototypeSkipHiddenPrototypes(isolate, obj);
13471 // Patches script source (should be called upon BeforeCompile event).
13472 RUNTIME_FUNCTION(Runtime_DebugSetScriptSource) {
13473 HandleScope scope(isolate);
13474 DCHECK(args.length() == 2);
13476 CONVERT_ARG_HANDLE_CHECKED(JSValue, script_wrapper, 0);
13477 CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
13479 RUNTIME_ASSERT(script_wrapper->value()->IsScript());
13480 Handle<Script> script(Script::cast(script_wrapper->value()));
13482 int compilation_state = script->compilation_state();
13483 RUNTIME_ASSERT(compilation_state == Script::COMPILATION_STATE_INITIAL);
13484 script->set_source(*source);
13486 return isolate->heap()->undefined_value();
13490 RUNTIME_FUNCTION(Runtime_SystemBreak) {
13491 SealHandleScope shs(isolate);
13492 DCHECK(args.length() == 0);
13493 base::OS::DebugBreak();
13494 return isolate->heap()->undefined_value();
13498 RUNTIME_FUNCTION(Runtime_DebugDisassembleFunction) {
13499 HandleScope scope(isolate);
13501 DCHECK(args.length() == 1);
13502 // Get the function and make sure it is compiled.
13503 CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0);
13504 if (!Compiler::EnsureCompiled(func, KEEP_EXCEPTION)) {
13505 return isolate->heap()->exception();
13507 OFStream os(stdout);
13508 func->code()->Print(os);
13511 return isolate->heap()->undefined_value();
13515 RUNTIME_FUNCTION(Runtime_DebugDisassembleConstructor) {
13516 HandleScope scope(isolate);
13518 DCHECK(args.length() == 1);
13519 // Get the function and make sure it is compiled.
13520 CONVERT_ARG_HANDLE_CHECKED(JSFunction, func, 0);
13521 if (!Compiler::EnsureCompiled(func, KEEP_EXCEPTION)) {
13522 return isolate->heap()->exception();
13524 OFStream os(stdout);
13525 func->shared()->construct_stub()->Print(os);
13528 return isolate->heap()->undefined_value();
13532 RUNTIME_FUNCTION(Runtime_FunctionGetInferredName) {
13533 SealHandleScope shs(isolate);
13534 DCHECK(args.length() == 1);
13536 CONVERT_ARG_CHECKED(JSFunction, f, 0);
13537 return f->shared()->inferred_name();
13541 static int FindSharedFunctionInfosForScript(HeapIterator* iterator,
13543 FixedArray* buffer) {
13544 DisallowHeapAllocation no_allocation;
13546 int buffer_size = buffer->length();
13547 for (HeapObject* obj = iterator->next();
13549 obj = iterator->next()) {
13550 DCHECK(obj != NULL);
13551 if (!obj->IsSharedFunctionInfo()) {
13554 SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
13555 if (shared->script() != script) {
13558 if (counter < buffer_size) {
13559 buffer->set(counter, shared);
13567 // For a script finds all SharedFunctionInfo's in the heap that points
13568 // to this script. Returns JSArray of SharedFunctionInfo wrapped
13569 // in OpaqueReferences.
13570 RUNTIME_FUNCTION(Runtime_LiveEditFindSharedFunctionInfosForScript) {
13571 HandleScope scope(isolate);
13572 CHECK(isolate->debug()->live_edit_enabled());
13573 DCHECK(args.length() == 1);
13574 CONVERT_ARG_CHECKED(JSValue, script_value, 0);
13576 RUNTIME_ASSERT(script_value->value()->IsScript());
13577 Handle<Script> script = Handle<Script>(Script::cast(script_value->value()));
13579 const int kBufferSize = 32;
13581 Handle<FixedArray> array;
13582 array = isolate->factory()->NewFixedArray(kBufferSize);
13584 Heap* heap = isolate->heap();
13586 HeapIterator heap_iterator(heap);
13587 Script* scr = *script;
13588 FixedArray* arr = *array;
13589 number = FindSharedFunctionInfosForScript(&heap_iterator, scr, arr);
13591 if (number > kBufferSize) {
13592 array = isolate->factory()->NewFixedArray(number);
13593 HeapIterator heap_iterator(heap);
13594 Script* scr = *script;
13595 FixedArray* arr = *array;
13596 FindSharedFunctionInfosForScript(&heap_iterator, scr, arr);
13599 Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(array);
13600 result->set_length(Smi::FromInt(number));
13602 LiveEdit::WrapSharedFunctionInfos(result);
13608 // For a script calculates compilation information about all its functions.
13609 // The script source is explicitly specified by the second argument.
13610 // The source of the actual script is not used, however it is important that
13611 // all generated code keeps references to this particular instance of script.
13612 // Returns a JSArray of compilation infos. The array is ordered so that
13613 // each function with all its descendant is always stored in a continues range
13614 // with the function itself going first. The root function is a script function.
13615 RUNTIME_FUNCTION(Runtime_LiveEditGatherCompileInfo) {
13616 HandleScope scope(isolate);
13617 CHECK(isolate->debug()->live_edit_enabled());
13618 DCHECK(args.length() == 2);
13619 CONVERT_ARG_CHECKED(JSValue, script, 0);
13620 CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
13622 RUNTIME_ASSERT(script->value()->IsScript());
13623 Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));
13625 Handle<JSArray> result;
13626 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
13627 isolate, result, LiveEdit::GatherCompileInfo(script_handle, source));
13632 // Changes the source of the script to a new_source.
13633 // If old_script_name is provided (i.e. is a String), also creates a copy of
13634 // the script with its original source and sends notification to debugger.
13635 RUNTIME_FUNCTION(Runtime_LiveEditReplaceScript) {
13636 HandleScope scope(isolate);
13637 CHECK(isolate->debug()->live_edit_enabled());
13638 DCHECK(args.length() == 3);
13639 CONVERT_ARG_CHECKED(JSValue, original_script_value, 0);
13640 CONVERT_ARG_HANDLE_CHECKED(String, new_source, 1);
13641 CONVERT_ARG_HANDLE_CHECKED(Object, old_script_name, 2);
13643 RUNTIME_ASSERT(original_script_value->value()->IsScript());
13644 Handle<Script> original_script(Script::cast(original_script_value->value()));
13646 Handle<Object> old_script = LiveEdit::ChangeScriptSource(
13647 original_script, new_source, old_script_name);
13649 if (old_script->IsScript()) {
13650 Handle<Script> script_handle = Handle<Script>::cast(old_script);
13651 return *Script::GetWrapper(script_handle);
13653 return isolate->heap()->null_value();
13658 RUNTIME_FUNCTION(Runtime_LiveEditFunctionSourceUpdated) {
13659 HandleScope scope(isolate);
13660 CHECK(isolate->debug()->live_edit_enabled());
13661 DCHECK(args.length() == 1);
13662 CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 0);
13663 RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_info));
13665 LiveEdit::FunctionSourceUpdated(shared_info);
13666 return isolate->heap()->undefined_value();
13670 // Replaces code of SharedFunctionInfo with a new one.
13671 RUNTIME_FUNCTION(Runtime_LiveEditReplaceFunctionCode) {
13672 HandleScope scope(isolate);
13673 CHECK(isolate->debug()->live_edit_enabled());
13674 DCHECK(args.length() == 2);
13675 CONVERT_ARG_HANDLE_CHECKED(JSArray, new_compile_info, 0);
13676 CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 1);
13677 RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_info));
13679 LiveEdit::ReplaceFunctionCode(new_compile_info, shared_info);
13680 return isolate->heap()->undefined_value();
13684 // Connects SharedFunctionInfo to another script.
13685 RUNTIME_FUNCTION(Runtime_LiveEditFunctionSetScript) {
13686 HandleScope scope(isolate);
13687 CHECK(isolate->debug()->live_edit_enabled());
13688 DCHECK(args.length() == 2);
13689 CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
13690 CONVERT_ARG_HANDLE_CHECKED(Object, script_object, 1);
13692 if (function_object->IsJSValue()) {
13693 Handle<JSValue> function_wrapper = Handle<JSValue>::cast(function_object);
13694 if (script_object->IsJSValue()) {
13695 RUNTIME_ASSERT(JSValue::cast(*script_object)->value()->IsScript());
13696 Script* script = Script::cast(JSValue::cast(*script_object)->value());
13697 script_object = Handle<Object>(script, isolate);
13699 RUNTIME_ASSERT(function_wrapper->value()->IsSharedFunctionInfo());
13700 LiveEdit::SetFunctionScript(function_wrapper, script_object);
13702 // Just ignore this. We may not have a SharedFunctionInfo for some functions
13703 // and we check it in this function.
13706 return isolate->heap()->undefined_value();
13710 // In a code of a parent function replaces original function as embedded object
13711 // with a substitution one.
13712 RUNTIME_FUNCTION(Runtime_LiveEditReplaceRefToNestedFunction) {
13713 HandleScope scope(isolate);
13714 CHECK(isolate->debug()->live_edit_enabled());
13715 DCHECK(args.length() == 3);
13717 CONVERT_ARG_HANDLE_CHECKED(JSValue, parent_wrapper, 0);
13718 CONVERT_ARG_HANDLE_CHECKED(JSValue, orig_wrapper, 1);
13719 CONVERT_ARG_HANDLE_CHECKED(JSValue, subst_wrapper, 2);
13720 RUNTIME_ASSERT(parent_wrapper->value()->IsSharedFunctionInfo());
13721 RUNTIME_ASSERT(orig_wrapper->value()->IsSharedFunctionInfo());
13722 RUNTIME_ASSERT(subst_wrapper->value()->IsSharedFunctionInfo());
13724 LiveEdit::ReplaceRefToNestedFunction(
13725 parent_wrapper, orig_wrapper, subst_wrapper);
13726 return isolate->heap()->undefined_value();
13730 // Updates positions of a shared function info (first parameter) according
13731 // to script source change. Text change is described in second parameter as
13732 // array of groups of 3 numbers:
13733 // (change_begin, change_end, change_end_new_position).
13734 // Each group describes a change in text; groups are sorted by change_begin.
13735 RUNTIME_FUNCTION(Runtime_LiveEditPatchFunctionPositions) {
13736 HandleScope scope(isolate);
13737 CHECK(isolate->debug()->live_edit_enabled());
13738 DCHECK(args.length() == 2);
13739 CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0);
13740 CONVERT_ARG_HANDLE_CHECKED(JSArray, position_change_array, 1);
13741 RUNTIME_ASSERT(SharedInfoWrapper::IsInstance(shared_array))
13743 LiveEdit::PatchFunctionPositions(shared_array, position_change_array);
13744 return isolate->heap()->undefined_value();
13748 // For array of SharedFunctionInfo's (each wrapped in JSValue)
13749 // checks that none of them have activations on stacks (of any thread).
13750 // Returns array of the same length with corresponding results of
13751 // LiveEdit::FunctionPatchabilityStatus type.
13752 RUNTIME_FUNCTION(Runtime_LiveEditCheckAndDropActivations) {
13753 HandleScope scope(isolate);
13754 CHECK(isolate->debug()->live_edit_enabled());
13755 DCHECK(args.length() == 2);
13756 CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0);
13757 CONVERT_BOOLEAN_ARG_CHECKED(do_drop, 1);
13758 RUNTIME_ASSERT(shared_array->length()->IsSmi());
13759 RUNTIME_ASSERT(shared_array->HasFastElements())
13760 int array_length = Smi::cast(shared_array->length())->value();
13761 for (int i = 0; i < array_length; i++) {
13762 Handle<Object> element =
13763 Object::GetElement(isolate, shared_array, i).ToHandleChecked();
13765 element->IsJSValue() &&
13766 Handle<JSValue>::cast(element)->value()->IsSharedFunctionInfo());
13769 return *LiveEdit::CheckAndDropActivations(shared_array, do_drop);
13773 // Compares 2 strings line-by-line, then token-wise and returns diff in form
13774 // of JSArray of triplets (pos1, pos1_end, pos2_end) describing list
13776 RUNTIME_FUNCTION(Runtime_LiveEditCompareStrings) {
13777 HandleScope scope(isolate);
13778 CHECK(isolate->debug()->live_edit_enabled());
13779 DCHECK(args.length() == 2);
13780 CONVERT_ARG_HANDLE_CHECKED(String, s1, 0);
13781 CONVERT_ARG_HANDLE_CHECKED(String, s2, 1);
13783 return *LiveEdit::CompareStrings(s1, s2);
13787 // Restarts a call frame and completely drops all frames above.
13788 // Returns true if successful. Otherwise returns undefined or an error message.
13789 RUNTIME_FUNCTION(Runtime_LiveEditRestartFrame) {
13790 HandleScope scope(isolate);
13791 CHECK(isolate->debug()->live_edit_enabled());
13792 DCHECK(args.length() == 2);
13793 CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
13794 RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
13796 CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
13797 Heap* heap = isolate->heap();
13799 // Find the relevant frame with the requested index.
13800 StackFrame::Id id = isolate->debug()->break_frame_id();
13801 if (id == StackFrame::NO_ID) {
13802 // If there are no JavaScript stack frames return undefined.
13803 return heap->undefined_value();
13806 JavaScriptFrameIterator it(isolate, id);
13807 int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index);
13808 if (inlined_jsframe_index == -1) return heap->undefined_value();
13809 // We don't really care what the inlined frame index is, since we are
13810 // throwing away the entire frame anyways.
13811 const char* error_message = LiveEdit::RestartFrame(it.frame());
13812 if (error_message) {
13813 return *(isolate->factory()->InternalizeUtf8String(error_message));
13815 return heap->true_value();
13819 // A testing entry. Returns statement position which is the closest to
13820 // source_position.
13821 RUNTIME_FUNCTION(Runtime_GetFunctionCodePositionFromSource) {
13822 HandleScope scope(isolate);
13823 CHECK(isolate->debug()->live_edit_enabled());
13824 DCHECK(args.length() == 2);
13825 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
13826 CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
13828 Handle<Code> code(function->code(), isolate);
13830 if (code->kind() != Code::FUNCTION &&
13831 code->kind() != Code::OPTIMIZED_FUNCTION) {
13832 return isolate->heap()->undefined_value();
13835 RelocIterator it(*code, RelocInfo::ModeMask(RelocInfo::STATEMENT_POSITION));
13836 int closest_pc = 0;
13837 int distance = kMaxInt;
13838 while (!it.done()) {
13839 int statement_position = static_cast<int>(it.rinfo()->data());
13840 // Check if this break point is closer that what was previously found.
13841 if (source_position <= statement_position &&
13842 statement_position - source_position < distance) {
13844 static_cast<int>(it.rinfo()->pc() - code->instruction_start());
13845 distance = statement_position - source_position;
13846 // Check whether we can't get any closer.
13847 if (distance == 0) break;
13852 return Smi::FromInt(closest_pc);
13856 // Calls specified function with or without entering the debugger.
13857 // This is used in unit tests to run code as if debugger is entered or simply
13858 // to have a stack with C++ frame in the middle.
13859 RUNTIME_FUNCTION(Runtime_ExecuteInDebugContext) {
13860 HandleScope scope(isolate);
13861 DCHECK(args.length() == 2);
13862 CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
13863 CONVERT_BOOLEAN_ARG_CHECKED(without_debugger, 1);
13865 MaybeHandle<Object> maybe_result;
13866 if (without_debugger) {
13867 maybe_result = Execution::Call(isolate,
13869 handle(function->global_proxy()),
13873 DebugScope debug_scope(isolate->debug());
13874 maybe_result = Execution::Call(isolate,
13876 handle(function->global_proxy()),
13880 Handle<Object> result;
13881 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, maybe_result);
13887 RUNTIME_FUNCTION(Runtime_SetFlags) {
13888 SealHandleScope shs(isolate);
13889 DCHECK(args.length() == 1);
13890 CONVERT_ARG_CHECKED(String, arg, 0);
13891 SmartArrayPointer<char> flags =
13892 arg->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
13893 FlagList::SetFlagsFromString(flags.get(), StrLength(flags.get()));
13894 return isolate->heap()->undefined_value();
13899 // Presently, it only does a full GC.
13900 RUNTIME_FUNCTION(Runtime_CollectGarbage) {
13901 SealHandleScope shs(isolate);
13902 DCHECK(args.length() == 1);
13903 isolate->heap()->CollectAllGarbage(Heap::kNoGCFlags, "%CollectGarbage");
13904 return isolate->heap()->undefined_value();
13908 // Gets the current heap usage.
13909 RUNTIME_FUNCTION(Runtime_GetHeapUsage) {
13910 SealHandleScope shs(isolate);
13911 DCHECK(args.length() == 0);
13912 int usage = static_cast<int>(isolate->heap()->SizeOfObjects());
13913 if (!Smi::IsValid(usage)) {
13914 return *isolate->factory()->NewNumberFromInt(usage);
13916 return Smi::FromInt(usage);
13920 #ifdef V8_I18N_SUPPORT
13921 RUNTIME_FUNCTION(Runtime_CanonicalizeLanguageTag) {
13922 HandleScope scope(isolate);
13923 Factory* factory = isolate->factory();
13925 DCHECK(args.length() == 1);
13926 CONVERT_ARG_HANDLE_CHECKED(String, locale_id_str, 0);
13928 v8::String::Utf8Value locale_id(v8::Utils::ToLocal(locale_id_str));
13930 // Return value which denotes invalid language tag.
13931 const char* const kInvalidTag = "invalid-tag";
13933 UErrorCode error = U_ZERO_ERROR;
13934 char icu_result[ULOC_FULLNAME_CAPACITY];
13935 int icu_length = 0;
13937 uloc_forLanguageTag(*locale_id, icu_result, ULOC_FULLNAME_CAPACITY,
13938 &icu_length, &error);
13939 if (U_FAILURE(error) || icu_length == 0) {
13940 return *factory->NewStringFromAsciiChecked(kInvalidTag);
13943 char result[ULOC_FULLNAME_CAPACITY];
13945 // Force strict BCP47 rules.
13946 uloc_toLanguageTag(icu_result, result, ULOC_FULLNAME_CAPACITY, TRUE, &error);
13948 if (U_FAILURE(error)) {
13949 return *factory->NewStringFromAsciiChecked(kInvalidTag);
13952 return *factory->NewStringFromAsciiChecked(result);
13956 RUNTIME_FUNCTION(Runtime_AvailableLocalesOf) {
13957 HandleScope scope(isolate);
13958 Factory* factory = isolate->factory();
13960 DCHECK(args.length() == 1);
13961 CONVERT_ARG_HANDLE_CHECKED(String, service, 0);
13963 const icu::Locale* available_locales = NULL;
13966 if (service->IsUtf8EqualTo(CStrVector("collator"))) {
13967 available_locales = icu::Collator::getAvailableLocales(count);
13968 } else if (service->IsUtf8EqualTo(CStrVector("numberformat"))) {
13969 available_locales = icu::NumberFormat::getAvailableLocales(count);
13970 } else if (service->IsUtf8EqualTo(CStrVector("dateformat"))) {
13971 available_locales = icu::DateFormat::getAvailableLocales(count);
13972 } else if (service->IsUtf8EqualTo(CStrVector("breakiterator"))) {
13973 available_locales = icu::BreakIterator::getAvailableLocales(count);
13976 UErrorCode error = U_ZERO_ERROR;
13977 char result[ULOC_FULLNAME_CAPACITY];
13978 Handle<JSObject> locales =
13979 factory->NewJSObject(isolate->object_function());
13981 for (int32_t i = 0; i < count; ++i) {
13982 const char* icu_name = available_locales[i].getName();
13984 error = U_ZERO_ERROR;
13985 // No need to force strict BCP47 rules.
13986 uloc_toLanguageTag(icu_name, result, ULOC_FULLNAME_CAPACITY, FALSE, &error);
13987 if (U_FAILURE(error)) {
13988 // This shouldn't happen, but lets not break the user.
13992 RETURN_FAILURE_ON_EXCEPTION(isolate,
13993 JSObject::SetOwnPropertyIgnoreAttributes(
13995 factory->NewStringFromAsciiChecked(result),
13996 factory->NewNumber(i),
14004 RUNTIME_FUNCTION(Runtime_GetDefaultICULocale) {
14005 HandleScope scope(isolate);
14006 Factory* factory = isolate->factory();
14008 DCHECK(args.length() == 0);
14010 icu::Locale default_locale;
14013 char result[ULOC_FULLNAME_CAPACITY];
14014 UErrorCode status = U_ZERO_ERROR;
14015 uloc_toLanguageTag(
14016 default_locale.getName(), result, ULOC_FULLNAME_CAPACITY, FALSE, &status);
14017 if (U_SUCCESS(status)) {
14018 return *factory->NewStringFromAsciiChecked(result);
14021 return *factory->NewStringFromStaticChars("und");
14025 RUNTIME_FUNCTION(Runtime_GetLanguageTagVariants) {
14026 HandleScope scope(isolate);
14027 Factory* factory = isolate->factory();
14029 DCHECK(args.length() == 1);
14031 CONVERT_ARG_HANDLE_CHECKED(JSArray, input, 0);
14033 uint32_t length = static_cast<uint32_t>(input->length()->Number());
14034 // Set some limit to prevent fuzz tests from going OOM.
14035 // Can be bumped when callers' requirements change.
14036 RUNTIME_ASSERT(length < 100);
14037 Handle<FixedArray> output = factory->NewFixedArray(length);
14038 Handle<Name> maximized = factory->NewStringFromStaticChars("maximized");
14039 Handle<Name> base = factory->NewStringFromStaticChars("base");
14040 for (unsigned int i = 0; i < length; ++i) {
14041 Handle<Object> locale_id;
14042 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14043 isolate, locale_id, Object::GetElement(isolate, input, i));
14044 if (!locale_id->IsString()) {
14045 return isolate->Throw(*factory->illegal_argument_string());
14048 v8::String::Utf8Value utf8_locale_id(
14049 v8::Utils::ToLocal(Handle<String>::cast(locale_id)));
14051 UErrorCode error = U_ZERO_ERROR;
14053 // Convert from BCP47 to ICU format.
14054 // de-DE-u-co-phonebk -> de_DE@collation=phonebook
14055 char icu_locale[ULOC_FULLNAME_CAPACITY];
14056 int icu_locale_length = 0;
14057 uloc_forLanguageTag(*utf8_locale_id, icu_locale, ULOC_FULLNAME_CAPACITY,
14058 &icu_locale_length, &error);
14059 if (U_FAILURE(error) || icu_locale_length == 0) {
14060 return isolate->Throw(*factory->illegal_argument_string());
14063 // Maximize the locale.
14064 // de_DE@collation=phonebook -> de_Latn_DE@collation=phonebook
14065 char icu_max_locale[ULOC_FULLNAME_CAPACITY];
14066 uloc_addLikelySubtags(
14067 icu_locale, icu_max_locale, ULOC_FULLNAME_CAPACITY, &error);
14069 // Remove extensions from maximized locale.
14070 // de_Latn_DE@collation=phonebook -> de_Latn_DE
14071 char icu_base_max_locale[ULOC_FULLNAME_CAPACITY];
14073 icu_max_locale, icu_base_max_locale, ULOC_FULLNAME_CAPACITY, &error);
14075 // Get original name without extensions.
14076 // de_DE@collation=phonebook -> de_DE
14077 char icu_base_locale[ULOC_FULLNAME_CAPACITY];
14079 icu_locale, icu_base_locale, ULOC_FULLNAME_CAPACITY, &error);
14081 // Convert from ICU locale format to BCP47 format.
14082 // de_Latn_DE -> de-Latn-DE
14083 char base_max_locale[ULOC_FULLNAME_CAPACITY];
14084 uloc_toLanguageTag(icu_base_max_locale, base_max_locale,
14085 ULOC_FULLNAME_CAPACITY, FALSE, &error);
14088 char base_locale[ULOC_FULLNAME_CAPACITY];
14089 uloc_toLanguageTag(
14090 icu_base_locale, base_locale, ULOC_FULLNAME_CAPACITY, FALSE, &error);
14092 if (U_FAILURE(error)) {
14093 return isolate->Throw(*factory->illegal_argument_string());
14096 Handle<JSObject> result = factory->NewJSObject(isolate->object_function());
14097 Handle<String> value = factory->NewStringFromAsciiChecked(base_max_locale);
14098 JSObject::AddProperty(result, maximized, value, NONE);
14099 value = factory->NewStringFromAsciiChecked(base_locale);
14100 JSObject::AddProperty(result, base, value, NONE);
14101 output->set(i, *result);
14104 Handle<JSArray> result = factory->NewJSArrayWithElements(output);
14105 result->set_length(Smi::FromInt(length));
14110 RUNTIME_FUNCTION(Runtime_IsInitializedIntlObject) {
14111 HandleScope scope(isolate);
14113 DCHECK(args.length() == 1);
14115 CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
14117 if (!input->IsJSObject()) return isolate->heap()->false_value();
14118 Handle<JSObject> obj = Handle<JSObject>::cast(input);
14120 Handle<String> marker = isolate->factory()->intl_initialized_marker_string();
14121 Handle<Object> tag(obj->GetHiddenProperty(marker), isolate);
14122 return isolate->heap()->ToBoolean(!tag->IsTheHole());
14126 RUNTIME_FUNCTION(Runtime_IsInitializedIntlObjectOfType) {
14127 HandleScope scope(isolate);
14129 DCHECK(args.length() == 2);
14131 CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
14132 CONVERT_ARG_HANDLE_CHECKED(String, expected_type, 1);
14134 if (!input->IsJSObject()) return isolate->heap()->false_value();
14135 Handle<JSObject> obj = Handle<JSObject>::cast(input);
14137 Handle<String> marker = isolate->factory()->intl_initialized_marker_string();
14138 Handle<Object> tag(obj->GetHiddenProperty(marker), isolate);
14139 return isolate->heap()->ToBoolean(
14140 tag->IsString() && String::cast(*tag)->Equals(*expected_type));
14144 RUNTIME_FUNCTION(Runtime_MarkAsInitializedIntlObjectOfType) {
14145 HandleScope scope(isolate);
14147 DCHECK(args.length() == 3);
14149 CONVERT_ARG_HANDLE_CHECKED(JSObject, input, 0);
14150 CONVERT_ARG_HANDLE_CHECKED(String, type, 1);
14151 CONVERT_ARG_HANDLE_CHECKED(JSObject, impl, 2);
14153 Handle<String> marker = isolate->factory()->intl_initialized_marker_string();
14154 JSObject::SetHiddenProperty(input, marker, type);
14156 marker = isolate->factory()->intl_impl_object_string();
14157 JSObject::SetHiddenProperty(input, marker, impl);
14159 return isolate->heap()->undefined_value();
14163 RUNTIME_FUNCTION(Runtime_GetImplFromInitializedIntlObject) {
14164 HandleScope scope(isolate);
14166 DCHECK(args.length() == 1);
14168 CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
14170 if (!input->IsJSObject()) {
14171 Vector< Handle<Object> > arguments = HandleVector(&input, 1);
14172 THROW_NEW_ERROR_RETURN_FAILURE(isolate,
14173 NewTypeError("not_intl_object", arguments));
14176 Handle<JSObject> obj = Handle<JSObject>::cast(input);
14178 Handle<String> marker = isolate->factory()->intl_impl_object_string();
14179 Handle<Object> impl(obj->GetHiddenProperty(marker), isolate);
14180 if (impl->IsTheHole()) {
14181 Vector< Handle<Object> > arguments = HandleVector(&obj, 1);
14182 THROW_NEW_ERROR_RETURN_FAILURE(isolate,
14183 NewTypeError("not_intl_object", arguments));
14189 RUNTIME_FUNCTION(Runtime_CreateDateTimeFormat) {
14190 HandleScope scope(isolate);
14192 DCHECK(args.length() == 3);
14194 CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14195 CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14196 CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14198 Handle<ObjectTemplateInfo> date_format_template =
14199 I18N::GetTemplate(isolate);
14201 // Create an empty object wrapper.
14202 Handle<JSObject> local_object;
14203 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14204 isolate, local_object,
14205 Execution::InstantiateObject(date_format_template));
14207 // Set date time formatter as internal field of the resulting JS object.
14208 icu::SimpleDateFormat* date_format = DateFormat::InitializeDateTimeFormat(
14209 isolate, locale, options, resolved);
14211 if (!date_format) return isolate->ThrowIllegalOperation();
14213 local_object->SetInternalField(0, reinterpret_cast<Smi*>(date_format));
14215 Factory* factory = isolate->factory();
14216 Handle<String> key = factory->NewStringFromStaticChars("dateFormat");
14217 Handle<String> value = factory->NewStringFromStaticChars("valid");
14218 JSObject::AddProperty(local_object, key, value, NONE);
14220 // Make object handle weak so we can delete the data format once GC kicks in.
14221 Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14222 GlobalHandles::MakeWeak(wrapper.location(),
14223 reinterpret_cast<void*>(wrapper.location()),
14224 DateFormat::DeleteDateFormat);
14225 return *local_object;
14229 RUNTIME_FUNCTION(Runtime_InternalDateFormat) {
14230 HandleScope scope(isolate);
14232 DCHECK(args.length() == 2);
14234 CONVERT_ARG_HANDLE_CHECKED(JSObject, date_format_holder, 0);
14235 CONVERT_ARG_HANDLE_CHECKED(JSDate, date, 1);
14237 Handle<Object> value;
14238 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14239 isolate, value, Execution::ToNumber(isolate, date));
14241 icu::SimpleDateFormat* date_format =
14242 DateFormat::UnpackDateFormat(isolate, date_format_holder);
14243 if (!date_format) return isolate->ThrowIllegalOperation();
14245 icu::UnicodeString result;
14246 date_format->format(value->Number(), result);
14248 Handle<String> result_str;
14249 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14250 isolate, result_str,
14251 isolate->factory()->NewStringFromTwoByte(
14252 Vector<const uint16_t>(
14253 reinterpret_cast<const uint16_t*>(result.getBuffer()),
14254 result.length())));
14255 return *result_str;
14259 RUNTIME_FUNCTION(Runtime_InternalDateParse) {
14260 HandleScope scope(isolate);
14262 DCHECK(args.length() == 2);
14264 CONVERT_ARG_HANDLE_CHECKED(JSObject, date_format_holder, 0);
14265 CONVERT_ARG_HANDLE_CHECKED(String, date_string, 1);
14267 v8::String::Utf8Value utf8_date(v8::Utils::ToLocal(date_string));
14268 icu::UnicodeString u_date(icu::UnicodeString::fromUTF8(*utf8_date));
14269 icu::SimpleDateFormat* date_format =
14270 DateFormat::UnpackDateFormat(isolate, date_format_holder);
14271 if (!date_format) return isolate->ThrowIllegalOperation();
14273 UErrorCode status = U_ZERO_ERROR;
14274 UDate date = date_format->parse(u_date, status);
14275 if (U_FAILURE(status)) return isolate->heap()->undefined_value();
14277 Handle<Object> result;
14278 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14280 Execution::NewDate(isolate, static_cast<double>(date)));
14281 DCHECK(result->IsJSDate());
14286 RUNTIME_FUNCTION(Runtime_CreateNumberFormat) {
14287 HandleScope scope(isolate);
14289 DCHECK(args.length() == 3);
14291 CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14292 CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14293 CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14295 Handle<ObjectTemplateInfo> number_format_template =
14296 I18N::GetTemplate(isolate);
14298 // Create an empty object wrapper.
14299 Handle<JSObject> local_object;
14300 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14301 isolate, local_object,
14302 Execution::InstantiateObject(number_format_template));
14304 // Set number formatter as internal field of the resulting JS object.
14305 icu::DecimalFormat* number_format = NumberFormat::InitializeNumberFormat(
14306 isolate, locale, options, resolved);
14308 if (!number_format) return isolate->ThrowIllegalOperation();
14310 local_object->SetInternalField(0, reinterpret_cast<Smi*>(number_format));
14312 Factory* factory = isolate->factory();
14313 Handle<String> key = factory->NewStringFromStaticChars("numberFormat");
14314 Handle<String> value = factory->NewStringFromStaticChars("valid");
14315 JSObject::AddProperty(local_object, key, value, NONE);
14317 Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14318 GlobalHandles::MakeWeak(wrapper.location(),
14319 reinterpret_cast<void*>(wrapper.location()),
14320 NumberFormat::DeleteNumberFormat);
14321 return *local_object;
14325 RUNTIME_FUNCTION(Runtime_InternalNumberFormat) {
14326 HandleScope scope(isolate);
14328 DCHECK(args.length() == 2);
14330 CONVERT_ARG_HANDLE_CHECKED(JSObject, number_format_holder, 0);
14331 CONVERT_ARG_HANDLE_CHECKED(Object, number, 1);
14333 Handle<Object> value;
14334 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14335 isolate, value, Execution::ToNumber(isolate, number));
14337 icu::DecimalFormat* number_format =
14338 NumberFormat::UnpackNumberFormat(isolate, number_format_holder);
14339 if (!number_format) return isolate->ThrowIllegalOperation();
14341 icu::UnicodeString result;
14342 number_format->format(value->Number(), result);
14344 Handle<String> result_str;
14345 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14346 isolate, result_str,
14347 isolate->factory()->NewStringFromTwoByte(
14348 Vector<const uint16_t>(
14349 reinterpret_cast<const uint16_t*>(result.getBuffer()),
14350 result.length())));
14351 return *result_str;
14355 RUNTIME_FUNCTION(Runtime_InternalNumberParse) {
14356 HandleScope scope(isolate);
14358 DCHECK(args.length() == 2);
14360 CONVERT_ARG_HANDLE_CHECKED(JSObject, number_format_holder, 0);
14361 CONVERT_ARG_HANDLE_CHECKED(String, number_string, 1);
14363 v8::String::Utf8Value utf8_number(v8::Utils::ToLocal(number_string));
14364 icu::UnicodeString u_number(icu::UnicodeString::fromUTF8(*utf8_number));
14365 icu::DecimalFormat* number_format =
14366 NumberFormat::UnpackNumberFormat(isolate, number_format_holder);
14367 if (!number_format) return isolate->ThrowIllegalOperation();
14369 UErrorCode status = U_ZERO_ERROR;
14370 icu::Formattable result;
14371 // ICU 4.6 doesn't support parseCurrency call. We need to wait for ICU49
14372 // to be part of Chrome.
14373 // TODO(cira): Include currency parsing code using parseCurrency call.
14374 // We need to check if the formatter parses all currencies or only the
14375 // one it was constructed with (it will impact the API - how to return ISO
14376 // code and the value).
14377 number_format->parse(u_number, result, status);
14378 if (U_FAILURE(status)) return isolate->heap()->undefined_value();
14380 switch (result.getType()) {
14381 case icu::Formattable::kDouble:
14382 return *isolate->factory()->NewNumber(result.getDouble());
14383 case icu::Formattable::kLong:
14384 return *isolate->factory()->NewNumberFromInt(result.getLong());
14385 case icu::Formattable::kInt64:
14386 return *isolate->factory()->NewNumber(
14387 static_cast<double>(result.getInt64()));
14389 return isolate->heap()->undefined_value();
14394 RUNTIME_FUNCTION(Runtime_CreateCollator) {
14395 HandleScope scope(isolate);
14397 DCHECK(args.length() == 3);
14399 CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14400 CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14401 CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14403 Handle<ObjectTemplateInfo> collator_template = I18N::GetTemplate(isolate);
14405 // Create an empty object wrapper.
14406 Handle<JSObject> local_object;
14407 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14408 isolate, local_object, Execution::InstantiateObject(collator_template));
14410 // Set collator as internal field of the resulting JS object.
14411 icu::Collator* collator = Collator::InitializeCollator(
14412 isolate, locale, options, resolved);
14414 if (!collator) return isolate->ThrowIllegalOperation();
14416 local_object->SetInternalField(0, reinterpret_cast<Smi*>(collator));
14418 Factory* factory = isolate->factory();
14419 Handle<String> key = factory->NewStringFromStaticChars("collator");
14420 Handle<String> value = factory->NewStringFromStaticChars("valid");
14421 JSObject::AddProperty(local_object, key, value, NONE);
14423 Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14424 GlobalHandles::MakeWeak(wrapper.location(),
14425 reinterpret_cast<void*>(wrapper.location()),
14426 Collator::DeleteCollator);
14427 return *local_object;
14431 RUNTIME_FUNCTION(Runtime_InternalCompare) {
14432 HandleScope scope(isolate);
14434 DCHECK(args.length() == 3);
14436 CONVERT_ARG_HANDLE_CHECKED(JSObject, collator_holder, 0);
14437 CONVERT_ARG_HANDLE_CHECKED(String, string1, 1);
14438 CONVERT_ARG_HANDLE_CHECKED(String, string2, 2);
14440 icu::Collator* collator = Collator::UnpackCollator(isolate, collator_holder);
14441 if (!collator) return isolate->ThrowIllegalOperation();
14443 v8::String::Value string_value1(v8::Utils::ToLocal(string1));
14444 v8::String::Value string_value2(v8::Utils::ToLocal(string2));
14445 const UChar* u_string1 = reinterpret_cast<const UChar*>(*string_value1);
14446 const UChar* u_string2 = reinterpret_cast<const UChar*>(*string_value2);
14447 UErrorCode status = U_ZERO_ERROR;
14448 UCollationResult result = collator->compare(u_string1,
14449 string_value1.length(),
14451 string_value2.length(),
14453 if (U_FAILURE(status)) return isolate->ThrowIllegalOperation();
14455 return *isolate->factory()->NewNumberFromInt(result);
14459 RUNTIME_FUNCTION(Runtime_StringNormalize) {
14460 HandleScope scope(isolate);
14461 static const UNormalizationMode normalizationForms[] =
14462 { UNORM_NFC, UNORM_NFD, UNORM_NFKC, UNORM_NFKD };
14464 DCHECK(args.length() == 2);
14466 CONVERT_ARG_HANDLE_CHECKED(String, stringValue, 0);
14467 CONVERT_NUMBER_CHECKED(int, form_id, Int32, args[1]);
14468 RUNTIME_ASSERT(form_id >= 0 &&
14469 static_cast<size_t>(form_id) < arraysize(normalizationForms));
14471 v8::String::Value string_value(v8::Utils::ToLocal(stringValue));
14472 const UChar* u_value = reinterpret_cast<const UChar*>(*string_value);
14474 // TODO(mnita): check Normalizer2 (not available in ICU 46)
14475 UErrorCode status = U_ZERO_ERROR;
14476 icu::UnicodeString result;
14477 icu::Normalizer::normalize(u_value, normalizationForms[form_id], 0,
14479 if (U_FAILURE(status)) {
14480 return isolate->heap()->undefined_value();
14483 Handle<String> result_str;
14484 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14485 isolate, result_str,
14486 isolate->factory()->NewStringFromTwoByte(
14487 Vector<const uint16_t>(
14488 reinterpret_cast<const uint16_t*>(result.getBuffer()),
14489 result.length())));
14490 return *result_str;
14494 RUNTIME_FUNCTION(Runtime_CreateBreakIterator) {
14495 HandleScope scope(isolate);
14497 DCHECK(args.length() == 3);
14499 CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
14500 CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
14501 CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
14503 Handle<ObjectTemplateInfo> break_iterator_template =
14504 I18N::GetTemplate2(isolate);
14506 // Create an empty object wrapper.
14507 Handle<JSObject> local_object;
14508 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14509 isolate, local_object,
14510 Execution::InstantiateObject(break_iterator_template));
14512 // Set break iterator as internal field of the resulting JS object.
14513 icu::BreakIterator* break_iterator = BreakIterator::InitializeBreakIterator(
14514 isolate, locale, options, resolved);
14516 if (!break_iterator) return isolate->ThrowIllegalOperation();
14518 local_object->SetInternalField(0, reinterpret_cast<Smi*>(break_iterator));
14519 // Make sure that the pointer to adopted text is NULL.
14520 local_object->SetInternalField(1, reinterpret_cast<Smi*>(NULL));
14522 Factory* factory = isolate->factory();
14523 Handle<String> key = factory->NewStringFromStaticChars("breakIterator");
14524 Handle<String> value = factory->NewStringFromStaticChars("valid");
14525 JSObject::AddProperty(local_object, key, value, NONE);
14527 // Make object handle weak so we can delete the break iterator once GC kicks
14529 Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
14530 GlobalHandles::MakeWeak(wrapper.location(),
14531 reinterpret_cast<void*>(wrapper.location()),
14532 BreakIterator::DeleteBreakIterator);
14533 return *local_object;
14537 RUNTIME_FUNCTION(Runtime_BreakIteratorAdoptText) {
14538 HandleScope scope(isolate);
14540 DCHECK(args.length() == 2);
14542 CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14543 CONVERT_ARG_HANDLE_CHECKED(String, text, 1);
14545 icu::BreakIterator* break_iterator =
14546 BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14547 if (!break_iterator) return isolate->ThrowIllegalOperation();
14549 icu::UnicodeString* u_text = reinterpret_cast<icu::UnicodeString*>(
14550 break_iterator_holder->GetInternalField(1));
14553 v8::String::Value text_value(v8::Utils::ToLocal(text));
14554 u_text = new icu::UnicodeString(
14555 reinterpret_cast<const UChar*>(*text_value), text_value.length());
14556 break_iterator_holder->SetInternalField(1, reinterpret_cast<Smi*>(u_text));
14558 break_iterator->setText(*u_text);
14560 return isolate->heap()->undefined_value();
14564 RUNTIME_FUNCTION(Runtime_BreakIteratorFirst) {
14565 HandleScope scope(isolate);
14567 DCHECK(args.length() == 1);
14569 CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14571 icu::BreakIterator* break_iterator =
14572 BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14573 if (!break_iterator) return isolate->ThrowIllegalOperation();
14575 return *isolate->factory()->NewNumberFromInt(break_iterator->first());
14579 RUNTIME_FUNCTION(Runtime_BreakIteratorNext) {
14580 HandleScope scope(isolate);
14582 DCHECK(args.length() == 1);
14584 CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14586 icu::BreakIterator* break_iterator =
14587 BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14588 if (!break_iterator) return isolate->ThrowIllegalOperation();
14590 return *isolate->factory()->NewNumberFromInt(break_iterator->next());
14594 RUNTIME_FUNCTION(Runtime_BreakIteratorCurrent) {
14595 HandleScope scope(isolate);
14597 DCHECK(args.length() == 1);
14599 CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14601 icu::BreakIterator* break_iterator =
14602 BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14603 if (!break_iterator) return isolate->ThrowIllegalOperation();
14605 return *isolate->factory()->NewNumberFromInt(break_iterator->current());
14609 RUNTIME_FUNCTION(Runtime_BreakIteratorBreakType) {
14610 HandleScope scope(isolate);
14612 DCHECK(args.length() == 1);
14614 CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
14616 icu::BreakIterator* break_iterator =
14617 BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
14618 if (!break_iterator) return isolate->ThrowIllegalOperation();
14620 // TODO(cira): Remove cast once ICU fixes base BreakIterator class.
14621 icu::RuleBasedBreakIterator* rule_based_iterator =
14622 static_cast<icu::RuleBasedBreakIterator*>(break_iterator);
14623 int32_t status = rule_based_iterator->getRuleStatus();
14624 // Keep return values in sync with JavaScript BreakType enum.
14625 if (status >= UBRK_WORD_NONE && status < UBRK_WORD_NONE_LIMIT) {
14626 return *isolate->factory()->NewStringFromStaticChars("none");
14627 } else if (status >= UBRK_WORD_NUMBER && status < UBRK_WORD_NUMBER_LIMIT) {
14628 return *isolate->factory()->number_string();
14629 } else if (status >= UBRK_WORD_LETTER && status < UBRK_WORD_LETTER_LIMIT) {
14630 return *isolate->factory()->NewStringFromStaticChars("letter");
14631 } else if (status >= UBRK_WORD_KANA && status < UBRK_WORD_KANA_LIMIT) {
14632 return *isolate->factory()->NewStringFromStaticChars("kana");
14633 } else if (status >= UBRK_WORD_IDEO && status < UBRK_WORD_IDEO_LIMIT) {
14634 return *isolate->factory()->NewStringFromStaticChars("ideo");
14636 return *isolate->factory()->NewStringFromStaticChars("unknown");
14639 #endif // V8_I18N_SUPPORT
14642 // Finds the script object from the script data. NOTE: This operation uses
14643 // heap traversal to find the function generated for the source position
14644 // for the requested break point. For lazily compiled functions several heap
14645 // traversals might be required rendering this operation as a rather slow
14646 // operation. However for setting break points which is normally done through
14647 // some kind of user interaction the performance is not crucial.
14648 static Handle<Object> Runtime_GetScriptFromScriptName(
14649 Handle<String> script_name) {
14650 // Scan the heap for Script objects to find the script with the requested
14652 Handle<Script> script;
14653 Factory* factory = script_name->GetIsolate()->factory();
14654 Heap* heap = script_name->GetHeap();
14655 HeapIterator iterator(heap);
14656 HeapObject* obj = NULL;
14657 while (script.is_null() && ((obj = iterator.next()) != NULL)) {
14658 // If a script is found check if it has the script data requested.
14659 if (obj->IsScript()) {
14660 if (Script::cast(obj)->name()->IsString()) {
14661 if (String::cast(Script::cast(obj)->name())->Equals(*script_name)) {
14662 script = Handle<Script>(Script::cast(obj));
14668 // If no script with the requested script data is found return undefined.
14669 if (script.is_null()) return factory->undefined_value();
14671 // Return the script found.
14672 return Script::GetWrapper(script);
14676 // Get the script object from script data. NOTE: Regarding performance
14677 // see the NOTE for GetScriptFromScriptData.
14678 // args[0]: script data for the script to find the source for
14679 RUNTIME_FUNCTION(Runtime_GetScript) {
14680 HandleScope scope(isolate);
14682 DCHECK(args.length() == 1);
14684 CONVERT_ARG_CHECKED(String, script_name, 0);
14686 // Find the requested script.
14687 Handle<Object> result =
14688 Runtime_GetScriptFromScriptName(Handle<String>(script_name));
14693 // Collect the raw data for a stack trace. Returns an array of 4
14694 // element segments each containing a receiver, function, code and
14695 // native code offset.
14696 RUNTIME_FUNCTION(Runtime_CollectStackTrace) {
14697 HandleScope scope(isolate);
14698 DCHECK(args.length() == 2);
14699 CONVERT_ARG_HANDLE_CHECKED(JSObject, error_object, 0);
14700 CONVERT_ARG_HANDLE_CHECKED(Object, caller, 1);
14702 if (!isolate->bootstrapper()->IsActive()) {
14703 // Optionally capture a more detailed stack trace for the message.
14704 isolate->CaptureAndSetDetailedStackTrace(error_object);
14705 // Capture a simple stack trace for the stack property.
14706 isolate->CaptureAndSetSimpleStackTrace(error_object, caller);
14708 return isolate->heap()->undefined_value();
14712 // Returns V8 version as a string.
14713 RUNTIME_FUNCTION(Runtime_GetV8Version) {
14714 HandleScope scope(isolate);
14715 DCHECK(args.length() == 0);
14717 const char* version_string = v8::V8::GetVersion();
14719 return *isolate->factory()->NewStringFromAsciiChecked(version_string);
14723 // Returns function of generator activation.
14724 RUNTIME_FUNCTION(Runtime_GeneratorGetFunction) {
14725 HandleScope scope(isolate);
14726 DCHECK(args.length() == 1);
14727 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14729 return generator->function();
14733 // Returns context of generator activation.
14734 RUNTIME_FUNCTION(Runtime_GeneratorGetContext) {
14735 HandleScope scope(isolate);
14736 DCHECK(args.length() == 1);
14737 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14739 return generator->context();
14743 // Returns receiver of generator activation.
14744 RUNTIME_FUNCTION(Runtime_GeneratorGetReceiver) {
14745 HandleScope scope(isolate);
14746 DCHECK(args.length() == 1);
14747 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14749 return generator->receiver();
14753 // Returns generator continuation as a PC offset, or the magic -1 or 0 values.
14754 RUNTIME_FUNCTION(Runtime_GeneratorGetContinuation) {
14755 HandleScope scope(isolate);
14756 DCHECK(args.length() == 1);
14757 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14759 return Smi::FromInt(generator->continuation());
14763 RUNTIME_FUNCTION(Runtime_GeneratorGetSourcePosition) {
14764 HandleScope scope(isolate);
14765 DCHECK(args.length() == 1);
14766 CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
14768 if (generator->is_suspended()) {
14769 Handle<Code> code(generator->function()->code(), isolate);
14770 int offset = generator->continuation();
14772 RUNTIME_ASSERT(0 <= offset && offset < code->Size());
14773 Address pc = code->address() + offset;
14775 return Smi::FromInt(code->SourcePosition(pc));
14778 return isolate->heap()->undefined_value();
14782 RUNTIME_FUNCTION(Runtime_Abort) {
14783 SealHandleScope shs(isolate);
14784 DCHECK(args.length() == 1);
14785 CONVERT_SMI_ARG_CHECKED(message_id, 0);
14786 const char* message = GetBailoutReason(
14787 static_cast<BailoutReason>(message_id));
14788 base::OS::PrintError("abort: %s\n", message);
14789 isolate->PrintStack(stderr);
14796 RUNTIME_FUNCTION(Runtime_AbortJS) {
14797 HandleScope scope(isolate);
14798 DCHECK(args.length() == 1);
14799 CONVERT_ARG_HANDLE_CHECKED(String, message, 0);
14800 base::OS::PrintError("abort: %s\n", message->ToCString().get());
14801 isolate->PrintStack(stderr);
14808 RUNTIME_FUNCTION(Runtime_FlattenString) {
14809 HandleScope scope(isolate);
14810 DCHECK(args.length() == 1);
14811 CONVERT_ARG_HANDLE_CHECKED(String, str, 0);
14812 return *String::Flatten(str);
14816 RUNTIME_FUNCTION(Runtime_NotifyContextDisposed) {
14817 HandleScope scope(isolate);
14818 DCHECK(args.length() == 0);
14819 isolate->heap()->NotifyContextDisposed();
14820 return isolate->heap()->undefined_value();
14824 RUNTIME_FUNCTION(Runtime_LoadMutableDouble) {
14825 HandleScope scope(isolate);
14826 DCHECK(args.length() == 2);
14827 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
14828 CONVERT_ARG_HANDLE_CHECKED(Smi, index, 1);
14829 RUNTIME_ASSERT((index->value() & 1) == 1);
14830 FieldIndex field_index =
14831 FieldIndex::ForLoadByFieldIndex(object->map(), index->value());
14832 if (field_index.is_inobject()) {
14833 RUNTIME_ASSERT(field_index.property_index() <
14834 object->map()->inobject_properties());
14836 RUNTIME_ASSERT(field_index.outobject_array_index() <
14837 object->properties()->length());
14839 Handle<Object> raw_value(object->RawFastPropertyAt(field_index), isolate);
14840 RUNTIME_ASSERT(raw_value->IsMutableHeapNumber());
14841 return *Object::WrapForRead(isolate, raw_value, Representation::Double());
14845 RUNTIME_FUNCTION(Runtime_TryMigrateInstance) {
14846 HandleScope scope(isolate);
14847 DCHECK(args.length() == 1);
14848 CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
14849 if (!object->IsJSObject()) return Smi::FromInt(0);
14850 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
14851 if (!js_object->map()->is_deprecated()) return Smi::FromInt(0);
14852 // This call must not cause lazy deopts, because it's called from deferred
14853 // code where we can't handle lazy deopts for lack of a suitable bailout
14854 // ID. So we just try migration and signal failure if necessary,
14855 // which will also trigger a deopt.
14856 if (!JSObject::TryMigrateInstance(js_object)) return Smi::FromInt(0);
14861 RUNTIME_FUNCTION(Runtime_GetFromCache) {
14862 SealHandleScope shs(isolate);
14863 // This is only called from codegen, so checks might be more lax.
14864 CONVERT_ARG_CHECKED(JSFunctionResultCache, cache, 0);
14865 CONVERT_ARG_CHECKED(Object, key, 1);
14868 DisallowHeapAllocation no_alloc;
14870 int finger_index = cache->finger_index();
14871 Object* o = cache->get(finger_index);
14873 // The fastest case: hit the same place again.
14874 return cache->get(finger_index + 1);
14877 for (int i = finger_index - 2;
14878 i >= JSFunctionResultCache::kEntriesIndex;
14882 cache->set_finger_index(i);
14883 return cache->get(i + 1);
14887 int size = cache->size();
14888 DCHECK(size <= cache->length());
14890 for (int i = size - 2; i > finger_index; i -= 2) {
14893 cache->set_finger_index(i);
14894 return cache->get(i + 1);
14899 // There is no value in the cache. Invoke the function and cache result.
14900 HandleScope scope(isolate);
14902 Handle<JSFunctionResultCache> cache_handle(cache);
14903 Handle<Object> key_handle(key, isolate);
14904 Handle<Object> value;
14906 Handle<JSFunction> factory(JSFunction::cast(
14907 cache_handle->get(JSFunctionResultCache::kFactoryIndex)));
14908 // TODO(antonm): consider passing a receiver when constructing a cache.
14909 Handle<JSObject> receiver(isolate->global_proxy());
14910 // This handle is nor shared, nor used later, so it's safe.
14911 Handle<Object> argv[] = { key_handle };
14912 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
14914 Execution::Call(isolate, factory, receiver, arraysize(argv), argv));
14918 if (FLAG_verify_heap) {
14919 cache_handle->JSFunctionResultCacheVerify();
14923 // Function invocation may have cleared the cache. Reread all the data.
14924 int finger_index = cache_handle->finger_index();
14925 int size = cache_handle->size();
14927 // If we have spare room, put new data into it, otherwise evict post finger
14928 // entry which is likely to be the least recently used.
14930 if (size < cache_handle->length()) {
14931 cache_handle->set_size(size + JSFunctionResultCache::kEntrySize);
14934 index = finger_index + JSFunctionResultCache::kEntrySize;
14935 if (index == cache_handle->length()) {
14936 index = JSFunctionResultCache::kEntriesIndex;
14940 DCHECK(index % 2 == 0);
14941 DCHECK(index >= JSFunctionResultCache::kEntriesIndex);
14942 DCHECK(index < cache_handle->length());
14944 cache_handle->set(index, *key_handle);
14945 cache_handle->set(index + 1, *value);
14946 cache_handle->set_finger_index(index);
14949 if (FLAG_verify_heap) {
14950 cache_handle->JSFunctionResultCacheVerify();
14958 RUNTIME_FUNCTION(Runtime_MessageGetStartPosition) {
14959 SealHandleScope shs(isolate);
14960 DCHECK(args.length() == 1);
14961 CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
14962 return Smi::FromInt(message->start_position());
14966 RUNTIME_FUNCTION(Runtime_MessageGetScript) {
14967 SealHandleScope shs(isolate);
14968 DCHECK(args.length() == 1);
14969 CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
14970 return message->script();
14975 // ListNatives is ONLY used by the fuzz-natives.js in debug mode
14976 // Exclude the code in release mode.
14977 RUNTIME_FUNCTION(Runtime_ListNatives) {
14978 HandleScope scope(isolate);
14979 DCHECK(args.length() == 0);
14980 #define COUNT_ENTRY(Name, argc, ressize) + 1
14981 int entry_count = 0
14982 RUNTIME_FUNCTION_LIST(COUNT_ENTRY)
14983 INLINE_FUNCTION_LIST(COUNT_ENTRY)
14984 INLINE_OPTIMIZED_FUNCTION_LIST(COUNT_ENTRY);
14986 Factory* factory = isolate->factory();
14987 Handle<FixedArray> elements = factory->NewFixedArray(entry_count);
14989 bool inline_runtime_functions = false;
14990 #define ADD_ENTRY(Name, argc, ressize) \
14992 HandleScope inner(isolate); \
14993 Handle<String> name; \
14994 /* Inline runtime functions have an underscore in front of the name. */ \
14995 if (inline_runtime_functions) { \
14996 name = factory->NewStringFromStaticChars("_" #Name); \
14998 name = factory->NewStringFromStaticChars(#Name); \
15000 Handle<FixedArray> pair_elements = factory->NewFixedArray(2); \
15001 pair_elements->set(0, *name); \
15002 pair_elements->set(1, Smi::FromInt(argc)); \
15003 Handle<JSArray> pair = factory->NewJSArrayWithElements(pair_elements); \
15004 elements->set(index++, *pair); \
15006 inline_runtime_functions = false;
15007 RUNTIME_FUNCTION_LIST(ADD_ENTRY)
15008 INLINE_OPTIMIZED_FUNCTION_LIST(ADD_ENTRY)
15009 inline_runtime_functions = true;
15010 INLINE_FUNCTION_LIST(ADD_ENTRY)
15012 DCHECK_EQ(index, entry_count);
15013 Handle<JSArray> result = factory->NewJSArrayWithElements(elements);
15019 RUNTIME_FUNCTION(Runtime_IS_VAR) {
15020 UNREACHABLE(); // implemented as macro in the parser
15025 #define ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(Name) \
15026 RUNTIME_FUNCTION(Runtime_Has##Name) { \
15027 CONVERT_ARG_CHECKED(JSObject, obj, 0); \
15028 return isolate->heap()->ToBoolean(obj->Has##Name()); \
15031 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastSmiElements)
15032 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastObjectElements)
15033 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastSmiOrObjectElements)
15034 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastDoubleElements)
15035 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastHoleyElements)
15036 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(DictionaryElements)
15037 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(SloppyArgumentsElements)
15038 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(ExternalArrayElements)
15039 // Properties test sitting with elements tests - not fooling anyone.
15040 ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION(FastProperties)
15042 #undef ELEMENTS_KIND_CHECK_RUNTIME_FUNCTION
15045 #define TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, size) \
15046 RUNTIME_FUNCTION(Runtime_HasExternal##Type##Elements) { \
15047 CONVERT_ARG_CHECKED(JSObject, obj, 0); \
15048 return isolate->heap()->ToBoolean(obj->HasExternal##Type##Elements()); \
15051 TYPED_ARRAYS(TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION)
15053 #undef TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
15056 #define FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, s) \
15057 RUNTIME_FUNCTION(Runtime_HasFixed##Type##Elements) { \
15058 CONVERT_ARG_CHECKED(JSObject, obj, 0); \
15059 return isolate->heap()->ToBoolean(obj->HasFixed##Type##Elements()); \
15062 TYPED_ARRAYS(FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION)
15064 #undef FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
15067 RUNTIME_FUNCTION(Runtime_HaveSameMap) {
15068 SealHandleScope shs(isolate);
15069 DCHECK(args.length() == 2);
15070 CONVERT_ARG_CHECKED(JSObject, obj1, 0);
15071 CONVERT_ARG_CHECKED(JSObject, obj2, 1);
15072 return isolate->heap()->ToBoolean(obj1->map() == obj2->map());
15076 RUNTIME_FUNCTION(Runtime_IsJSGlobalProxy) {
15077 SealHandleScope shs(isolate);
15078 DCHECK(args.length() == 1);
15079 CONVERT_ARG_CHECKED(Object, obj, 0);
15080 return isolate->heap()->ToBoolean(obj->IsJSGlobalProxy());
15084 RUNTIME_FUNCTION(Runtime_IsObserved) {
15085 SealHandleScope shs(isolate);
15086 DCHECK(args.length() == 1);
15088 if (!args[0]->IsJSReceiver()) return isolate->heap()->false_value();
15089 CONVERT_ARG_CHECKED(JSReceiver, obj, 0);
15090 DCHECK(!obj->IsJSGlobalProxy() || !obj->map()->is_observed());
15091 return isolate->heap()->ToBoolean(obj->map()->is_observed());
15095 RUNTIME_FUNCTION(Runtime_SetIsObserved) {
15096 HandleScope scope(isolate);
15097 DCHECK(args.length() == 1);
15098 CONVERT_ARG_HANDLE_CHECKED(JSReceiver, obj, 0);
15099 RUNTIME_ASSERT(!obj->IsJSGlobalProxy());
15100 if (obj->IsJSProxy()) return isolate->heap()->undefined_value();
15101 RUNTIME_ASSERT(!obj->map()->is_observed());
15103 DCHECK(obj->IsJSObject());
15104 JSObject::SetObserved(Handle<JSObject>::cast(obj));
15105 return isolate->heap()->undefined_value();
15109 RUNTIME_FUNCTION(Runtime_EnqueueMicrotask) {
15110 HandleScope scope(isolate);
15111 DCHECK(args.length() == 1);
15112 CONVERT_ARG_HANDLE_CHECKED(JSFunction, microtask, 0);
15113 isolate->EnqueueMicrotask(microtask);
15114 return isolate->heap()->undefined_value();
15118 RUNTIME_FUNCTION(Runtime_RunMicrotasks) {
15119 HandleScope scope(isolate);
15120 DCHECK(args.length() == 0);
15121 isolate->RunMicrotasks();
15122 return isolate->heap()->undefined_value();
15126 RUNTIME_FUNCTION(Runtime_GetObservationState) {
15127 SealHandleScope shs(isolate);
15128 DCHECK(args.length() == 0);
15129 return isolate->heap()->observation_state();
15133 RUNTIME_FUNCTION(Runtime_ObservationWeakMapCreate) {
15134 HandleScope scope(isolate);
15135 DCHECK(args.length() == 0);
15136 // TODO(adamk): Currently this runtime function is only called three times per
15137 // isolate. If it's called more often, the map should be moved into the
15138 // strong root list.
15140 isolate->factory()->NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
15141 Handle<JSWeakMap> weakmap =
15142 Handle<JSWeakMap>::cast(isolate->factory()->NewJSObjectFromMap(map));
15143 return *WeakCollectionInitialize(isolate, weakmap);
15147 static bool ContextsHaveSameOrigin(Handle<Context> context1,
15148 Handle<Context> context2) {
15149 return context1->security_token() == context2->security_token();
15153 RUNTIME_FUNCTION(Runtime_ObserverObjectAndRecordHaveSameOrigin) {
15154 HandleScope scope(isolate);
15155 DCHECK(args.length() == 3);
15156 CONVERT_ARG_HANDLE_CHECKED(JSFunction, observer, 0);
15157 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 1);
15158 CONVERT_ARG_HANDLE_CHECKED(JSObject, record, 2);
15160 Handle<Context> observer_context(observer->context()->native_context());
15161 Handle<Context> object_context(object->GetCreationContext());
15162 Handle<Context> record_context(record->GetCreationContext());
15164 return isolate->heap()->ToBoolean(
15165 ContextsHaveSameOrigin(object_context, observer_context) &&
15166 ContextsHaveSameOrigin(object_context, record_context));
15170 RUNTIME_FUNCTION(Runtime_ObjectWasCreatedInCurrentOrigin) {
15171 HandleScope scope(isolate);
15172 DCHECK(args.length() == 1);
15173 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
15175 Handle<Context> creation_context(object->GetCreationContext(), isolate);
15176 return isolate->heap()->ToBoolean(
15177 ContextsHaveSameOrigin(creation_context, isolate->native_context()));
15181 RUNTIME_FUNCTION(Runtime_GetObjectContextObjectObserve) {
15182 HandleScope scope(isolate);
15183 DCHECK(args.length() == 1);
15184 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
15186 Handle<Context> context(object->GetCreationContext(), isolate);
15187 return context->native_object_observe();
15191 RUNTIME_FUNCTION(Runtime_GetObjectContextObjectGetNotifier) {
15192 HandleScope scope(isolate);
15193 DCHECK(args.length() == 1);
15194 CONVERT_ARG_HANDLE_CHECKED(JSObject, object, 0);
15196 Handle<Context> context(object->GetCreationContext(), isolate);
15197 return context->native_object_get_notifier();
15201 RUNTIME_FUNCTION(Runtime_GetObjectContextNotifierPerformChange) {
15202 HandleScope scope(isolate);
15203 DCHECK(args.length() == 1);
15204 CONVERT_ARG_HANDLE_CHECKED(JSObject, object_info, 0);
15206 Handle<Context> context(object_info->GetCreationContext(), isolate);
15207 return context->native_object_notifier_perform_change();
15211 static Object* ArrayConstructorCommon(Isolate* isolate,
15212 Handle<JSFunction> constructor,
15213 Handle<AllocationSite> site,
15214 Arguments* caller_args) {
15215 Factory* factory = isolate->factory();
15217 bool holey = false;
15218 bool can_use_type_feedback = true;
15219 if (caller_args->length() == 1) {
15220 Handle<Object> argument_one = caller_args->at<Object>(0);
15221 if (argument_one->IsSmi()) {
15222 int value = Handle<Smi>::cast(argument_one)->value();
15223 if (value < 0 || value >= JSObject::kInitialMaxFastElementArray) {
15224 // the array is a dictionary in this case.
15225 can_use_type_feedback = false;
15226 } else if (value != 0) {
15230 // Non-smi length argument produces a dictionary
15231 can_use_type_feedback = false;
15235 Handle<JSArray> array;
15236 if (!site.is_null() && can_use_type_feedback) {
15237 ElementsKind to_kind = site->GetElementsKind();
15238 if (holey && !IsFastHoleyElementsKind(to_kind)) {
15239 to_kind = GetHoleyElementsKind(to_kind);
15240 // Update the allocation site info to reflect the advice alteration.
15241 site->SetElementsKind(to_kind);
15244 // We should allocate with an initial map that reflects the allocation site
15245 // advice. Therefore we use AllocateJSObjectFromMap instead of passing
15246 // the constructor.
15247 Handle<Map> initial_map(constructor->initial_map(), isolate);
15248 if (to_kind != initial_map->elements_kind()) {
15249 initial_map = Map::AsElementsKind(initial_map, to_kind);
15252 // If we don't care to track arrays of to_kind ElementsKind, then
15253 // don't emit a memento for them.
15254 Handle<AllocationSite> allocation_site;
15255 if (AllocationSite::GetMode(to_kind) == TRACK_ALLOCATION_SITE) {
15256 allocation_site = site;
15259 array = Handle<JSArray>::cast(factory->NewJSObjectFromMap(
15260 initial_map, NOT_TENURED, true, allocation_site));
15262 array = Handle<JSArray>::cast(factory->NewJSObject(constructor));
15264 // We might need to transition to holey
15265 ElementsKind kind = constructor->initial_map()->elements_kind();
15266 if (holey && !IsFastHoleyElementsKind(kind)) {
15267 kind = GetHoleyElementsKind(kind);
15268 JSObject::TransitionElementsKind(array, kind);
15272 factory->NewJSArrayStorage(array, 0, 0, DONT_INITIALIZE_ARRAY_ELEMENTS);
15274 ElementsKind old_kind = array->GetElementsKind();
15275 RETURN_FAILURE_ON_EXCEPTION(
15276 isolate, ArrayConstructInitializeElements(array, caller_args));
15277 if (!site.is_null() &&
15278 (old_kind != array->GetElementsKind() ||
15279 !can_use_type_feedback)) {
15280 // The arguments passed in caused a transition. This kind of complexity
15281 // can't be dealt with in the inlined hydrogen array constructor case.
15282 // We must mark the allocationsite as un-inlinable.
15283 site->SetDoNotInlineCall();
15289 RUNTIME_FUNCTION(Runtime_ArrayConstructor) {
15290 HandleScope scope(isolate);
15291 // If we get 2 arguments then they are the stub parameters (constructor, type
15292 // info). If we get 4, then the first one is a pointer to the arguments
15293 // passed by the caller, and the last one is the length of the arguments
15294 // passed to the caller (redundant, but useful to check on the deoptimizer
15295 // with an assert).
15296 Arguments empty_args(0, NULL);
15297 bool no_caller_args = args.length() == 2;
15298 DCHECK(no_caller_args || args.length() == 4);
15299 int parameters_start = no_caller_args ? 0 : 1;
15300 Arguments* caller_args = no_caller_args
15302 : reinterpret_cast<Arguments*>(args[0]);
15303 CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start);
15304 CONVERT_ARG_HANDLE_CHECKED(Object, type_info, parameters_start + 1);
15306 if (!no_caller_args) {
15307 CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 2);
15308 DCHECK(arg_count == caller_args->length());
15312 Handle<AllocationSite> site;
15313 if (!type_info.is_null() &&
15314 *type_info != isolate->heap()->undefined_value()) {
15315 site = Handle<AllocationSite>::cast(type_info);
15316 DCHECK(!site->SitePointsToLiteral());
15319 return ArrayConstructorCommon(isolate,
15326 RUNTIME_FUNCTION(Runtime_InternalArrayConstructor) {
15327 HandleScope scope(isolate);
15328 Arguments empty_args(0, NULL);
15329 bool no_caller_args = args.length() == 1;
15330 DCHECK(no_caller_args || args.length() == 3);
15331 int parameters_start = no_caller_args ? 0 : 1;
15332 Arguments* caller_args = no_caller_args
15334 : reinterpret_cast<Arguments*>(args[0]);
15335 CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start);
15337 if (!no_caller_args) {
15338 CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 1);
15339 DCHECK(arg_count == caller_args->length());
15342 return ArrayConstructorCommon(isolate,
15344 Handle<AllocationSite>::null(),
15349 RUNTIME_FUNCTION(Runtime_NormalizeElements) {
15350 HandleScope scope(isolate);
15351 DCHECK(args.length() == 1);
15352 CONVERT_ARG_HANDLE_CHECKED(JSObject, array, 0);
15353 RUNTIME_ASSERT(!array->HasExternalArrayElements() &&
15354 !array->HasFixedTypedArrayElements());
15355 JSObject::NormalizeElements(array);
15360 RUNTIME_FUNCTION(Runtime_MaxSmi) {
15361 SealHandleScope shs(isolate);
15362 DCHECK(args.length() == 0);
15363 return Smi::FromInt(Smi::kMaxValue);
15367 // TODO(dcarney): remove this function when TurboFan supports it.
15368 // Takes the object to be iterated over and the result of GetPropertyNamesFast
15369 // Returns pair (cache_array, cache_type).
15370 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInInit) {
15371 SealHandleScope scope(isolate);
15372 DCHECK(args.length() == 2);
15373 // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs.
15374 // Not worth creating a macro atm as this function should be removed.
15375 if (!args[0]->IsJSReceiver() || !args[1]->IsObject()) {
15376 Object* error = isolate->ThrowIllegalOperation();
15377 return MakePair(error, isolate->heap()->undefined_value());
15379 Handle<JSReceiver> object = args.at<JSReceiver>(0);
15380 Handle<Object> cache_type = args.at<Object>(1);
15381 if (cache_type->IsMap()) {
15382 // Enum cache case.
15383 if (Map::EnumLengthBits::decode(Map::cast(*cache_type)->bit_field3()) ==
15386 // Can't handle this case in the graph builder,
15387 // so transform it into the empty fixed array case.
15388 return MakePair(isolate->heap()->empty_fixed_array(), Smi::FromInt(1));
15390 return MakePair(object->map()->instance_descriptors()->GetEnumCache(),
15393 // FixedArray case.
15394 Smi* new_cache_type = Smi::FromInt(object->IsJSProxy() ? 0 : 1);
15395 return MakePair(*Handle<FixedArray>::cast(cache_type), new_cache_type);
15400 // TODO(dcarney): remove this function when TurboFan supports it.
15401 RUNTIME_FUNCTION(Runtime_ForInCacheArrayLength) {
15402 SealHandleScope shs(isolate);
15403 DCHECK(args.length() == 2);
15404 CONVERT_ARG_HANDLE_CHECKED(Object, cache_type, 0);
15405 CONVERT_ARG_HANDLE_CHECKED(FixedArray, array, 1);
15407 if (cache_type->IsMap()) {
15408 length = Map::cast(*cache_type)->EnumLength();
15410 DCHECK(cache_type->IsSmi());
15411 length = array->length();
15413 return Smi::FromInt(length);
15417 // TODO(dcarney): remove this function when TurboFan supports it.
15418 // Takes (the object to be iterated over,
15419 // cache_array from ForInInit,
15420 // cache_type from ForInInit,
15421 // the current index)
15422 // Returns pair (array[index], needs_filtering).
15423 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInNext) {
15424 SealHandleScope scope(isolate);
15425 DCHECK(args.length() == 4);
15427 // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs.
15428 // Not worth creating a macro atm as this function should be removed.
15429 if (!args[0]->IsJSReceiver() || !args[1]->IsFixedArray() ||
15430 !args[2]->IsObject() || !args[3]->ToInt32(&index)) {
15431 Object* error = isolate->ThrowIllegalOperation();
15432 return MakePair(error, isolate->heap()->undefined_value());
15434 Handle<JSReceiver> object = args.at<JSReceiver>(0);
15435 Handle<FixedArray> array = args.at<FixedArray>(1);
15436 Handle<Object> cache_type = args.at<Object>(2);
15437 // Figure out first if a slow check is needed for this object.
15438 bool slow_check_needed = false;
15439 if (cache_type->IsMap()) {
15440 if (object->map() != Map::cast(*cache_type)) {
15441 // Object transitioned. Need slow check.
15442 slow_check_needed = true;
15445 // No slow check needed for proxies.
15446 slow_check_needed = Smi::cast(*cache_type)->value() == 1;
15448 return MakePair(array->get(index),
15449 isolate->heap()->ToBoolean(slow_check_needed));
15453 template<typename T, int Bytes>
15454 inline static bool SimdTypeLoadValue(
15456 Handle<JSArrayBuffer> buffer,
15457 Handle<Object> byte_offset_obj,
15459 size_t byte_offset = 0;
15460 if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
15464 size_t buffer_byte_length =
15465 NumberToSize(isolate, buffer->byte_length());
15466 if (byte_offset + Bytes > buffer_byte_length) { // overflow
15472 uint8_t bytes[sizeof(T)];
15476 memset(value.bytes, 0, sizeof(T));
15478 static_cast<uint8_t*>(buffer->backing_store()) + byte_offset;
15479 DCHECK(Bytes <= sizeof(T));
15480 CopyBytes<Bytes>(value.bytes, source);
15481 *result = value.data;
15486 template<typename T, int Bytes>
15487 static bool SimdTypeStoreValue(
15489 Handle<JSArrayBuffer> buffer,
15490 Handle<Object> byte_offset_obj,
15492 size_t byte_offset = 0;
15493 if (!TryNumberToSize(isolate, *byte_offset_obj, &byte_offset)) {
15497 size_t buffer_byte_length =
15498 NumberToSize(isolate, buffer->byte_length());
15499 if (byte_offset + Bytes > buffer_byte_length) { // overflow
15505 uint8_t bytes[sizeof(T)];
15512 static_cast<uint8_t*>(buffer->backing_store()) + byte_offset;
15513 DCHECK(Bytes <= sizeof(T));
15514 CopyBytes<Bytes>(target, value.bytes);
15519 #define SIMD128_LOAD_RUNTIME_FUNCTION(Type, ValueType, Lanes, Bytes) \
15520 RUNTIME_FUNCTION(Runtime_##Type##Load##Lanes) { \
15521 HandleScope scope(isolate); \
15522 DCHECK(args.length() == 2); \
15523 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0); \
15524 CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1); \
15525 ValueType result; \
15526 if (SimdTypeLoadValue<ValueType, Bytes>( \
15527 isolate, buffer, offset, &result)) { \
15528 return *isolate->factory()->New##Type(result); \
15530 THROW_NEW_ERROR_RETURN_FAILURE( \
15531 isolate, NewRangeError("invalid_offset", \
15532 HandleVector<Object>(NULL, 0))); \
15537 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZW, 16)
15538 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZ, 12)
15539 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XY, 8)
15540 SIMD128_LOAD_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, X, 4)
15541 SIMD128_LOAD_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, XY, 16)
15542 SIMD128_LOAD_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, X, 8)
15543 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZW, 16)
15544 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZ, 12)
15545 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XY, 8)
15546 SIMD128_LOAD_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, X, 4)
15549 #define SIMD128_STORE_RUNTIME_FUNCTION(Type, ValueType, Lanes, Bytes) \
15550 RUNTIME_FUNCTION(Runtime_##Type##Store##Lanes) { \
15551 HandleScope scope(isolate); \
15552 DCHECK(args.length() == 3); \
15553 CONVERT_ARG_HANDLE_CHECKED(JSArrayBuffer, buffer, 0); \
15554 CONVERT_NUMBER_ARG_HANDLE_CHECKED(offset, 1); \
15555 CONVERT_ARG_CHECKED(Type, value, 2); \
15556 ValueType v = value->get(); \
15557 if (SimdTypeStoreValue<ValueType, Bytes>(isolate, buffer, offset, v)) { \
15558 return isolate->heap()->undefined_value(); \
15560 THROW_NEW_ERROR_RETURN_FAILURE( \
15561 isolate, NewRangeError("invalid_offset", \
15562 HandleVector<Object>(NULL, 0))); \
15567 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZW, 16)
15568 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XYZ, 12)
15569 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, XY, 8)
15570 SIMD128_STORE_RUNTIME_FUNCTION(Float32x4, float32x4_value_t, X, 4)
15571 SIMD128_STORE_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, XY, 16)
15572 SIMD128_STORE_RUNTIME_FUNCTION(Float64x2, float64x2_value_t, X, 8)
15573 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZW, 16)
15574 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XYZ, 12)
15575 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, XY, 8)
15576 SIMD128_STORE_RUNTIME_FUNCTION(Int32x4, int32x4_value_t, X, 4)
15579 #define RETURN_Float32x4_RESULT(value) \
15580 return *isolate->factory()->NewFloat32x4(value);
15583 #define RETURN_Float64x2_RESULT(value) \
15584 return *isolate->factory()->NewFloat64x2(value);
15587 #define RETURN_Int32x4_RESULT(value) \
15588 return *isolate->factory()->NewInt32x4(value);
15591 RUNTIME_FUNCTION(Runtime_CreateFloat32x4) {
15592 HandleScope scope(isolate);
15593 DCHECK(args.length() == 4);
15594 RUNTIME_ASSERT(args[0]->IsNumber());
15595 RUNTIME_ASSERT(args[1]->IsNumber());
15596 RUNTIME_ASSERT(args[2]->IsNumber());
15597 RUNTIME_ASSERT(args[3]->IsNumber());
15599 float32x4_value_t value;
15600 value.storage[0] = static_cast<float>(args.number_at(0));
15601 value.storage[1] = static_cast<float>(args.number_at(1));
15602 value.storage[2] = static_cast<float>(args.number_at(2));
15603 value.storage[3] = static_cast<float>(args.number_at(3));
15605 RETURN_Float32x4_RESULT(value);
15609 RUNTIME_FUNCTION(Runtime_CreateFloat64x2) {
15610 HandleScope scope(isolate);
15611 DCHECK(args.length() == 2);
15612 RUNTIME_ASSERT(args[0]->IsNumber());
15613 RUNTIME_ASSERT(args[1]->IsNumber());
15615 float64x2_value_t value;
15616 value.storage[0] = args.number_at(0);
15617 value.storage[1] = args.number_at(1);
15619 RETURN_Float64x2_RESULT(value);
15623 RUNTIME_FUNCTION(Runtime_CreateInt32x4) {
15624 HandleScope scope(isolate);
15625 DCHECK(args.length() == 4);
15626 RUNTIME_ASSERT(args[0]->IsNumber());
15627 RUNTIME_ASSERT(args[1]->IsNumber());
15628 RUNTIME_ASSERT(args[2]->IsNumber());
15629 RUNTIME_ASSERT(args[3]->IsNumber());
15631 int32x4_value_t value;
15632 value.storage[0] = NumberToInt32(args[0]);
15633 value.storage[1] = NumberToInt32(args[1]);
15634 value.storage[2] = NumberToInt32(args[2]);
15635 value.storage[3] = NumberToInt32(args[3]);
15637 RETURN_Int32x4_RESULT(value);
15641 // Used to convert between uint32_t and float32 without breaking strict
15643 union float32_uint32 {
15646 float32_uint32(float v) {
15649 float32_uint32(uint32_t v) {
15655 union float64_uint64 {
15658 float64_uint64(double v) {
15661 float64_uint64(uint64_t v) {
15667 RUNTIME_FUNCTION(Runtime_Float32x4GetSignMask) {
15668 HandleScope scope(isolate);
15669 DCHECK(args.length() == 1);
15670 CONVERT_ARG_CHECKED(Float32x4, self, 0);
15671 float32_uint32 x(self->x());
15672 float32_uint32 y(self->y());
15673 float32_uint32 z(self->z());
15674 float32_uint32 w(self->w());
15675 uint32_t mx = (x.u & 0x80000000) >> 31;
15676 uint32_t my = (y.u & 0x80000000) >> 31;
15677 uint32_t mz = (z.u & 0x80000000) >> 31;
15678 uint32_t mw = (w.u & 0x80000000) >> 31;
15679 uint32_t value = mx | (my << 1) | (mz << 2) | (mw << 3);
15680 return *isolate->factory()->NewNumberFromUint(value);
15684 RUNTIME_FUNCTION(Runtime_Float64x2GetSignMask) {
15685 HandleScope scope(isolate);
15686 DCHECK(args.length() == 1);
15687 CONVERT_ARG_CHECKED(Float64x2, self, 0);
15688 float64_uint64 x(self->x());
15689 float64_uint64 y(self->y());
15690 uint64_t mx = x.u >> 63;
15691 uint64_t my = y.u >> 63;
15692 uint32_t value = uint32_t(mx | (my << 1));
15693 return *isolate->factory()->NewNumberFromUint(value);
15697 RUNTIME_FUNCTION(Runtime_Int32x4GetSignMask) {
15698 HandleScope scope(isolate);
15699 DCHECK(args.length() == 1);
15700 CONVERT_ARG_CHECKED(Int32x4, self, 0);
15701 uint32_t mx = (self->x() & 0x80000000) >> 31;
15702 uint32_t my = (self->y() & 0x80000000) >> 31;
15703 uint32_t mz = (self->z() & 0x80000000) >> 31;
15704 uint32_t mw = (self->w() & 0x80000000) >> 31;
15705 uint32_t value = mx | (my << 1) | (mz << 2) | (mw << 3);
15706 return *isolate->factory()->NewNumberFromUint(value);
15710 #define LANE_VALUE(VALUE, LANE) \
15714 #define LANE_FLAG(VALUE, LANE) \
15718 #define SIMD128_LANE_ACCESS_FUNCTIONS(V) \
15719 V(Float32x4, GetX, NewNumber, x, LANE_VALUE) \
15720 V(Float32x4, GetY, NewNumber, y, LANE_VALUE) \
15721 V(Float32x4, GetZ, NewNumber, z, LANE_VALUE) \
15722 V(Float32x4, GetW, NewNumber, w, LANE_VALUE) \
15723 V(Float64x2, GetX, NewNumber, x, LANE_VALUE) \
15724 V(Float64x2, GetY, NewNumber, y, LANE_VALUE) \
15725 V(Int32x4, GetX, NewNumberFromInt, x, LANE_VALUE) \
15726 V(Int32x4, GetY, NewNumberFromInt, y, LANE_VALUE) \
15727 V(Int32x4, GetZ, NewNumberFromInt, z, LANE_VALUE) \
15728 V(Int32x4, GetW, NewNumberFromInt, w, LANE_VALUE) \
15729 V(Int32x4, GetFlagX, ToBoolean, x, LANE_FLAG) \
15730 V(Int32x4, GetFlagY, ToBoolean, y, LANE_FLAG) \
15731 V(Int32x4, GetFlagZ, ToBoolean, z, LANE_FLAG) \
15732 V(Int32x4, GetFlagW, ToBoolean, w, LANE_FLAG)
15735 #define DECLARE_SIMD_LANE_ACCESS_FUNCTION( \
15736 TYPE, NAME, HEAP_FUNCTION, LANE, ACCESS_FUNCTION) \
15737 RUNTIME_FUNCTION(Runtime_##TYPE##NAME) { \
15738 HandleScope scope(isolate); \
15739 DCHECK(args.length() == 1); \
15741 CONVERT_ARG_CHECKED(TYPE, a, 0); \
15743 return *isolate->factory()->HEAP_FUNCTION( \
15744 ACCESS_FUNCTION(a, LANE)); \
15748 SIMD128_LANE_ACCESS_FUNCTIONS(DECLARE_SIMD_LANE_ACCESS_FUNCTION)
15751 template<typename T>
15752 static inline T Neg(T a) {
15757 template<typename T>
15758 static inline T Not(T a) {
15763 template<typename T>
15764 static inline T Reciprocal(T a) {
15770 inline float Reciprocal<float>(float a) {
15775 template<typename T>
15776 static inline T ReciprocalSqrt(T a) {
15782 inline float ReciprocalSqrt<float>(float a) {
15783 return sqrtf(1.0f / a);
15787 template<typename T>
15788 static inline T Sqrt(T a) {
15794 inline float Sqrt<float>(float a) {
15800 inline double Sqrt<double>(double a) {
15805 #define SIMD128_UNARY_FUNCTIONS(V) \
15806 V(Float32x4, Abs) \
15807 V(Float32x4, Neg) \
15808 V(Float32x4, Reciprocal) \
15809 V(Float32x4, ReciprocalSqrt) \
15810 V(Float32x4, Sqrt) \
15811 V(Float64x2, Abs) \
15812 V(Float64x2, Neg) \
15813 V(Float64x2, Sqrt) \
15818 #define DECLARE_SIMD_UNARY_FUNCTION(TYPE, FUNCTION) \
15819 RUNTIME_FUNCTION(Runtime_##TYPE##FUNCTION) { \
15820 HandleScope scope(isolate); \
15821 DCHECK(args.length() == 1); \
15823 CONVERT_ARG_CHECKED(TYPE, a, 0); \
15825 TYPE::value_t result; \
15826 for (int i = 0; i < TYPE::kLanes; i++) { \
15827 result.storage[i] = FUNCTION(a->getAt(i)); \
15830 RETURN_##TYPE##_RESULT(result); \
15834 SIMD128_UNARY_FUNCTIONS(DECLARE_SIMD_UNARY_FUNCTION)
15837 template<typename T1, typename T2>
15838 inline void BitsTo(T1 s, T2* t) {
15839 memcpy(t, &s, sizeof(T2));
15843 template<typename T1, typename T2>
15844 inline void To(T1 s, T2* t) {
15849 inline void To<int32_t, float>(int32_t s, float* t) {
15850 *t = static_cast<float>(s);
15855 inline void To<float, int32_t>(float s, int32_t* t) {
15856 *t = DoubleToInt32(static_cast<double>(s));
15860 #define SIMD128_CONVERSION_FUNCTIONS(V) \
15861 V(Float32x4, BitsTo, Int32x4) \
15862 V(Float32x4, To, Int32x4) \
15863 V(Int32x4, BitsTo, Float32x4) \
15864 V(Int32x4, To, Float32x4)
15867 #define DECLARE_SIMD_CONVERSION_FUNCTION( \
15868 SOURCE_TYPE, FUNCTION, TARGET_TYPE) \
15869 RUNTIME_FUNCTION( \
15870 Runtime_##SOURCE_TYPE##FUNCTION##TARGET_TYPE) { \
15871 HandleScope scope(isolate); \
15872 DCHECK(args.length() == 1); \
15874 CONVERT_ARG_CHECKED(SOURCE_TYPE, a, 0); \
15876 TARGET_TYPE::value_t result; \
15877 for (int i = 0; i < SOURCE_TYPE::kLanes; i++) { \
15878 FUNCTION(a->getAt(i), &result.storage[i]); \
15881 RETURN_##TARGET_TYPE##_RESULT(result); \
15885 SIMD128_CONVERSION_FUNCTIONS(DECLARE_SIMD_CONVERSION_FUNCTION)
15888 template<typename T>
15889 static inline T Add(T a, T b) {
15894 template<typename T>
15895 static inline T Div(T a, T b) {
15900 template<typename T>
15901 static inline T Mul(T a, T b) {
15906 template<typename T>
15907 static inline T Sub(T a, T b) {
15912 template<typename T>
15913 static inline int32_t Equal(T a, T b) {
15914 return a == b ? -1 : 0;
15918 template<typename T>
15919 static inline int32_t NotEqual(T a, T b) {
15920 return a != b ? -1 : 0;
15924 template<typename T>
15925 static inline int32_t GreaterThanOrEqual(T a, T b) {
15926 return a >= b ? -1 : 0;
15930 template<typename T>
15931 static inline int32_t GreaterThan(T a, T b) {
15932 return a > b ? -1 : 0;
15936 template<typename T>
15937 static inline int32_t LessThan(T a, T b) {
15938 return a < b ? -1 : 0;
15942 template<typename T>
15943 static inline int32_t LessThanOrEqual(T a, T b) {
15944 return a <= b ? -1 : 0;
15948 template<typename T>
15949 static inline T And(T a, T b) {
15954 template<typename T>
15955 static inline T Or(T a, T b) {
15960 template<typename T>
15961 static inline T Xor(T a, T b) {
15966 #define SIMD128_BINARY_FUNCTIONS(V) \
15967 V(Float32x4, Add, Float32x4) \
15968 V(Float32x4, Div, Float32x4) \
15969 V(Float32x4, Max, Float32x4) \
15970 V(Float32x4, Min, Float32x4) \
15971 V(Float32x4, Mul, Float32x4) \
15972 V(Float32x4, Sub, Float32x4) \
15973 V(Float32x4, Equal, Int32x4) \
15974 V(Float32x4, NotEqual, Int32x4) \
15975 V(Float32x4, GreaterThanOrEqual, Int32x4) \
15976 V(Float32x4, GreaterThan, Int32x4) \
15977 V(Float32x4, LessThan, Int32x4) \
15978 V(Float32x4, LessThanOrEqual, Int32x4) \
15979 V(Float64x2, Add, Float64x2) \
15980 V(Float64x2, Div, Float64x2) \
15981 V(Float64x2, Max, Float64x2) \
15982 V(Float64x2, Min, Float64x2) \
15983 V(Float64x2, Mul, Float64x2) \
15984 V(Float64x2, Sub, Float64x2) \
15985 V(Int32x4, Add, Int32x4) \
15986 V(Int32x4, And, Int32x4) \
15987 V(Int32x4, Mul, Int32x4) \
15988 V(Int32x4, Or, Int32x4) \
15989 V(Int32x4, Sub, Int32x4) \
15990 V(Int32x4, Xor, Int32x4) \
15991 V(Int32x4, Equal, Int32x4) \
15992 V(Int32x4, GreaterThan, Int32x4) \
15993 V(Int32x4, LessThan, Int32x4)
15996 #define DECLARE_SIMD_BINARY_FUNCTION( \
15997 TYPE, FUNCTION, RETURN_TYPE) \
15998 RUNTIME_FUNCTION(Runtime_##TYPE##FUNCTION) { \
15999 HandleScope scope(isolate); \
16000 DCHECK(args.length() == 2); \
16002 CONVERT_ARG_CHECKED(TYPE, a, 0); \
16003 CONVERT_ARG_CHECKED(TYPE, b, 1); \
16005 RETURN_TYPE::value_t result; \
16006 for (int i = 0; i < TYPE::kLanes; i++) { \
16007 result.storage[i] = FUNCTION(a->getAt(i), b->getAt(i)); \
16010 RETURN_##RETURN_TYPE##_RESULT(result); \
16014 SIMD128_BINARY_FUNCTIONS(DECLARE_SIMD_BINARY_FUNCTION)
16017 #define SIMD128_SHUFFLE_FUNCTIONS(V) \
16022 #define DECLARE_SIMD_SHUFFLE_FUNCTION(TYPE) \
16023 RUNTIME_FUNCTION(Runtime_##TYPE##Shuffle) { \
16024 HandleScope scope(isolate); \
16025 DCHECK(args.length() == 2); \
16027 CONVERT_ARG_CHECKED(TYPE, a, 0); \
16028 RUNTIME_ASSERT(args[1]->IsNumber()); \
16029 uint32_t m = NumberToUint32(args[1]); \
16031 TYPE::value_t result; \
16032 for (int i = 0; i < TYPE::kLanes; i++) { \
16033 result.storage[i] = a->getAt((m >> (i * 2)) & 0x3); \
16036 RETURN_##TYPE##_RESULT(result); \
16040 SIMD128_SHUFFLE_FUNCTIONS(DECLARE_SIMD_SHUFFLE_FUNCTION)
16043 RUNTIME_FUNCTION(Runtime_Float32x4Scale) {
16044 HandleScope scope(isolate);
16045 DCHECK(args.length() == 2);
16047 CONVERT_ARG_CHECKED(Float32x4, self, 0);
16048 RUNTIME_ASSERT(args[1]->IsNumber());
16050 float _s = static_cast<float>(args.number_at(1));
16051 float32x4_value_t result;
16052 result.storage[0] = self->x() * _s;
16053 result.storage[1] = self->y() * _s;
16054 result.storage[2] = self->z() * _s;
16055 result.storage[3] = self->w() * _s;
16057 RETURN_Float32x4_RESULT(result);
16061 RUNTIME_FUNCTION(Runtime_Float64x2Scale) {
16062 HandleScope scope(isolate);
16063 DCHECK(args.length() == 2);
16065 CONVERT_ARG_CHECKED(Float64x2, self, 0);
16066 RUNTIME_ASSERT(args[1]->IsNumber());
16068 double _s = args.number_at(1);
16069 float64x2_value_t result;
16070 result.storage[0] = self->x() * _s;
16071 result.storage[1] = self->y() * _s;
16073 RETURN_Float64x2_RESULT(result);
16077 #define ARG_TO_FLOAT32(x) \
16078 CONVERT_DOUBLE_ARG_CHECKED(t, 1); \
16079 float x = static_cast<float>(t);
16082 #define ARG_TO_FLOAT64(x) \
16083 CONVERT_DOUBLE_ARG_CHECKED(x, 1); \
16086 #define ARG_TO_INT32(x) \
16087 RUNTIME_ASSERT(args[1]->IsNumber()); \
16088 int32_t x = NumberToInt32(args[1]);
16091 #define ARG_TO_BOOLEAN(x) \
16092 CONVERT_BOOLEAN_ARG_CHECKED(flag, 1); \
16093 int32_t x = flag ? -1 : 0;
16095 #define SIMD128_SET_LANE_FUNCTIONS(V) \
16096 V(Float32x4, WithX, ARG_TO_FLOAT32, 0) \
16097 V(Float32x4, WithY, ARG_TO_FLOAT32, 1) \
16098 V(Float32x4, WithZ, ARG_TO_FLOAT32, 2) \
16099 V(Float32x4, WithW, ARG_TO_FLOAT32, 3) \
16100 V(Float64x2, WithX, ARG_TO_FLOAT64, 0) \
16101 V(Float64x2, WithY, ARG_TO_FLOAT64, 1) \
16102 V(Int32x4, WithX, ARG_TO_INT32, 0) \
16103 V(Int32x4, WithY, ARG_TO_INT32, 1) \
16104 V(Int32x4, WithZ, ARG_TO_INT32, 2) \
16105 V(Int32x4, WithW, ARG_TO_INT32, 3) \
16106 V(Int32x4, WithFlagX, ARG_TO_BOOLEAN, 0) \
16107 V(Int32x4, WithFlagY, ARG_TO_BOOLEAN, 1) \
16108 V(Int32x4, WithFlagZ, ARG_TO_BOOLEAN, 2) \
16109 V(Int32x4, WithFlagW, ARG_TO_BOOLEAN, 3)
16112 #define DECLARE_SIMD_SET_LANE_FUNCTION( \
16113 TYPE, NAME, ARG_FUNCTION, LANE) \
16114 RUNTIME_FUNCTION(Runtime_##TYPE##NAME) { \
16115 HandleScope scope(isolate); \
16116 DCHECK(args.length() == 2); \
16118 CONVERT_ARG_CHECKED(TYPE, a, 0); \
16119 ARG_FUNCTION(value); \
16121 TYPE::value_t result; \
16122 for (int i = 0; i < TYPE::kLanes; i++) { \
16124 result.storage[i] = a->getAt(i); \
16126 result.storage[i] = value; \
16129 RETURN_##TYPE##_RESULT(result); \
16133 SIMD128_SET_LANE_FUNCTIONS(DECLARE_SIMD_SET_LANE_FUNCTION)
16136 RUNTIME_FUNCTION(Runtime_Float32x4Clamp) {
16137 HandleScope scope(isolate);
16138 DCHECK(args.length() == 3);
16140 CONVERT_ARG_CHECKED(Float32x4, self, 0);
16141 CONVERT_ARG_CHECKED(Float32x4, lo, 1);
16142 CONVERT_ARG_CHECKED(Float32x4, hi, 2);
16144 float32x4_value_t result;
16145 float _x = self->x() > lo->x() ? self->x() : lo->x();
16146 float _y = self->y() > lo->y() ? self->y() : lo->y();
16147 float _z = self->z() > lo->z() ? self->z() : lo->z();
16148 float _w = self->w() > lo->w() ? self->w() : lo->w();
16149 result.storage[0] = _x > hi->x() ? hi->x() : _x;
16150 result.storage[1] = _y > hi->y() ? hi->y() : _y;
16151 result.storage[2] = _z > hi->z() ? hi->z() : _z;
16152 result.storage[3] = _w > hi->w() ? hi->w() : _w;
16154 RETURN_Float32x4_RESULT(result);
16158 RUNTIME_FUNCTION(Runtime_Float64x2Clamp) {
16159 HandleScope scope(isolate);
16160 DCHECK(args.length() == 3);
16162 CONVERT_ARG_CHECKED(Float64x2, self, 0);
16163 CONVERT_ARG_CHECKED(Float64x2, lo, 1);
16164 CONVERT_ARG_CHECKED(Float64x2, hi, 2);
16166 float64x2_value_t result;
16167 double _x = self->x() > lo->x() ? self->x() : lo->x();
16168 double _y = self->y() > lo->y() ? self->y() : lo->y();
16169 result.storage[0] = _x > hi->x() ? hi->x() : _x;
16170 result.storage[1] = _y > hi->y() ? hi->y() : _y;
16172 RETURN_Float64x2_RESULT(result);
16176 RUNTIME_FUNCTION(Runtime_Float32x4ShuffleMix) {
16177 HandleScope scope(isolate);
16178 DCHECK(args.length() == 3);
16180 CONVERT_ARG_CHECKED(Float32x4, first, 0);
16181 CONVERT_ARG_CHECKED(Float32x4, second, 1);
16182 RUNTIME_ASSERT(args[2]->IsNumber());
16184 uint32_t m = NumberToUint32(args[2]);
16185 float32x4_value_t result;
16186 float data1[4] = { first->x(), first->y(), first->z(), first->w() };
16187 float data2[4] = { second->x(), second->y(), second->z(), second->w() };
16188 result.storage[0] = data1[m & 0x3];
16189 result.storage[1] = data1[(m >> 2) & 0x3];
16190 result.storage[2] = data2[(m >> 4) & 0x3];
16191 result.storage[3] = data2[(m >> 6) & 0x3];
16193 RETURN_Float32x4_RESULT(result);
16197 RUNTIME_FUNCTION(Runtime_Float32x4Select) {
16198 HandleScope scope(isolate);
16199 DCHECK(args.length() == 3);
16201 CONVERT_ARG_CHECKED(Int32x4, self, 0);
16202 CONVERT_ARG_CHECKED(Float32x4, tv, 1);
16203 CONVERT_ARG_CHECKED(Float32x4, fv, 2);
16205 uint32_t _maskX = self->x();
16206 uint32_t _maskY = self->y();
16207 uint32_t _maskZ = self->z();
16208 uint32_t _maskW = self->w();
16209 // Extract floats and interpret them as masks.
16210 float32_uint32 tvx(tv->x());
16211 float32_uint32 tvy(tv->y());
16212 float32_uint32 tvz(tv->z());
16213 float32_uint32 tvw(tv->w());
16214 float32_uint32 fvx(fv->x());
16215 float32_uint32 fvy(fv->y());
16216 float32_uint32 fvz(fv->z());
16217 float32_uint32 fvw(fv->w());
16219 float32_uint32 tempX((_maskX & tvx.u) | (~_maskX & fvx.u));
16220 float32_uint32 tempY((_maskY & tvy.u) | (~_maskY & fvy.u));
16221 float32_uint32 tempZ((_maskZ & tvz.u) | (~_maskZ & fvz.u));
16222 float32_uint32 tempW((_maskW & tvw.u) | (~_maskW & fvw.u));
16224 float32x4_value_t result;
16225 result.storage[0] = tempX.f;
16226 result.storage[1] = tempY.f;
16227 result.storage[2] = tempZ.f;
16228 result.storage[3] = tempW.f;
16230 RETURN_Float32x4_RESULT(result);
16234 RUNTIME_FUNCTION(Runtime_Int32x4Select) {
16235 HandleScope scope(isolate);
16236 DCHECK(args.length() == 3);
16238 CONVERT_ARG_CHECKED(Int32x4, self, 0);
16239 CONVERT_ARG_CHECKED(Int32x4, tv, 1);
16240 CONVERT_ARG_CHECKED(Int32x4, fv, 2);
16242 uint32_t _maskX = self->x();
16243 uint32_t _maskY = self->y();
16244 uint32_t _maskZ = self->z();
16245 uint32_t _maskW = self->w();
16247 int32x4_value_t result;
16248 result.storage[0] = (_maskX & tv->x()) | (~_maskX & fv->x());
16249 result.storage[1] = (_maskY & tv->y()) | (~_maskY & fv->y());
16250 result.storage[2] = (_maskZ & tv->z()) | (~_maskZ & fv->z());
16251 result.storage[3] = (_maskW & tv->w()) | (~_maskW & fv->w());
16253 RETURN_Int32x4_RESULT(result);
16257 // ----------------------------------------------------------------------------
16258 // Reference implementation for inlined runtime functions. Only used when the
16259 // compiler does not support a certain intrinsic. Don't optimize these, but
16260 // implement the intrinsic in the respective compiler instead.
16262 // TODO(mstarzinger): These are place-holder stubs for TurboFan and will
16263 // eventually all have a C++ implementation and this macro will be gone.
16265 RUNTIME_FUNCTION(RuntimeReference_##name) { \
16270 U(IsStringWrapperSafeForDefaultValueOf)
16271 U(DebugBreakInOptimizedCode)
16276 RUNTIME_FUNCTION(RuntimeReference_IsSmi) {
16277 SealHandleScope shs(isolate);
16278 DCHECK(args.length() == 1);
16279 CONVERT_ARG_CHECKED(Object, obj, 0);
16280 return isolate->heap()->ToBoolean(obj->IsSmi());
16284 RUNTIME_FUNCTION(RuntimeReference_IsNonNegativeSmi) {
16285 SealHandleScope shs(isolate);
16286 DCHECK(args.length() == 1);
16287 CONVERT_ARG_CHECKED(Object, obj, 0);
16288 return isolate->heap()->ToBoolean(obj->IsSmi() &&
16289 Smi::cast(obj)->value() >= 0);
16293 RUNTIME_FUNCTION(RuntimeReference_IsArray) {
16294 SealHandleScope shs(isolate);
16295 DCHECK(args.length() == 1);
16296 CONVERT_ARG_CHECKED(Object, obj, 0);
16297 return isolate->heap()->ToBoolean(obj->IsJSArray());
16301 RUNTIME_FUNCTION(RuntimeReference_IsRegExp) {
16302 SealHandleScope shs(isolate);
16303 DCHECK(args.length() == 1);
16304 CONVERT_ARG_CHECKED(Object, obj, 0);
16305 return isolate->heap()->ToBoolean(obj->IsJSRegExp());
16309 RUNTIME_FUNCTION(RuntimeReference_IsConstructCall) {
16310 SealHandleScope shs(isolate);
16311 DCHECK(args.length() == 0);
16312 JavaScriptFrameIterator it(isolate);
16313 JavaScriptFrame* frame = it.frame();
16314 return isolate->heap()->ToBoolean(frame->IsConstructor());
16318 RUNTIME_FUNCTION(RuntimeReference_CallFunction) {
16319 SealHandleScope shs(isolate);
16320 return __RT_impl_Runtime_Call(args, isolate);
16324 RUNTIME_FUNCTION(RuntimeReference_ArgumentsLength) {
16325 SealHandleScope shs(isolate);
16326 DCHECK(args.length() == 0);
16327 JavaScriptFrameIterator it(isolate);
16328 JavaScriptFrame* frame = it.frame();
16329 return Smi::FromInt(frame->GetArgumentsLength());
16333 RUNTIME_FUNCTION(RuntimeReference_Arguments) {
16334 SealHandleScope shs(isolate);
16335 return __RT_impl_Runtime_GetArgumentsProperty(args, isolate);
16339 RUNTIME_FUNCTION(RuntimeReference_ValueOf) {
16340 SealHandleScope shs(isolate);
16341 DCHECK(args.length() == 1);
16342 CONVERT_ARG_CHECKED(Object, obj, 0);
16343 if (!obj->IsJSValue()) return obj;
16344 return JSValue::cast(obj)->value();
16348 RUNTIME_FUNCTION(RuntimeReference_SetValueOf) {
16349 SealHandleScope shs(isolate);
16350 DCHECK(args.length() == 2);
16351 CONVERT_ARG_CHECKED(Object, obj, 0);
16352 CONVERT_ARG_CHECKED(Object, value, 1);
16353 if (!obj->IsJSValue()) return value;
16354 JSValue::cast(obj)->set_value(value);
16359 RUNTIME_FUNCTION(RuntimeReference_DateField) {
16360 SealHandleScope shs(isolate);
16361 DCHECK(args.length() == 2);
16362 CONVERT_ARG_CHECKED(Object, obj, 0);
16363 CONVERT_SMI_ARG_CHECKED(index, 1);
16364 if (!obj->IsJSDate()) {
16365 HandleScope scope(isolate);
16366 THROW_NEW_ERROR_RETURN_FAILURE(
16368 NewTypeError("not_date_object", HandleVector<Object>(NULL, 0)));
16370 JSDate* date = JSDate::cast(obj);
16371 if (index == 0) return date->value();
16372 return JSDate::GetField(date, Smi::FromInt(index));
16376 RUNTIME_FUNCTION(RuntimeReference_StringCharFromCode) {
16377 SealHandleScope shs(isolate);
16378 return __RT_impl_Runtime_CharFromCode(args, isolate);
16382 RUNTIME_FUNCTION(RuntimeReference_StringCharAt) {
16383 SealHandleScope shs(isolate);
16384 DCHECK(args.length() == 2);
16385 if (!args[0]->IsString()) return Smi::FromInt(0);
16386 if (!args[1]->IsNumber()) return Smi::FromInt(0);
16387 if (std::isinf(args.number_at(1))) return isolate->heap()->empty_string();
16388 Object* code = __RT_impl_Runtime_StringCharCodeAtRT(args, isolate);
16389 if (code->IsNaN()) return isolate->heap()->empty_string();
16390 return __RT_impl_Runtime_CharFromCode(Arguments(1, &code), isolate);
16394 RUNTIME_FUNCTION(RuntimeReference_OneByteSeqStringSetChar) {
16395 SealHandleScope shs(isolate);
16396 DCHECK(args.length() == 3);
16397 CONVERT_INT32_ARG_CHECKED(index, 0);
16398 CONVERT_INT32_ARG_CHECKED(value, 1);
16399 CONVERT_ARG_CHECKED(SeqOneByteString, string, 2);
16400 string->SeqOneByteStringSet(index, value);
16405 RUNTIME_FUNCTION(RuntimeReference_TwoByteSeqStringSetChar) {
16406 SealHandleScope shs(isolate);
16407 DCHECK(args.length() == 3);
16408 CONVERT_INT32_ARG_CHECKED(index, 0);
16409 CONVERT_INT32_ARG_CHECKED(value, 1);
16410 CONVERT_ARG_CHECKED(SeqTwoByteString, string, 2);
16411 string->SeqTwoByteStringSet(index, value);
16416 RUNTIME_FUNCTION(RuntimeReference_ObjectEquals) {
16417 SealHandleScope shs(isolate);
16418 DCHECK(args.length() == 2);
16419 CONVERT_ARG_CHECKED(Object, obj1, 0);
16420 CONVERT_ARG_CHECKED(Object, obj2, 1);
16421 return isolate->heap()->ToBoolean(obj1 == obj2);
16425 RUNTIME_FUNCTION(RuntimeReference_IsObject) {
16426 SealHandleScope shs(isolate);
16427 DCHECK(args.length() == 1);
16428 CONVERT_ARG_CHECKED(Object, obj, 0);
16429 if (!obj->IsHeapObject()) return isolate->heap()->false_value();
16430 if (obj->IsNull()) return isolate->heap()->true_value();
16431 if (obj->IsUndetectableObject()) return isolate->heap()->false_value();
16432 Map* map = HeapObject::cast(obj)->map();
16433 bool is_non_callable_spec_object =
16434 map->instance_type() >= FIRST_NONCALLABLE_SPEC_OBJECT_TYPE &&
16435 map->instance_type() <= LAST_NONCALLABLE_SPEC_OBJECT_TYPE;
16436 return isolate->heap()->ToBoolean(is_non_callable_spec_object);
16440 RUNTIME_FUNCTION(RuntimeReference_IsFunction) {
16441 SealHandleScope shs(isolate);
16442 DCHECK(args.length() == 1);
16443 CONVERT_ARG_CHECKED(Object, obj, 0);
16444 return isolate->heap()->ToBoolean(obj->IsJSFunction());
16448 RUNTIME_FUNCTION(RuntimeReference_IsUndetectableObject) {
16449 SealHandleScope shs(isolate);
16450 DCHECK(args.length() == 1);
16451 CONVERT_ARG_CHECKED(Object, obj, 0);
16452 return isolate->heap()->ToBoolean(obj->IsUndetectableObject());
16456 RUNTIME_FUNCTION(RuntimeReference_IsSpecObject) {
16457 SealHandleScope shs(isolate);
16458 DCHECK(args.length() == 1);
16459 CONVERT_ARG_CHECKED(Object, obj, 0);
16460 return isolate->heap()->ToBoolean(obj->IsSpecObject());
16464 RUNTIME_FUNCTION(RuntimeReference_MathPow) {
16465 SealHandleScope shs(isolate);
16466 return __RT_impl_Runtime_MathPowSlow(args, isolate);
16470 RUNTIME_FUNCTION(RuntimeReference_IsMinusZero) {
16471 SealHandleScope shs(isolate);
16472 DCHECK(args.length() == 1);
16473 CONVERT_ARG_CHECKED(Object, obj, 0);
16474 if (!obj->IsHeapNumber()) return isolate->heap()->false_value();
16475 HeapNumber* number = HeapNumber::cast(obj);
16476 return isolate->heap()->ToBoolean(IsMinusZero(number->value()));
16480 RUNTIME_FUNCTION(RuntimeReference_HasCachedArrayIndex) {
16481 SealHandleScope shs(isolate);
16482 DCHECK(args.length() == 1);
16483 return isolate->heap()->false_value();
16487 RUNTIME_FUNCTION(RuntimeReference_GetCachedArrayIndex) {
16488 SealHandleScope shs(isolate);
16489 DCHECK(args.length() == 1);
16490 return isolate->heap()->undefined_value();
16494 RUNTIME_FUNCTION(RuntimeReference_FastOneByteArrayJoin) {
16495 SealHandleScope shs(isolate);
16496 DCHECK(args.length() == 2);
16497 return isolate->heap()->undefined_value();
16501 RUNTIME_FUNCTION(RuntimeReference_GeneratorNext) {
16502 UNREACHABLE(); // Optimization disabled in SetUpGenerators().
16507 RUNTIME_FUNCTION(RuntimeReference_GeneratorThrow) {
16508 UNREACHABLE(); // Optimization disabled in SetUpGenerators().
16513 RUNTIME_FUNCTION(RuntimeReference_ClassOf) {
16514 SealHandleScope shs(isolate);
16515 DCHECK(args.length() == 1);
16516 CONVERT_ARG_CHECKED(Object, obj, 0);
16517 if (!obj->IsJSReceiver()) return isolate->heap()->null_value();
16518 return JSReceiver::cast(obj)->class_name();
16522 RUNTIME_FUNCTION(RuntimeReference_StringCharCodeAt) {
16523 SealHandleScope shs(isolate);
16524 DCHECK(args.length() == 2);
16525 if (!args[0]->IsString()) return isolate->heap()->undefined_value();
16526 if (!args[1]->IsNumber()) return isolate->heap()->undefined_value();
16527 if (std::isinf(args.number_at(1))) return isolate->heap()->nan_value();
16528 return __RT_impl_Runtime_StringCharCodeAtRT(args, isolate);
16532 RUNTIME_FUNCTION(RuntimeReference_StringAdd) {
16533 SealHandleScope shs(isolate);
16534 return __RT_impl_Runtime_StringAdd(args, isolate);
16538 RUNTIME_FUNCTION(RuntimeReference_SubString) {
16539 SealHandleScope shs(isolate);
16540 return __RT_impl_Runtime_SubString(args, isolate);
16544 RUNTIME_FUNCTION(RuntimeReference_StringCompare) {
16545 SealHandleScope shs(isolate);
16546 return __RT_impl_Runtime_StringCompare(args, isolate);
16550 RUNTIME_FUNCTION(RuntimeReference_RegExpExec) {
16551 SealHandleScope shs(isolate);
16552 return __RT_impl_Runtime_RegExpExecRT(args, isolate);
16556 RUNTIME_FUNCTION(RuntimeReference_RegExpConstructResult) {
16557 SealHandleScope shs(isolate);
16558 return __RT_impl_Runtime_RegExpConstructResult(args, isolate);
16562 RUNTIME_FUNCTION(RuntimeReference_GetFromCache) {
16563 HandleScope scope(isolate);
16564 DCHECK(args.length() == 2);
16565 CONVERT_SMI_ARG_CHECKED(id, 0);
16566 args[0] = isolate->native_context()->jsfunction_result_caches()->get(id);
16567 return __RT_impl_Runtime_GetFromCache(args, isolate);
16571 RUNTIME_FUNCTION(RuntimeReference_NumberToString) {
16572 SealHandleScope shs(isolate);
16573 return __RT_impl_Runtime_NumberToStringRT(args, isolate);
16577 RUNTIME_FUNCTION(RuntimeReference_DebugIsActive) {
16578 SealHandleScope shs(isolate);
16579 return Smi::FromInt(isolate->debug()->is_active());
16583 // ----------------------------------------------------------------------------
16584 // Implementation of Runtime
16586 #define F(name, number_of_args, result_size) \
16588 Runtime::k##name, Runtime::RUNTIME, #name, FUNCTION_ADDR(Runtime_##name), \
16589 number_of_args, result_size \
16594 #define I(name, number_of_args, result_size) \
16596 Runtime::kInline##name, Runtime::INLINE, "_" #name, \
16597 FUNCTION_ADDR(RuntimeReference_##name), number_of_args, result_size \
16602 #define IO(name, number_of_args, result_size) \
16604 Runtime::kInlineOptimized##name, Runtime::INLINE_OPTIMIZED, "_" #name, \
16605 FUNCTION_ADDR(Runtime_##name), number_of_args, result_size \
16610 static const Runtime::Function kIntrinsicFunctions[] = {
16611 RUNTIME_FUNCTION_LIST(F)
16612 INLINE_OPTIMIZED_FUNCTION_LIST(F)
16613 INLINE_FUNCTION_LIST(I)
16614 INLINE_OPTIMIZED_FUNCTION_LIST(IO)
16622 void Runtime::InitializeIntrinsicFunctionNames(Isolate* isolate,
16623 Handle<NameDictionary> dict) {
16624 DCHECK(dict->NumberOfElements() == 0);
16625 HandleScope scope(isolate);
16626 for (int i = 0; i < kNumFunctions; ++i) {
16627 const char* name = kIntrinsicFunctions[i].name;
16628 if (name == NULL) continue;
16629 Handle<NameDictionary> new_dict = NameDictionary::Add(
16631 isolate->factory()->InternalizeUtf8String(name),
16632 Handle<Smi>(Smi::FromInt(i), isolate),
16633 PropertyDetails(NONE, NORMAL, Representation::None()));
16634 // The dictionary does not need to grow.
16635 CHECK(new_dict.is_identical_to(dict));
16640 const Runtime::Function* Runtime::FunctionForName(Handle<String> name) {
16641 Heap* heap = name->GetHeap();
16642 int entry = heap->intrinsic_function_names()->FindEntry(name);
16643 if (entry != kNotFound) {
16644 Object* smi_index = heap->intrinsic_function_names()->ValueAt(entry);
16645 int function_index = Smi::cast(smi_index)->value();
16646 return &(kIntrinsicFunctions[function_index]);
16652 const Runtime::Function* Runtime::FunctionForEntry(Address entry) {
16653 for (size_t i = 0; i < arraysize(kIntrinsicFunctions); ++i) {
16654 if (entry == kIntrinsicFunctions[i].entry) {
16655 return &(kIntrinsicFunctions[i]);
16662 const Runtime::Function* Runtime::FunctionForId(Runtime::FunctionId id) {
16663 return &(kIntrinsicFunctions[static_cast<int>(id)]);
16666 } } // namespace v8::internal