V8 Project
runtime.cc
Go to the documentation of this file.
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.
4 
5 #include <stdlib.h>
6 #include <limits>
7 
8 #include "src/v8.h"
9 
10 #include "src/accessors.h"
12 #include "src/api.h"
13 #include "src/arguments.h"
14 #include "src/bailout-reason.h"
15 #include "src/base/cpu.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"
23 #include "src/date.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/liveedit.h"
32 #include "src/misc-intrinsics.h"
33 #include "src/parser.h"
34 #include "src/prototype.h"
35 #include "src/runtime/runtime.h"
37 #include "src/runtime-profiler.h"
38 #include "src/scopeinfo.h"
39 #include "src/smart-pointers.h"
40 #include "src/utils.h"
41 #include "src/v8threads.h"
42 #include "src/vm-state-inl.h"
43 
44 
45 namespace v8 {
46 namespace internal {
47 
48 // Header of runtime functions.
49 #define F(name, number_of_args, result_size) \
50  Object* Runtime_##name(int args_length, Object** args_object, \
51  Isolate* isolate);
52 
53 #define P(name, number_of_args, result_size) \
54  ObjectPair Runtime_##name(int args_length, Object** args_object, \
55  Isolate* isolate);
56 
57 #define I(name, number_of_args, result_size) \
58  Object* RuntimeReference_##name(int args_length, Object** args_object, \
59  Isolate* isolate);
60 
65 
66 #undef I
67 #undef F
68 #undef P
69 
70 
72  Handle<Context> context, Handle<FixedArray> constant_properties,
73  bool* is_result_from_cache) {
74  Isolate* isolate = context->GetIsolate();
75  int properties_length = constant_properties->length();
76  int number_of_properties = properties_length / 2;
77  // Check that there are only internal strings and array indices among keys.
78  int number_of_string_keys = 0;
79  for (int p = 0; p != properties_length; p += 2) {
80  Object* key = constant_properties->get(p);
81  uint32_t element_index = 0;
82  if (key->IsInternalizedString()) {
83  number_of_string_keys++;
84  } else if (key->ToArrayIndex(&element_index)) {
85  // An index key does not require space in the property backing store.
86  number_of_properties--;
87  } else {
88  // Bail out as a non-internalized-string non-index key makes caching
89  // impossible.
90  // DCHECK to make sure that the if condition after the loop is false.
91  DCHECK(number_of_string_keys != number_of_properties);
92  break;
93  }
94  }
95  // If we only have internalized strings and array indices among keys then we
96  // can use the map cache in the native context.
97  const int kMaxKeys = 10;
98  if ((number_of_string_keys == number_of_properties) &&
99  (number_of_string_keys < kMaxKeys)) {
100  // Create the fixed array with the key.
102  isolate->factory()->NewFixedArray(number_of_string_keys);
103  if (number_of_string_keys > 0) {
104  int index = 0;
105  for (int p = 0; p < properties_length; p += 2) {
106  Object* key = constant_properties->get(p);
107  if (key->IsInternalizedString()) {
108  keys->set(index++, key);
109  }
110  }
111  DCHECK(index == number_of_string_keys);
112  }
113  *is_result_from_cache = true;
114  return isolate->factory()->ObjectLiteralMapFromCache(context, keys);
115  }
116  *is_result_from_cache = false;
117  return Map::Create(isolate, number_of_properties);
118 }
119 
120 
121 MUST_USE_RESULT static MaybeHandle<Object> CreateLiteralBoilerplate(
123  Handle<FixedArray> constant_properties);
124 
125 
128  Handle<FixedArray> constant_properties, bool should_have_fast_elements,
129  bool has_function_literal) {
130  // Get the native context from the literals array. This is the
131  // context in which the function was created and we use the object
132  // function from this context to create the object literal. We do
133  // not use the object function from the current native context
134  // because this might be the object function from another context
135  // which we should not have access to.
136  Handle<Context> context =
138 
139  // In case we have function literals, we want the object to be in
140  // slow properties mode for now. We don't go in the map cache because
141  // maps with constant functions can't be shared if the functions are
142  // not the same (which is the common case).
143  bool is_result_from_cache = false;
144  Handle<Map> map = has_function_literal
145  ? Handle<Map>(context->object_function()->initial_map())
146  : ComputeObjectLiteralMap(context, constant_properties,
147  &is_result_from_cache);
148 
149  PretenureFlag pretenure_flag =
150  isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED;
151 
152  Handle<JSObject> boilerplate =
153  isolate->factory()->NewJSObjectFromMap(map, pretenure_flag);
154 
155  // Normalize the elements of the boilerplate to save space if needed.
156  if (!should_have_fast_elements) JSObject::NormalizeElements(boilerplate);
157 
158  // Add the constant properties to the boilerplate.
159  int length = constant_properties->length();
160  bool should_transform =
161  !is_result_from_cache && boilerplate->HasFastProperties();
162  bool should_normalize = should_transform || has_function_literal;
163  if (should_normalize) {
164  // TODO(verwaest): We might not want to ever normalize here.
166  length / 2);
167  }
168  // TODO(verwaest): Support tracking representations in the boilerplate.
169  for (int index = 0; index < length; index += 2) {
170  Handle<Object> key(constant_properties->get(index + 0), isolate);
171  Handle<Object> value(constant_properties->get(index + 1), isolate);
172  if (value->IsFixedArray()) {
173  // The value contains the constant_properties of a
174  // simple object or array literal.
177  isolate, value, CreateLiteralBoilerplate(isolate, literals, array),
178  Object);
179  }
180  MaybeHandle<Object> maybe_result;
181  uint32_t element_index = 0;
182  if (key->IsInternalizedString()) {
183  if (Handle<String>::cast(key)->AsArrayIndex(&element_index)) {
184  // Array index as string (uint32).
185  if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate);
186  maybe_result =
187  JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY);
188  } else {
189  Handle<String> name(String::cast(*key));
190  DCHECK(!name->AsArrayIndex(&element_index));
192  boilerplate, name, value, NONE);
193  }
194  } else if (key->ToArrayIndex(&element_index)) {
195  // Array index (uint32).
196  if (value->IsUninitialized()) value = handle(Smi::FromInt(0), isolate);
197  maybe_result =
198  JSObject::SetOwnElement(boilerplate, element_index, value, SLOPPY);
199  } else {
200  // Non-uint32 number.
201  DCHECK(key->IsNumber());
202  double num = key->Number();
203  char arr[100];
204  Vector<char> buffer(arr, arraysize(arr));
205  const char* str = DoubleToCString(num, buffer);
206  Handle<String> name = isolate->factory()->NewStringFromAsciiChecked(str);
207  maybe_result = JSObject::SetOwnPropertyIgnoreAttributes(boilerplate, name,
208  value, NONE);
209  }
210  // If setting the property on the boilerplate throws an
211  // exception, the exception is converted to an empty handle in
212  // the handle based operations. In that case, we need to
213  // convert back to an exception.
214  RETURN_ON_EXCEPTION(isolate, maybe_result, Object);
215  }
216 
217  // Transform to fast properties if necessary. For object literals with
218  // containing function literals we defer this operation until after all
219  // computed properties have been assigned so that we can generate
220  // constant function properties.
221  if (should_transform && !has_function_literal) {
222  JSObject::MigrateSlowToFast(boilerplate,
223  boilerplate->map()->unused_property_fields());
224  }
225 
226  return boilerplate;
227 }
228 
229 
231  Handle<Object> object, ElementsKind to_kind, Isolate* isolate) {
232  HandleScope scope(isolate);
233  if (!object->IsJSObject()) {
234  isolate->ThrowIllegalOperation();
235  return MaybeHandle<Object>();
236  }
237  ElementsKind from_kind =
238  Handle<JSObject>::cast(object)->map()->elements_kind();
239  if (Map::IsValidElementsTransition(from_kind, to_kind)) {
241  return object;
242  }
243  isolate->ThrowIllegalOperation();
244  return MaybeHandle<Object>();
245 }
246 
247 
250  Handle<FixedArray> elements) {
251  // Create the JSArray.
252  Handle<JSFunction> constructor(
253  JSFunction::NativeContextFromLiterals(*literals)->array_function());
254 
255  PretenureFlag pretenure_flag =
256  isolate->heap()->InNewSpace(*literals) ? NOT_TENURED : TENURED;
257 
259  isolate->factory()->NewJSObject(constructor, pretenure_flag));
260 
261  ElementsKind constant_elements_kind =
262  static_cast<ElementsKind>(Smi::cast(elements->get(0))->value());
263  Handle<FixedArrayBase> constant_elements_values(
264  FixedArrayBase::cast(elements->get(1)));
265 
266  {
268  DCHECK(IsFastElementsKind(constant_elements_kind));
269  Context* native_context = isolate->context()->native_context();
270  Object* maps_array = native_context->js_array_maps();
271  DCHECK(!maps_array->IsUndefined());
272  Object* map = FixedArray::cast(maps_array)->get(constant_elements_kind);
273  object->set_map(Map::cast(map));
274  }
275 
276  Handle<FixedArrayBase> copied_elements_values;
277  if (IsFastDoubleElementsKind(constant_elements_kind)) {
278  copied_elements_values = isolate->factory()->CopyFixedDoubleArray(
279  Handle<FixedDoubleArray>::cast(constant_elements_values));
280  } else {
281  DCHECK(IsFastSmiOrObjectElementsKind(constant_elements_kind));
282  const bool is_cow = (constant_elements_values->map() ==
283  isolate->heap()->fixed_cow_array_map());
284  if (is_cow) {
285  copied_elements_values = constant_elements_values;
286 #if DEBUG
287  Handle<FixedArray> fixed_array_values =
288  Handle<FixedArray>::cast(copied_elements_values);
289  for (int i = 0; i < fixed_array_values->length(); i++) {
290  DCHECK(!fixed_array_values->get(i)->IsFixedArray());
291  }
292 #endif
293  } else {
294  Handle<FixedArray> fixed_array_values =
295  Handle<FixedArray>::cast(constant_elements_values);
296  Handle<FixedArray> fixed_array_values_copy =
297  isolate->factory()->CopyFixedArray(fixed_array_values);
298  copied_elements_values = fixed_array_values_copy;
299  for (int i = 0; i < fixed_array_values->length(); i++) {
300  if (fixed_array_values->get(i)->IsFixedArray()) {
301  // The value contains the constant_properties of a
302  // simple object or array literal.
303  Handle<FixedArray> fa(FixedArray::cast(fixed_array_values->get(i)));
304  Handle<Object> result;
306  isolate, result, CreateLiteralBoilerplate(isolate, literals, fa),
307  Object);
308  fixed_array_values_copy->set(i, *result);
309  }
310  }
311  }
312  }
313  object->set_elements(*copied_elements_values);
314  object->set_length(Smi::FromInt(copied_elements_values->length()));
315 
317  return object;
318 }
319 
320 
324  const bool kHasNoFunctionLiteral = false;
325  switch (CompileTimeValue::GetLiteralType(array)) {
327  return CreateObjectLiteralBoilerplate(isolate, literals, elements, true,
328  kHasNoFunctionLiteral);
330  return CreateObjectLiteralBoilerplate(isolate, literals, elements, false,
331  kHasNoFunctionLiteral);
334  elements);
335  default:
336  UNREACHABLE();
337  return MaybeHandle<Object>();
338  }
339 }
340 
341 
342 RUNTIME_FUNCTION(Runtime_CreateObjectLiteral) {
343  HandleScope scope(isolate);
344  DCHECK(args.length() == 4);
346  CONVERT_SMI_ARG_CHECKED(literals_index, 1);
347  CONVERT_ARG_HANDLE_CHECKED(FixedArray, constant_properties, 2);
349  bool should_have_fast_elements = (flags & ObjectLiteral::kFastElements) != 0;
350  bool has_function_literal = (flags & ObjectLiteral::kHasFunction) != 0;
351 
352  RUNTIME_ASSERT(literals_index >= 0 && literals_index < literals->length());
353 
354  // Check if boilerplate exists. If not, create it first.
355  Handle<Object> literal_site(literals->get(literals_index), isolate);
357  Handle<JSObject> boilerplate;
358  if (*literal_site == isolate->heap()->undefined_value()) {
359  Handle<Object> raw_boilerplate;
361  isolate, raw_boilerplate,
362  CreateObjectLiteralBoilerplate(isolate, literals, constant_properties,
363  should_have_fast_elements,
364  has_function_literal));
365  boilerplate = Handle<JSObject>::cast(raw_boilerplate);
366 
367  AllocationSiteCreationContext creation_context(isolate);
368  site = creation_context.EnterNewScope();
370  isolate, JSObject::DeepWalk(boilerplate, &creation_context));
371  creation_context.ExitScope(site, boilerplate);
372 
373  // Update the functions literal and return the boilerplate.
374  literals->set(literals_index, *site);
375  } else {
376  site = Handle<AllocationSite>::cast(literal_site);
377  boilerplate =
378  Handle<JSObject>(JSObject::cast(site->transition_info()), isolate);
379  }
380 
381  AllocationSiteUsageContext usage_context(isolate, site, true);
382  usage_context.EnterNewScope();
383  MaybeHandle<Object> maybe_copy =
384  JSObject::DeepCopy(boilerplate, &usage_context);
385  usage_context.ExitScope(site, boilerplate);
386  Handle<Object> copy;
387  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, copy, maybe_copy);
388  return *copy;
389 }
390 
391 
393  Isolate* isolate, Handle<FixedArray> literals, int literals_index,
394  Handle<FixedArray> elements) {
395  // Check if boilerplate exists. If not, create it first.
396  Handle<Object> literal_site(literals->get(literals_index), isolate);
398  if (*literal_site == isolate->heap()->undefined_value()) {
399  DCHECK(*elements != isolate->heap()->empty_fixed_array());
400  Handle<Object> boilerplate;
402  isolate, boilerplate,
405 
406  AllocationSiteCreationContext creation_context(isolate);
407  site = creation_context.EnterNewScope();
409  &creation_context).is_null()) {
411  }
412  creation_context.ExitScope(site, Handle<JSObject>::cast(boilerplate));
413 
414  literals->set(literals_index, *site);
415  } else {
416  site = Handle<AllocationSite>::cast(literal_site);
417  }
418 
419  return site;
420 }
421 
422 
425  int literals_index,
426  Handle<FixedArray> elements,
427  int flags) {
429  literals_index >= 0 && literals_index < literals->length(), JSObject);
432  isolate, site,
433  GetLiteralAllocationSite(isolate, literals, literals_index, elements),
434  JSObject);
435 
436  bool enable_mementos = (flags & ArrayLiteral::kDisableMementos) == 0;
437  Handle<JSObject> boilerplate(JSObject::cast(site->transition_info()));
438  AllocationSiteUsageContext usage_context(isolate, site, enable_mementos);
439  usage_context.EnterNewScope();
440  JSObject::DeepCopyHints hints = (flags & ArrayLiteral::kShallowElements) == 0
443  MaybeHandle<JSObject> copy =
444  JSObject::DeepCopy(boilerplate, &usage_context, hints);
445  usage_context.ExitScope(site, boilerplate);
446  return copy;
447 }
448 
449 
450 RUNTIME_FUNCTION(Runtime_CreateArrayLiteral) {
451  HandleScope scope(isolate);
452  DCHECK(args.length() == 4);
454  CONVERT_SMI_ARG_CHECKED(literals_index, 1);
457 
458  Handle<JSObject> result;
460  isolate, result, CreateArrayLiteralImpl(isolate, literals, literals_index,
461  elements, flags));
462  return *result;
463 }
464 
465 
466 RUNTIME_FUNCTION(Runtime_CreateArrayLiteralStubBailout) {
467  HandleScope scope(isolate);
468  DCHECK(args.length() == 3);
470  CONVERT_SMI_ARG_CHECKED(literals_index, 1);
472 
473  Handle<JSObject> result;
475  isolate, result,
476  CreateArrayLiteralImpl(isolate, literals, literals_index, elements,
477  ArrayLiteral::kShallowElements));
478  return *result;
479 }
480 
481 
482 RUNTIME_FUNCTION(Runtime_CreateSymbol) {
483  HandleScope scope(isolate);
484  DCHECK(args.length() == 1);
486  RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
487  Handle<Symbol> symbol = isolate->factory()->NewSymbol();
488  if (name->IsString()) symbol->set_name(*name);
489  return *symbol;
490 }
491 
492 
493 RUNTIME_FUNCTION(Runtime_CreatePrivateSymbol) {
494  HandleScope scope(isolate);
495  DCHECK(args.length() == 1);
497  RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
498  Handle<Symbol> symbol = isolate->factory()->NewPrivateSymbol();
499  if (name->IsString()) symbol->set_name(*name);
500  return *symbol;
501 }
502 
503 
504 RUNTIME_FUNCTION(Runtime_CreatePrivateOwnSymbol) {
505  HandleScope scope(isolate);
506  DCHECK(args.length() == 1);
508  RUNTIME_ASSERT(name->IsString() || name->IsUndefined());
509  Handle<Symbol> symbol = isolate->factory()->NewPrivateOwnSymbol();
510  if (name->IsString()) symbol->set_name(*name);
511  return *symbol;
512 }
513 
514 
515 RUNTIME_FUNCTION(Runtime_CreateGlobalPrivateOwnSymbol) {
516  HandleScope scope(isolate);
517  DCHECK(args.length() == 1);
519  Handle<JSObject> registry = isolate->GetSymbolRegistry();
520  Handle<String> part = isolate->factory()->private_intern_string();
521  Handle<Object> privates;
523  isolate, privates, Object::GetPropertyOrElement(registry, part));
524  Handle<Object> symbol;
526  isolate, symbol, Object::GetPropertyOrElement(privates, name));
527  if (!symbol->IsSymbol()) {
528  DCHECK(symbol->IsUndefined());
529  symbol = isolate->factory()->NewPrivateSymbol();
530  Handle<Symbol>::cast(symbol)->set_name(*name);
531  Handle<Symbol>::cast(symbol)->set_is_own(true);
533  STRICT).Assert();
534  }
535  return *symbol;
536 }
537 
538 
539 RUNTIME_FUNCTION(Runtime_NewSymbolWrapper) {
540  HandleScope scope(isolate);
541  DCHECK(args.length() == 1);
543  return *Object::ToObject(isolate, symbol).ToHandleChecked();
544 }
545 
546 
547 RUNTIME_FUNCTION(Runtime_SymbolDescription) {
548  SealHandleScope shs(isolate);
549  DCHECK(args.length() == 1);
550  CONVERT_ARG_CHECKED(Symbol, symbol, 0);
551  return symbol->name();
552 }
553 
554 
555 RUNTIME_FUNCTION(Runtime_SymbolRegistry) {
556  HandleScope scope(isolate);
557  DCHECK(args.length() == 0);
558  return *isolate->GetSymbolRegistry();
559 }
560 
561 
562 RUNTIME_FUNCTION(Runtime_SymbolIsPrivate) {
563  SealHandleScope shs(isolate);
564  DCHECK(args.length() == 1);
565  CONVERT_ARG_CHECKED(Symbol, symbol, 0);
566  return isolate->heap()->ToBoolean(symbol->is_private());
567 }
568 
569 
570 RUNTIME_FUNCTION(Runtime_CreateJSProxy) {
571  HandleScope scope(isolate);
572  DCHECK(args.length() == 2);
574  CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
575  if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value();
576  return *isolate->factory()->NewJSProxy(handler, prototype);
577 }
578 
579 
580 RUNTIME_FUNCTION(Runtime_CreateJSFunctionProxy) {
581  HandleScope scope(isolate);
582  DCHECK(args.length() == 4);
584  CONVERT_ARG_HANDLE_CHECKED(Object, call_trap, 1);
585  RUNTIME_ASSERT(call_trap->IsJSFunction() || call_trap->IsJSFunctionProxy());
586  CONVERT_ARG_HANDLE_CHECKED(JSFunction, construct_trap, 2);
587  CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 3);
588  if (!prototype->IsJSReceiver()) prototype = isolate->factory()->null_value();
589  return *isolate->factory()->NewJSFunctionProxy(handler, call_trap,
590  construct_trap, prototype);
591 }
592 
593 
594 RUNTIME_FUNCTION(Runtime_IsJSProxy) {
595  SealHandleScope shs(isolate);
596  DCHECK(args.length() == 1);
598  return isolate->heap()->ToBoolean(obj->IsJSProxy());
599 }
600 
601 
602 RUNTIME_FUNCTION(Runtime_IsJSFunctionProxy) {
603  SealHandleScope shs(isolate);
604  DCHECK(args.length() == 1);
606  return isolate->heap()->ToBoolean(obj->IsJSFunctionProxy());
607 }
608 
609 
610 RUNTIME_FUNCTION(Runtime_GetHandler) {
611  SealHandleScope shs(isolate);
612  DCHECK(args.length() == 1);
613  CONVERT_ARG_CHECKED(JSProxy, proxy, 0);
614  return proxy->handler();
615 }
616 
617 
618 RUNTIME_FUNCTION(Runtime_GetCallTrap) {
619  SealHandleScope shs(isolate);
620  DCHECK(args.length() == 1);
622  return proxy->call_trap();
623 }
624 
625 
626 RUNTIME_FUNCTION(Runtime_GetConstructTrap) {
627  SealHandleScope shs(isolate);
628  DCHECK(args.length() == 1);
630  return proxy->construct_trap();
631 }
632 
633 
634 RUNTIME_FUNCTION(Runtime_Fix) {
635  HandleScope scope(isolate);
636  DCHECK(args.length() == 1);
638  JSProxy::Fix(proxy);
639  return isolate->heap()->undefined_value();
640 }
641 
642 
643 RUNTIME_FUNCTION(Runtime_GetPrototype) {
644  HandleScope scope(isolate);
645  DCHECK(args.length() == 1);
647  // We don't expect access checks to be needed on JSProxy objects.
648  DCHECK(!obj->IsAccessCheckNeeded() || obj->IsJSObject());
650  do {
651  if (PrototypeIterator::GetCurrent(iter)->IsAccessCheckNeeded() &&
652  !isolate->MayNamedAccess(
654  isolate->factory()->proto_string(), v8::ACCESS_GET)) {
655  isolate->ReportFailedAccessCheck(
659  return isolate->heap()->undefined_value();
660  }
661  iter.AdvanceIgnoringProxies();
662  if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) {
663  return *PrototypeIterator::GetCurrent(iter);
664  }
666  return *PrototypeIterator::GetCurrent(iter);
667 }
668 
669 
671  Isolate* isolate, Handle<Object> receiver) {
672  PrototypeIterator iter(isolate, receiver);
674  if (PrototypeIterator::GetCurrent(iter)->IsJSProxy()) {
675  return PrototypeIterator::GetCurrent(iter);
676  }
677  iter.Advance();
678  }
679  return PrototypeIterator::GetCurrent(iter);
680 }
681 
682 
683 RUNTIME_FUNCTION(Runtime_InternalSetPrototype) {
684  HandleScope scope(isolate);
685  DCHECK(args.length() == 2);
687  CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
688  DCHECK(!obj->IsAccessCheckNeeded());
689  DCHECK(!obj->map()->is_observed());
690  Handle<Object> result;
692  isolate, result, JSObject::SetPrototype(obj, prototype, false));
693  return *result;
694 }
695 
696 
697 RUNTIME_FUNCTION(Runtime_SetPrototype) {
698  HandleScope scope(isolate);
699  DCHECK(args.length() == 2);
701  CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
702  if (obj->IsAccessCheckNeeded() &&
703  !isolate->MayNamedAccess(obj, isolate->factory()->proto_string(),
704  v8::ACCESS_SET)) {
705  isolate->ReportFailedAccessCheck(obj, v8::ACCESS_SET);
707  return isolate->heap()->undefined_value();
708  }
709  if (obj->map()->is_observed()) {
710  Handle<Object> old_value = GetPrototypeSkipHiddenPrototypes(isolate, obj);
711  Handle<Object> result;
713  isolate, result, JSObject::SetPrototype(obj, prototype, true));
714 
715  Handle<Object> new_value = GetPrototypeSkipHiddenPrototypes(isolate, obj);
716  if (!new_value->SameValue(*old_value)) {
718  obj, "setPrototype", isolate->factory()->proto_string(), old_value);
719  }
720  return *result;
721  }
722  Handle<Object> result;
724  isolate, result, JSObject::SetPrototype(obj, prototype, true));
725  return *result;
726 }
727 
728 
729 RUNTIME_FUNCTION(Runtime_IsInPrototypeChain) {
730  HandleScope shs(isolate);
731  DCHECK(args.length() == 2);
732  // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8).
736  while (true) {
737  iter.AdvanceIgnoringProxies();
738  if (iter.IsAtEnd()) return isolate->heap()->false_value();
739  if (iter.IsAtEnd(O)) return isolate->heap()->true_value();
740  }
741 }
742 
743 
744 // Enumerator used as indices into the array returned from GetOwnProperty
754 };
755 
756 
758  Handle<JSObject> obj,
759  Handle<Name> name) {
760  Heap* heap = isolate->heap();
761  Factory* factory = isolate->factory();
762 
763  PropertyAttributes attrs;
764  uint32_t index = 0;
765  Handle<Object> value;
766  MaybeHandle<AccessorPair> maybe_accessors;
767  // TODO(verwaest): Unify once indexed properties can be handled by the
768  // LookupIterator.
769  if (name->AsArrayIndex(&index)) {
770  // Get attributes.
773  if (!maybe.has_value) return MaybeHandle<Object>();
774  attrs = maybe.value;
775  if (attrs == ABSENT) return factory->undefined_value();
776 
777  // Get AccessorPair if present.
778  maybe_accessors = JSObject::GetOwnElementAccessorPair(obj, index);
779 
780  // Get value if not an AccessorPair.
781  if (maybe_accessors.is_null()) {
783  isolate, value, Runtime::GetElementOrCharAt(isolate, obj, index),
784  Object);
785  }
786  } else {
787  // Get attributes.
788  LookupIterator it(obj, name, LookupIterator::HIDDEN);
790  if (!maybe.has_value) return MaybeHandle<Object>();
791  attrs = maybe.value;
792  if (attrs == ABSENT) return factory->undefined_value();
793 
794  // Get AccessorPair if present.
795  if (it.state() == LookupIterator::ACCESSOR &&
796  it.GetAccessors()->IsAccessorPair()) {
797  maybe_accessors = Handle<AccessorPair>::cast(it.GetAccessors());
798  }
799 
800  // Get value if not an AccessorPair.
801  if (maybe_accessors.is_null()) {
802  ASSIGN_RETURN_ON_EXCEPTION(isolate, value, Object::GetProperty(&it),
803  Object);
804  }
805  }
806  DCHECK(!isolate->has_pending_exception());
807  Handle<FixedArray> elms = factory->NewFixedArray(DESCRIPTOR_SIZE);
808  elms->set(ENUMERABLE_INDEX, heap->ToBoolean((attrs & DONT_ENUM) == 0));
809  elms->set(CONFIGURABLE_INDEX, heap->ToBoolean((attrs & DONT_DELETE) == 0));
810  elms->set(IS_ACCESSOR_INDEX, heap->ToBoolean(!maybe_accessors.is_null()));
811 
812  Handle<AccessorPair> accessors;
813  if (maybe_accessors.ToHandle(&accessors)) {
814  Handle<Object> getter(accessors->GetComponent(ACCESSOR_GETTER), isolate);
815  Handle<Object> setter(accessors->GetComponent(ACCESSOR_SETTER), isolate);
816  elms->set(GETTER_INDEX, *getter);
817  elms->set(SETTER_INDEX, *setter);
818  } else {
819  elms->set(WRITABLE_INDEX, heap->ToBoolean((attrs & READ_ONLY) == 0));
820  elms->set(VALUE_INDEX, *value);
821  }
822 
823  return factory->NewJSArrayWithElements(elms);
824 }
825 
826 
827 // Returns an array with the property description:
828 // if args[1] is not a property on args[0]
829 // returns undefined
830 // if args[1] is a data property on args[0]
831 // [false, value, Writeable, Enumerable, Configurable]
832 // if args[1] is an accessor on args[0]
833 // [true, GetFunction, SetFunction, Enumerable, Configurable]
834 RUNTIME_FUNCTION(Runtime_GetOwnProperty) {
835  HandleScope scope(isolate);
836  DCHECK(args.length() == 2);
839  Handle<Object> result;
840  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
841  GetOwnProperty(isolate, obj, name));
842  return *result;
843 }
844 
845 
846 RUNTIME_FUNCTION(Runtime_PreventExtensions) {
847  HandleScope scope(isolate);
848  DCHECK(args.length() == 1);
850  Handle<Object> result;
851  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
853  return *result;
854 }
855 
856 
857 RUNTIME_FUNCTION(Runtime_ToMethod) {
858  HandleScope scope(isolate);
859  DCHECK(args.length() == 2);
861  CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1);
863  Handle<Symbol> home_object_symbol(isolate->heap()->home_object_symbol());
864  JSObject::SetOwnPropertyIgnoreAttributes(clone, home_object_symbol,
865  home_object, DONT_ENUM).Assert();
866  return *clone;
867 }
868 
869 
870 RUNTIME_FUNCTION(Runtime_HomeObjectSymbol) {
871  DCHECK(args.length() == 0);
872  return isolate->heap()->home_object_symbol();
873 }
874 
875 
876 RUNTIME_FUNCTION(Runtime_LoadFromSuper) {
877  HandleScope scope(isolate);
878  DCHECK(args.length() == 3);
879  CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0);
880  CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1);
882 
883  if (home_object->IsAccessCheckNeeded() &&
884  !isolate->MayNamedAccess(home_object, name, v8::ACCESS_GET)) {
885  isolate->ReportFailedAccessCheck(home_object, v8::ACCESS_GET);
887  }
888 
889  PrototypeIterator iter(isolate, home_object);
891  if (!proto->IsJSReceiver()) return isolate->heap()->undefined_value();
892 
893  LookupIterator it(receiver, name, Handle<JSReceiver>::cast(proto));
894  Handle<Object> result;
896  return *result;
897 }
898 
899 
900 static Object* StoreToSuper(Isolate* isolate, Handle<JSObject> home_object,
901  Handle<Object> receiver, Handle<Name> name,
902  Handle<Object> value, StrictMode strict_mode) {
903  if (home_object->IsAccessCheckNeeded() &&
904  !isolate->MayNamedAccess(home_object, name, v8::ACCESS_SET)) {
905  isolate->ReportFailedAccessCheck(home_object, v8::ACCESS_SET);
907  }
908 
909  PrototypeIterator iter(isolate, home_object);
911  if (!proto->IsJSReceiver()) return isolate->heap()->undefined_value();
912 
913  LookupIterator it(receiver, name, Handle<JSReceiver>::cast(proto));
914  Handle<Object> result;
916  isolate, result,
917  Object::SetProperty(&it, value, strict_mode,
920  return *result;
921 }
922 
923 
924 RUNTIME_FUNCTION(Runtime_StoreToSuper_Strict) {
925  HandleScope scope(isolate);
926  DCHECK(args.length() == 4);
927  CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0);
928  CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1);
931 
932  return StoreToSuper(isolate, home_object, receiver, name, value, STRICT);
933 }
934 
935 
936 RUNTIME_FUNCTION(Runtime_StoreToSuper_Sloppy) {
937  HandleScope scope(isolate);
938  DCHECK(args.length() == 4);
939  CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 0);
940  CONVERT_ARG_HANDLE_CHECKED(JSObject, home_object, 1);
943 
944  return StoreToSuper(isolate, home_object, receiver, name, value, SLOPPY);
945 }
946 
947 
948 RUNTIME_FUNCTION(Runtime_IsExtensible) {
949  SealHandleScope shs(isolate);
950  DCHECK(args.length() == 1);
951  CONVERT_ARG_CHECKED(JSObject, obj, 0);
952  if (obj->IsJSGlobalProxy()) {
953  PrototypeIterator iter(isolate, obj);
954  if (iter.IsAtEnd()) return isolate->heap()->false_value();
955  DCHECK(iter.GetCurrent()->IsJSGlobalObject());
956  obj = JSObject::cast(iter.GetCurrent());
957  }
958  return isolate->heap()->ToBoolean(obj->map()->is_extensible());
959 }
960 
961 
962 RUNTIME_FUNCTION(Runtime_CreateApiFunction) {
963  HandleScope scope(isolate);
964  DCHECK(args.length() == 2);
966  CONVERT_ARG_HANDLE_CHECKED(Object, prototype, 1);
967  return *isolate->factory()->CreateApiFunction(data, prototype);
968 }
969 
970 
971 RUNTIME_FUNCTION(Runtime_IsTemplate) {
972  SealHandleScope shs(isolate);
973  DCHECK(args.length() == 1);
975  bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo();
976  return isolate->heap()->ToBoolean(result);
977 }
978 
979 
980 RUNTIME_FUNCTION(Runtime_GetTemplateField) {
981  SealHandleScope shs(isolate);
982  DCHECK(args.length() == 2);
983  CONVERT_ARG_CHECKED(HeapObject, templ, 0);
984  CONVERT_SMI_ARG_CHECKED(index, 1);
985  int offset = index * kPointerSize + HeapObject::kHeaderSize;
986  InstanceType type = templ->map()->instance_type();
988  type == OBJECT_TEMPLATE_INFO_TYPE);
989  RUNTIME_ASSERT(offset > 0);
990  if (type == FUNCTION_TEMPLATE_INFO_TYPE) {
992  } else {
994  }
995  return *HeapObject::RawField(templ, offset);
996 }
997 
998 
999 RUNTIME_FUNCTION(Runtime_DisableAccessChecks) {
1000  HandleScope scope(isolate);
1001  DCHECK(args.length() == 1);
1003  Handle<Map> old_map(object->map());
1004  bool needs_access_checks = old_map->is_access_check_needed();
1005  if (needs_access_checks) {
1006  // Copy map so it won't interfere constructor's initial map.
1007  Handle<Map> new_map = Map::Copy(old_map);
1008  new_map->set_is_access_check_needed(false);
1010  }
1011  return isolate->heap()->ToBoolean(needs_access_checks);
1012 }
1013 
1014 
1015 RUNTIME_FUNCTION(Runtime_EnableAccessChecks) {
1016  HandleScope scope(isolate);
1017  DCHECK(args.length() == 1);
1019  Handle<Map> old_map(object->map());
1020  RUNTIME_ASSERT(!old_map->is_access_check_needed());
1021  // Copy map so it won't interfere constructor's initial map.
1022  Handle<Map> new_map = Map::Copy(old_map);
1023  new_map->set_is_access_check_needed(true);
1024  JSObject::MigrateToMap(object, new_map);
1025  return isolate->heap()->undefined_value();
1026 }
1027 
1028 
1030  HandleScope scope(isolate);
1031  Handle<Object> args[1] = {name};
1033  isolate, NewTypeError("var_redeclaration", HandleVector(args, 1)));
1034 }
1035 
1036 
1037 // May throw a RedeclarationError.
1040  PropertyAttributes attr, bool is_var,
1041  bool is_const, bool is_function) {
1042  // Do the lookup own properties only, see ES5 erratum.
1043  LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
1045  if (!maybe.has_value) return isolate->heap()->exception();
1046 
1047  if (it.IsFound()) {
1048  PropertyAttributes old_attributes = maybe.value;
1049  // The name was declared before; check for conflicting re-declarations.
1050  if (is_const) return ThrowRedeclarationError(isolate, name);
1051 
1052  // Skip var re-declarations.
1053  if (is_var) return isolate->heap()->undefined_value();
1054 
1055  DCHECK(is_function);
1056  if ((old_attributes & DONT_DELETE) != 0) {
1057  // Only allow reconfiguring globals to functions in user code (no
1058  // natives, which are marked as read-only).
1059  DCHECK((attr & READ_ONLY) == 0);
1060 
1061  // Check whether we can reconfigure the existing property into a
1062  // function.
1063  PropertyDetails old_details = it.property_details();
1064  // TODO(verwaest): CALLBACKS invalidly includes ExecutableAccessInfo,
1065  // which are actually data properties, not accessor properties.
1066  if (old_details.IsReadOnly() || old_details.IsDontEnum() ||
1067  old_details.type() == CALLBACKS) {
1068  return ThrowRedeclarationError(isolate, name);
1069  }
1070  // If the existing property is not configurable, keep its attributes. Do
1071  attr = old_attributes;
1072  }
1073  }
1074 
1075  // Define or redefine own property.
1077  global, name, value, attr));
1078 
1079  return isolate->heap()->undefined_value();
1080 }
1081 
1082 
1083 RUNTIME_FUNCTION(Runtime_DeclareGlobals) {
1084  HandleScope scope(isolate);
1085  DCHECK(args.length() == 3);
1086  Handle<GlobalObject> global(isolate->global_object());
1087 
1088  CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
1091 
1092  // Traverse the name/value pairs and set the properties.
1093  int length = pairs->length();
1094  for (int i = 0; i < length; i += 2) {
1095  HandleScope scope(isolate);
1096  Handle<String> name(String::cast(pairs->get(i)));
1097  Handle<Object> initial_value(pairs->get(i + 1), isolate);
1098 
1099  // We have to declare a global const property. To capture we only
1100  // assign to it when evaluating the assignment for "const x =
1101  // <expr>" the initial value is the hole.
1102  bool is_var = initial_value->IsUndefined();
1103  bool is_const = initial_value->IsTheHole();
1104  bool is_function = initial_value->IsSharedFunctionInfo();
1105  DCHECK(is_var + is_const + is_function == 1);
1106 
1107  Handle<Object> value;
1108  if (is_function) {
1109  // Copy the function and update its context. Use it as value.
1111  Handle<SharedFunctionInfo>::cast(initial_value);
1112  Handle<JSFunction> function =
1113  isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
1114  TENURED);
1115  value = function;
1116  } else {
1117  value = isolate->factory()->undefined_value();
1118  }
1119 
1120  // Compute the property attributes. According to ECMA-262,
1121  // the property must be non-configurable except in eval.
1122  bool is_native = DeclareGlobalsNativeFlag::decode(flags);
1123  bool is_eval = DeclareGlobalsEvalFlag::decode(flags);
1124  int attr = NONE;
1125  if (is_const) attr |= READ_ONLY;
1126  if (is_function && is_native) attr |= READ_ONLY;
1127  if (!is_const && !is_eval) attr |= DONT_DELETE;
1128 
1129  Object* result = DeclareGlobals(isolate, global, name, value,
1130  static_cast<PropertyAttributes>(attr),
1131  is_var, is_const, is_function);
1132  if (isolate->has_pending_exception()) return result;
1133  }
1134 
1135  return isolate->heap()->undefined_value();
1136 }
1137 
1138 
1139 RUNTIME_FUNCTION(Runtime_InitializeVarGlobal) {
1140  HandleScope scope(isolate);
1141  // args[0] == name
1142  // args[1] == language_mode
1143  // args[2] == value (optional)
1144 
1145  // Determine if we need to assign to the variable if it already
1146  // exists (based on the number of arguments).
1147  RUNTIME_ASSERT(args.length() == 3);
1148 
1150  CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 1);
1152 
1153  Handle<GlobalObject> global(isolate->context()->global_object());
1154  Handle<Object> result;
1156  isolate, result, Object::SetProperty(global, name, value, strict_mode));
1157  return *result;
1158 }
1159 
1160 
1161 RUNTIME_FUNCTION(Runtime_InitializeConstGlobal) {
1162  HandleScope handle_scope(isolate);
1163  // All constants are declared with an initial value. The name
1164  // of the constant is the first argument and the initial value
1165  // is the second.
1166  RUNTIME_ASSERT(args.length() == 2);
1169 
1170  Handle<GlobalObject> global = isolate->global_object();
1171 
1172  // Lookup the property as own on the global object.
1173  LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
1175  DCHECK(maybe.has_value);
1176  PropertyAttributes old_attributes = maybe.value;
1177 
1178  PropertyAttributes attr =
1179  static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
1180  // Set the value if the property is either missing, or the property attributes
1181  // allow setting the value without invoking an accessor.
1182  if (it.IsFound()) {
1183  // Ignore if we can't reconfigure the value.
1184  if ((old_attributes & DONT_DELETE) != 0) {
1185  if ((old_attributes & READ_ONLY) != 0 ||
1186  it.state() == LookupIterator::ACCESSOR) {
1187  return *value;
1188  }
1189  attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
1190  }
1191  }
1192 
1194  global, name, value, attr));
1195 
1196  return *value;
1197 }
1198 
1199 
1200 RUNTIME_FUNCTION(Runtime_DeclareLookupSlot) {
1201  HandleScope scope(isolate);
1202  DCHECK(args.length() == 4);
1203 
1204  // Declarations are always made in a function, native, or global context. In
1205  // the case of eval code, the context passed is the context of the caller,
1206  // which may be some nested context and not the declaration context.
1207  CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 0);
1208  Handle<Context> context(context_arg->declaration_context());
1210  CONVERT_SMI_ARG_CHECKED(attr_arg, 2);
1211  PropertyAttributes attr = static_cast<PropertyAttributes>(attr_arg);
1212  RUNTIME_ASSERT(attr == READ_ONLY || attr == NONE);
1213  CONVERT_ARG_HANDLE_CHECKED(Object, initial_value, 3);
1214 
1215  // TODO(verwaest): Unify the encoding indicating "var" with DeclareGlobals.
1216  bool is_var = *initial_value == NULL;
1217  bool is_const = initial_value->IsTheHole();
1218  bool is_function = initial_value->IsJSFunction();
1219  DCHECK(is_var + is_const + is_function == 1);
1220 
1221  int index;
1222  PropertyAttributes attributes;
1224  BindingFlags binding_flags;
1225  Handle<Object> holder =
1226  context->Lookup(name, flags, &index, &attributes, &binding_flags);
1227 
1228  Handle<JSObject> object;
1229  Handle<Object> value =
1230  is_function ? initial_value
1231  : Handle<Object>::cast(isolate->factory()->undefined_value());
1232 
1233  // TODO(verwaest): This case should probably not be covered by this function,
1234  // but by DeclareGlobals instead.
1235  if ((attributes != ABSENT && holder->IsJSGlobalObject()) ||
1236  (context_arg->has_extension() &&
1237  context_arg->extension()->IsJSGlobalObject())) {
1238  return DeclareGlobals(isolate, Handle<JSGlobalObject>::cast(holder), name,
1239  value, attr, is_var, is_const, is_function);
1240  }
1241 
1242  if (attributes != ABSENT) {
1243  // The name was declared before; check for conflicting re-declarations.
1244  if (is_const || (attributes & READ_ONLY) != 0) {
1245  return ThrowRedeclarationError(isolate, name);
1246  }
1247 
1248  // Skip var re-declarations.
1249  if (is_var) return isolate->heap()->undefined_value();
1250 
1251  DCHECK(is_function);
1252  if (index >= 0) {
1253  DCHECK(holder.is_identical_to(context));
1254  context->set(index, *initial_value);
1255  return isolate->heap()->undefined_value();
1256  }
1257 
1258  object = Handle<JSObject>::cast(holder);
1259 
1260  } else if (context->has_extension()) {
1261  object = handle(JSObject::cast(context->extension()));
1262  DCHECK(object->IsJSContextExtensionObject() || object->IsJSGlobalObject());
1263  } else {
1264  DCHECK(context->IsFunctionContext());
1265  object =
1266  isolate->factory()->NewJSObject(isolate->context_extension_function());
1267  context->set_extension(*object);
1268  }
1269 
1271  object, name, value, attr));
1272 
1273  return isolate->heap()->undefined_value();
1274 }
1275 
1276 
1277 RUNTIME_FUNCTION(Runtime_InitializeLegacyConstLookupSlot) {
1278  HandleScope scope(isolate);
1279  DCHECK(args.length() == 3);
1280 
1282  DCHECK(!value->IsTheHole());
1283  // Initializations are always done in a function or native context.
1284  CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 1);
1285  Handle<Context> context(context_arg->declaration_context());
1287 
1288  int index;
1289  PropertyAttributes attributes;
1291  BindingFlags binding_flags;
1292  Handle<Object> holder =
1293  context->Lookup(name, flags, &index, &attributes, &binding_flags);
1294 
1295  if (index >= 0) {
1296  DCHECK(holder->IsContext());
1297  // Property was found in a context. Perform the assignment if the constant
1298  // was uninitialized.
1299  Handle<Context> context = Handle<Context>::cast(holder);
1300  DCHECK((attributes & READ_ONLY) != 0);
1301  if (context->get(index)->IsTheHole()) context->set(index, *value);
1302  return *value;
1303  }
1304 
1305  PropertyAttributes attr =
1306  static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
1307 
1308  // Strict mode handling not needed (legacy const is disallowed in strict
1309  // mode).
1310 
1311  // The declared const was configurable, and may have been deleted in the
1312  // meanwhile. If so, re-introduce the variable in the context extension.
1313  DCHECK(context_arg->has_extension());
1314  if (attributes == ABSENT) {
1315  holder = handle(context_arg->extension(), isolate);
1316  } else {
1317  // For JSContextExtensionObjects, the initializer can be run multiple times
1318  // if in a for loop: for (var i = 0; i < 2; i++) { const x = i; }. Only the
1319  // first assignment should go through. For JSGlobalObjects, additionally any
1320  // code can run in between that modifies the declared property.
1321  DCHECK(holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject());
1322 
1323  LookupIterator it(holder, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
1325  if (!maybe.has_value) return isolate->heap()->exception();
1326  PropertyAttributes old_attributes = maybe.value;
1327 
1328  // Ignore if we can't reconfigure the value.
1329  if ((old_attributes & DONT_DELETE) != 0) {
1330  if ((old_attributes & READ_ONLY) != 0 ||
1331  it.state() == LookupIterator::ACCESSOR) {
1332  return *value;
1333  }
1334  attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
1335  }
1336  }
1337 
1340  Handle<JSObject>::cast(holder), name, value, attr));
1341 
1342  return *value;
1343 }
1344 
1345 
1346 RUNTIME_FUNCTION(Runtime_OptimizeObjectForAddingMultipleProperties) {
1347  HandleScope scope(isolate);
1348  DCHECK(args.length() == 2);
1350  CONVERT_SMI_ARG_CHECKED(properties, 1);
1351  // Conservative upper limit to prevent fuzz tests from going OOM.
1352  RUNTIME_ASSERT(properties <= 100000);
1353  if (object->HasFastProperties() && !object->IsJSGlobalProxy()) {
1355  }
1356  return *object;
1357 }
1358 
1359 
1360 RUNTIME_FUNCTION(Runtime_FinishArrayPrototypeSetup) {
1361  HandleScope scope(isolate);
1362  DCHECK(args.length() == 1);
1363  CONVERT_ARG_HANDLE_CHECKED(JSArray, prototype, 0);
1364  Object* length = prototype->length();
1365  RUNTIME_ASSERT(length->IsSmi() && Smi::cast(length)->value() == 0);
1366  RUNTIME_ASSERT(prototype->HasFastSmiOrObjectElements());
1367  // This is necessary to enable fast checks for absence of elements
1368  // on Array.prototype and below.
1369  prototype->set_elements(isolate->heap()->empty_fixed_array());
1370  return Smi::FromInt(0);
1371 }
1372 
1373 
1374 static void InstallBuiltin(Isolate* isolate, Handle<JSObject> holder,
1375  const char* name, Builtins::Name builtin_name) {
1376  Handle<String> key = isolate->factory()->InternalizeUtf8String(name);
1377  Handle<Code> code(isolate->builtins()->builtin(builtin_name));
1378  Handle<JSFunction> optimized =
1379  isolate->factory()->NewFunctionWithoutPrototype(key, code);
1380  optimized->shared()->DontAdaptArguments();
1381  JSObject::AddProperty(holder, key, optimized, NONE);
1382 }
1383 
1384 
1385 RUNTIME_FUNCTION(Runtime_SpecialArrayFunctions) {
1386  HandleScope scope(isolate);
1387  DCHECK(args.length() == 0);
1388  Handle<JSObject> holder =
1389  isolate->factory()->NewJSObject(isolate->object_function());
1390 
1391  InstallBuiltin(isolate, holder, "pop", Builtins::kArrayPop);
1392  InstallBuiltin(isolate, holder, "push", Builtins::kArrayPush);
1393  InstallBuiltin(isolate, holder, "shift", Builtins::kArrayShift);
1394  InstallBuiltin(isolate, holder, "unshift", Builtins::kArrayUnshift);
1395  InstallBuiltin(isolate, holder, "slice", Builtins::kArraySlice);
1396  InstallBuiltin(isolate, holder, "splice", Builtins::kArraySplice);
1397  InstallBuiltin(isolate, holder, "concat", Builtins::kArrayConcat);
1398 
1399  return *holder;
1400 }
1401 
1402 
1403 RUNTIME_FUNCTION(Runtime_IsSloppyModeFunction) {
1404  SealHandleScope shs(isolate);
1405  DCHECK(args.length() == 1);
1406  CONVERT_ARG_CHECKED(JSReceiver, callable, 0);
1407  if (!callable->IsJSFunction()) {
1408  HandleScope scope(isolate);
1409  Handle<Object> delegate;
1411  isolate, delegate, Execution::TryGetFunctionDelegate(
1412  isolate, Handle<JSReceiver>(callable)));
1413  callable = JSFunction::cast(*delegate);
1414  }
1415  JSFunction* function = JSFunction::cast(callable);
1416  SharedFunctionInfo* shared = function->shared();
1417  return isolate->heap()->ToBoolean(shared->strict_mode() == SLOPPY);
1418 }
1419 
1420 
1421 RUNTIME_FUNCTION(Runtime_GetDefaultReceiver) {
1422  SealHandleScope shs(isolate);
1423  DCHECK(args.length() == 1);
1424  CONVERT_ARG_CHECKED(JSReceiver, callable, 0);
1425 
1426  if (!callable->IsJSFunction()) {
1427  HandleScope scope(isolate);
1428  Handle<Object> delegate;
1430  isolate, delegate, Execution::TryGetFunctionDelegate(
1431  isolate, Handle<JSReceiver>(callable)));
1432  callable = JSFunction::cast(*delegate);
1433  }
1434  JSFunction* function = JSFunction::cast(callable);
1435 
1436  SharedFunctionInfo* shared = function->shared();
1437  if (shared->native() || shared->strict_mode() == STRICT) {
1438  return isolate->heap()->undefined_value();
1439  }
1440  // Returns undefined for strict or native functions, or
1441  // the associated global receiver for "normal" functions.
1442 
1443  return function->global_proxy();
1444 }
1445 
1446 
1447 RUNTIME_FUNCTION(Runtime_FunctionGetName) {
1448  SealHandleScope shs(isolate);
1449  DCHECK(args.length() == 1);
1450 
1452  return f->shared()->name();
1453 }
1454 
1455 
1456 RUNTIME_FUNCTION(Runtime_FunctionSetName) {
1457  SealHandleScope shs(isolate);
1458  DCHECK(args.length() == 2);
1459 
1462  f->shared()->set_name(name);
1463  return isolate->heap()->undefined_value();
1464 }
1465 
1466 
1467 RUNTIME_FUNCTION(Runtime_FunctionNameShouldPrintAsAnonymous) {
1468  SealHandleScope shs(isolate);
1469  DCHECK(args.length() == 1);
1471  return isolate->heap()->ToBoolean(
1472  f->shared()->name_should_print_as_anonymous());
1473 }
1474 
1475 
1476 RUNTIME_FUNCTION(Runtime_FunctionMarkNameShouldPrintAsAnonymous) {
1477  SealHandleScope shs(isolate);
1478  DCHECK(args.length() == 1);
1480  f->shared()->set_name_should_print_as_anonymous(true);
1481  return isolate->heap()->undefined_value();
1482 }
1483 
1484 
1485 RUNTIME_FUNCTION(Runtime_FunctionIsGenerator) {
1486  SealHandleScope shs(isolate);
1487  DCHECK(args.length() == 1);
1489  return isolate->heap()->ToBoolean(f->shared()->is_generator());
1490 }
1491 
1492 
1493 RUNTIME_FUNCTION(Runtime_FunctionIsArrow) {
1494  SealHandleScope shs(isolate);
1495  DCHECK(args.length() == 1);
1497  return isolate->heap()->ToBoolean(f->shared()->is_arrow());
1498 }
1499 
1500 
1501 RUNTIME_FUNCTION(Runtime_FunctionIsConciseMethod) {
1502  SealHandleScope shs(isolate);
1503  DCHECK(args.length() == 1);
1505  return isolate->heap()->ToBoolean(f->shared()->is_concise_method());
1506 }
1507 
1508 
1509 RUNTIME_FUNCTION(Runtime_FunctionRemovePrototype) {
1510  SealHandleScope shs(isolate);
1511  DCHECK(args.length() == 1);
1512 
1514  RUNTIME_ASSERT(f->RemovePrototype());
1515 
1516  return isolate->heap()->undefined_value();
1517 }
1518 
1519 
1520 RUNTIME_FUNCTION(Runtime_FunctionGetScript) {
1521  HandleScope scope(isolate);
1522  DCHECK(args.length() == 1);
1523 
1525  Handle<Object> script = Handle<Object>(fun->shared()->script(), isolate);
1526  if (!script->IsScript()) return isolate->heap()->undefined_value();
1527 
1528  return *Script::GetWrapper(Handle<Script>::cast(script));
1529 }
1530 
1531 
1532 RUNTIME_FUNCTION(Runtime_FunctionGetSourceCode) {
1533  HandleScope scope(isolate);
1534  DCHECK(args.length() == 1);
1535 
1537  Handle<SharedFunctionInfo> shared(f->shared());
1538  return *shared->GetSourceCode();
1539 }
1540 
1541 
1542 RUNTIME_FUNCTION(Runtime_FunctionGetScriptSourcePosition) {
1543  SealHandleScope shs(isolate);
1544  DCHECK(args.length() == 1);
1545 
1547  int pos = fun->shared()->start_position();
1548  return Smi::FromInt(pos);
1549 }
1550 
1551 
1552 RUNTIME_FUNCTION(Runtime_FunctionGetPositionForOffset) {
1553  SealHandleScope shs(isolate);
1554  DCHECK(args.length() == 2);
1555 
1556  CONVERT_ARG_CHECKED(Code, code, 0);
1557  CONVERT_NUMBER_CHECKED(int, offset, Int32, args[1]);
1558 
1559  RUNTIME_ASSERT(0 <= offset && offset < code->Size());
1560 
1561  Address pc = code->address() + offset;
1562  return Smi::FromInt(code->SourcePosition(pc));
1563 }
1564 
1565 
1566 RUNTIME_FUNCTION(Runtime_FunctionSetInstanceClassName) {
1567  SealHandleScope shs(isolate);
1568  DCHECK(args.length() == 2);
1569 
1572  fun->SetInstanceClassName(name);
1573  return isolate->heap()->undefined_value();
1574 }
1575 
1576 
1577 RUNTIME_FUNCTION(Runtime_FunctionSetLength) {
1578  SealHandleScope shs(isolate);
1579  DCHECK(args.length() == 2);
1580 
1582  CONVERT_SMI_ARG_CHECKED(length, 1);
1583  RUNTIME_ASSERT((length & 0xC0000000) == 0xC0000000 ||
1584  (length & 0xC0000000) == 0x0);
1585  fun->shared()->set_length(length);
1586  return isolate->heap()->undefined_value();
1587 }
1588 
1589 
1590 RUNTIME_FUNCTION(Runtime_FunctionSetPrototype) {
1591  HandleScope scope(isolate);
1592  DCHECK(args.length() == 2);
1593 
1596  RUNTIME_ASSERT(fun->should_have_prototype());
1597  Accessors::FunctionSetPrototype(fun, value);
1598  return args[0]; // return TOS
1599 }
1600 
1601 
1602 RUNTIME_FUNCTION(Runtime_FunctionIsAPIFunction) {
1603  SealHandleScope shs(isolate);
1604  DCHECK(args.length() == 1);
1605 
1607  return isolate->heap()->ToBoolean(f->shared()->IsApiFunction());
1608 }
1609 
1610 
1611 RUNTIME_FUNCTION(Runtime_FunctionIsBuiltin) {
1612  SealHandleScope shs(isolate);
1613  DCHECK(args.length() == 1);
1614 
1616  return isolate->heap()->ToBoolean(f->IsBuiltin());
1617 }
1618 
1619 
1620 RUNTIME_FUNCTION(Runtime_SetCode) {
1621  HandleScope scope(isolate);
1622  DCHECK(args.length() == 2);
1623 
1626 
1627  Handle<SharedFunctionInfo> target_shared(target->shared());
1628  Handle<SharedFunctionInfo> source_shared(source->shared());
1629  RUNTIME_ASSERT(!source_shared->bound());
1630 
1631  if (!Compiler::EnsureCompiled(source, KEEP_EXCEPTION)) {
1632  return isolate->heap()->exception();
1633  }
1634 
1635  // Mark both, the source and the target, as un-flushable because the
1636  // shared unoptimized code makes them impossible to enqueue in a list.
1637  DCHECK(target_shared->code()->gc_metadata() == NULL);
1638  DCHECK(source_shared->code()->gc_metadata() == NULL);
1639  target_shared->set_dont_flush(true);
1640  source_shared->set_dont_flush(true);
1641 
1642  // Set the code, scope info, formal parameter count, and the length
1643  // of the target shared function info.
1644  target_shared->ReplaceCode(source_shared->code());
1645  target_shared->set_scope_info(source_shared->scope_info());
1646  target_shared->set_length(source_shared->length());
1647  target_shared->set_feedback_vector(source_shared->feedback_vector());
1648  target_shared->set_formal_parameter_count(
1649  source_shared->formal_parameter_count());
1650  target_shared->set_script(source_shared->script());
1651  target_shared->set_start_position_and_type(
1652  source_shared->start_position_and_type());
1653  target_shared->set_end_position(source_shared->end_position());
1654  bool was_native = target_shared->native();
1655  target_shared->set_compiler_hints(source_shared->compiler_hints());
1656  target_shared->set_native(was_native);
1657  target_shared->set_profiler_ticks(source_shared->profiler_ticks());
1658 
1659  // Set the code of the target function.
1660  target->ReplaceCode(source_shared->code());
1661  DCHECK(target->next_function_link()->IsUndefined());
1662 
1663  // Make sure we get a fresh copy of the literal vector to avoid cross
1664  // context contamination.
1665  Handle<Context> context(source->context());
1666  int number_of_literals = source->NumberOfLiterals();
1668  isolate->factory()->NewFixedArray(number_of_literals, TENURED);
1669  if (number_of_literals > 0) {
1671  context->native_context());
1672  }
1673  target->set_context(*context);
1674  target->set_literals(*literals);
1675 
1676  if (isolate->logger()->is_logging_code_events() ||
1677  isolate->cpu_profiler()->is_profiling()) {
1678  isolate->logger()->LogExistingFunction(source_shared,
1679  Handle<Code>(source_shared->code()));
1680  }
1681 
1682  return *target;
1683 }
1684 
1685 
1686 RUNTIME_FUNCTION(Runtime_CreateJSGeneratorObject) {
1687  HandleScope scope(isolate);
1688  DCHECK(args.length() == 0);
1689 
1690  JavaScriptFrameIterator it(isolate);
1691  JavaScriptFrame* frame = it.frame();
1692  Handle<JSFunction> function(frame->function());
1693  RUNTIME_ASSERT(function->shared()->is_generator());
1694 
1695  Handle<JSGeneratorObject> generator;
1696  if (frame->IsConstructor()) {
1697  generator = handle(JSGeneratorObject::cast(frame->receiver()));
1698  } else {
1699  generator = isolate->factory()->NewJSGeneratorObject(function);
1700  }
1701  generator->set_function(*function);
1702  generator->set_context(Context::cast(frame->context()));
1703  generator->set_receiver(frame->receiver());
1704  generator->set_continuation(0);
1705  generator->set_operand_stack(isolate->heap()->empty_fixed_array());
1706  generator->set_stack_handler_index(-1);
1707 
1708  return *generator;
1709 }
1710 
1711 
1712 RUNTIME_FUNCTION(Runtime_SuspendJSGeneratorObject) {
1713  HandleScope handle_scope(isolate);
1714  DCHECK(args.length() == 1);
1715  CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator_object, 0);
1716 
1717  JavaScriptFrameIterator stack_iterator(isolate);
1718  JavaScriptFrame* frame = stack_iterator.frame();
1719  RUNTIME_ASSERT(frame->function()->shared()->is_generator());
1720  DCHECK_EQ(frame->function(), generator_object->function());
1721 
1722  // The caller should have saved the context and continuation already.
1723  DCHECK_EQ(generator_object->context(), Context::cast(frame->context()));
1724  DCHECK_LT(0, generator_object->continuation());
1725 
1726  // We expect there to be at least two values on the operand stack: the return
1727  // value of the yield expression, and the argument to this runtime call.
1728  // Neither of those should be saved.
1729  int operands_count = frame->ComputeOperandsCount();
1730  DCHECK_GE(operands_count, 2);
1731  operands_count -= 2;
1732 
1733  if (operands_count == 0) {
1734  // Although it's semantically harmless to call this function with an
1735  // operands_count of zero, it is also unnecessary.
1736  DCHECK_EQ(generator_object->operand_stack(),
1737  isolate->heap()->empty_fixed_array());
1738  DCHECK_EQ(generator_object->stack_handler_index(), -1);
1739  // If there are no operands on the stack, there shouldn't be a handler
1740  // active either.
1741  DCHECK(!frame->HasHandler());
1742  } else {
1743  int stack_handler_index = -1;
1744  Handle<FixedArray> operand_stack =
1745  isolate->factory()->NewFixedArray(operands_count);
1746  frame->SaveOperandStack(*operand_stack, &stack_handler_index);
1747  generator_object->set_operand_stack(*operand_stack);
1748  generator_object->set_stack_handler_index(stack_handler_index);
1749  }
1750 
1751  return isolate->heap()->undefined_value();
1752 }
1753 
1754 
1755 // Note that this function is the slow path for resuming generators. It is only
1756 // called if the suspended activation had operands on the stack, stack handlers
1757 // needing rewinding, or if the resume should throw an exception. The fast path
1758 // is handled directly in FullCodeGenerator::EmitGeneratorResume(), which is
1759 // inlined into GeneratorNext and GeneratorThrow. EmitGeneratorResumeResume is
1760 // called in any case, as it needs to reconstruct the stack frame and make space
1761 // for arguments and operands.
1762 RUNTIME_FUNCTION(Runtime_ResumeJSGeneratorObject) {
1763  SealHandleScope shs(isolate);
1764  DCHECK(args.length() == 3);
1765  CONVERT_ARG_CHECKED(JSGeneratorObject, generator_object, 0);
1766  CONVERT_ARG_CHECKED(Object, value, 1);
1767  CONVERT_SMI_ARG_CHECKED(resume_mode_int, 2);
1768  JavaScriptFrameIterator stack_iterator(isolate);
1769  JavaScriptFrame* frame = stack_iterator.frame();
1770 
1771  DCHECK_EQ(frame->function(), generator_object->function());
1772  DCHECK(frame->function()->is_compiled());
1773 
1776 
1777  Address pc = generator_object->function()->code()->instruction_start();
1778  int offset = generator_object->continuation();
1779  DCHECK(offset > 0);
1780  frame->set_pc(pc + offset);
1781  if (FLAG_enable_ool_constant_pool) {
1782  frame->set_constant_pool(
1783  generator_object->function()->code()->constant_pool());
1784  }
1785  generator_object->set_continuation(JSGeneratorObject::kGeneratorExecuting);
1786 
1787  FixedArray* operand_stack = generator_object->operand_stack();
1788  int operands_count = operand_stack->length();
1789  if (operands_count != 0) {
1790  frame->RestoreOperandStack(operand_stack,
1791  generator_object->stack_handler_index());
1792  generator_object->set_operand_stack(isolate->heap()->empty_fixed_array());
1793  generator_object->set_stack_handler_index(-1);
1794  }
1795 
1796  JSGeneratorObject::ResumeMode resume_mode =
1797  static_cast<JSGeneratorObject::ResumeMode>(resume_mode_int);
1798  switch (resume_mode) {
1800  return value;
1802  return isolate->Throw(value);
1803  }
1804 
1805  UNREACHABLE();
1806  return isolate->ThrowIllegalOperation();
1807 }
1808 
1809 
1810 RUNTIME_FUNCTION(Runtime_ThrowGeneratorStateError) {
1811  HandleScope scope(isolate);
1812  DCHECK(args.length() == 1);
1814  int continuation = generator->continuation();
1815  const char* message = continuation == JSGeneratorObject::kGeneratorClosed
1816  ? "generator_finished"
1817  : "generator_running";
1818  Vector<Handle<Object> > argv = HandleVector<Object>(NULL, 0);
1819  THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewError(message, argv));
1820 }
1821 
1822 
1823 RUNTIME_FUNCTION(Runtime_ObjectFreeze) {
1824  HandleScope scope(isolate);
1825  DCHECK(args.length() == 1);
1827 
1828  // %ObjectFreeze is a fast path and these cases are handled elsewhere.
1829  RUNTIME_ASSERT(!object->HasSloppyArgumentsElements() &&
1830  !object->map()->is_observed() && !object->IsJSProxy());
1831 
1832  Handle<Object> result;
1833  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, JSObject::Freeze(object));
1834  return *result;
1835 }
1836 
1837 
1838 // Returns a single character string where first character equals
1839 // string->Get(index).
1841  if (index < static_cast<uint32_t>(string->length())) {
1842  Factory* factory = string->GetIsolate()->factory();
1843  return factory->LookupSingleCharacterStringFromCode(
1844  String::Flatten(string)->Get(index));
1845  }
1846  return Execution::CharAt(string, index);
1847 }
1848 
1849 
1851  Handle<Object> object,
1852  uint32_t index) {
1853  // Handle [] indexing on Strings
1854  if (object->IsString()) {
1855  Handle<Object> result = GetCharAt(Handle<String>::cast(object), index);
1856  if (!result->IsUndefined()) return result;
1857  }
1858 
1859  // Handle [] indexing on String objects
1860  if (object->IsStringObjectWithCharacterAt(index)) {
1861  Handle<JSValue> js_value = Handle<JSValue>::cast(object);
1862  Handle<Object> result =
1863  GetCharAt(Handle<String>(String::cast(js_value->value())), index);
1864  if (!result->IsUndefined()) return result;
1865  }
1866 
1867  Handle<Object> result;
1868  if (object->IsString() || object->IsNumber() || object->IsBoolean()) {
1869  PrototypeIterator iter(isolate, object);
1870  return Object::GetElement(isolate, PrototypeIterator::GetCurrent(iter),
1871  index);
1872  } else {
1873  return Object::GetElement(isolate, object, index);
1874  }
1875 }
1876 
1877 
1880  if (key->IsName()) {
1881  return Handle<Name>::cast(key);
1882  } else {
1883  Handle<Object> converted;
1884  ASSIGN_RETURN_ON_EXCEPTION(isolate, converted,
1885  Execution::ToString(isolate, key), Name);
1886  return Handle<Name>::cast(converted);
1887  }
1888 }
1889 
1890 
1892  Handle<JSReceiver> object,
1893  Handle<Object> key) {
1895  // Check if the given key is an array index.
1896  uint32_t index;
1897  if (key->ToArrayIndex(&index)) {
1898  maybe = JSReceiver::HasElement(object, index);
1899  } else {
1900  // Convert the key to a name - possibly by calling back into JavaScript.
1902  ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object);
1903 
1904  maybe = JSReceiver::HasProperty(object, name);
1905  }
1906 
1907  if (!maybe.has_value) return MaybeHandle<Object>();
1908  return isolate->factory()->ToBoolean(maybe.value);
1909 }
1910 
1911 
1913  Handle<Object> object,
1914  Handle<Object> key) {
1915  if (object->IsUndefined() || object->IsNull()) {
1916  Handle<Object> args[2] = {key, object};
1917  THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_load",
1918  HandleVector(args, 2)),
1919  Object);
1920  }
1921 
1922  // Check if the given key is an array index.
1923  uint32_t index;
1924  if (key->ToArrayIndex(&index)) {
1925  return GetElementOrCharAt(isolate, object, index);
1926  }
1927 
1928  // Convert the key to a name - possibly by calling back into JavaScript.
1930  ASSIGN_RETURN_ON_EXCEPTION(isolate, name, ToName(isolate, key), Object);
1931 
1932  // Check if the name is trivially convertible to an index and get
1933  // the element if so.
1934  if (name->AsArrayIndex(&index)) {
1935  return GetElementOrCharAt(isolate, object, index);
1936  } else {
1937  return Object::GetProperty(object, name);
1938  }
1939 }
1940 
1941 
1942 RUNTIME_FUNCTION(Runtime_GetProperty) {
1943  HandleScope scope(isolate);
1944  DCHECK(args.length() == 2);
1945 
1946  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
1948  Handle<Object> result;
1950  isolate, result, Runtime::GetObjectProperty(isolate, object, key));
1951  return *result;
1952 }
1953 
1954 
1955 // KeyedGetProperty is called from KeyedLoadIC::GenerateGeneric.
1956 RUNTIME_FUNCTION(Runtime_KeyedGetProperty) {
1957  HandleScope scope(isolate);
1958  DCHECK(args.length() == 2);
1959 
1960  CONVERT_ARG_HANDLE_CHECKED(Object, receiver_obj, 0);
1961  CONVERT_ARG_HANDLE_CHECKED(Object, key_obj, 1);
1962 
1963  // Fast cases for getting named properties of the receiver JSObject
1964  // itself.
1965  //
1966  // The global proxy objects has to be excluded since LookupOwn on
1967  // the global proxy object can return a valid result even though the
1968  // global proxy object never has properties. This is the case
1969  // because the global proxy object forwards everything to its hidden
1970  // prototype including own lookups.
1971  //
1972  // Additionally, we need to make sure that we do not cache results
1973  // for objects that require access checks.
1974  if (receiver_obj->IsJSObject()) {
1975  if (!receiver_obj->IsJSGlobalProxy() &&
1976  !receiver_obj->IsAccessCheckNeeded() && key_obj->IsName()) {
1977  DisallowHeapAllocation no_allocation;
1978  Handle<JSObject> receiver = Handle<JSObject>::cast(receiver_obj);
1979  Handle<Name> key = Handle<Name>::cast(key_obj);
1980  if (receiver->HasFastProperties()) {
1981  // Attempt to use lookup cache.
1982  Handle<Map> receiver_map(receiver->map(), isolate);
1983  KeyedLookupCache* keyed_lookup_cache = isolate->keyed_lookup_cache();
1984  int index = keyed_lookup_cache->Lookup(receiver_map, key);
1985  if (index != -1) {
1986  // Doubles are not cached, so raw read the value.
1987  return receiver->RawFastPropertyAt(
1988  FieldIndex::ForKeyedLookupCacheIndex(*receiver_map, index));
1989  }
1990  // Lookup cache miss. Perform lookup and update the cache if
1991  // appropriate.
1992  LookupIterator it(receiver, key, LookupIterator::OWN);
1993  if (it.state() == LookupIterator::DATA &&
1994  it.property_details().type() == FIELD) {
1995  FieldIndex field_index = it.GetFieldIndex();
1996  // Do not track double fields in the keyed lookup cache. Reading
1997  // double values requires boxing.
1998  if (!it.representation().IsDouble()) {
1999  keyed_lookup_cache->Update(receiver_map, key,
2000  field_index.GetKeyedLookupCacheIndex());
2001  }
2002  AllowHeapAllocation allow_allocation;
2003  return *JSObject::FastPropertyAt(receiver, it.representation(),
2004  field_index);
2005  }
2006  } else {
2007  // Attempt dictionary lookup.
2008  NameDictionary* dictionary = receiver->property_dictionary();
2009  int entry = dictionary->FindEntry(key);
2010  if ((entry != NameDictionary::kNotFound) &&
2011  (dictionary->DetailsAt(entry).type() == NORMAL)) {
2012  Object* value = dictionary->ValueAt(entry);
2013  if (!receiver->IsGlobalObject()) return value;
2014  value = PropertyCell::cast(value)->value();
2015  if (!value->IsTheHole()) return value;
2016  // If value is the hole (meaning, absent) do the general lookup.
2017  }
2018  }
2019  } else if (key_obj->IsSmi()) {
2020  // JSObject without a name key. If the key is a Smi, check for a
2021  // definite out-of-bounds access to elements, which is a strong indicator
2022  // that subsequent accesses will also call the runtime. Proactively
2023  // transition elements to FAST_*_ELEMENTS to avoid excessive boxing of
2024  // doubles for those future calls in the case that the elements would
2025  // become FAST_DOUBLE_ELEMENTS.
2026  Handle<JSObject> js_object = Handle<JSObject>::cast(receiver_obj);
2027  ElementsKind elements_kind = js_object->GetElementsKind();
2028  if (IsFastDoubleElementsKind(elements_kind)) {
2029  Handle<Smi> key = Handle<Smi>::cast(key_obj);
2030  if (key->value() >= js_object->elements()->length()) {
2031  if (IsFastHoleyElementsKind(elements_kind)) {
2032  elements_kind = FAST_HOLEY_ELEMENTS;
2033  } else {
2034  elements_kind = FAST_ELEMENTS;
2035  }
2037  isolate, TransitionElements(js_object, elements_kind, isolate));
2038  }
2039  } else {
2040  DCHECK(IsFastSmiOrObjectElementsKind(elements_kind) ||
2041  !IsFastElementsKind(elements_kind));
2042  }
2043  }
2044  } else if (receiver_obj->IsString() && key_obj->IsSmi()) {
2045  // Fast case for string indexing using [] with a smi index.
2046  Handle<String> str = Handle<String>::cast(receiver_obj);
2047  int index = args.smi_at(1);
2048  if (index >= 0 && index < str->length()) {
2049  return *GetCharAt(str, index);
2050  }
2051  }
2052 
2053  // Fall back to GetObjectProperty.
2054  Handle<Object> result;
2056  isolate, result,
2057  Runtime::GetObjectProperty(isolate, receiver_obj, key_obj));
2058  return *result;
2059 }
2060 
2061 
2063  return obj->IsUndefined() || obj->IsSpecFunction() || obj->IsNull();
2064 }
2065 
2066 
2067 // Transform getter or setter into something DefineAccessor can handle.
2069  Handle<Object> component) {
2070  if (component->IsUndefined()) return isolate->factory()->undefined_value();
2073  return Utils::OpenHandle(*Utils::ToLocal(info)->GetFunction());
2074 }
2075 
2076 
2077 RUNTIME_FUNCTION(Runtime_DefineApiAccessorProperty) {
2078  HandleScope scope(isolate);
2079  DCHECK(args.length() == 5);
2082  CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2);
2083  CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3);
2084  CONVERT_SMI_ARG_CHECKED(attribute, 4);
2085  RUNTIME_ASSERT(getter->IsUndefined() || getter->IsFunctionTemplateInfo());
2086  RUNTIME_ASSERT(setter->IsUndefined() || setter->IsFunctionTemplateInfo());
2087  RUNTIME_ASSERT(PropertyDetails::AttributesField::is_valid(
2088  static_cast<PropertyAttributes>(attribute)));
2090  isolate, JSObject::DefineAccessor(
2091  object, name, InstantiateAccessorComponent(isolate, getter),
2092  InstantiateAccessorComponent(isolate, setter),
2093  static_cast<PropertyAttributes>(attribute)));
2094  return isolate->heap()->undefined_value();
2095 }
2096 
2097 
2098 // Implements part of 8.12.9 DefineOwnProperty.
2099 // There are 3 cases that lead here:
2100 // Step 4b - define a new accessor property.
2101 // Steps 9c & 12 - replace an existing data property with an accessor property.
2102 // Step 12 - update an existing accessor property with an accessor or generic
2103 // descriptor.
2104 RUNTIME_FUNCTION(Runtime_DefineAccessorPropertyUnchecked) {
2105  HandleScope scope(isolate);
2106  DCHECK(args.length() == 5);
2108  RUNTIME_ASSERT(!obj->IsNull());
2110  CONVERT_ARG_HANDLE_CHECKED(Object, getter, 2);
2112  CONVERT_ARG_HANDLE_CHECKED(Object, setter, 3);
2114  CONVERT_SMI_ARG_CHECKED(unchecked, 4);
2115  RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
2116  PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
2117 
2118  bool fast = obj->HasFastProperties();
2120  isolate, JSObject::DefineAccessor(obj, name, getter, setter, attr));
2121  if (fast) JSObject::MigrateSlowToFast(obj, 0);
2122  return isolate->heap()->undefined_value();
2123 }
2124 
2125 
2126 // Implements part of 8.12.9 DefineOwnProperty.
2127 // There are 3 cases that lead here:
2128 // Step 4a - define a new data property.
2129 // Steps 9b & 12 - replace an existing accessor property with a data property.
2130 // Step 12 - update an existing data property with a data or generic
2131 // descriptor.
2132 RUNTIME_FUNCTION(Runtime_DefineDataPropertyUnchecked) {
2133  HandleScope scope(isolate);
2134  DCHECK(args.length() == 4);
2135  CONVERT_ARG_HANDLE_CHECKED(JSObject, js_object, 0);
2137  CONVERT_ARG_HANDLE_CHECKED(Object, obj_value, 2);
2138  CONVERT_SMI_ARG_CHECKED(unchecked, 3);
2139  RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
2140  PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
2141 
2142  LookupIterator it(js_object, name, LookupIterator::OWN_SKIP_INTERCEPTOR);
2143  if (it.IsFound() && it.state() == LookupIterator::ACCESS_CHECK) {
2144  if (!isolate->MayNamedAccess(js_object, name, v8::ACCESS_SET)) {
2145  return isolate->heap()->undefined_value();
2146  }
2147  it.Next();
2148  }
2149 
2150  // Take special care when attributes are different and there is already
2151  // a property.
2152  if (it.state() == LookupIterator::ACCESSOR) {
2153  // Use IgnoreAttributes version since a readonly property may be
2154  // overridden and SetProperty does not allow this.
2155  Handle<Object> result;
2157  isolate, result,
2159  js_object, name, obj_value, attr, JSObject::DONT_FORCE_FIELD));
2160  return *result;
2161  }
2162 
2163  Handle<Object> result;
2165  isolate, result,
2166  Runtime::DefineObjectProperty(js_object, name, obj_value, attr));
2167  return *result;
2168 }
2169 
2170 
2171 // Return property without being observable by accessors or interceptors.
2172 RUNTIME_FUNCTION(Runtime_GetDataProperty) {
2173  HandleScope scope(isolate);
2174  DCHECK(args.length() == 2);
2177  return *JSObject::GetDataProperty(object, key);
2178 }
2179 
2180 
2182  Handle<Object> object,
2183  Handle<Object> key,
2184  Handle<Object> value,
2185  StrictMode strict_mode) {
2186  if (object->IsUndefined() || object->IsNull()) {
2187  Handle<Object> args[2] = {key, object};
2188  THROW_NEW_ERROR(isolate, NewTypeError("non_object_property_store",
2189  HandleVector(args, 2)),
2190  Object);
2191  }
2192 
2193  if (object->IsJSProxy()) {
2194  Handle<Object> name_object;
2195  if (key->IsSymbol()) {
2196  name_object = key;
2197  } else {
2198  ASSIGN_RETURN_ON_EXCEPTION(isolate, name_object,
2199  Execution::ToString(isolate, key), Object);
2200  }
2201  Handle<Name> name = Handle<Name>::cast(name_object);
2202  return Object::SetProperty(Handle<JSProxy>::cast(object), name, value,
2203  strict_mode);
2204  }
2205 
2206  // Check if the given key is an array index.
2207  uint32_t index;
2208  if (key->ToArrayIndex(&index)) {
2209  // TODO(verwaest): Support non-JSObject receivers.
2210  if (!object->IsJSObject()) return value;
2211  Handle<JSObject> js_object = Handle<JSObject>::cast(object);
2212 
2213  // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
2214  // of a string using [] notation. We need to support this too in
2215  // JavaScript.
2216  // In the case of a String object we just need to redirect the assignment to
2217  // the underlying string if the index is in range. Since the underlying
2218  // string does nothing with the assignment then we can ignore such
2219  // assignments.
2220  if (js_object->IsStringObjectWithCharacterAt(index)) {
2221  return value;
2222  }
2223 
2224  JSObject::ValidateElements(js_object);
2225  if (js_object->HasExternalArrayElements() ||
2226  js_object->HasFixedTypedArrayElements()) {
2227  if (!value->IsNumber() && !value->IsUndefined()) {
2228  ASSIGN_RETURN_ON_EXCEPTION(isolate, value,
2229  Execution::ToNumber(isolate, value), Object);
2230  }
2231  }
2232 
2234  js_object, index, value, NONE, strict_mode, true, SET_PROPERTY);
2235  JSObject::ValidateElements(js_object);
2236 
2237  return result.is_null() ? result : value;
2238  }
2239 
2240  if (key->IsName()) {
2242  if (name->AsArrayIndex(&index)) {
2243  // TODO(verwaest): Support non-JSObject receivers.
2244  if (!object->IsJSObject()) return value;
2245  Handle<JSObject> js_object = Handle<JSObject>::cast(object);
2246  if (js_object->HasExternalArrayElements()) {
2247  if (!value->IsNumber() && !value->IsUndefined()) {
2249  isolate, value, Execution::ToNumber(isolate, value), Object);
2250  }
2251  }
2252  return JSObject::SetElement(js_object, index, value, NONE, strict_mode,
2253  true, SET_PROPERTY);
2254  } else {
2255  if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
2256  return Object::SetProperty(object, name, value, strict_mode);
2257  }
2258  }
2259 
2260  // Call-back into JavaScript to convert the key to a string.
2261  Handle<Object> converted;
2262  ASSIGN_RETURN_ON_EXCEPTION(isolate, converted,
2263  Execution::ToString(isolate, key), Object);
2265 
2266  if (name->AsArrayIndex(&index)) {
2267  // TODO(verwaest): Support non-JSObject receivers.
2268  if (!object->IsJSObject()) return value;
2269  Handle<JSObject> js_object = Handle<JSObject>::cast(object);
2270  return JSObject::SetElement(js_object, index, value, NONE, strict_mode,
2271  true, SET_PROPERTY);
2272  }
2273  return Object::SetProperty(object, name, value, strict_mode);
2274 }
2275 
2276 
2278  Handle<Object> key,
2279  Handle<Object> value,
2280  PropertyAttributes attr) {
2281  Isolate* isolate = js_object->GetIsolate();
2282  // Check if the given key is an array index.
2283  uint32_t index;
2284  if (key->ToArrayIndex(&index)) {
2285  // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
2286  // of a string using [] notation. We need to support this too in
2287  // JavaScript.
2288  // In the case of a String object we just need to redirect the assignment to
2289  // the underlying string if the index is in range. Since the underlying
2290  // string does nothing with the assignment then we can ignore such
2291  // assignments.
2292  if (js_object->IsStringObjectWithCharacterAt(index)) {
2293  return value;
2294  }
2295 
2296  return JSObject::SetElement(js_object, index, value, attr, SLOPPY, false,
2297  DEFINE_PROPERTY);
2298  }
2299 
2300  if (key->IsName()) {
2302  if (name->AsArrayIndex(&index)) {
2303  return JSObject::SetElement(js_object, index, value, attr, SLOPPY, false,
2304  DEFINE_PROPERTY);
2305  } else {
2306  if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
2307  return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value,
2308  attr);
2309  }
2310  }
2311 
2312  // Call-back into JavaScript to convert the key to a string.
2313  Handle<Object> converted;
2314  ASSIGN_RETURN_ON_EXCEPTION(isolate, converted,
2315  Execution::ToString(isolate, key), Object);
2317 
2318  if (name->AsArrayIndex(&index)) {
2319  return JSObject::SetElement(js_object, index, value, attr, SLOPPY, false,
2320  DEFINE_PROPERTY);
2321  } else {
2322  return JSObject::SetOwnPropertyIgnoreAttributes(js_object, name, value,
2323  attr);
2324  }
2325 }
2326 
2327 
2329  Handle<JSReceiver> receiver,
2330  Handle<Object> key,
2332  // Check if the given key is an array index.
2333  uint32_t index;
2334  if (key->ToArrayIndex(&index)) {
2335  // In Firefox/SpiderMonkey, Safari and Opera you can access the
2336  // characters of a string using [] notation. In the case of a
2337  // String object we just need to redirect the deletion to the
2338  // underlying string if the index is in range. Since the
2339  // underlying string does nothing with the deletion, we can ignore
2340  // such deletions.
2341  if (receiver->IsStringObjectWithCharacterAt(index)) {
2342  return isolate->factory()->true_value();
2343  }
2344 
2345  return JSReceiver::DeleteElement(receiver, index, mode);
2346  }
2347 
2349  if (key->IsName()) {
2350  name = Handle<Name>::cast(key);
2351  } else {
2352  // Call-back into JavaScript to convert the key to a string.
2353  Handle<Object> converted;
2354  ASSIGN_RETURN_ON_EXCEPTION(isolate, converted,
2355  Execution::ToString(isolate, key), Object);
2356  name = Handle<String>::cast(converted);
2357  }
2358 
2359  if (name->IsString()) name = String::Flatten(Handle<String>::cast(name));
2360  return JSReceiver::DeleteProperty(receiver, name, mode);
2361 }
2362 
2363 
2364 RUNTIME_FUNCTION(Runtime_SetHiddenProperty) {
2365  HandleScope scope(isolate);
2366  RUNTIME_ASSERT(args.length() == 3);
2367 
2371  RUNTIME_ASSERT(key->IsUniqueName());
2372  return *JSObject::SetHiddenProperty(object, key, value);
2373 }
2374 
2375 
2376 RUNTIME_FUNCTION(Runtime_AddNamedProperty) {
2377  HandleScope scope(isolate);
2378  RUNTIME_ASSERT(args.length() == 4);
2379 
2383  CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
2385  (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
2386  // Compute attributes.
2387  PropertyAttributes attributes =
2388  static_cast<PropertyAttributes>(unchecked_attributes);
2389 
2390 #ifdef DEBUG
2391  uint32_t index = 0;
2392  DCHECK(!key->ToArrayIndex(&index));
2393  LookupIterator it(object, key, LookupIterator::OWN_SKIP_INTERCEPTOR);
2395  if (!maybe.has_value) return isolate->heap()->exception();
2396  RUNTIME_ASSERT(!it.IsFound());
2397 #endif
2398 
2399  Handle<Object> result;
2401  isolate, result,
2402  JSObject::SetOwnPropertyIgnoreAttributes(object, key, value, attributes));
2403  return *result;
2404 }
2405 
2406 
2407 RUNTIME_FUNCTION(Runtime_AddPropertyForTemplate) {
2408  HandleScope scope(isolate);
2409  RUNTIME_ASSERT(args.length() == 4);
2410 
2414  CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
2416  (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
2417  // Compute attributes.
2418  PropertyAttributes attributes =
2419  static_cast<PropertyAttributes>(unchecked_attributes);
2420 
2421 #ifdef DEBUG
2422  bool duplicate;
2423  if (key->IsName()) {
2424  LookupIterator it(object, Handle<Name>::cast(key),
2425  LookupIterator::OWN_SKIP_INTERCEPTOR);
2427  DCHECK(maybe.has_value);
2428  duplicate = it.IsFound();
2429  } else {
2430  uint32_t index = 0;
2431  RUNTIME_ASSERT(key->ToArrayIndex(&index));
2432  Maybe<bool> maybe = JSReceiver::HasOwnElement(object, index);
2433  if (!maybe.has_value) return isolate->heap()->exception();
2434  duplicate = maybe.value;
2435  }
2436  if (duplicate) {
2437  Handle<Object> args[1] = {key};
2439  isolate,
2440  NewTypeError("duplicate_template_property", HandleVector(args, 1)));
2441  }
2442 #endif
2443 
2444  Handle<Object> result;
2446  isolate, result,
2447  Runtime::DefineObjectProperty(object, key, value, attributes));
2448  return *result;
2449 }
2450 
2451 
2452 RUNTIME_FUNCTION(Runtime_SetProperty) {
2453  HandleScope scope(isolate);
2454  RUNTIME_ASSERT(args.length() == 4);
2455 
2456  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
2459  CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode_arg, 3);
2460  StrictMode strict_mode = strict_mode_arg;
2461 
2462  Handle<Object> result;
2464  isolate, result,
2465  Runtime::SetObjectProperty(isolate, object, key, value, strict_mode));
2466  return *result;
2467 }
2468 
2469 
2470 // Adds an element to an array.
2471 // This is used to create an indexed data property into an array.
2472 RUNTIME_FUNCTION(Runtime_AddElement) {
2473  HandleScope scope(isolate);
2474  RUNTIME_ASSERT(args.length() == 4);
2475 
2479  CONVERT_SMI_ARG_CHECKED(unchecked_attributes, 3);
2481  (unchecked_attributes & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
2482  // Compute attributes.
2483  PropertyAttributes attributes =
2484  static_cast<PropertyAttributes>(unchecked_attributes);
2485 
2486  uint32_t index = 0;
2487  key->ToArrayIndex(&index);
2488 
2489  Handle<Object> result;
2491  isolate, result, JSObject::SetElement(object, index, value, attributes,
2492  SLOPPY, false, DEFINE_PROPERTY));
2493  return *result;
2494 }
2495 
2496 
2497 RUNTIME_FUNCTION(Runtime_TransitionElementsKind) {
2498  HandleScope scope(isolate);
2499  RUNTIME_ASSERT(args.length() == 2);
2502  JSObject::TransitionElementsKind(array, map->elements_kind());
2503  return *array;
2504 }
2505 
2506 
2507 // Set the native flag on the function.
2508 // This is used to decide if we should transform null and undefined
2509 // into the global object when doing call and apply.
2510 RUNTIME_FUNCTION(Runtime_SetNativeFlag) {
2511  SealHandleScope shs(isolate);
2512  RUNTIME_ASSERT(args.length() == 1);
2513 
2514  CONVERT_ARG_CHECKED(Object, object, 0);
2515 
2516  if (object->IsJSFunction()) {
2517  JSFunction* func = JSFunction::cast(object);
2518  func->shared()->set_native(true);
2519  }
2520  return isolate->heap()->undefined_value();
2521 }
2522 
2523 
2524 RUNTIME_FUNCTION(Runtime_SetInlineBuiltinFlag) {
2525  SealHandleScope shs(isolate);
2526  RUNTIME_ASSERT(args.length() == 1);
2527  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
2528 
2529  if (object->IsJSFunction()) {
2530  JSFunction* func = JSFunction::cast(*object);
2531  func->shared()->set_inline_builtin(true);
2532  }
2533  return isolate->heap()->undefined_value();
2534 }
2535 
2536 
2537 RUNTIME_FUNCTION(Runtime_StoreArrayLiteralElement) {
2538  HandleScope scope(isolate);
2539  RUNTIME_ASSERT(args.length() == 5);
2541  CONVERT_SMI_ARG_CHECKED(store_index, 1);
2544  CONVERT_SMI_ARG_CHECKED(literal_index, 4);
2545 
2546  Object* raw_literal_cell = literals->get(literal_index);
2547  JSArray* boilerplate = NULL;
2548  if (raw_literal_cell->IsAllocationSite()) {
2549  AllocationSite* site = AllocationSite::cast(raw_literal_cell);
2550  boilerplate = JSArray::cast(site->transition_info());
2551  } else {
2552  boilerplate = JSArray::cast(raw_literal_cell);
2553  }
2554  Handle<JSArray> boilerplate_object(boilerplate);
2555  ElementsKind elements_kind = object->GetElementsKind();
2556  DCHECK(IsFastElementsKind(elements_kind));
2557  // Smis should never trigger transitions.
2558  DCHECK(!value->IsSmi());
2559 
2560  if (value->IsNumber()) {
2561  DCHECK(IsFastSmiElementsKind(elements_kind));
2562  ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind)
2566  boilerplate_object->GetElementsKind(), transitioned_kind)) {
2567  JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind);
2568  }
2569  JSObject::TransitionElementsKind(object, transitioned_kind);
2570  DCHECK(IsFastDoubleElementsKind(object->GetElementsKind()));
2571  FixedDoubleArray* double_array = FixedDoubleArray::cast(object->elements());
2572  HeapNumber* number = HeapNumber::cast(*value);
2573  double_array->set(store_index, number->Number());
2574  } else {
2575  if (!IsFastObjectElementsKind(elements_kind)) {
2576  ElementsKind transitioned_kind = IsFastHoleyElementsKind(elements_kind)
2578  : FAST_ELEMENTS;
2579  JSObject::TransitionElementsKind(object, transitioned_kind);
2580  ElementsKind boilerplate_elements_kind =
2581  boilerplate_object->GetElementsKind();
2582  if (IsMoreGeneralElementsKindTransition(boilerplate_elements_kind,
2583  transitioned_kind)) {
2584  JSObject::TransitionElementsKind(boilerplate_object, transitioned_kind);
2585  }
2586  }
2587  FixedArray* object_array = FixedArray::cast(object->elements());
2588  object_array->set(store_index, *value);
2589  }
2590  return *object;
2591 }
2592 
2593 
2594 // Check whether debugger and is about to step into the callback that is passed
2595 // to a built-in function such as Array.forEach.
2596 RUNTIME_FUNCTION(Runtime_DebugCallbackSupportsStepping) {
2597  DCHECK(args.length() == 1);
2598  if (!isolate->debug()->is_active() || !isolate->debug()->StepInActive()) {
2599  return isolate->heap()->false_value();
2600  }
2601  CONVERT_ARG_CHECKED(Object, callback, 0);
2602  // We do not step into the callback if it's a builtin or not even a function.
2603  return isolate->heap()->ToBoolean(callback->IsJSFunction() &&
2604  !JSFunction::cast(callback)->IsBuiltin());
2605 }
2606 
2607 
2608 // Set one shot breakpoints for the callback function that is passed to a
2609 // built-in function such as Array.forEach to enable stepping into the callback.
2610 RUNTIME_FUNCTION(Runtime_DebugPrepareStepInIfStepping) {
2611  DCHECK(args.length() == 1);
2612  Debug* debug = isolate->debug();
2613  if (!debug->IsStepping()) return isolate->heap()->undefined_value();
2614 
2615  HandleScope scope(isolate);
2616  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
2617  RUNTIME_ASSERT(object->IsJSFunction() || object->IsJSGeneratorObject());
2618  Handle<JSFunction> fun;
2619  if (object->IsJSFunction()) {
2620  fun = Handle<JSFunction>::cast(object);
2621  } else {
2622  fun = Handle<JSFunction>(
2623  Handle<JSGeneratorObject>::cast(object)->function(), isolate);
2624  }
2625  // When leaving the function, step out has been activated, but not performed
2626  // if we do not leave the builtin. To be able to step into the function
2627  // again, we need to clear the step out at this point.
2628  debug->ClearStepOut();
2629  debug->FloodWithOneShot(fun);
2630  return isolate->heap()->undefined_value();
2631 }
2632 
2633 
2634 RUNTIME_FUNCTION(Runtime_DebugPushPromise) {
2635  DCHECK(args.length() == 1);
2636  HandleScope scope(isolate);
2637  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
2638  isolate->PushPromise(promise);
2639  return isolate->heap()->undefined_value();
2640 }
2641 
2642 
2643 RUNTIME_FUNCTION(Runtime_DebugPopPromise) {
2644  DCHECK(args.length() == 0);
2645  SealHandleScope shs(isolate);
2646  isolate->PopPromise();
2647  return isolate->heap()->undefined_value();
2648 }
2649 
2650 
2651 RUNTIME_FUNCTION(Runtime_DebugPromiseEvent) {
2652  DCHECK(args.length() == 1);
2653  HandleScope scope(isolate);
2655  isolate->debug()->OnPromiseEvent(data);
2656  return isolate->heap()->undefined_value();
2657 }
2658 
2659 
2660 RUNTIME_FUNCTION(Runtime_DebugPromiseRejectEvent) {
2661  DCHECK(args.length() == 2);
2662  HandleScope scope(isolate);
2663  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
2665  isolate->debug()->OnPromiseReject(promise, value);
2666  return isolate->heap()->undefined_value();
2667 }
2668 
2669 
2670 RUNTIME_FUNCTION(Runtime_DebugAsyncTaskEvent) {
2671  DCHECK(args.length() == 1);
2672  HandleScope scope(isolate);
2674  isolate->debug()->OnAsyncTaskEvent(data);
2675  return isolate->heap()->undefined_value();
2676 }
2677 
2678 
2679 RUNTIME_FUNCTION(Runtime_DeleteProperty) {
2680  HandleScope scope(isolate);
2681  DCHECK(args.length() == 3);
2684  CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 2);
2685  JSReceiver::DeleteMode delete_mode = strict_mode == STRICT
2688  Handle<Object> result;
2690  isolate, result, JSReceiver::DeleteProperty(object, key, delete_mode));
2691  return *result;
2692 }
2693 
2694 
2696  Handle<JSObject> object,
2697  Handle<Name> key) {
2699  if (!maybe.has_value) return isolate->heap()->exception();
2700  if (maybe.value) return isolate->heap()->true_value();
2701  // Handle hidden prototypes. If there's a hidden prototype above this thing
2702  // then we have to check it for properties, because they are supposed to
2703  // look like they are on this object.
2704  PrototypeIterator iter(isolate, object);
2705  if (!iter.IsAtEnd() &&
2707  ->map()
2708  ->is_hidden_prototype()) {
2709  // TODO(verwaest): The recursion is not necessary for keys that are array
2710  // indices. Removing this.
2713  key);
2714  }
2716  return isolate->heap()->false_value();
2717 }
2718 
2719 
2720 RUNTIME_FUNCTION(Runtime_HasOwnProperty) {
2721  HandleScope scope(isolate);
2722  DCHECK(args.length() == 2);
2725 
2726  uint32_t index;
2727  const bool key_is_array_index = key->AsArrayIndex(&index);
2728 
2729  // Only JS objects can have properties.
2730  if (object->IsJSObject()) {
2731  Handle<JSObject> js_obj = Handle<JSObject>::cast(object);
2732  // Fast case: either the key is a real named property or it is not
2733  // an array index and there are no interceptors or hidden
2734  // prototypes.
2736  if (!maybe.has_value) return isolate->heap()->exception();
2737  DCHECK(!isolate->has_pending_exception());
2738  if (maybe.value) {
2739  return isolate->heap()->true_value();
2740  }
2741  Map* map = js_obj->map();
2742  if (!key_is_array_index && !map->has_named_interceptor() &&
2743  !HeapObject::cast(map->prototype())->map()->is_hidden_prototype()) {
2744  return isolate->heap()->false_value();
2745  }
2746  // Slow case.
2747  return HasOwnPropertyImplementation(isolate, Handle<JSObject>(js_obj),
2748  Handle<Name>(key));
2749  } else if (object->IsString() && key_is_array_index) {
2750  // Well, there is one exception: Handle [] on strings.
2751  Handle<String> string = Handle<String>::cast(object);
2752  if (index < static_cast<uint32_t>(string->length())) {
2753  return isolate->heap()->true_value();
2754  }
2755  }
2756  return isolate->heap()->false_value();
2757 }
2758 
2759 
2760 RUNTIME_FUNCTION(Runtime_HasProperty) {
2761  HandleScope scope(isolate);
2762  DCHECK(args.length() == 2);
2763  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
2765 
2766  Maybe<bool> maybe = JSReceiver::HasProperty(receiver, key);
2767  if (!maybe.has_value) return isolate->heap()->exception();
2768  return isolate->heap()->ToBoolean(maybe.value);
2769 }
2770 
2771 
2772 RUNTIME_FUNCTION(Runtime_HasElement) {
2773  HandleScope scope(isolate);
2774  DCHECK(args.length() == 2);
2775  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
2776  CONVERT_SMI_ARG_CHECKED(index, 1);
2777 
2778  Maybe<bool> maybe = JSReceiver::HasElement(receiver, index);
2779  if (!maybe.has_value) return isolate->heap()->exception();
2780  return isolate->heap()->ToBoolean(maybe.value);
2781 }
2782 
2783 
2784 RUNTIME_FUNCTION(Runtime_IsPropertyEnumerable) {
2785  HandleScope scope(isolate);
2786  DCHECK(args.length() == 2);
2787 
2790 
2793  if (!maybe.has_value) return isolate->heap()->exception();
2794  if (maybe.value == ABSENT) maybe.value = DONT_ENUM;
2795  return isolate->heap()->ToBoolean((maybe.value & DONT_ENUM) == 0);
2796 }
2797 
2798 
2799 RUNTIME_FUNCTION(Runtime_GetPropertyNames) {
2800  HandleScope scope(isolate);
2801  DCHECK(args.length() == 1);
2803  Handle<JSArray> result;
2804 
2805  isolate->counters()->for_in()->Increment();
2806  Handle<FixedArray> elements;
2808  isolate, elements,
2810  return *isolate->factory()->NewJSArrayWithElements(elements);
2811 }
2812 
2813 
2814 // Returns either a FixedArray as Runtime_GetPropertyNames,
2815 // or, if the given object has an enum cache that contains
2816 // all enumerable properties of the object and its prototypes
2817 // have none, the map of the object. This is used to speed up
2818 // the check for deletions during a for-in.
2819 RUNTIME_FUNCTION(Runtime_GetPropertyNamesFast) {
2820  SealHandleScope shs(isolate);
2821  DCHECK(args.length() == 1);
2822 
2823  CONVERT_ARG_CHECKED(JSReceiver, raw_object, 0);
2824 
2825  if (raw_object->IsSimpleEnum()) return raw_object->map();
2826 
2827  HandleScope scope(isolate);
2828  Handle<JSReceiver> object(raw_object);
2829  Handle<FixedArray> content;
2831  isolate, content,
2833 
2834  // Test again, since cache may have been built by preceding call.
2835  if (object->IsSimpleEnum()) return object->map();
2836 
2837  return *content;
2838 }
2839 
2840 
2841 // Find the length of the prototype chain that is to be handled as one. If a
2842 // prototype object is hidden it is to be viewed as part of the the object it
2843 // is prototype for.
2845  int count = 1;
2846  for (PrototypeIterator iter(obj->GetIsolate(), obj);
2847  !iter.IsAtEnd(PrototypeIterator::END_AT_NON_HIDDEN); iter.Advance()) {
2848  count++;
2849  }
2850  return count;
2851 }
2852 
2853 
2854 // Return the names of the own named properties.
2855 // args[0]: object
2856 // args[1]: PropertyAttributes as int
2857 RUNTIME_FUNCTION(Runtime_GetOwnPropertyNames) {
2858  HandleScope scope(isolate);
2859  DCHECK(args.length() == 2);
2860  if (!args[0]->IsJSObject()) {
2861  return isolate->heap()->undefined_value();
2862  }
2864  CONVERT_SMI_ARG_CHECKED(filter_value, 1);
2865  PropertyAttributes filter = static_cast<PropertyAttributes>(filter_value);
2866 
2867  // Skip the global proxy as it has no properties and always delegates to the
2868  // real global object.
2869  if (obj->IsJSGlobalProxy()) {
2870  // Only collect names if access is permitted.
2871  if (obj->IsAccessCheckNeeded() &&
2872  !isolate->MayNamedAccess(obj, isolate->factory()->undefined_value(),
2873  v8::ACCESS_KEYS)) {
2874  isolate->ReportFailedAccessCheck(obj, v8::ACCESS_KEYS);
2876  return *isolate->factory()->NewJSArray(0);
2877  }
2878  PrototypeIterator iter(isolate, obj);
2880  }
2881 
2882  // Find the number of objects making up this.
2883  int length = OwnPrototypeChainLength(*obj);
2884 
2885  // Find the number of own properties for each of the objects.
2886  ScopedVector<int> own_property_count(length);
2887  int total_property_count = 0;
2888  {
2890  for (int i = 0; i < length; i++) {
2891  DCHECK(!iter.IsAtEnd());
2892  Handle<JSObject> jsproto =
2894  // Only collect names if access is permitted.
2895  if (jsproto->IsAccessCheckNeeded() &&
2896  !isolate->MayNamedAccess(jsproto,
2897  isolate->factory()->undefined_value(),
2898  v8::ACCESS_KEYS)) {
2899  isolate->ReportFailedAccessCheck(jsproto, v8::ACCESS_KEYS);
2901  return *isolate->factory()->NewJSArray(0);
2902  }
2903  int n;
2904  n = jsproto->NumberOfOwnProperties(filter);
2905  own_property_count[i] = n;
2906  total_property_count += n;
2907  iter.Advance();
2908  }
2909  }
2910 
2911  // Allocate an array with storage for all the property names.
2912  Handle<FixedArray> names =
2913  isolate->factory()->NewFixedArray(total_property_count);
2914 
2915  // Get the property names.
2916  int next_copy_index = 0;
2917  int hidden_strings = 0;
2918  {
2920  for (int i = 0; i < length; i++) {
2921  DCHECK(!iter.IsAtEnd());
2922  Handle<JSObject> jsproto =
2924  jsproto->GetOwnPropertyNames(*names, next_copy_index, filter);
2925  if (i > 0) {
2926  // Names from hidden prototypes may already have been added
2927  // for inherited function template instances. Count the duplicates
2928  // and stub them out; the final copy pass at the end ignores holes.
2929  for (int j = next_copy_index;
2930  j < next_copy_index + own_property_count[i]; j++) {
2931  Object* name_from_hidden_proto = names->get(j);
2932  for (int k = 0; k < next_copy_index; k++) {
2933  if (names->get(k) != isolate->heap()->hidden_string()) {
2934  Object* name = names->get(k);
2935  if (name_from_hidden_proto == name) {
2936  names->set(j, isolate->heap()->hidden_string());
2937  hidden_strings++;
2938  break;
2939  }
2940  }
2941  }
2942  }
2943  }
2944  next_copy_index += own_property_count[i];
2945 
2946  // Hidden properties only show up if the filter does not skip strings.
2947  if ((filter & STRING) == 0 && JSObject::HasHiddenProperties(jsproto)) {
2948  hidden_strings++;
2949  }
2950  iter.Advance();
2951  }
2952  }
2953 
2954  // Filter out name of hidden properties object and
2955  // hidden prototype duplicates.
2956  if (hidden_strings > 0) {
2957  Handle<FixedArray> old_names = names;
2958  names = isolate->factory()->NewFixedArray(names->length() - hidden_strings);
2959  int dest_pos = 0;
2960  for (int i = 0; i < total_property_count; i++) {
2961  Object* name = old_names->get(i);
2962  if (name == isolate->heap()->hidden_string()) {
2963  hidden_strings--;
2964  continue;
2965  }
2966  names->set(dest_pos++, name);
2967  }
2968  DCHECK_EQ(0, hidden_strings);
2969  }
2970 
2971  return *isolate->factory()->NewJSArrayWithElements(names);
2972 }
2973 
2974 
2975 // Return the names of the own indexed properties.
2976 // args[0]: object
2977 RUNTIME_FUNCTION(Runtime_GetOwnElementNames) {
2978  HandleScope scope(isolate);
2979  DCHECK(args.length() == 1);
2980  if (!args[0]->IsJSObject()) {
2981  return isolate->heap()->undefined_value();
2982  }
2984 
2985  int n = obj->NumberOfOwnElements(static_cast<PropertyAttributes>(NONE));
2986  Handle<FixedArray> names = isolate->factory()->NewFixedArray(n);
2987  obj->GetOwnElementKeys(*names, static_cast<PropertyAttributes>(NONE));
2988  return *isolate->factory()->NewJSArrayWithElements(names);
2989 }
2990 
2991 
2992 // Return information on whether an object has a named or indexed interceptor.
2993 // args[0]: object
2994 RUNTIME_FUNCTION(Runtime_GetInterceptorInfo) {
2995  HandleScope scope(isolate);
2996  DCHECK(args.length() == 1);
2997  if (!args[0]->IsJSObject()) {
2998  return Smi::FromInt(0);
2999  }
3001 
3002  int result = 0;
3003  if (obj->HasNamedInterceptor()) result |= 2;
3004  if (obj->HasIndexedInterceptor()) result |= 1;
3005 
3006  return Smi::FromInt(result);
3007 }
3008 
3009 
3010 // Return property names from named interceptor.
3011 // args[0]: object
3012 RUNTIME_FUNCTION(Runtime_GetNamedInterceptorPropertyNames) {
3013  HandleScope scope(isolate);
3014  DCHECK(args.length() == 1);
3016 
3017  if (obj->HasNamedInterceptor()) {
3018  Handle<JSObject> result;
3019  if (JSObject::GetKeysForNamedInterceptor(obj, obj).ToHandle(&result)) {
3020  return *result;
3021  }
3022  }
3023  return isolate->heap()->undefined_value();
3024 }
3025 
3026 
3027 // Return element names from indexed interceptor.
3028 // args[0]: object
3029 RUNTIME_FUNCTION(Runtime_GetIndexedInterceptorElementNames) {
3030  HandleScope scope(isolate);
3031  DCHECK(args.length() == 1);
3033 
3034  if (obj->HasIndexedInterceptor()) {
3035  Handle<JSObject> result;
3036  if (JSObject::GetKeysForIndexedInterceptor(obj, obj).ToHandle(&result)) {
3037  return *result;
3038  }
3039  }
3040  return isolate->heap()->undefined_value();
3041 }
3042 
3043 
3044 RUNTIME_FUNCTION(Runtime_OwnKeys) {
3045  HandleScope scope(isolate);
3046  DCHECK(args.length() == 1);
3047  CONVERT_ARG_CHECKED(JSObject, raw_object, 0);
3048  Handle<JSObject> object(raw_object);
3049 
3050  if (object->IsJSGlobalProxy()) {
3051  // Do access checks before going to the global object.
3052  if (object->IsAccessCheckNeeded() &&
3053  !isolate->MayNamedAccess(object, isolate->factory()->undefined_value(),
3054  v8::ACCESS_KEYS)) {
3055  isolate->ReportFailedAccessCheck(object, v8::ACCESS_KEYS);
3057  return *isolate->factory()->NewJSArray(0);
3058  }
3059 
3060  PrototypeIterator iter(isolate, object);
3061  // If proxy is detached we simply return an empty array.
3062  if (iter.IsAtEnd()) return *isolate->factory()->NewJSArray(0);
3064  }
3065 
3066  Handle<FixedArray> contents;
3068  isolate, contents, JSReceiver::GetKeys(object, JSReceiver::OWN_ONLY));
3069 
3070  // Some fast paths through GetKeysInFixedArrayFor reuse a cached
3071  // property array and since the result is mutable we have to create
3072  // a fresh clone on each invocation.
3073  int length = contents->length();
3074  Handle<FixedArray> copy = isolate->factory()->NewFixedArray(length);
3075  for (int i = 0; i < length; i++) {
3076  Object* entry = contents->get(i);
3077  if (entry->IsString()) {
3078  copy->set(i, entry);
3079  } else {
3080  DCHECK(entry->IsNumber());
3081  HandleScope scope(isolate);
3082  Handle<Object> entry_handle(entry, isolate);
3083  Handle<Object> entry_str =
3084  isolate->factory()->NumberToString(entry_handle);
3085  copy->set(i, *entry_str);
3086  }
3087  }
3088  return *isolate->factory()->NewJSArrayWithElements(copy);
3089 }
3090 
3091 
3092 RUNTIME_FUNCTION(Runtime_GetArgumentsProperty) {
3093  SealHandleScope shs(isolate);
3094  DCHECK(args.length() == 1);
3095  CONVERT_ARG_HANDLE_CHECKED(Object, raw_key, 0);
3096 
3097  // Compute the frame holding the arguments.
3098  JavaScriptFrameIterator it(isolate);
3099  it.AdvanceToArgumentsFrame();
3100  JavaScriptFrame* frame = it.frame();
3101 
3102  // Get the actual number of provided arguments.
3103  const uint32_t n = frame->ComputeParametersCount();
3104 
3105  // Try to convert the key to an index. If successful and within
3106  // index return the the argument from the frame.
3107  uint32_t index;
3108  if (raw_key->ToArrayIndex(&index) && index < n) {
3109  return frame->GetParameter(index);
3110  }
3111 
3112  HandleScope scope(isolate);
3113  if (raw_key->IsSymbol()) {
3114  Handle<Symbol> symbol = Handle<Symbol>::cast(raw_key);
3115  if (symbol->Equals(isolate->native_context()->iterator_symbol())) {
3116  return isolate->native_context()->array_values_iterator();
3117  }
3118  // Lookup in the initial Object.prototype object.
3119  Handle<Object> result;
3121  isolate, result,
3122  Object::GetProperty(isolate->initial_object_prototype(),
3123  Handle<Symbol>::cast(raw_key)));
3124  return *result;
3125  }
3126 
3127  // Convert the key to a string.
3128  Handle<Object> converted;
3129  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, converted,
3130  Execution::ToString(isolate, raw_key));
3131  Handle<String> key = Handle<String>::cast(converted);
3132 
3133  // Try to convert the string key into an array index.
3134  if (key->AsArrayIndex(&index)) {
3135  if (index < n) {
3136  return frame->GetParameter(index);
3137  } else {
3138  Handle<Object> initial_prototype(isolate->initial_object_prototype());
3139  Handle<Object> result;
3141  isolate, result,
3142  Object::GetElement(isolate, initial_prototype, index));
3143  return *result;
3144  }
3145  }
3146 
3147  // Handle special arguments properties.
3148  if (String::Equals(isolate->factory()->length_string(), key)) {
3149  return Smi::FromInt(n);
3150  }
3151  if (String::Equals(isolate->factory()->callee_string(), key)) {
3152  JSFunction* function = frame->function();
3153  if (function->shared()->strict_mode() == STRICT) {
3155  isolate, NewTypeError("strict_arguments_callee",
3156  HandleVector<Object>(NULL, 0)));
3157  }
3158  return function;
3159  }
3160 
3161  // Lookup in the initial Object.prototype object.
3162  Handle<Object> result;
3164  isolate, result,
3165  Object::GetProperty(isolate->initial_object_prototype(), key));
3166  return *result;
3167 }
3168 
3169 
3170 RUNTIME_FUNCTION(Runtime_ToFastProperties) {
3171  HandleScope scope(isolate);
3172  DCHECK(args.length() == 1);
3173  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
3174  if (object->IsJSObject() && !object->IsGlobalObject()) {
3176  }
3177  return *object;
3178 }
3179 
3180 
3181 RUNTIME_FUNCTION(Runtime_ToBool) {
3182  SealHandleScope shs(isolate);
3183  DCHECK(args.length() == 1);
3184  CONVERT_ARG_CHECKED(Object, object, 0);
3185 
3186  return isolate->heap()->ToBoolean(object->BooleanValue());
3187 }
3188 
3189 
3190 // Returns the type string of a value; see ECMA-262, 11.4.3 (p 47).
3191 // Possible optimizations: put the type string into the oddballs.
3192 RUNTIME_FUNCTION(Runtime_Typeof) {
3193  SealHandleScope shs(isolate);
3194  DCHECK(args.length() == 1);
3195  CONVERT_ARG_CHECKED(Object, obj, 0);
3196  if (obj->IsNumber()) return isolate->heap()->number_string();
3197  HeapObject* heap_obj = HeapObject::cast(obj);
3198 
3199  // typeof an undetectable object is 'undefined'
3200  if (heap_obj->map()->is_undetectable()) {
3201  return isolate->heap()->undefined_string();
3202  }
3203 
3204  InstanceType instance_type = heap_obj->map()->instance_type();
3205  if (instance_type < FIRST_NONSTRING_TYPE) {
3206  return isolate->heap()->string_string();
3207  }
3208 
3209  switch (instance_type) {
3210  case ODDBALL_TYPE:
3211  if (heap_obj->IsTrue() || heap_obj->IsFalse()) {
3212  return isolate->heap()->boolean_string();
3213  }
3214  if (heap_obj->IsNull()) {
3215  return isolate->heap()->object_string();
3216  }
3217  DCHECK(heap_obj->IsUndefined());
3218  return isolate->heap()->undefined_string();
3219  case SYMBOL_TYPE:
3220  return isolate->heap()->symbol_string();
3221  case JS_FUNCTION_TYPE:
3223  return isolate->heap()->function_string();
3224  default:
3225  // For any kind of object not handled above, the spec rule for
3226  // host objects gives that it is okay to return "object"
3227  return isolate->heap()->object_string();
3228  }
3229 }
3230 
3231 
3232 RUNTIME_FUNCTION(Runtime_Booleanize) {
3233  SealHandleScope shs(isolate);
3234  DCHECK(args.length() == 2);
3235  CONVERT_ARG_CHECKED(Object, value_raw, 0);
3236  CONVERT_SMI_ARG_CHECKED(token_raw, 1);
3237  intptr_t value = reinterpret_cast<intptr_t>(value_raw);
3238  Token::Value token = static_cast<Token::Value>(token_raw);
3239  switch (token) {
3240  case Token::EQ:
3241  case Token::EQ_STRICT:
3242  return isolate->heap()->ToBoolean(value == 0);
3243  case Token::NE:
3244  case Token::NE_STRICT:
3245  return isolate->heap()->ToBoolean(value != 0);
3246  case Token::LT:
3247  return isolate->heap()->ToBoolean(value < 0);
3248  case Token::GT:
3249  return isolate->heap()->ToBoolean(value > 0);
3250  case Token::LTE:
3251  return isolate->heap()->ToBoolean(value <= 0);
3252  case Token::GTE:
3253  return isolate->heap()->ToBoolean(value >= 0);
3254  default:
3255  // This should only happen during natives fuzzing.
3256  return isolate->heap()->undefined_value();
3257  }
3258 }
3259 
3260 
3261 RUNTIME_FUNCTION(Runtime_NewStringWrapper) {
3262  HandleScope scope(isolate);
3263  DCHECK(args.length() == 1);
3265  return *Object::ToObject(isolate, value).ToHandleChecked();
3266 }
3267 
3268 
3269 RUNTIME_FUNCTION(Runtime_AllocateHeapNumber) {
3270  HandleScope scope(isolate);
3271  DCHECK(args.length() == 0);
3272  return *isolate->factory()->NewHeapNumber(0);
3273 }
3274 
3275 
3276 
3277 
3278 
3279 RUNTIME_FUNCTION(Runtime_DateMakeDay) {
3280  SealHandleScope shs(isolate);
3281  DCHECK(args.length() == 2);
3282 
3283  CONVERT_SMI_ARG_CHECKED(year, 0);
3284  CONVERT_SMI_ARG_CHECKED(month, 1);
3285 
3286  int days = isolate->date_cache()->DaysFromYearMonth(year, month);
3288  return Smi::FromInt(days);
3289 }
3290 
3291 
3292 RUNTIME_FUNCTION(Runtime_DateSetValue) {
3293  HandleScope scope(isolate);
3294  DCHECK(args.length() == 3);
3295 
3297  CONVERT_DOUBLE_ARG_CHECKED(time, 1);
3298  CONVERT_SMI_ARG_CHECKED(is_utc, 2);
3299 
3300  DateCache* date_cache = isolate->date_cache();
3301 
3302  Handle<Object> value;
3303  ;
3304  bool is_value_nan = false;
3305  if (std::isnan(time)) {
3306  value = isolate->factory()->nan_value();
3307  is_value_nan = true;
3308  } else if (!is_utc && (time < -DateCache::kMaxTimeBeforeUTCInMs ||
3310  value = isolate->factory()->nan_value();
3311  is_value_nan = true;
3312  } else {
3313  time = is_utc ? time : date_cache->ToUTC(static_cast<int64_t>(time));
3314  if (time < -DateCache::kMaxTimeInMs || time > DateCache::kMaxTimeInMs) {
3315  value = isolate->factory()->nan_value();
3316  is_value_nan = true;
3317  } else {
3318  value = isolate->factory()->NewNumber(DoubleToInteger(time));
3319  }
3320  }
3321  date->SetValue(*value, is_value_nan);
3322  return *value;
3323 }
3324 
3325 
3327  Handle<JSFunction> callee,
3328  Object** parameters,
3329  int argument_count) {
3330  Handle<JSObject> result =
3331  isolate->factory()->NewArgumentsObject(callee, argument_count);
3332 
3333  // Allocate the elements if needed.
3334  int parameter_count = callee->shared()->formal_parameter_count();
3335  if (argument_count > 0) {
3336  if (parameter_count > 0) {
3337  int mapped_count = Min(argument_count, parameter_count);
3338  Handle<FixedArray> parameter_map =
3339  isolate->factory()->NewFixedArray(mapped_count + 2, NOT_TENURED);
3340  parameter_map->set_map(isolate->heap()->sloppy_arguments_elements_map());
3341 
3342  Handle<Map> map = Map::Copy(handle(result->map()));
3343  map->set_elements_kind(SLOPPY_ARGUMENTS_ELEMENTS);
3344 
3345  result->set_map(*map);
3346  result->set_elements(*parameter_map);
3347 
3348  // Store the context and the arguments array at the beginning of the
3349  // parameter map.
3350  Handle<Context> context(isolate->context());
3351  Handle<FixedArray> arguments =
3352  isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
3353  parameter_map->set(0, *context);
3354  parameter_map->set(1, *arguments);
3355 
3356  // Loop over the actual parameters backwards.
3357  int index = argument_count - 1;
3358  while (index >= mapped_count) {
3359  // These go directly in the arguments array and have no
3360  // corresponding slot in the parameter map.
3361  arguments->set(index, *(parameters - index - 1));
3362  --index;
3363  }
3364 
3365  Handle<ScopeInfo> scope_info(callee->shared()->scope_info());
3366  while (index >= 0) {
3367  // Detect duplicate names to the right in the parameter list.
3368  Handle<String> name(scope_info->ParameterName(index));
3369  int context_local_count = scope_info->ContextLocalCount();
3370  bool duplicate = false;
3371  for (int j = index + 1; j < parameter_count; ++j) {
3372  if (scope_info->ParameterName(j) == *name) {
3373  duplicate = true;
3374  break;
3375  }
3376  }
3377 
3378  if (duplicate) {
3379  // This goes directly in the arguments array with a hole in the
3380  // parameter map.
3381  arguments->set(index, *(parameters - index - 1));
3382  parameter_map->set_the_hole(index + 2);
3383  } else {
3384  // The context index goes in the parameter map with a hole in the
3385  // arguments array.
3386  int context_index = -1;
3387  for (int j = 0; j < context_local_count; ++j) {
3388  if (scope_info->ContextLocalName(j) == *name) {
3389  context_index = j;
3390  break;
3391  }
3392  }
3393  DCHECK(context_index >= 0);
3394  arguments->set_the_hole(index);
3395  parameter_map->set(
3396  index + 2,
3397  Smi::FromInt(Context::MIN_CONTEXT_SLOTS + context_index));
3398  }
3399 
3400  --index;
3401  }
3402  } else {
3403  // If there is no aliasing, the arguments object elements are not
3404  // special in any way.
3405  Handle<FixedArray> elements =
3406  isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
3407  result->set_elements(*elements);
3408  for (int i = 0; i < argument_count; ++i) {
3409  elements->set(i, *(parameters - i - 1));
3410  }
3411  }
3412  }
3413  return result;
3414 }
3415 
3416 
3418  Handle<JSFunction> callee,
3419  Object** parameters,
3420  int argument_count) {
3421  Handle<JSObject> result =
3422  isolate->factory()->NewArgumentsObject(callee, argument_count);
3423 
3424  if (argument_count > 0) {
3425  Handle<FixedArray> array =
3426  isolate->factory()->NewUninitializedFixedArray(argument_count);
3427  DisallowHeapAllocation no_gc;
3428  WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc);
3429  for (int i = 0; i < argument_count; i++) {
3430  array->set(i, *--parameters, mode);
3431  }
3432  result->set_elements(*array);
3433  }
3434  return result;
3435 }
3436 
3437 
3438 RUNTIME_FUNCTION(Runtime_NewArguments) {
3439  HandleScope scope(isolate);
3440  DCHECK(args.length() == 1);
3442  JavaScriptFrameIterator it(isolate);
3443 
3444  // Find the frame that holds the actual arguments passed to the function.
3445  it.AdvanceToArgumentsFrame();
3446  JavaScriptFrame* frame = it.frame();
3447 
3448  // Determine parameter location on the stack and dispatch on language mode.
3449  int argument_count = frame->GetArgumentsLength();
3450  Object** parameters = reinterpret_cast<Object**>(frame->GetParameterSlot(-1));
3451  return callee->shared()->strict_mode() == STRICT
3452  ? *NewStrictArguments(isolate, callee, parameters, argument_count)
3453  : *NewSloppyArguments(isolate, callee, parameters, argument_count);
3454 }
3455 
3456 
3457 RUNTIME_FUNCTION(Runtime_NewSloppyArguments) {
3458  HandleScope scope(isolate);
3459  DCHECK(args.length() == 3);
3461  Object** parameters = reinterpret_cast<Object**>(args[1]);
3462  CONVERT_SMI_ARG_CHECKED(argument_count, 2);
3463  return *NewSloppyArguments(isolate, callee, parameters, argument_count);
3464 }
3465 
3466 
3467 RUNTIME_FUNCTION(Runtime_NewStrictArguments) {
3468  HandleScope scope(isolate);
3469  DCHECK(args.length() == 3);
3471  Object** parameters = reinterpret_cast<Object**>(args[1]);
3472  CONVERT_SMI_ARG_CHECKED(argument_count, 2);
3473  return *NewStrictArguments(isolate, callee, parameters, argument_count);
3474 }
3475 
3476 
3477 RUNTIME_FUNCTION(Runtime_NewClosureFromStubFailure) {
3478  HandleScope scope(isolate);
3479  DCHECK(args.length() == 1);
3481  Handle<Context> context(isolate->context());
3482  PretenureFlag pretenure_flag = NOT_TENURED;
3483  return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
3484  pretenure_flag);
3485 }
3486 
3487 
3488 RUNTIME_FUNCTION(Runtime_NewClosure) {
3489  HandleScope scope(isolate);
3490  DCHECK(args.length() == 3);
3491  CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
3493  CONVERT_BOOLEAN_ARG_CHECKED(pretenure, 2);
3494 
3495  // The caller ensures that we pretenure closures that are assigned
3496  // directly to properties.
3497  PretenureFlag pretenure_flag = pretenure ? TENURED : NOT_TENURED;
3498  return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
3499  pretenure_flag);
3500 }
3501 
3502 
3503 // Find the arguments of the JavaScript function invocation that called
3504 // into C++ code. Collect these in a newly allocated array of handles (possibly
3505 // prefixed by a number of empty handles).
3507  int prefix_argc,
3508  int* total_argc) {
3509  // Find frame containing arguments passed to the caller.
3510  JavaScriptFrameIterator it(isolate);
3511  JavaScriptFrame* frame = it.frame();
3512  List<JSFunction*> functions(2);
3513  frame->GetFunctions(&functions);
3514  if (functions.length() > 1) {
3515  int inlined_jsframe_index = functions.length() - 1;
3516  JSFunction* inlined_function = functions[inlined_jsframe_index];
3517  SlotRefValueBuilder slot_refs(
3518  frame, inlined_jsframe_index,
3519  inlined_function->shared()->formal_parameter_count());
3520 
3521  int args_count = slot_refs.args_length();
3522 
3523  *total_argc = prefix_argc + args_count;
3524  SmartArrayPointer<Handle<Object> > param_data(
3525  NewArray<Handle<Object> >(*total_argc));
3526  slot_refs.Prepare(isolate);
3527  for (int i = 0; i < args_count; i++) {
3528  Handle<Object> val = slot_refs.GetNext(isolate, 0);
3529  param_data[prefix_argc + i] = val;
3530  }
3531  slot_refs.Finish(isolate);
3532 
3533  return param_data;
3534  } else {
3535  it.AdvanceToArgumentsFrame();
3536  frame = it.frame();
3537  int args_count = frame->ComputeParametersCount();
3538 
3539  *total_argc = prefix_argc + args_count;
3540  SmartArrayPointer<Handle<Object> > param_data(
3541  NewArray<Handle<Object> >(*total_argc));
3542  for (int i = 0; i < args_count; i++) {
3543  Handle<Object> val = Handle<Object>(frame->GetParameter(i), isolate);
3544  param_data[prefix_argc + i] = val;
3545  }
3546  return param_data;
3547  }
3548 }
3549 
3550 
3551 RUNTIME_FUNCTION(Runtime_FunctionBindArguments) {
3552  HandleScope scope(isolate);
3553  DCHECK(args.length() == 4);
3554  CONVERT_ARG_HANDLE_CHECKED(JSFunction, bound_function, 0);
3555  CONVERT_ARG_HANDLE_CHECKED(Object, bindee, 1);
3556  CONVERT_ARG_HANDLE_CHECKED(Object, this_object, 2);
3557  CONVERT_NUMBER_ARG_HANDLE_CHECKED(new_length, 3);
3558 
3559  // TODO(lrn): Create bound function in C++ code from premade shared info.
3560  bound_function->shared()->set_bound(true);
3561  // Get all arguments of calling function (Function.prototype.bind).
3562  int argc = 0;
3563  SmartArrayPointer<Handle<Object> > arguments =
3564  GetCallerArguments(isolate, 0, &argc);
3565  // Don't count the this-arg.
3566  if (argc > 0) {
3567  RUNTIME_ASSERT(arguments[0].is_identical_to(this_object));
3568  argc--;
3569  } else {
3570  RUNTIME_ASSERT(this_object->IsUndefined());
3571  }
3572  // Initialize array of bindings (function, this, and any existing arguments
3573  // if the function was already bound).
3574  Handle<FixedArray> new_bindings;
3575  int i;
3576  if (bindee->IsJSFunction() && JSFunction::cast(*bindee)->shared()->bound()) {
3577  Handle<FixedArray> old_bindings(
3578  JSFunction::cast(*bindee)->function_bindings());
3579  RUNTIME_ASSERT(old_bindings->length() > JSFunction::kBoundFunctionIndex);
3580  new_bindings =
3581  isolate->factory()->NewFixedArray(old_bindings->length() + argc);
3582  bindee = Handle<Object>(old_bindings->get(JSFunction::kBoundFunctionIndex),
3583  isolate);
3584  i = 0;
3585  for (int n = old_bindings->length(); i < n; i++) {
3586  new_bindings->set(i, old_bindings->get(i));
3587  }
3588  } else {
3589  int array_size = JSFunction::kBoundArgumentsStartIndex + argc;
3590  new_bindings = isolate->factory()->NewFixedArray(array_size);
3591  new_bindings->set(JSFunction::kBoundFunctionIndex, *bindee);
3592  new_bindings->set(JSFunction::kBoundThisIndex, *this_object);
3593  i = 2;
3594  }
3595  // Copy arguments, skipping the first which is "this_arg".
3596  for (int j = 0; j < argc; j++, i++) {
3597  new_bindings->set(i, *arguments[j + 1]);
3598  }
3599  new_bindings->set_map_no_write_barrier(
3600  isolate->heap()->fixed_cow_array_map());
3601  bound_function->set_function_bindings(*new_bindings);
3602 
3603  // Update length. Have to remove the prototype first so that map migration
3604  // is happy about the number of fields.
3605  RUNTIME_ASSERT(bound_function->RemovePrototype());
3606  Handle<Map> bound_function_map(
3607  isolate->native_context()->bound_function_map());
3608  JSObject::MigrateToMap(bound_function, bound_function_map);
3609  Handle<String> length_string = isolate->factory()->length_string();
3610  PropertyAttributes attr =
3614  bound_function, length_string, new_length, attr));
3615  return *bound_function;
3616 }
3617 
3618 
3619 RUNTIME_FUNCTION(Runtime_BoundFunctionGetBindings) {
3620  HandleScope handles(isolate);
3621  DCHECK(args.length() == 1);
3622  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, callable, 0);
3623  if (callable->IsJSFunction()) {
3624  Handle<JSFunction> function = Handle<JSFunction>::cast(callable);
3625  if (function->shared()->bound()) {
3626  Handle<FixedArray> bindings(function->function_bindings());
3627  RUNTIME_ASSERT(bindings->map() == isolate->heap()->fixed_cow_array_map());
3628  return *isolate->factory()->NewJSArrayWithElements(bindings);
3629  }
3630  }
3631  return isolate->heap()->undefined_value();
3632 }
3633 
3634 
3635 RUNTIME_FUNCTION(Runtime_NewObjectFromBound) {
3636  HandleScope scope(isolate);
3637  DCHECK(args.length() == 1);
3638  // First argument is a function to use as a constructor.
3639  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
3640  RUNTIME_ASSERT(function->shared()->bound());
3641 
3642  // The argument is a bound function. Extract its bound arguments
3643  // and callable.
3644  Handle<FixedArray> bound_args =
3645  Handle<FixedArray>(FixedArray::cast(function->function_bindings()));
3646  int bound_argc = bound_args->length() - JSFunction::kBoundArgumentsStartIndex;
3647  Handle<Object> bound_function(
3648  JSReceiver::cast(bound_args->get(JSFunction::kBoundFunctionIndex)),
3649  isolate);
3650  DCHECK(!bound_function->IsJSFunction() ||
3651  !Handle<JSFunction>::cast(bound_function)->shared()->bound());
3652 
3653  int total_argc = 0;
3654  SmartArrayPointer<Handle<Object> > param_data =
3655  GetCallerArguments(isolate, bound_argc, &total_argc);
3656  for (int i = 0; i < bound_argc; i++) {
3657  param_data[i] = Handle<Object>(
3658  bound_args->get(JSFunction::kBoundArgumentsStartIndex + i), isolate);
3659  }
3660 
3661  if (!bound_function->IsJSFunction()) {
3663  isolate, bound_function,
3664  Execution::TryGetConstructorDelegate(isolate, bound_function));
3665  }
3666  DCHECK(bound_function->IsJSFunction());
3667 
3668  Handle<Object> result;
3670  isolate, result, Execution::New(Handle<JSFunction>::cast(bound_function),
3671  total_argc, param_data.get()));
3672  return *result;
3673 }
3674 
3675 
3677  Handle<Object> constructor,
3678  Handle<AllocationSite> site) {
3679  // If the constructor isn't a proper function we throw a type error.
3680  if (!constructor->IsJSFunction()) {
3681  Vector<Handle<Object> > arguments = HandleVector(&constructor, 1);
3683  NewTypeError("not_constructor", arguments));
3684  }
3685 
3686  Handle<JSFunction> function = Handle<JSFunction>::cast(constructor);
3687 
3688  // If function should not have prototype, construction is not allowed. In this
3689  // case generated code bailouts here, since function has no initial_map.
3690  if (!function->should_have_prototype() && !function->shared()->bound()) {
3691  Vector<Handle<Object> > arguments = HandleVector(&constructor, 1);
3693  NewTypeError("not_constructor", arguments));
3694  }
3695 
3696  Debug* debug = isolate->debug();
3697  // Handle stepping into constructors if step into is active.
3698  if (debug->StepInActive()) {
3699  debug->HandleStepIn(function, Handle<Object>::null(), 0, true);
3700  }
3701 
3702  if (function->has_initial_map()) {
3703  if (function->initial_map()->instance_type() == JS_FUNCTION_TYPE) {
3704  // The 'Function' function ignores the receiver object when
3705  // called using 'new' and creates a new JSFunction object that
3706  // is returned. The receiver object is only used for error
3707  // reporting if an error occurs when constructing the new
3708  // JSFunction. Factory::NewJSObject() should not be used to
3709  // allocate JSFunctions since it does not properly initialize
3710  // the shared part of the function. Since the receiver is
3711  // ignored anyway, we use the global object as the receiver
3712  // instead of a new JSFunction object. This way, errors are
3713  // reported the same way whether or not 'Function' is called
3714  // using 'new'.
3715  return isolate->global_proxy();
3716  }
3717  }
3718 
3719  // The function should be compiled for the optimization hints to be
3720  // available.
3722 
3723  Handle<JSObject> result;
3724  if (site.is_null()) {
3725  result = isolate->factory()->NewJSObject(function);
3726  } else {
3727  result = isolate->factory()->NewJSObjectWithMemento(function, site);
3728  }
3729 
3730  isolate->counters()->constructed_objects()->Increment();
3731  isolate->counters()->constructed_objects_runtime()->Increment();
3732 
3733  return *result;
3734 }
3735 
3736 
3737 RUNTIME_FUNCTION(Runtime_NewObject) {
3738  HandleScope scope(isolate);
3739  DCHECK(args.length() == 1);
3740  CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 0);
3741  return Runtime_NewObjectHelper(isolate, constructor,
3743 }
3744 
3745 
3746 RUNTIME_FUNCTION(Runtime_NewObjectWithAllocationSite) {
3747  HandleScope scope(isolate);
3748  DCHECK(args.length() == 2);
3749  CONVERT_ARG_HANDLE_CHECKED(Object, constructor, 1);
3750  CONVERT_ARG_HANDLE_CHECKED(Object, feedback, 0);
3752  if (feedback->IsAllocationSite()) {
3753  // The feedback can be an AllocationSite or undefined.
3754  site = Handle<AllocationSite>::cast(feedback);
3755  }
3756  return Runtime_NewObjectHelper(isolate, constructor, site);
3757 }
3758 
3759 
3760 RUNTIME_FUNCTION(Runtime_FinalizeInstanceSize) {
3761  HandleScope scope(isolate);
3762  DCHECK(args.length() == 1);
3763 
3764  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
3765  function->CompleteInobjectSlackTracking();
3766 
3767  return isolate->heap()->undefined_value();
3768 }
3769 
3770 
3771 RUNTIME_FUNCTION(Runtime_CheckIsBootstrapping) {
3772  SealHandleScope shs(isolate);
3773  DCHECK(args.length() == 0);
3774  RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
3775  return isolate->heap()->undefined_value();
3776 }
3777 
3778 
3779 RUNTIME_FUNCTION(Runtime_GetRootNaN) {
3780  SealHandleScope shs(isolate);
3781  DCHECK(args.length() == 0);
3782  RUNTIME_ASSERT(isolate->bootstrapper()->IsActive());
3783  return isolate->heap()->nan_value();
3784 }
3785 
3786 
3787 RUNTIME_FUNCTION(Runtime_Call) {
3788  HandleScope scope(isolate);
3789  DCHECK(args.length() >= 2);
3790  int argc = args.length() - 2;
3791  CONVERT_ARG_CHECKED(JSReceiver, fun, argc + 1);
3792  Object* receiver = args[0];
3793 
3794  // If there are too many arguments, allocate argv via malloc.
3795  const int argv_small_size = 10;
3796  Handle<Object> argv_small_buffer[argv_small_size];
3797  SmartArrayPointer<Handle<Object> > argv_large_buffer;
3798  Handle<Object>* argv = argv_small_buffer;
3799  if (argc > argv_small_size) {
3800  argv = new Handle<Object>[argc];
3801  if (argv == NULL) return isolate->StackOverflow();
3802  argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv);
3803  }
3804 
3805  for (int i = 0; i < argc; ++i) {
3806  argv[i] = Handle<Object>(args[1 + i], isolate);
3807  }
3808 
3809  Handle<JSReceiver> hfun(fun);
3810  Handle<Object> hreceiver(receiver, isolate);
3811  Handle<Object> result;
3813  isolate, result,
3814  Execution::Call(isolate, hfun, hreceiver, argc, argv, true));
3815  return *result;
3816 }
3817 
3818 
3819 RUNTIME_FUNCTION(Runtime_Apply) {
3820  HandleScope scope(isolate);
3821  DCHECK(args.length() == 5);
3823  CONVERT_ARG_HANDLE_CHECKED(Object, receiver, 1);
3824  CONVERT_ARG_HANDLE_CHECKED(JSObject, arguments, 2);
3825  CONVERT_INT32_ARG_CHECKED(offset, 3);
3826  CONVERT_INT32_ARG_CHECKED(argc, 4);
3827  RUNTIME_ASSERT(offset >= 0);
3828  // Loose upper bound to allow fuzzing. We'll most likely run out of
3829  // stack space before hitting this limit.
3830  static int kMaxArgc = 1000000;
3831  RUNTIME_ASSERT(argc >= 0 && argc <= kMaxArgc);
3832 
3833  // If there are too many arguments, allocate argv via malloc.
3834  const int argv_small_size = 10;
3835  Handle<Object> argv_small_buffer[argv_small_size];
3836  SmartArrayPointer<Handle<Object> > argv_large_buffer;
3837  Handle<Object>* argv = argv_small_buffer;
3838  if (argc > argv_small_size) {
3839  argv = new Handle<Object>[argc];
3840  if (argv == NULL) return isolate->StackOverflow();
3841  argv_large_buffer = SmartArrayPointer<Handle<Object> >(argv);
3842  }
3843 
3844  for (int i = 0; i < argc; ++i) {
3846  isolate, argv[i], Object::GetElement(isolate, arguments, offset + i));
3847  }
3848 
3849  Handle<Object> result;
3851  isolate, result,
3852  Execution::Call(isolate, fun, receiver, argc, argv, true));
3853  return *result;
3854 }
3855 
3856 
3857 RUNTIME_FUNCTION(Runtime_GetFunctionDelegate) {
3858  HandleScope scope(isolate);
3859  DCHECK(args.length() == 1);
3860  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
3861  RUNTIME_ASSERT(!object->IsJSFunction());
3862  return *Execution::GetFunctionDelegate(isolate, object);
3863 }
3864 
3865 
3866 RUNTIME_FUNCTION(Runtime_GetConstructorDelegate) {
3867  HandleScope scope(isolate);
3868  DCHECK(args.length() == 1);
3869  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
3870  RUNTIME_ASSERT(!object->IsJSFunction());
3871  return *Execution::GetConstructorDelegate(isolate, object);
3872 }
3873 
3874 
3875 RUNTIME_FUNCTION(Runtime_NewGlobalContext) {
3876  HandleScope scope(isolate);
3877  DCHECK(args.length() == 2);
3878 
3879  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
3880  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
3881  Handle<Context> result =
3882  isolate->factory()->NewGlobalContext(function, scope_info);
3883 
3884  DCHECK(function->context() == isolate->context());
3885  DCHECK(function->context()->global_object() == result->global_object());
3886  result->global_object()->set_global_context(*result);
3887  return *result;
3888 }
3889 
3890 
3891 RUNTIME_FUNCTION(Runtime_NewFunctionContext) {
3892  HandleScope scope(isolate);
3893  DCHECK(args.length() == 1);
3894 
3895  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
3896 
3897  DCHECK(function->context() == isolate->context());
3898  int length = function->shared()->scope_info()->ContextLength();
3899  return *isolate->factory()->NewFunctionContext(length, function);
3900 }
3901 
3902 
3903 RUNTIME_FUNCTION(Runtime_PushWithContext) {
3904  HandleScope scope(isolate);
3905  DCHECK(args.length() == 2);
3906  Handle<JSReceiver> extension_object;
3907  if (args[0]->IsJSReceiver()) {
3908  extension_object = args.at<JSReceiver>(0);
3909  } else {
3910  // Try to convert the object to a proper JavaScript object.
3911  MaybeHandle<JSReceiver> maybe_object =
3912  Object::ToObject(isolate, args.at<Object>(0));
3913  if (!maybe_object.ToHandle(&extension_object)) {
3914  Handle<Object> handle = args.at<Object>(0);
3916  isolate, NewTypeError("with_expression", HandleVector(&handle, 1)));
3917  }
3918  }
3919 
3920  Handle<JSFunction> function;
3921  if (args[1]->IsSmi()) {
3922  // A smi sentinel indicates a context nested inside global code rather
3923  // than some function. There is a canonical empty function that can be
3924  // gotten from the native context.
3925  function = handle(isolate->native_context()->closure());
3926  } else {
3927  function = args.at<JSFunction>(1);
3928  }
3929 
3930  Handle<Context> current(isolate->context());
3931  Handle<Context> context =
3932  isolate->factory()->NewWithContext(function, current, extension_object);
3933  isolate->set_context(*context);
3934  return *context;
3935 }
3936 
3937 
3938 RUNTIME_FUNCTION(Runtime_PushCatchContext) {
3939  HandleScope scope(isolate);
3940  DCHECK(args.length() == 3);
3942  CONVERT_ARG_HANDLE_CHECKED(Object, thrown_object, 1);
3943  Handle<JSFunction> function;
3944  if (args[2]->IsSmi()) {
3945  // A smi sentinel indicates a context nested inside global code rather
3946  // than some function. There is a canonical empty function that can be
3947  // gotten from the native context.
3948  function = handle(isolate->native_context()->closure());
3949  } else {
3950  function = args.at<JSFunction>(2);
3951  }
3952  Handle<Context> current(isolate->context());
3953  Handle<Context> context = isolate->factory()->NewCatchContext(
3954  function, current, name, thrown_object);
3955  isolate->set_context(*context);
3956  return *context;
3957 }
3958 
3959 
3960 RUNTIME_FUNCTION(Runtime_PushBlockContext) {
3961  HandleScope scope(isolate);
3962  DCHECK(args.length() == 2);
3963  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
3964  Handle<JSFunction> function;
3965  if (args[1]->IsSmi()) {
3966  // A smi sentinel indicates a context nested inside global code rather
3967  // than some function. There is a canonical empty function that can be
3968  // gotten from the native context.
3969  function = handle(isolate->native_context()->closure());
3970  } else {
3971  function = args.at<JSFunction>(1);
3972  }
3973  Handle<Context> current(isolate->context());
3974  Handle<Context> context =
3975  isolate->factory()->NewBlockContext(function, current, scope_info);
3976  isolate->set_context(*context);
3977  return *context;
3978 }
3979 
3980 
3981 RUNTIME_FUNCTION(Runtime_IsJSModule) {
3982  SealHandleScope shs(isolate);
3983  DCHECK(args.length() == 1);
3984  CONVERT_ARG_CHECKED(Object, obj, 0);
3985  return isolate->heap()->ToBoolean(obj->IsJSModule());
3986 }
3987 
3988 
3989 RUNTIME_FUNCTION(Runtime_PushModuleContext) {
3990  SealHandleScope shs(isolate);
3991  DCHECK(args.length() == 2);
3992  CONVERT_SMI_ARG_CHECKED(index, 0);
3993 
3994  if (!args[1]->IsScopeInfo()) {
3995  // Module already initialized. Find hosting context and retrieve context.
3996  Context* host = Context::cast(isolate->context())->global_context();
3997  Context* context = Context::cast(host->get(index));
3998  DCHECK(context->previous() == isolate->context());
3999  isolate->set_context(context);
4000  return context;
4001  }
4002 
4003  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
4004 
4005  // Allocate module context.
4006  HandleScope scope(isolate);
4007  Factory* factory = isolate->factory();
4008  Handle<Context> context = factory->NewModuleContext(scope_info);
4009  Handle<JSModule> module = factory->NewJSModule(context, scope_info);
4010  context->set_module(*module);
4011  Context* previous = isolate->context();
4012  context->set_previous(previous);
4013  context->set_closure(previous->closure());
4014  context->set_global_object(previous->global_object());
4015  isolate->set_context(*context);
4016 
4017  // Find hosting scope and initialize internal variable holding module there.
4018  previous->global_context()->set(index, *context);
4019 
4020  return *context;
4021 }
4022 
4023 
4024 RUNTIME_FUNCTION(Runtime_DeclareModules) {
4025  HandleScope scope(isolate);
4026  DCHECK(args.length() == 1);
4027  CONVERT_ARG_HANDLE_CHECKED(FixedArray, descriptions, 0);
4028  Context* host_context = isolate->context();
4029 
4030  for (int i = 0; i < descriptions->length(); ++i) {
4031  Handle<ModuleInfo> description(ModuleInfo::cast(descriptions->get(i)));
4032  int host_index = description->host_index();
4033  Handle<Context> context(Context::cast(host_context->get(host_index)));
4034  Handle<JSModule> module(context->module());
4035 
4036  for (int j = 0; j < description->length(); ++j) {
4037  Handle<String> name(description->name(j));
4038  VariableMode mode = description->mode(j);
4039  int index = description->index(j);
4040  switch (mode) {
4041  case VAR:
4042  case LET:
4043  case CONST:
4044  case CONST_LEGACY: {
4045  PropertyAttributes attr =
4047  Handle<AccessorInfo> info =
4048  Accessors::MakeModuleExport(name, index, attr);
4049  Handle<Object> result =
4050  JSObject::SetAccessor(module, info).ToHandleChecked();
4051  DCHECK(!result->IsUndefined());
4052  USE(result);
4053  break;
4054  }
4055  case MODULE: {
4056  Object* referenced_context = Context::cast(host_context)->get(index);
4057  Handle<JSModule> value(Context::cast(referenced_context)->module());
4059  .Assert();
4060  break;
4061  }
4062  case INTERNAL:
4063  case TEMPORARY:
4064  case DYNAMIC:
4065  case DYNAMIC_GLOBAL:
4066  case DYNAMIC_LOCAL:
4067  UNREACHABLE();
4068  }
4069  }
4070 
4071  JSObject::PreventExtensions(module).Assert();
4072  }
4073 
4074  DCHECK(!isolate->has_pending_exception());
4075  return isolate->heap()->undefined_value();
4076 }
4077 
4078 
4079 RUNTIME_FUNCTION(Runtime_DeleteLookupSlot) {
4080  HandleScope scope(isolate);
4081  DCHECK(args.length() == 2);
4082 
4083  CONVERT_ARG_HANDLE_CHECKED(Context, context, 0);
4085 
4086  int index;
4087  PropertyAttributes attributes;
4089  BindingFlags binding_flags;
4090  Handle<Object> holder =
4091  context->Lookup(name, flags, &index, &attributes, &binding_flags);
4092 
4093  // If the slot was not found the result is true.
4094  if (holder.is_null()) {
4095  return isolate->heap()->true_value();
4096  }
4097 
4098  // If the slot was found in a context, it should be DONT_DELETE.
4099  if (holder->IsContext()) {
4100  return isolate->heap()->false_value();
4101  }
4102 
4103  // The slot was found in a JSObject, either a context extension object,
4104  // the global object, or the subject of a with. Try to delete it
4105  // (respecting DONT_DELETE).
4106  Handle<JSObject> object = Handle<JSObject>::cast(holder);
4107  Handle<Object> result;
4108  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
4109  JSReceiver::DeleteProperty(object, name));
4110  return *result;
4111 }
4112 
4113 
4115  DCHECK(!holder->IsGlobalObject());
4116  Context* top = isolate->context();
4117  // Get the context extension function.
4118  JSFunction* context_extension_function =
4119  top->native_context()->context_extension_function();
4120  // If the holder isn't a context extension object, we just return it
4121  // as the receiver. This allows arguments objects to be used as
4122  // receivers, but only if they are put in the context scope chain
4123  // explicitly via a with-statement.
4124  Object* constructor = holder->map()->constructor();
4125  if (constructor != context_extension_function) return holder;
4126  // Fall back to using the global object as the implicit receiver if
4127  // the property turns out to be a local variable allocated in a
4128  // context extension object - introduced via eval.
4129  return isolate->heap()->undefined_value();
4130 }
4131 
4132 
4134  bool throw_error) {
4135  HandleScope scope(isolate);
4136  DCHECK_EQ(2, args.length());
4137 
4138  if (!args[0]->IsContext() || !args[1]->IsString()) {
4139  return MakePair(isolate->ThrowIllegalOperation(), NULL);
4140  }
4141  Handle<Context> context = args.at<Context>(0);
4142  Handle<String> name = args.at<String>(1);
4143 
4144  int index;
4145  PropertyAttributes attributes;
4147  BindingFlags binding_flags;
4148  Handle<Object> holder =
4149  context->Lookup(name, flags, &index, &attributes, &binding_flags);
4150  if (isolate->has_pending_exception()) {
4151  return MakePair(isolate->heap()->exception(), NULL);
4152  }
4153 
4154  // If the index is non-negative, the slot has been found in a context.
4155  if (index >= 0) {
4156  DCHECK(holder->IsContext());
4157  // If the "property" we were looking for is a local variable, the
4158  // receiver is the global object; see ECMA-262, 3rd., 10.1.6 and 10.2.3.
4159  Handle<Object> receiver = isolate->factory()->undefined_value();
4160  Object* value = Context::cast(*holder)->get(index);
4161  // Check for uninitialized bindings.
4162  switch (binding_flags) {
4165  if (value->IsTheHole()) {
4166  Handle<Object> error;
4167  MaybeHandle<Object> maybe_error =
4168  isolate->factory()->NewReferenceError("not_defined",
4169  HandleVector(&name, 1));
4170  if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
4171  return MakePair(isolate->heap()->exception(), NULL);
4172  }
4173  // FALLTHROUGH
4177  DCHECK(!value->IsTheHole());
4178  return MakePair(value, *receiver);
4180  if (value->IsTheHole()) {
4181  DCHECK((attributes & READ_ONLY) != 0);
4182  value = isolate->heap()->undefined_value();
4183  }
4184  return MakePair(value, *receiver);
4185  case MISSING_BINDING:
4186  UNREACHABLE();
4187  return MakePair(NULL, NULL);
4188  }
4189  }
4190 
4191  // Otherwise, if the slot was found the holder is a context extension
4192  // object, subject of a with, or a global object. We read the named
4193  // property from it.
4194  if (!holder.is_null()) {
4196 #ifdef DEBUG
4197  if (!object->IsJSProxy()) {
4199  DCHECK(maybe.has_value);
4200  DCHECK(maybe.value);
4201  }
4202 #endif
4203  // GetProperty below can cause GC.
4204  Handle<Object> receiver_handle(
4205  object->IsGlobalObject()
4206  ? Object::cast(isolate->heap()->undefined_value())
4207  : object->IsJSProxy() ? static_cast<Object*>(*object)
4209  isolate, JSObject::cast(*object)),
4210  isolate);
4211 
4212  // No need to unhole the value here. This is taken care of by the
4213  // GetProperty function.
4214  Handle<Object> value;
4216  isolate, value, Object::GetProperty(object, name),
4217  MakePair(isolate->heap()->exception(), NULL));
4218  return MakePair(*value, *receiver_handle);
4219  }
4220 
4221  if (throw_error) {
4222  // The property doesn't exist - throw exception.
4223  Handle<Object> error;
4224  MaybeHandle<Object> maybe_error = isolate->factory()->NewReferenceError(
4225  "not_defined", HandleVector(&name, 1));
4226  if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
4227  return MakePair(isolate->heap()->exception(), NULL);
4228  } else {
4229  // The property doesn't exist - return undefined.
4230  return MakePair(isolate->heap()->undefined_value(),
4231  isolate->heap()->undefined_value());
4232  }
4233 }
4234 
4235 
4236 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlot) {
4237  return LoadLookupSlotHelper(args, isolate, true);
4238 }
4239 
4240 
4241 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlotNoReferenceError) {
4242  return LoadLookupSlotHelper(args, isolate, false);
4243 }
4244 
4245 
4246 RUNTIME_FUNCTION(Runtime_StoreLookupSlot) {
4247  HandleScope scope(isolate);
4248  DCHECK(args.length() == 4);
4249 
4251  CONVERT_ARG_HANDLE_CHECKED(Context, context, 1);
4253  CONVERT_STRICT_MODE_ARG_CHECKED(strict_mode, 3);
4254 
4255  int index;
4256  PropertyAttributes attributes;
4258  BindingFlags binding_flags;
4259  Handle<Object> holder =
4260  context->Lookup(name, flags, &index, &attributes, &binding_flags);
4261  // In case of JSProxy, an exception might have been thrown.
4262  if (isolate->has_pending_exception()) return isolate->heap()->exception();
4263 
4264  // The property was found in a context slot.
4265  if (index >= 0) {
4266  if ((attributes & READ_ONLY) == 0) {
4267  Handle<Context>::cast(holder)->set(index, *value);
4268  } else if (strict_mode == STRICT) {
4269  // Setting read only property in strict mode.
4271  isolate,
4272  NewTypeError("strict_cannot_assign", HandleVector(&name, 1)));
4273  }
4274  return *value;
4275  }
4276 
4277  // Slow case: The property is not in a context slot. It is either in a
4278  // context extension object, a property of the subject of a with, or a
4279  // property of the global object.
4280  Handle<JSReceiver> object;
4281  if (attributes != ABSENT) {
4282  // The property exists on the holder.
4283  object = Handle<JSReceiver>::cast(holder);
4284  } else if (strict_mode == STRICT) {
4285  // If absent in strict mode: throw.
4287  isolate, NewReferenceError("not_defined", HandleVector(&name, 1)));
4288  } else {
4289  // If absent in sloppy mode: add the property to the global object.
4290  object = Handle<JSReceiver>(context->global_object());
4291  }
4292 
4294  isolate, Object::SetProperty(object, name, value, strict_mode));
4295 
4296  return *value;
4297 }
4298 
4299 
4300 RUNTIME_FUNCTION(Runtime_Throw) {
4301  HandleScope scope(isolate);
4302  DCHECK(args.length() == 1);
4303 
4304  return isolate->Throw(args[0]);
4305 }
4306 
4307 
4308 RUNTIME_FUNCTION(Runtime_ReThrow) {
4309  HandleScope scope(isolate);
4310  DCHECK(args.length() == 1);
4311 
4312  return isolate->ReThrow(args[0]);
4313 }
4314 
4315 
4316 RUNTIME_FUNCTION(Runtime_PromoteScheduledException) {
4317  SealHandleScope shs(isolate);
4318  DCHECK(args.length() == 0);
4319  return isolate->PromoteScheduledException();
4320 }
4321 
4322 
4323 RUNTIME_FUNCTION(Runtime_ThrowReferenceError) {
4324  HandleScope scope(isolate);
4325  DCHECK(args.length() == 1);
4328  isolate, NewReferenceError("not_defined", HandleVector(&name, 1)));
4329 }
4330 
4331 
4332 RUNTIME_FUNCTION(Runtime_ThrowNonMethodError) {
4333  HandleScope scope(isolate);
4334  DCHECK(args.length() == 0);
4336  isolate, NewReferenceError("non_method", HandleVector<Object>(NULL, 0)));
4337 }
4338 
4339 
4340 RUNTIME_FUNCTION(Runtime_ThrowUnsupportedSuperError) {
4341  HandleScope scope(isolate);
4342  DCHECK(args.length() == 0);
4344  isolate,
4345  NewReferenceError("unsupported_super", HandleVector<Object>(NULL, 0)));
4346 }
4347 
4348 
4349 RUNTIME_FUNCTION(Runtime_ThrowNotDateError) {
4350  HandleScope scope(isolate);
4351  DCHECK(args.length() == 0);
4353  isolate, NewTypeError("not_date_object", HandleVector<Object>(NULL, 0)));
4354 }
4355 
4356 
4357 RUNTIME_FUNCTION(Runtime_StackGuard) {
4358  SealHandleScope shs(isolate);
4359  DCHECK(args.length() == 0);
4360 
4361  // First check if this is a real stack overflow.
4362  StackLimitCheck check(isolate);
4363  if (check.JsHasOverflowed()) {
4364  return isolate->StackOverflow();
4365  }
4366 
4367  return isolate->stack_guard()->HandleInterrupts();
4368 }
4369 
4370 
4371 RUNTIME_FUNCTION(Runtime_Interrupt) {
4372  SealHandleScope shs(isolate);
4373  DCHECK(args.length() == 0);
4374  return isolate->stack_guard()->HandleInterrupts();
4375 }
4376 
4377 
4378 static int StackSize(Isolate* isolate) {
4379  int n = 0;
4380  for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) n++;
4381  return n;
4382 }
4383 
4384 
4385 static void PrintTransition(Isolate* isolate, Object* result) {
4386  // indentation
4387  {
4388  const int nmax = 80;
4389  int n = StackSize(isolate);
4390  if (n <= nmax)
4391  PrintF("%4d:%*s", n, n, "");
4392  else
4393  PrintF("%4d:%*s", n, nmax, "...");
4394  }
4395 
4396  if (result == NULL) {
4397  JavaScriptFrame::PrintTop(isolate, stdout, true, false);
4398  PrintF(" {\n");
4399  } else {
4400  // function result
4401  PrintF("} -> ");
4402  result->ShortPrint();
4403  PrintF("\n");
4404  }
4405 }
4406 
4407 
4408 RUNTIME_FUNCTION(Runtime_TraceEnter) {
4409  SealHandleScope shs(isolate);
4410  DCHECK(args.length() == 0);
4411  PrintTransition(isolate, NULL);
4412  return isolate->heap()->undefined_value();
4413 }
4414 
4415 
4416 RUNTIME_FUNCTION(Runtime_TraceExit) {
4417  SealHandleScope shs(isolate);
4418  DCHECK(args.length() == 1);
4419  CONVERT_ARG_CHECKED(Object, obj, 0);
4420  PrintTransition(isolate, obj);
4421  return obj; // return TOS
4422 }
4423 
4424 
4425 RUNTIME_FUNCTION(Runtime_DateCurrentTime) {
4426  HandleScope scope(isolate);
4427  DCHECK(args.length() == 0);
4428  if (FLAG_log_timer_events) LOG(isolate, CurrentTimeEvent());
4429 
4430  // According to ECMA-262, section 15.9.1, page 117, the precision of
4431  // the number in a Date object representing a particular instant in
4432  // time is milliseconds. Therefore, we floor the result of getting
4433  // the OS time.
4434  double millis;
4435  if (FLAG_verify_predictable) {
4436  millis = 1388534400000.0; // Jan 1 2014 00:00:00 GMT+0000
4437  millis += Floor(isolate->heap()->synthetic_time());
4438  } else {
4439  millis = Floor(base::OS::TimeCurrentMillis());
4440  }
4441  return *isolate->factory()->NewNumber(millis);
4442 }
4443 
4444 
4445 RUNTIME_FUNCTION(Runtime_DateParseString) {
4446  HandleScope scope(isolate);
4447  DCHECK(args.length() == 2);
4449  CONVERT_ARG_HANDLE_CHECKED(JSArray, output, 1);
4450 
4451  RUNTIME_ASSERT(output->HasFastElements());
4453  RUNTIME_ASSERT(output->HasFastObjectElements());
4454  Handle<FixedArray> output_array(FixedArray::cast(output->elements()));
4455  RUNTIME_ASSERT(output_array->length() >= DateParser::OUTPUT_SIZE);
4456 
4457  str = String::Flatten(str);
4458  DisallowHeapAllocation no_gc;
4459 
4460  bool result;
4461  String::FlatContent str_content = str->GetFlatContent();
4462  if (str_content.IsOneByte()) {
4463  result = DateParser::Parse(str_content.ToOneByteVector(), *output_array,
4464  isolate->unicode_cache());
4465  } else {
4466  DCHECK(str_content.IsTwoByte());
4467  result = DateParser::Parse(str_content.ToUC16Vector(), *output_array,
4468  isolate->unicode_cache());
4469  }
4470 
4471  if (result) {
4472  return *output;
4473  } else {
4474  return isolate->heap()->null_value();
4475  }
4476 }
4477 
4478 
4479 RUNTIME_FUNCTION(Runtime_DateLocalTimezone) {
4480  HandleScope scope(isolate);
4481  DCHECK(args.length() == 1);
4482 
4486  const char* zone =
4487  isolate->date_cache()->LocalTimezone(static_cast<int64_t>(x));
4488  Handle<String> result =
4489  isolate->factory()->NewStringFromUtf8(CStrVector(zone)).ToHandleChecked();
4490  return *result;
4491 }
4492 
4493 
4494 RUNTIME_FUNCTION(Runtime_DateToUTC) {
4495  HandleScope scope(isolate);
4496  DCHECK(args.length() == 1);
4497 
4501  int64_t time = isolate->date_cache()->ToUTC(static_cast<int64_t>(x));
4502 
4503  return *isolate->factory()->NewNumber(static_cast<double>(time));
4504 }
4505 
4506 
4507 RUNTIME_FUNCTION(Runtime_DateCacheVersion) {
4508  HandleScope hs(isolate);
4509  DCHECK(args.length() == 0);
4510  if (!isolate->eternal_handles()->Exists(EternalHandles::DATE_CACHE_VERSION)) {
4511  Handle<FixedArray> date_cache_version =
4512  isolate->factory()->NewFixedArray(1, TENURED);
4513  date_cache_version->set(0, Smi::FromInt(0));
4514  isolate->eternal_handles()->CreateSingleton(
4515  isolate, *date_cache_version, EternalHandles::DATE_CACHE_VERSION);
4516  }
4517  Handle<FixedArray> date_cache_version =
4518  Handle<FixedArray>::cast(isolate->eternal_handles()->GetSingleton(
4520  // Return result as a JS array.
4521  Handle<JSObject> result =
4522  isolate->factory()->NewJSObject(isolate->array_function());
4523  JSArray::SetContent(Handle<JSArray>::cast(result), date_cache_version);
4524  return *result;
4525 }
4526 
4527 
4528 RUNTIME_FUNCTION(Runtime_GlobalProxy) {
4529  SealHandleScope shs(isolate);
4530  DCHECK(args.length() == 1);
4531  CONVERT_ARG_CHECKED(Object, global, 0);
4532  if (!global->IsJSGlobalObject()) return isolate->heap()->null_value();
4533  return JSGlobalObject::cast(global)->global_proxy();
4534 }
4535 
4536 
4537 RUNTIME_FUNCTION(Runtime_IsAttachedGlobal) {
4538  SealHandleScope shs(isolate);
4539  DCHECK(args.length() == 1);
4540  CONVERT_ARG_CHECKED(Object, global, 0);
4541  if (!global->IsJSGlobalObject()) return isolate->heap()->false_value();
4542  return isolate->heap()->ToBoolean(
4543  !JSGlobalObject::cast(global)->IsDetached());
4544 }
4545 
4546 
4547 RUNTIME_FUNCTION(Runtime_AllocateInNewSpace) {
4548  HandleScope scope(isolate);
4549  DCHECK(args.length() == 1);
4552  RUNTIME_ASSERT(size > 0);
4554  return *isolate->factory()->NewFillerObject(size, false, NEW_SPACE);
4555 }
4556 
4557 
4558 RUNTIME_FUNCTION(Runtime_AllocateInTargetSpace) {
4559  HandleScope scope(isolate);
4560  DCHECK(args.length() == 2);
4564  RUNTIME_ASSERT(size > 0);
4566  bool double_align = AllocateDoubleAlignFlag::decode(flags);
4568  return *isolate->factory()->NewFillerObject(size, double_align, space);
4569 }
4570 
4571 
4572 // Push an object unto an array of objects if it is not already in the
4573 // array. Returns true if the element was pushed on the stack and
4574 // false otherwise.
4575 RUNTIME_FUNCTION(Runtime_PushIfAbsent) {
4576  HandleScope scope(isolate);
4577  DCHECK(args.length() == 2);
4580  RUNTIME_ASSERT(array->HasFastSmiOrObjectElements());
4581  int length = Smi::cast(array->length())->value();
4582  FixedArray* elements = FixedArray::cast(array->elements());
4583  for (int i = 0; i < length; i++) {
4584  if (elements->get(i) == *element) return isolate->heap()->false_value();
4585  }
4586 
4587  // Strict not needed. Used for cycle detection in Array join implementation.
4589  isolate, JSObject::SetFastElement(array, length, element, SLOPPY, true));
4590  return isolate->heap()->true_value();
4591 }
4592 
4593 
4594 /**
4595  * A simple visitor visits every element of Array's.
4596  * The backend storage can be a fixed array for fast elements case,
4597  * or a dictionary for sparse array. Since Dictionary is a subtype
4598  * of FixedArray, the class can be used by both fast and slow cases.
4599  * The second parameter of the constructor, fast_elements, specifies
4600  * whether the storage is a FixedArray or Dictionary.
4601  *
4602  * An index limit is used to deal with the situation that a result array
4603  * length overflows 32-bit non-negative integer.
4604  */
4606  public:
4608  bool fast_elements)
4609  : isolate_(isolate),
4610  storage_(Handle<FixedArray>::cast(
4611  isolate->global_handles()->Create(*storage))),
4612  index_offset_(0u),
4613  fast_elements_(fast_elements),
4615 
4617 
4620  exceeds_array_limit_ = true;
4621  return;
4622  }
4623  uint32_t index = index_offset_ + i;
4624 
4625  if (fast_elements_) {
4626  if (index < static_cast<uint32_t>(storage_->length())) {
4627  storage_->set(index, *elm);
4628  return;
4629  }
4630  // Our initial estimate of length was foiled, possibly by
4631  // getters on the arrays increasing the length of later arrays
4632  // during iteration.
4633  // This shouldn't happen in anything but pathological cases.
4635  // Fall-through to dictionary mode.
4636  }
4639  SeededNumberDictionary::cast(*storage_));
4641  SeededNumberDictionary::AtNumberPut(dict, index, elm);
4642  if (!result.is_identical_to(dict)) {
4643  // Dictionary needed to grow.
4644  clear_storage();
4645  set_storage(*result);
4646  }
4647  }
4648 
4650  if (JSObject::kMaxElementCount - index_offset_ < delta) {
4652  } else {
4653  index_offset_ += delta;
4654  }
4655  // If the initial length estimate was off (see special case in visit()),
4656  // but the array blowing the limit didn't contain elements beyond the
4657  // provided-for index range, go to dictionary mode now.
4658  if (fast_elements_ &&
4659  index_offset_ >
4660  static_cast<uint32_t>(FixedArrayBase::cast(*storage_)->length())) {
4662  }
4663  }
4664 
4666 
4668  Handle<JSArray> array = isolate_->factory()->NewJSArray(0);
4669  Handle<Object> length =
4670  isolate_->factory()->NewNumber(static_cast<double>(index_offset_));
4673  array->set_map(*map);
4674  array->set_length(*length);
4675  array->set_elements(*storage_);
4676  return array;
4677  }
4678 
4679  private:
4680  // Convert storage to dictionary mode.
4683  Handle<FixedArray> current_storage(*storage_);
4684  Handle<SeededNumberDictionary> slow_storage(
4685  SeededNumberDictionary::New(isolate_, current_storage->length()));
4686  uint32_t current_length = static_cast<uint32_t>(current_storage->length());
4687  for (uint32_t i = 0; i < current_length; i++) {
4688  HandleScope loop_scope(isolate_);
4689  Handle<Object> element(current_storage->get(i), isolate_);
4690  if (!element->IsTheHole()) {
4691  Handle<SeededNumberDictionary> new_storage =
4692  SeededNumberDictionary::AtNumberPut(slow_storage, i, element);
4693  if (!new_storage.is_identical_to(slow_storage)) {
4694  slow_storage = loop_scope.CloseAndEscape(new_storage);
4695  }
4696  }
4697  }
4698  clear_storage();
4699  set_storage(*slow_storage);
4700  fast_elements_ = false;
4701  }
4702 
4703  inline void clear_storage() {
4705  }
4706 
4707  inline void set_storage(FixedArray* storage) {
4708  storage_ =
4710  }
4711 
4713  Handle<FixedArray> storage_; // Always a global handle.
4714  // Index after last seen index. Always less than or equal to
4715  // JSObject::kMaxElementCount.
4717  bool fast_elements_ : 1;
4719 };
4720 
4721 
4723  uint32_t length = static_cast<uint32_t>(array->length()->Number());
4724  int element_count = 0;
4725  switch (array->GetElementsKind()) {
4726  case FAST_SMI_ELEMENTS:
4728  case FAST_ELEMENTS:
4729  case FAST_HOLEY_ELEMENTS: {
4730  // Fast elements can't have lengths that are not representable by
4731  // a 32-bit signed integer.
4732  DCHECK(static_cast<int32_t>(FixedArray::kMaxLength) >= 0);
4733  int fast_length = static_cast<int>(length);
4734  Handle<FixedArray> elements(FixedArray::cast(array->elements()));
4735  for (int i = 0; i < fast_length; i++) {
4736  if (!elements->get(i)->IsTheHole()) element_count++;
4737  }
4738  break;
4739  }
4740  case FAST_DOUBLE_ELEMENTS:
4742  // Fast elements can't have lengths that are not representable by
4743  // a 32-bit signed integer.
4744  DCHECK(static_cast<int32_t>(FixedDoubleArray::kMaxLength) >= 0);
4745  int fast_length = static_cast<int>(length);
4746  if (array->elements()->IsFixedArray()) {
4747  DCHECK(FixedArray::cast(array->elements())->length() == 0);
4748  break;
4749  }
4750  Handle<FixedDoubleArray> elements(
4751  FixedDoubleArray::cast(array->elements()));
4752  for (int i = 0; i < fast_length; i++) {
4753  if (!elements->is_the_hole(i)) element_count++;
4754  }
4755  break;
4756  }
4757  case DICTIONARY_ELEMENTS: {
4758  Handle<SeededNumberDictionary> dictionary(
4759  SeededNumberDictionary::cast(array->elements()));
4760  int capacity = dictionary->Capacity();
4761  for (int i = 0; i < capacity; i++) {
4762  Handle<Object> key(dictionary->KeyAt(i), array->GetIsolate());
4763  if (dictionary->IsKey(*key)) {
4764  element_count++;
4765  }
4766  }
4767  break;
4768  }
4770 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
4771  case EXTERNAL_##TYPE##_ELEMENTS: \
4772  case TYPE##_ELEMENTS:
4773 
4775 #undef TYPED_ARRAY_CASE
4776  // External arrays are always dense.
4777  return length;
4778  }
4779  // As an estimate, we assume that the prototype doesn't contain any
4780  // inherited elements.
4781  return element_count;
4782 }
4783 
4784 
4785 template <class ExternalArrayClass, class ElementType>
4787  Handle<JSObject> receiver,
4788  bool elements_are_ints,
4789  bool elements_are_guaranteed_smis,
4790  ArrayConcatVisitor* visitor) {
4792  ExternalArrayClass::cast(receiver->elements()));
4793  uint32_t len = static_cast<uint32_t>(array->length());
4794 
4795  DCHECK(visitor != NULL);
4796  if (elements_are_ints) {
4797  if (elements_are_guaranteed_smis) {
4798  for (uint32_t j = 0; j < len; j++) {
4799  HandleScope loop_scope(isolate);
4800  Handle<Smi> e(Smi::FromInt(static_cast<int>(array->get_scalar(j))),
4801  isolate);
4802  visitor->visit(j, e);
4803  }
4804  } else {
4805  for (uint32_t j = 0; j < len; j++) {
4806  HandleScope loop_scope(isolate);
4807  int64_t val = static_cast<int64_t>(array->get_scalar(j));
4808  if (Smi::IsValid(static_cast<intptr_t>(val))) {
4809  Handle<Smi> e(Smi::FromInt(static_cast<int>(val)), isolate);
4810  visitor->visit(j, e);
4811  } else {
4812  Handle<Object> e =
4813  isolate->factory()->NewNumber(static_cast<ElementType>(val));
4814  visitor->visit(j, e);
4815  }
4816  }
4817  }
4818  } else {
4819  for (uint32_t j = 0; j < len; j++) {
4820  HandleScope loop_scope(isolate);
4821  Handle<Object> e = isolate->factory()->NewNumber(array->get_scalar(j));
4822  visitor->visit(j, e);
4823  }
4824  }
4825 }
4826 
4827 
4828 // Used for sorting indices in a List<uint32_t>.
4829 static int compareUInt32(const uint32_t* ap, const uint32_t* bp) {
4830  uint32_t a = *ap;
4831  uint32_t b = *bp;
4832  return (a == b) ? 0 : (a < b) ? -1 : 1;
4833 }
4834 
4835 
4837  List<uint32_t>* indices) {
4838  Isolate* isolate = object->GetIsolate();
4839  ElementsKind kind = object->GetElementsKind();
4840  switch (kind) {
4841  case FAST_SMI_ELEMENTS:
4842  case FAST_ELEMENTS:
4844  case FAST_HOLEY_ELEMENTS: {
4845  Handle<FixedArray> elements(FixedArray::cast(object->elements()));
4846  uint32_t length = static_cast<uint32_t>(elements->length());
4847  if (range < length) length = range;
4848  for (uint32_t i = 0; i < length; i++) {
4849  if (!elements->get(i)->IsTheHole()) {
4850  indices->Add(i);
4851  }
4852  }
4853  break;
4854  }
4856  case FAST_DOUBLE_ELEMENTS: {
4857  if (object->elements()->IsFixedArray()) {
4858  DCHECK(object->elements()->length() == 0);
4859  break;
4860  }
4861  Handle<FixedDoubleArray> elements(
4862  FixedDoubleArray::cast(object->elements()));
4863  uint32_t length = static_cast<uint32_t>(elements->length());
4864  if (range < length) length = range;
4865  for (uint32_t i = 0; i < length; i++) {
4866  if (!elements->is_the_hole(i)) {
4867  indices->Add(i);
4868  }
4869  }
4870  break;
4871  }
4872  case DICTIONARY_ELEMENTS: {
4874  SeededNumberDictionary::cast(object->elements()));
4875  uint32_t capacity = dict->Capacity();
4876  for (uint32_t j = 0; j < capacity; j++) {
4877  HandleScope loop_scope(isolate);
4878  Handle<Object> k(dict->KeyAt(j), isolate);
4879  if (dict->IsKey(*k)) {
4880  DCHECK(k->IsNumber());
4881  uint32_t index = static_cast<uint32_t>(k->Number());
4882  if (index < range) {
4883  indices->Add(index);
4884  }
4885  }
4886  }
4887  break;
4888  }
4889 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
4890  case TYPE##_ELEMENTS: \
4891  case EXTERNAL_##TYPE##_ELEMENTS:
4892 
4894 #undef TYPED_ARRAY_CASE
4895  {
4896  uint32_t length = static_cast<uint32_t>(
4897  FixedArrayBase::cast(object->elements())->length());
4898  if (range <= length) {
4899  length = range;
4900  // We will add all indices, so we might as well clear it first
4901  // and avoid duplicates.
4902  indices->Clear();
4903  }
4904  for (uint32_t i = 0; i < length; i++) {
4905  indices->Add(i);
4906  }
4907  if (length == range) return; // All indices accounted for already.
4908  break;
4909  }
4911  MaybeHandle<Object> length_obj =
4912  Object::GetProperty(object, isolate->factory()->length_string());
4913  double length_num = length_obj.ToHandleChecked()->Number();
4914  uint32_t length = static_cast<uint32_t>(DoubleToInt32(length_num));
4915  ElementsAccessor* accessor = object->GetElementsAccessor();
4916  for (uint32_t i = 0; i < length; i++) {
4917  if (accessor->HasElement(object, object, i)) {
4918  indices->Add(i);
4919  }
4920  }
4921  break;
4922  }
4923  }
4924 
4925  PrototypeIterator iter(isolate, object);
4926  if (!iter.IsAtEnd()) {
4927  // The prototype will usually have no inherited element indices,
4928  // but we have to check.
4931  indices);
4932  }
4933 }
4934 
4935 
4936 /**
4937  * A helper function that visits elements of a JSArray in numerical
4938  * order.
4939  *
4940  * The visitor argument called for each existing element in the array
4941  * with the element index and the element's value.
4942  * Afterwards it increments the base-index of the visitor by the array
4943  * length.
4944  * Returns false if any access threw an exception, otherwise true.
4945  */
4946 static bool IterateElements(Isolate* isolate, Handle<JSArray> receiver,
4947  ArrayConcatVisitor* visitor) {
4948  uint32_t length = static_cast<uint32_t>(receiver->length()->Number());
4949  switch (receiver->GetElementsKind()) {
4950  case FAST_SMI_ELEMENTS:
4951  case FAST_ELEMENTS:
4953  case FAST_HOLEY_ELEMENTS: {
4954  // Run through the elements FixedArray and use HasElement and GetElement
4955  // to check the prototype for missing elements.
4956  Handle<FixedArray> elements(FixedArray::cast(receiver->elements()));
4957  int fast_length = static_cast<int>(length);
4958  DCHECK(fast_length <= elements->length());
4959  for (int j = 0; j < fast_length; j++) {
4960  HandleScope loop_scope(isolate);
4961  Handle<Object> element_value(elements->get(j), isolate);
4962  if (!element_value->IsTheHole()) {
4963  visitor->visit(j, element_value);
4964  } else {
4965  Maybe<bool> maybe = JSReceiver::HasElement(receiver, j);
4966  if (!maybe.has_value) return false;
4967  if (maybe.value) {
4968  // Call GetElement on receiver, not its prototype, or getters won't
4969  // have the correct receiver.
4971  isolate, element_value,
4972  Object::GetElement(isolate, receiver, j), false);
4973  visitor->visit(j, element_value);
4974  }
4975  }
4976  }
4977  break;
4978  }
4980  case FAST_DOUBLE_ELEMENTS: {
4981  // Empty array is FixedArray but not FixedDoubleArray.
4982  if (length == 0) break;
4983  // Run through the elements FixedArray and use HasElement and GetElement
4984  // to check the prototype for missing elements.
4985  if (receiver->elements()->IsFixedArray()) {
4986  DCHECK(receiver->elements()->length() == 0);
4987  break;
4988  }
4989  Handle<FixedDoubleArray> elements(
4990  FixedDoubleArray::cast(receiver->elements()));
4991  int fast_length = static_cast<int>(length);
4992  DCHECK(fast_length <= elements->length());
4993  for (int j = 0; j < fast_length; j++) {
4994  HandleScope loop_scope(isolate);
4995  if (!elements->is_the_hole(j)) {
4996  double double_value = elements->get_scalar(j);
4997  Handle<Object> element_value =
4998  isolate->factory()->NewNumber(double_value);
4999  visitor->visit(j, element_value);
5000  } else {
5001  Maybe<bool> maybe = JSReceiver::HasElement(receiver, j);
5002  if (!maybe.has_value) return false;
5003  if (maybe.value) {
5004  // Call GetElement on receiver, not its prototype, or getters won't
5005  // have the correct receiver.
5006  Handle<Object> element_value;
5008  isolate, element_value,
5009  Object::GetElement(isolate, receiver, j), false);
5010  visitor->visit(j, element_value);
5011  }
5012  }
5013  }
5014  break;
5015  }
5016  case DICTIONARY_ELEMENTS: {
5017  Handle<SeededNumberDictionary> dict(receiver->element_dictionary());
5018  List<uint32_t> indices(dict->Capacity() / 2);
5019  // Collect all indices in the object and the prototypes less
5020  // than length. This might introduce duplicates in the indices list.
5021  CollectElementIndices(receiver, length, &indices);
5022  indices.Sort(&compareUInt32);
5023  int j = 0;
5024  int n = indices.length();
5025  while (j < n) {
5026  HandleScope loop_scope(isolate);
5027  uint32_t index = indices[j];
5028  Handle<Object> element;
5030  isolate, element, Object::GetElement(isolate, receiver, index),
5031  false);
5032  visitor->visit(index, element);
5033  // Skip to next different index (i.e., omit duplicates).
5034  do {
5035  j++;
5036  } while (j < n && indices[j] == index);
5037  }
5038  break;
5039  }
5042  ExternalUint8ClampedArray::cast(receiver->elements()));
5043  for (uint32_t j = 0; j < length; j++) {
5044  Handle<Smi> e(Smi::FromInt(pixels->get_scalar(j)), isolate);
5045  visitor->visit(j, e);
5046  }
5047  break;
5048  }
5049  case EXTERNAL_INT8_ELEMENTS: {
5050  IterateExternalArrayElements<ExternalInt8Array, int8_t>(
5051  isolate, receiver, true, true, visitor);
5052  break;
5053  }
5054  case EXTERNAL_UINT8_ELEMENTS: {
5055  IterateExternalArrayElements<ExternalUint8Array, uint8_t>(
5056  isolate, receiver, true, true, visitor);
5057  break;
5058  }
5059  case EXTERNAL_INT16_ELEMENTS: {
5060  IterateExternalArrayElements<ExternalInt16Array, int16_t>(
5061  isolate, receiver, true, true, visitor);
5062  break;
5063  }
5064  case EXTERNAL_UINT16_ELEMENTS: {
5065  IterateExternalArrayElements<ExternalUint16Array, uint16_t>(
5066  isolate, receiver, true, true, visitor);
5067  break;
5068  }
5069  case EXTERNAL_INT32_ELEMENTS: {
5070  IterateExternalArrayElements<ExternalInt32Array, int32_t>(
5071  isolate, receiver, true, false, visitor);
5072  break;
5073  }
5074  case EXTERNAL_UINT32_ELEMENTS: {
5075  IterateExternalArrayElements<ExternalUint32Array, uint32_t>(
5076  isolate, receiver, true, false, visitor);
5077  break;
5078  }
5080  IterateExternalArrayElements<ExternalFloat32Array, float>(
5081  isolate, receiver, false, false, visitor);
5082  break;
5083  }
5085  IterateExternalArrayElements<ExternalFloat64Array, double>(
5086  isolate, receiver, false, false, visitor);
5087  break;
5088  }
5089  default:
5090  UNREACHABLE();
5091  break;
5092  }
5093  visitor->increase_index_offset(length);
5094  return true;
5095 }
5096 
5097 
5098 /**
5099  * Array::concat implementation.
5100  * See ECMAScript 262, 15.4.4.4.
5101  * TODO(581): Fix non-compliance for very large concatenations and update to
5102  * following the ECMAScript 5 specification.
5103  */
5104 RUNTIME_FUNCTION(Runtime_ArrayConcat) {
5105  HandleScope handle_scope(isolate);
5106  DCHECK(args.length() == 1);
5107 
5108  CONVERT_ARG_HANDLE_CHECKED(JSArray, arguments, 0);
5109  int argument_count = static_cast<int>(arguments->length()->Number());
5110  RUNTIME_ASSERT(arguments->HasFastObjectElements());
5111  Handle<FixedArray> elements(FixedArray::cast(arguments->elements()));
5112 
5113  // Pass 1: estimate the length and number of elements of the result.
5114  // The actual length can be larger if any of the arguments have getters
5115  // that mutate other arguments (but will otherwise be precise).
5116  // The number of elements is precise if there are no inherited elements.
5117 
5119 
5120  uint32_t estimate_result_length = 0;
5121  uint32_t estimate_nof_elements = 0;
5122  for (int i = 0; i < argument_count; i++) {
5123  HandleScope loop_scope(isolate);
5124  Handle<Object> obj(elements->get(i), isolate);
5125  uint32_t length_estimate;
5126  uint32_t element_estimate;
5127  if (obj->IsJSArray()) {
5129  length_estimate = static_cast<uint32_t>(array->length()->Number());
5130  if (length_estimate != 0) {
5131  ElementsKind array_kind =
5132  GetPackedElementsKind(array->map()->elements_kind());
5133  if (IsMoreGeneralElementsKindTransition(kind, array_kind)) {
5134  kind = array_kind;
5135  }
5136  }
5137  element_estimate = EstimateElementCount(array);
5138  } else {
5139  if (obj->IsHeapObject()) {
5140  if (obj->IsNumber()) {
5142  kind = FAST_DOUBLE_ELEMENTS;
5143  }
5145  kind = FAST_ELEMENTS;
5146  }
5147  }
5148  length_estimate = 1;
5149  element_estimate = 1;
5150  }
5151  // Avoid overflows by capping at kMaxElementCount.
5152  if (JSObject::kMaxElementCount - estimate_result_length < length_estimate) {
5153  estimate_result_length = JSObject::kMaxElementCount;
5154  } else {
5155  estimate_result_length += length_estimate;
5156  }
5157  if (JSObject::kMaxElementCount - estimate_nof_elements < element_estimate) {
5158  estimate_nof_elements = JSObject::kMaxElementCount;
5159  } else {
5160  estimate_nof_elements += element_estimate;
5161  }
5162  }
5163 
5164  // If estimated number of elements is more than half of length, a
5165  // fixed array (fast case) is more time and space-efficient than a
5166  // dictionary.
5167  bool fast_case = (estimate_nof_elements * 2) >= estimate_result_length;
5168 
5169  if (fast_case && kind == FAST_DOUBLE_ELEMENTS) {
5170  Handle<FixedArrayBase> storage =
5171  isolate->factory()->NewFixedDoubleArray(estimate_result_length);
5172  int j = 0;
5173  bool failure = false;
5174  if (estimate_result_length > 0) {
5175  Handle<FixedDoubleArray> double_storage =
5177  for (int i = 0; i < argument_count; i++) {
5178  Handle<Object> obj(elements->get(i), isolate);
5179  if (obj->IsSmi()) {
5180  double_storage->set(j, Smi::cast(*obj)->value());
5181  j++;
5182  } else if (obj->IsNumber()) {
5183  double_storage->set(j, obj->Number());
5184  j++;
5185  } else {
5186  JSArray* array = JSArray::cast(*obj);
5187  uint32_t length = static_cast<uint32_t>(array->length()->Number());
5188  switch (array->map()->elements_kind()) {
5190  case FAST_DOUBLE_ELEMENTS: {
5191  // Empty array is FixedArray but not FixedDoubleArray.
5192  if (length == 0) break;
5193  FixedDoubleArray* elements =
5194  FixedDoubleArray::cast(array->elements());
5195  for (uint32_t i = 0; i < length; i++) {
5196  if (elements->is_the_hole(i)) {
5197  // TODO(jkummerow/verwaest): We could be a bit more clever
5198  // here: Check if there are no elements/getters on the
5199  // prototype chain, and if so, allow creation of a holey
5200  // result array.
5201  // Same thing below (holey smi case).
5202  failure = true;
5203  break;
5204  }
5205  double double_value = elements->get_scalar(i);
5206  double_storage->set(j, double_value);
5207  j++;
5208  }
5209  break;
5210  }
5212  case FAST_SMI_ELEMENTS: {
5213  FixedArray* elements(FixedArray::cast(array->elements()));
5214  for (uint32_t i = 0; i < length; i++) {
5215  Object* element = elements->get(i);
5216  if (element->IsTheHole()) {
5217  failure = true;
5218  break;
5219  }
5220  int32_t int_value = Smi::cast(element)->value();
5221  double_storage->set(j, int_value);
5222  j++;
5223  }
5224  break;
5225  }
5226  case FAST_HOLEY_ELEMENTS:
5227  case FAST_ELEMENTS:
5228  DCHECK_EQ(0, length);
5229  break;
5230  default:
5231  UNREACHABLE();
5232  }
5233  }
5234  if (failure) break;
5235  }
5236  }
5237  if (!failure) {
5238  Handle<JSArray> array = isolate->factory()->NewJSArray(0);
5239  Smi* length = Smi::FromInt(j);
5240  Handle<Map> map;
5241  map = JSObject::GetElementsTransitionMap(array, kind);
5242  array->set_map(*map);
5243  array->set_length(length);
5244  array->set_elements(*storage);
5245  return *array;
5246  }
5247  // In case of failure, fall through.
5248  }
5249 
5250  Handle<FixedArray> storage;
5251  if (fast_case) {
5252  // The backing storage array must have non-existing elements to preserve
5253  // holes across concat operations.
5254  storage =
5255  isolate->factory()->NewFixedArrayWithHoles(estimate_result_length);
5256  } else {
5257  // TODO(126): move 25% pre-allocation logic into Dictionary::Allocate
5258  uint32_t at_least_space_for =
5259  estimate_nof_elements + (estimate_nof_elements >> 2);
5260  storage = Handle<FixedArray>::cast(
5261  SeededNumberDictionary::New(isolate, at_least_space_for));
5262  }
5263 
5264  ArrayConcatVisitor visitor(isolate, storage, fast_case);
5265 
5266  for (int i = 0; i < argument_count; i++) {
5267  Handle<Object> obj(elements->get(i), isolate);
5268  if (obj->IsJSArray()) {
5270  if (!IterateElements(isolate, array, &visitor)) {
5271  return isolate->heap()->exception();
5272  }
5273  } else {
5274  visitor.visit(0, obj);
5275  visitor.increase_index_offset(1);
5276  }
5277  }
5278 
5279  if (visitor.exceeds_array_limit()) {
5281  isolate,
5282  NewRangeError("invalid_array_length", HandleVector<Object>(NULL, 0)));
5283  }
5284  return *visitor.ToArray();
5285 }
5286 
5287 
5288 // Moves all own elements of an object, that are below a limit, to positions
5289 // starting at zero. All undefined values are placed after non-undefined values,
5290 // and are followed by non-existing element. Does not change the length
5291 // property.
5292 // Returns the number of non-undefined elements collected.
5293 // Returns -1 if hole removal is not supported by this method.
5294 RUNTIME_FUNCTION(Runtime_RemoveArrayHoles) {
5295  HandleScope scope(isolate);
5296  DCHECK(args.length() == 2);
5298  CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
5299  return *JSObject::PrepareElementsForSort(object, limit);
5300 }
5301 
5302 
5303 // Move contents of argument 0 (an array) to argument 1 (an array)
5304 RUNTIME_FUNCTION(Runtime_MoveArrayContents) {
5305  HandleScope scope(isolate);
5306  DCHECK(args.length() == 2);
5311 
5312  Handle<FixedArrayBase> new_elements(from->elements());
5313  ElementsKind from_kind = from->GetElementsKind();
5314  Handle<Map> new_map = JSObject::GetElementsTransitionMap(to, from_kind);
5315  JSObject::SetMapAndElements(to, new_map, new_elements);
5316  to->set_length(from->length());
5317 
5319  from->set_length(Smi::FromInt(0));
5320 
5322  return *to;
5323 }
5324 
5325 
5326 // How many elements does this object/array have?
5327 RUNTIME_FUNCTION(Runtime_EstimateNumberOfElements) {
5328  HandleScope scope(isolate);
5329  DCHECK(args.length() == 1);
5331  Handle<FixedArrayBase> elements(array->elements(), isolate);
5332  SealHandleScope shs(isolate);
5333  if (elements->IsDictionary()) {
5334  int result =
5335  Handle<SeededNumberDictionary>::cast(elements)->NumberOfElements();
5336  return Smi::FromInt(result);
5337  } else {
5338  DCHECK(array->length()->IsSmi());
5339  // For packed elements, we know the exact number of elements
5340  int length = elements->length();
5341  ElementsKind kind = array->GetElementsKind();
5342  if (IsFastPackedElementsKind(kind)) {
5343  return Smi::FromInt(length);
5344  }
5345  // For holey elements, take samples from the buffer checking for holes
5346  // to generate the estimate.
5347  const int kNumberOfHoleCheckSamples = 97;
5348  int increment = (length < kNumberOfHoleCheckSamples)
5349  ? 1
5350  : static_cast<int>(length / kNumberOfHoleCheckSamples);
5351  ElementsAccessor* accessor = array->GetElementsAccessor();
5352  int holes = 0;
5353  for (int i = 0; i < length; i += increment) {
5354  if (!accessor->HasElement(array, array, i, elements)) {
5355  ++holes;
5356  }
5357  }
5358  int estimate = static_cast<int>((kNumberOfHoleCheckSamples - holes) /
5359  kNumberOfHoleCheckSamples * length);
5360  return Smi::FromInt(estimate);
5361  }
5362 }
5363 
5364 
5365 // Returns an array that tells you where in the [0, length) interval an array
5366 // might have elements. Can either return an array of keys (positive integers
5367 // or undefined) or a number representing the positive length of an interval
5368 // starting at index 0.
5369 // Intervals can span over some keys that are not in the object.
5370 RUNTIME_FUNCTION(Runtime_GetArrayKeys) {
5371  HandleScope scope(isolate);
5372  DCHECK(args.length() == 2);
5374  CONVERT_NUMBER_CHECKED(uint32_t, length, Uint32, args[1]);
5375  if (array->elements()->IsDictionary()) {
5376  Handle<FixedArray> keys = isolate->factory()->empty_fixed_array();
5377  for (PrototypeIterator iter(isolate, array,
5379  !iter.IsAtEnd(); iter.Advance()) {
5380  if (PrototypeIterator::GetCurrent(iter)->IsJSProxy() ||
5381  JSObject::cast(*PrototypeIterator::GetCurrent(iter))
5382  ->HasIndexedInterceptor()) {
5383  // Bail out if we find a proxy or interceptor, likely not worth
5384  // collecting keys in that case.
5385  return *isolate->factory()->NewNumberFromUint(length);
5386  }
5387  Handle<JSObject> current =
5389  Handle<FixedArray> current_keys =
5390  isolate->factory()->NewFixedArray(current->NumberOfOwnElements(NONE));
5391  current->GetOwnElementKeys(*current_keys, NONE);
5393  isolate, keys, FixedArray::UnionOfKeys(keys, current_keys));
5394  }
5395  // Erase any keys >= length.
5396  // TODO(adamk): Remove this step when the contract of %GetArrayKeys
5397  // is changed to let this happen on the JS side.
5398  for (int i = 0; i < keys->length(); i++) {
5399  if (NumberToUint32(keys->get(i)) >= length) keys->set_undefined(i);
5400  }
5401  return *isolate->factory()->NewJSArrayWithElements(keys);
5402  } else {
5403  RUNTIME_ASSERT(array->HasFastSmiOrObjectElements() ||
5404  array->HasFastDoubleElements());
5405  uint32_t actual_length = static_cast<uint32_t>(array->elements()->length());
5406  return *isolate->factory()->NewNumberFromUint(Min(actual_length, length));
5407  }
5408 }
5409 
5410 
5411 RUNTIME_FUNCTION(Runtime_LookupAccessor) {
5412  HandleScope scope(isolate);
5413  DCHECK(args.length() == 3);
5414  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0);
5418  if (!receiver->IsJSObject()) return isolate->heap()->undefined_value();
5419  Handle<Object> result;
5421  isolate, result,
5422  JSObject::GetAccessor(Handle<JSObject>::cast(receiver), name, component));
5423  return *result;
5424 }
5425 
5426 
5427 RUNTIME_FUNCTION(Runtime_DebugBreak) {
5428  SealHandleScope shs(isolate);
5429  DCHECK(args.length() == 0);
5430  isolate->debug()->HandleDebugBreak();
5431  return isolate->heap()->undefined_value();
5432 }
5433 
5434 
5435 // Helper functions for wrapping and unwrapping stack frame ids.
5436 static Smi* WrapFrameId(StackFrame::Id id) {
5437  DCHECK(IsAligned(OffsetFrom(id), static_cast<intptr_t>(4)));
5438  return Smi::FromInt(id >> 2);
5439 }
5440 
5441 
5442 static StackFrame::Id UnwrapFrameId(int wrapped) {
5443  return static_cast<StackFrame::Id>(wrapped << 2);
5444 }
5445 
5446 
5447 // Adds a JavaScript function as a debug event listener.
5448 // args[0]: debug event listener function to set or null or undefined for
5449 // clearing the event listener function
5450 // args[1]: object supplied during callback
5451 RUNTIME_FUNCTION(Runtime_SetDebugEventListener) {
5452  SealHandleScope shs(isolate);
5453  DCHECK(args.length() == 2);
5454  RUNTIME_ASSERT(args[0]->IsJSFunction() || args[0]->IsUndefined() ||
5455  args[0]->IsNull());
5456  CONVERT_ARG_HANDLE_CHECKED(Object, callback, 0);
5458  isolate->debug()->SetEventListener(callback, data);
5459 
5460  return isolate->heap()->undefined_value();
5461 }
5462 
5463 
5464 RUNTIME_FUNCTION(Runtime_Break) {
5465  SealHandleScope shs(isolate);
5466  DCHECK(args.length() == 0);
5467  isolate->stack_guard()->RequestDebugBreak();
5468  return isolate->heap()->undefined_value();
5469 }
5470 
5471 
5472 static Handle<Object> DebugGetProperty(LookupIterator* it,
5473  bool* has_caught = NULL) {
5474  for (; it->IsFound(); it->Next()) {
5475  switch (it->state()) {
5476  case LookupIterator::NOT_FOUND:
5477  case LookupIterator::TRANSITION:
5478  UNREACHABLE();
5479  case LookupIterator::ACCESS_CHECK:
5480  // Ignore access checks.
5481  break;
5482  case LookupIterator::INTERCEPTOR:
5483  case LookupIterator::JSPROXY:
5484  return it->isolate()->factory()->undefined_value();
5485  case LookupIterator::ACCESSOR: {
5486  Handle<Object> accessors = it->GetAccessors();
5487  if (!accessors->IsAccessorInfo()) {
5488  return it->isolate()->factory()->undefined_value();
5489  }
5491  it->GetReceiver(), it->name(), it->GetHolder<JSObject>(),
5492  accessors);
5493  Handle<Object> result;
5494  if (!maybe_result.ToHandle(&result)) {
5495  result = handle(it->isolate()->pending_exception(), it->isolate());
5496  it->isolate()->clear_pending_exception();
5497  if (has_caught != NULL) *has_caught = true;
5498  }
5499  return result;
5500  }
5501 
5502  case LookupIterator::DATA:
5503  return it->GetDataValue();
5504  }
5505  }
5506 
5507  return it->isolate()->factory()->undefined_value();
5508 }
5509 
5510 
5511 // Get debugger related details for an object property, in the following format:
5512 // 0: Property value
5513 // 1: Property details
5514 // 2: Property value is exception
5515 // 3: Getter function if defined
5516 // 4: Setter function if defined
5517 // Items 2-4 are only filled if the property has either a getter or a setter.
5518 RUNTIME_FUNCTION(Runtime_DebugGetPropertyDetails) {
5519  HandleScope scope(isolate);
5520 
5521  DCHECK(args.length() == 2);
5522 
5525 
5526  // Make sure to set the current context to the context before the debugger was
5527  // entered (if the debugger is entered). The reason for switching context here
5528  // is that for some property lookups (accessors and interceptors) callbacks
5529  // into the embedding application can occour, and the embedding application
5530  // could have the assumption that its own native context is the current
5531  // context and not some internal debugger context.
5532  SaveContext save(isolate);
5533  if (isolate->debug()->in_debug_scope()) {
5534  isolate->set_context(*isolate->debug()->debugger_entry()->GetContext());
5535  }
5536 
5537  // Check if the name is trivially convertible to an index and get the element
5538  // if so.
5539  uint32_t index;
5540  if (name->AsArrayIndex(&index)) {
5541  Handle<FixedArray> details = isolate->factory()->NewFixedArray(2);
5542  Handle<Object> element_or_char;
5544  isolate, element_or_char,
5545  Runtime::GetElementOrCharAt(isolate, obj, index));
5546  details->set(0, *element_or_char);
5547  details->set(1,
5548  PropertyDetails(NONE, NORMAL, Representation::None()).AsSmi());
5549  return *isolate->factory()->NewJSArrayWithElements(details);
5550  }
5551 
5552  LookupIterator it(obj, name, LookupIterator::HIDDEN);
5553  bool has_caught = false;
5554  Handle<Object> value = DebugGetProperty(&it, &has_caught);
5555  if (!it.IsFound()) return isolate->heap()->undefined_value();
5556 
5557  Handle<Object> maybe_pair;
5558  if (it.state() == LookupIterator::ACCESSOR) {
5559  maybe_pair = it.GetAccessors();
5560  }
5561 
5562  // If the callback object is a fixed array then it contains JavaScript
5563  // getter and/or setter.
5564  bool has_js_accessors = !maybe_pair.is_null() && maybe_pair->IsAccessorPair();
5565  Handle<FixedArray> details =
5566  isolate->factory()->NewFixedArray(has_js_accessors ? 6 : 3);
5567  details->set(0, *value);
5568  // TODO(verwaest): Get rid of this random way of handling interceptors.
5569  PropertyDetails d = it.state() == LookupIterator::INTERCEPTOR
5570  ? PropertyDetails(NONE, NORMAL, 0)
5571  : it.property_details();
5572  details->set(1, d.AsSmi());
5573  details->set(
5574  2, isolate->heap()->ToBoolean(it.state() == LookupIterator::INTERCEPTOR));
5575  if (has_js_accessors) {
5576  AccessorPair* accessors = AccessorPair::cast(*maybe_pair);
5577  details->set(3, isolate->heap()->ToBoolean(has_caught));
5578  details->set(4, accessors->GetComponent(ACCESSOR_GETTER));
5579  details->set(5, accessors->GetComponent(ACCESSOR_SETTER));
5580  }
5581 
5582  return *isolate->factory()->NewJSArrayWithElements(details);
5583 }
5584 
5585 
5586 RUNTIME_FUNCTION(Runtime_DebugGetProperty) {
5587  HandleScope scope(isolate);
5588 
5589  DCHECK(args.length() == 2);
5590 
5593 
5594  LookupIterator it(obj, name);
5595  return *DebugGetProperty(&it);
5596 }
5597 
5598 
5599 // Return the property type calculated from the property details.
5600 // args[0]: smi with property details.
5601 RUNTIME_FUNCTION(Runtime_DebugPropertyTypeFromDetails) {
5602  SealHandleScope shs(isolate);
5603  DCHECK(args.length() == 1);
5605  return Smi::FromInt(static_cast<int>(details.type()));
5606 }
5607 
5608 
5609 // Return the property attribute calculated from the property details.
5610 // args[0]: smi with property details.
5611 RUNTIME_FUNCTION(Runtime_DebugPropertyAttributesFromDetails) {
5612  SealHandleScope shs(isolate);
5613  DCHECK(args.length() == 1);
5615  return Smi::FromInt(static_cast<int>(details.attributes()));
5616 }
5617 
5618 
5619 // Return the property insertion index calculated from the property details.
5620 // args[0]: smi with property details.
5621 RUNTIME_FUNCTION(Runtime_DebugPropertyIndexFromDetails) {
5622  SealHandleScope shs(isolate);
5623  DCHECK(args.length() == 1);
5625  // TODO(verwaest): Depends on the type of details.
5626  return Smi::FromInt(details.dictionary_index());
5627 }
5628 
5629 
5630 // Return property value from named interceptor.
5631 // args[0]: object
5632 // args[1]: property name
5633 RUNTIME_FUNCTION(Runtime_DebugNamedInterceptorPropertyValue) {
5634  HandleScope scope(isolate);
5635  DCHECK(args.length() == 2);
5637  RUNTIME_ASSERT(obj->HasNamedInterceptor());
5639 
5640  Handle<Object> result;
5641  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
5642  JSObject::GetProperty(obj, name));
5643  return *result;
5644 }
5645 
5646 
5647 // Return element value from indexed interceptor.
5648 // args[0]: object
5649 // args[1]: index
5650 RUNTIME_FUNCTION(Runtime_DebugIndexedInterceptorElementValue) {
5651  HandleScope scope(isolate);
5652  DCHECK(args.length() == 2);
5654  RUNTIME_ASSERT(obj->HasIndexedInterceptor());
5655  CONVERT_NUMBER_CHECKED(uint32_t, index, Uint32, args[1]);
5656  Handle<Object> result;
5658  isolate, result, JSObject::GetElementWithInterceptor(obj, obj, index));
5659  return *result;
5660 }
5661 
5662 
5663 static bool CheckExecutionState(Isolate* isolate, int break_id) {
5664  return !isolate->debug()->debug_context().is_null() &&
5665  isolate->debug()->break_id() != 0 &&
5666  isolate->debug()->break_id() == break_id;
5667 }
5668 
5669 
5670 RUNTIME_FUNCTION(Runtime_CheckExecutionState) {
5671  SealHandleScope shs(isolate);
5672  DCHECK(args.length() == 1);
5673  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
5674  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
5675  return isolate->heap()->true_value();
5676 }
5677 
5678 
5679 RUNTIME_FUNCTION(Runtime_GetFrameCount) {
5680  HandleScope scope(isolate);
5681  DCHECK(args.length() == 1);
5682  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
5683  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
5684 
5685  // Count all frames which are relevant to debugging stack trace.
5686  int n = 0;
5687  StackFrame::Id id = isolate->debug()->break_frame_id();
5688  if (id == StackFrame::NO_ID) {
5689  // If there is no JavaScript stack frame count is 0.
5690  return Smi::FromInt(0);
5691  }
5692 
5693  for (JavaScriptFrameIterator it(isolate, id); !it.done(); it.Advance()) {
5694  List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
5695  it.frame()->Summarize(&frames);
5696  for (int i = frames.length() - 1; i >= 0; i--) {
5697  // Omit functions from native scripts.
5698  if (!frames[i].function()->IsFromNativeScript()) n++;
5699  }
5700  }
5701  return Smi::FromInt(n);
5702 }
5703 
5704 
5706  public:
5707  FrameInspector(JavaScriptFrame* frame, int inlined_jsframe_index,
5708  Isolate* isolate)
5709  : frame_(frame), deoptimized_frame_(NULL), isolate_(isolate) {
5710  // Calculate the deoptimized frame.
5711  if (frame->is_optimized()) {
5713  frame, inlined_jsframe_index, isolate);
5714  }
5716  is_bottommost_ = inlined_jsframe_index == 0;
5717  is_optimized_ = frame_->is_optimized();
5718  }
5719 
5721  // Get rid of the calculated deoptimized frame if any.
5722  if (deoptimized_frame_ != NULL) {
5724  }
5725  }
5726 
5730  }
5734  : frame_->function();
5735  }
5736  Object* GetParameter(int index) {
5738  : frame_->GetParameter(index);
5739  }
5740  Object* GetExpression(int index) {
5742  : frame_->GetExpression(index);
5743  }
5746  : frame_->LookupCode()->SourcePosition(frame_->pc());
5747  }
5748  bool IsConstructor() {
5749  return is_optimized_ && !is_bottommost_
5751  : frame_->IsConstructor();
5752  }
5755  }
5756 
5757  // To inspect all the provided arguments the frame might need to be
5758  // replaced with the arguments frame.
5761  frame_ = frame;
5762  is_optimized_ = frame_->is_optimized();
5764  }
5765 
5766  private:
5773 
5775 };
5776 
5777 
5778 static const int kFrameDetailsFrameIdIndex = 0;
5779 static const int kFrameDetailsReceiverIndex = 1;
5780 static const int kFrameDetailsFunctionIndex = 2;
5781 static const int kFrameDetailsArgumentCountIndex = 3;
5782 static const int kFrameDetailsLocalCountIndex = 4;
5784 static const int kFrameDetailsConstructCallIndex = 6;
5785 static const int kFrameDetailsAtReturnIndex = 7;
5786 static const int kFrameDetailsFlagsIndex = 8;
5787 static const int kFrameDetailsFirstDynamicIndex = 9;
5788 
5789 
5790 static SaveContext* FindSavedContextForFrame(Isolate* isolate,
5791  JavaScriptFrame* frame) {
5792  SaveContext* save = isolate->save_context();
5793  while (save != NULL && !save->IsBelowFrame(frame)) {
5794  save = save->prev();
5795  }
5796  DCHECK(save != NULL);
5797  return save;
5798 }
5799 
5800 
5801 // Advances the iterator to the frame that matches the index and returns the
5802 // inlined frame index, or -1 if not found. Skips native JS functions.
5803 static int FindIndexedNonNativeFrame(JavaScriptFrameIterator* it, int index) {
5804  int count = -1;
5805  for (; !it->done(); it->Advance()) {
5806  List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
5807  it->frame()->Summarize(&frames);
5808  for (int i = frames.length() - 1; i >= 0; i--) {
5809  // Omit functions from native scripts.
5810  if (frames[i].function()->IsFromNativeScript()) continue;
5811  if (++count == index) return i;
5812  }
5813  }
5814  return -1;
5815 }
5816 
5817 
5818 // Return an array with frame details
5819 // args[0]: number: break id
5820 // args[1]: number: frame index
5821 //
5822 // The array returned contains the following information:
5823 // 0: Frame id
5824 // 1: Receiver
5825 // 2: Function
5826 // 3: Argument count
5827 // 4: Local count
5828 // 5: Source position
5829 // 6: Constructor call
5830 // 7: Is at return
5831 // 8: Flags
5832 // Arguments name, value
5833 // Locals name, value
5834 // Return value if any
5835 RUNTIME_FUNCTION(Runtime_GetFrameDetails) {
5836  HandleScope scope(isolate);
5837  DCHECK(args.length() == 2);
5838  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
5839  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
5840 
5841  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
5842  Heap* heap = isolate->heap();
5843 
5844  // Find the relevant frame with the requested index.
5845  StackFrame::Id id = isolate->debug()->break_frame_id();
5846  if (id == StackFrame::NO_ID) {
5847  // If there are no JavaScript stack frames return undefined.
5848  return heap->undefined_value();
5849  }
5850 
5851  JavaScriptFrameIterator it(isolate, id);
5852  // Inlined frame index in optimized frame, starting from outer function.
5853  int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index);
5854  if (inlined_jsframe_index == -1) return heap->undefined_value();
5855 
5856  FrameInspector frame_inspector(it.frame(), inlined_jsframe_index, isolate);
5857  bool is_optimized = it.frame()->is_optimized();
5858 
5859  // Traverse the saved contexts chain to find the active context for the
5860  // selected frame.
5861  SaveContext* save = FindSavedContextForFrame(isolate, it.frame());
5862 
5863  // Get the frame id.
5864  Handle<Object> frame_id(WrapFrameId(it.frame()->id()), isolate);
5865 
5866  // Find source position in unoptimized code.
5867  int position = frame_inspector.GetSourcePosition();
5868 
5869  // Check for constructor frame.
5870  bool constructor = frame_inspector.IsConstructor();
5871 
5872  // Get scope info and read from it for local variable information.
5873  Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
5874  Handle<SharedFunctionInfo> shared(function->shared());
5875  Handle<ScopeInfo> scope_info(shared->scope_info());
5876  DCHECK(*scope_info != ScopeInfo::Empty(isolate));
5877 
5878  // Get the locals names and values into a temporary array.
5879  int local_count = scope_info->LocalCount();
5880  for (int slot = 0; slot < scope_info->LocalCount(); ++slot) {
5881  // Hide compiler-introduced temporary variables, whether on the stack or on
5882  // the context.
5883  if (scope_info->LocalIsSynthetic(slot)) local_count--;
5884  }
5885 
5886  Handle<FixedArray> locals =
5887  isolate->factory()->NewFixedArray(local_count * 2);
5888 
5889  // Fill in the values of the locals.
5890  int local = 0;
5891  int i = 0;
5892  for (; i < scope_info->StackLocalCount(); ++i) {
5893  // Use the value from the stack.
5894  if (scope_info->LocalIsSynthetic(i)) continue;
5895  locals->set(local * 2, scope_info->LocalName(i));
5896  locals->set(local * 2 + 1, frame_inspector.GetExpression(i));
5897  local++;
5898  }
5899  if (local < local_count) {
5900  // Get the context containing declarations.
5901  Handle<Context> context(
5902  Context::cast(frame_inspector.GetContext())->declaration_context());
5903  for (; i < scope_info->LocalCount(); ++i) {
5904  if (scope_info->LocalIsSynthetic(i)) continue;
5905  Handle<String> name(scope_info->LocalName(i));
5907  InitializationFlag init_flag;
5908  MaybeAssignedFlag maybe_assigned_flag;
5909  locals->set(local * 2, *name);
5910  int context_slot_index = ScopeInfo::ContextSlotIndex(
5911  scope_info, name, &mode, &init_flag, &maybe_assigned_flag);
5912  Object* value = context->get(context_slot_index);
5913  locals->set(local * 2 + 1, value);
5914  local++;
5915  }
5916  }
5917 
5918  // Check whether this frame is positioned at return. If not top
5919  // frame or if the frame is optimized it cannot be at a return.
5920  bool at_return = false;
5921  if (!is_optimized && index == 0) {
5922  at_return = isolate->debug()->IsBreakAtReturn(it.frame());
5923  }
5924 
5925  // If positioned just before return find the value to be returned and add it
5926  // to the frame information.
5927  Handle<Object> return_value = isolate->factory()->undefined_value();
5928  if (at_return) {
5929  StackFrameIterator it2(isolate);
5930  Address internal_frame_sp = NULL;
5931  while (!it2.done()) {
5932  if (it2.frame()->is_internal()) {
5933  internal_frame_sp = it2.frame()->sp();
5934  } else {
5935  if (it2.frame()->is_java_script()) {
5936  if (it2.frame()->id() == it.frame()->id()) {
5937  // The internal frame just before the JavaScript frame contains the
5938  // value to return on top. A debug break at return will create an
5939  // internal frame to store the return value (eax/rax/r0) before
5940  // entering the debug break exit frame.
5941  if (internal_frame_sp != NULL) {
5942  return_value =
5943  Handle<Object>(Memory::Object_at(internal_frame_sp), isolate);
5944  break;
5945  }
5946  }
5947  }
5948 
5949  // Indicate that the previous frame was not an internal frame.
5950  internal_frame_sp = NULL;
5951  }
5952  it2.Advance();
5953  }
5954  }
5955 
5956  // Now advance to the arguments adapter frame (if any). It contains all
5957  // the provided parameters whereas the function frame always have the number
5958  // of arguments matching the functions parameters. The rest of the
5959  // information (except for what is collected above) is the same.
5960  if ((inlined_jsframe_index == 0) && it.frame()->has_adapted_arguments()) {
5961  it.AdvanceToArgumentsFrame();
5962  frame_inspector.SetArgumentsFrame(it.frame());
5963  }
5964 
5965  // Find the number of arguments to fill. At least fill the number of
5966  // parameters for the function and fill more if more parameters are provided.
5967  int argument_count = scope_info->ParameterCount();
5968  if (argument_count < frame_inspector.GetParametersCount()) {
5969  argument_count = frame_inspector.GetParametersCount();
5970  }
5971 
5972  // Calculate the size of the result.
5973  int details_size = kFrameDetailsFirstDynamicIndex +
5974  2 * (argument_count + local_count) + (at_return ? 1 : 0);
5975  Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);
5976 
5977  // Add the frame id.
5978  details->set(kFrameDetailsFrameIdIndex, *frame_id);
5979 
5980  // Add the function (same as in function frame).
5981  details->set(kFrameDetailsFunctionIndex, frame_inspector.GetFunction());
5982 
5983  // Add the arguments count.
5984  details->set(kFrameDetailsArgumentCountIndex, Smi::FromInt(argument_count));
5985 
5986  // Add the locals count
5987  details->set(kFrameDetailsLocalCountIndex, Smi::FromInt(local_count));
5988 
5989  // Add the source position.
5990  if (position != RelocInfo::kNoPosition) {
5991  details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position));
5992  } else {
5993  details->set(kFrameDetailsSourcePositionIndex, heap->undefined_value());
5994  }
5995 
5996  // Add the constructor information.
5997  details->set(kFrameDetailsConstructCallIndex, heap->ToBoolean(constructor));
5998 
5999  // Add the at return information.
6000  details->set(kFrameDetailsAtReturnIndex, heap->ToBoolean(at_return));
6001 
6002  // Add flags to indicate information on whether this frame is
6003  // bit 0: invoked in the debugger context.
6004  // bit 1: optimized frame.
6005  // bit 2: inlined in optimized frame
6006  int flags = 0;
6007  if (*save->context() == *isolate->debug()->debug_context()) {
6008  flags |= 1 << 0;
6009  }
6010  if (is_optimized) {
6011  flags |= 1 << 1;
6012  flags |= inlined_jsframe_index << 2;
6013  }
6014  details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags));
6015 
6016  // Fill the dynamic part.
6017  int details_index = kFrameDetailsFirstDynamicIndex;
6018 
6019  // Add arguments name and value.
6020  for (int i = 0; i < argument_count; i++) {
6021  // Name of the argument.
6022  if (i < scope_info->ParameterCount()) {
6023  details->set(details_index++, scope_info->ParameterName(i));
6024  } else {
6025  details->set(details_index++, heap->undefined_value());
6026  }
6027 
6028  // Parameter value.
6029  if (i < frame_inspector.GetParametersCount()) {
6030  // Get the value from the stack.
6031  details->set(details_index++, frame_inspector.GetParameter(i));
6032  } else {
6033  details->set(details_index++, heap->undefined_value());
6034  }
6035  }
6036 
6037  // Add locals name and value from the temporary copy from the function frame.
6038  for (int i = 0; i < local_count * 2; i++) {
6039  details->set(details_index++, locals->get(i));
6040  }
6041 
6042  // Add the value being returned.
6043  if (at_return) {
6044  details->set(details_index++, *return_value);
6045  }
6046 
6047  // Add the receiver (same as in function frame).
6048  // THIS MUST BE DONE LAST SINCE WE MIGHT ADVANCE
6049  // THE FRAME ITERATOR TO WRAP THE RECEIVER.
6050  Handle<Object> receiver(it.frame()->receiver(), isolate);
6051  if (!receiver->IsJSObject() && shared->strict_mode() == SLOPPY &&
6052  !function->IsBuiltin()) {
6053  // If the receiver is not a JSObject and the function is not a
6054  // builtin or strict-mode we have hit an optimization where a
6055  // value object is not converted into a wrapped JS objects. To
6056  // hide this optimization from the debugger, we wrap the receiver
6057  // by creating correct wrapper object based on the calling frame's
6058  // native context.
6059  it.Advance();
6060  if (receiver->IsUndefined()) {
6061  receiver = handle(function->global_proxy());
6062  } else {
6063  Context* context = Context::cast(it.frame()->context());
6064  Handle<Context> native_context(Context::cast(context->native_context()));
6065  if (!Object::ToObject(isolate, receiver, native_context)
6066  .ToHandle(&receiver)) {
6067  // This only happens if the receiver is forcibly set in %_CallFunction.
6068  return heap->undefined_value();
6069  }
6070  }
6071  }
6072  details->set(kFrameDetailsReceiverIndex, *receiver);
6073 
6074  DCHECK_EQ(details_size, details_index);
6075  return *isolate->factory()->NewJSArrayWithElements(details);
6076 }
6077 
6078 
6080  Handle<String> parameter_name) {
6082  InitializationFlag init_flag;
6083  MaybeAssignedFlag maybe_assigned_flag;
6084  return ScopeInfo::ContextSlotIndex(info, parameter_name, &mode, &init_flag,
6085  &maybe_assigned_flag) != -1;
6086 }
6087 
6088 
6089 // Create a plain JSObject which materializes the local scope for the specified
6090 // frame.
6093  Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function,
6094  FrameInspector* frame_inspector) {
6095  Handle<SharedFunctionInfo> shared(function->shared());
6096  Handle<ScopeInfo> scope_info(shared->scope_info());
6097 
6098  // First fill all parameters.
6099  for (int i = 0; i < scope_info->ParameterCount(); ++i) {
6100  // Do not materialize the parameter if it is shadowed by a context local.
6101  Handle<String> name(scope_info->ParameterName(i));
6102  if (ParameterIsShadowedByContextLocal(scope_info, name)) continue;
6103 
6104  HandleScope scope(isolate);
6105  Handle<Object> value(i < frame_inspector->GetParametersCount()
6106  ? frame_inspector->GetParameter(i)
6107  : isolate->heap()->undefined_value(),
6108  isolate);
6109  DCHECK(!value->IsTheHole());
6110 
6112  isolate, target, name, value, SLOPPY),
6113  JSObject);
6114  }
6115 
6116  // Second fill all stack locals.
6117  for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
6118  if (scope_info->LocalIsSynthetic(i)) continue;
6119  Handle<String> name(scope_info->StackLocalName(i));
6120  Handle<Object> value(frame_inspector->GetExpression(i), isolate);
6121  if (value->IsTheHole()) continue;
6122 
6124  isolate, target, name, value, SLOPPY),
6125  JSObject);
6126  }
6127 
6128  return target;
6129 }
6130 
6131 
6133  Handle<JSObject> target,
6134  Handle<JSFunction> function,
6135  JavaScriptFrame* frame,
6136  int inlined_jsframe_index) {
6137  if (inlined_jsframe_index != 0 || frame->is_optimized()) {
6138  // Optimized frames are not supported.
6139  // TODO(yangguo): make sure all code deoptimized when debugger is active
6140  // and assert that this cannot happen.
6141  return;
6142  }
6143 
6144  Handle<SharedFunctionInfo> shared(function->shared());
6145  Handle<ScopeInfo> scope_info(shared->scope_info());
6146 
6147  // Parameters.
6148  for (int i = 0; i < scope_info->ParameterCount(); ++i) {
6149  // Shadowed parameters were not materialized.
6150  Handle<String> name(scope_info->ParameterName(i));
6151  if (ParameterIsShadowedByContextLocal(scope_info, name)) continue;
6152 
6153  DCHECK(!frame->GetParameter(i)->IsTheHole());
6154  HandleScope scope(isolate);
6155  Handle<Object> value =
6156  Object::GetPropertyOrElement(target, name).ToHandleChecked();
6157  frame->SetParameterValue(i, *value);
6158  }
6159 
6160  // Stack locals.
6161  for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
6162  if (scope_info->LocalIsSynthetic(i)) continue;
6163  if (frame->GetExpression(i)->IsTheHole()) continue;
6164  HandleScope scope(isolate);
6166  target, handle(scope_info->StackLocalName(i),
6167  isolate)).ToHandleChecked();
6168  frame->SetExpression(i, *value);
6169  }
6170 }
6171 
6172 
6174  Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function,
6175  JavaScriptFrame* frame) {
6176  HandleScope scope(isolate);
6177  Handle<SharedFunctionInfo> shared(function->shared());
6178  Handle<ScopeInfo> scope_info(shared->scope_info());
6179 
6180  if (!scope_info->HasContext()) return target;
6181 
6182  // Third fill all context locals.
6183  Handle<Context> frame_context(Context::cast(frame->context()));
6184  Handle<Context> function_context(frame_context->declaration_context());
6185  if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, function_context,
6186  target)) {
6187  return MaybeHandle<JSObject>();
6188  }
6189 
6190  // Finally copy any properties from the function context extension.
6191  // These will be variables introduced by eval.
6192  if (function_context->closure() == *function) {
6193  if (function_context->has_extension() &&
6194  !function_context->IsNativeContext()) {
6195  Handle<JSObject> ext(JSObject::cast(function_context->extension()));
6199  JSObject);
6200 
6201  for (int i = 0; i < keys->length(); i++) {
6202  // Names of variables introduced by eval are strings.
6203  DCHECK(keys->get(i)->IsString());
6204  Handle<String> key(String::cast(keys->get(i)));
6205  Handle<Object> value;
6207  isolate, value, Object::GetPropertyOrElement(ext, key), JSObject);
6209  isolate, target, key, value, SLOPPY),
6210  JSObject);
6211  }
6212  }
6213  }
6214 
6215  return target;
6216 }
6217 
6218 
6220  Isolate* isolate, JavaScriptFrame* frame, int inlined_jsframe_index) {
6221  FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
6222  Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
6223 
6224  Handle<JSObject> local_scope =
6225  isolate->factory()->NewJSObject(isolate->object_function());
6227  isolate, local_scope,
6228  MaterializeStackLocalsWithFrameInspector(isolate, local_scope, function,
6229  &frame_inspector),
6230  JSObject);
6231 
6232  return MaterializeLocalContext(isolate, local_scope, function, frame);
6233 }
6234 
6235 
6236 // Set the context local variable value.
6237 static bool SetContextLocalValue(Isolate* isolate, Handle<ScopeInfo> scope_info,
6238  Handle<Context> context,
6239  Handle<String> variable_name,
6240  Handle<Object> new_value) {
6241  for (int i = 0; i < scope_info->ContextLocalCount(); i++) {
6242  Handle<String> next_name(scope_info->ContextLocalName(i));
6243  if (String::Equals(variable_name, next_name)) {
6245  InitializationFlag init_flag;
6246  MaybeAssignedFlag maybe_assigned_flag;
6247  int context_index = ScopeInfo::ContextSlotIndex(
6248  scope_info, next_name, &mode, &init_flag, &maybe_assigned_flag);
6249  context->set(context_index, *new_value);
6250  return true;
6251  }
6252  }
6253 
6254  return false;
6255 }
6256 
6257 
6258 static bool SetLocalVariableValue(Isolate* isolate, JavaScriptFrame* frame,
6259  int inlined_jsframe_index,
6260  Handle<String> variable_name,
6261  Handle<Object> new_value) {
6262  if (inlined_jsframe_index != 0 || frame->is_optimized()) {
6263  // Optimized frames are not supported.
6264  return false;
6265  }
6266 
6267  Handle<JSFunction> function(frame->function());
6268  Handle<SharedFunctionInfo> shared(function->shared());
6269  Handle<ScopeInfo> scope_info(shared->scope_info());
6270 
6271  bool default_result = false;
6272 
6273  // Parameters.
6274  for (int i = 0; i < scope_info->ParameterCount(); ++i) {
6275  HandleScope scope(isolate);
6276  if (String::Equals(handle(scope_info->ParameterName(i)), variable_name)) {
6277  frame->SetParameterValue(i, *new_value);
6278  // Argument might be shadowed in heap context, don't stop here.
6279  default_result = true;
6280  }
6281  }
6282 
6283  // Stack locals.
6284  for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
6285  HandleScope scope(isolate);
6286  if (String::Equals(handle(scope_info->StackLocalName(i)), variable_name)) {
6287  frame->SetExpression(i, *new_value);
6288  return true;
6289  }
6290  }
6291 
6292  if (scope_info->HasContext()) {
6293  // Context locals.
6294  Handle<Context> frame_context(Context::cast(frame->context()));
6295  Handle<Context> function_context(frame_context->declaration_context());
6296  if (SetContextLocalValue(isolate, scope_info, function_context,
6297  variable_name, new_value)) {
6298  return true;
6299  }
6300 
6301  // Function context extension. These are variables introduced by eval.
6302  if (function_context->closure() == *function) {
6303  if (function_context->has_extension() &&
6304  !function_context->IsNativeContext()) {
6305  Handle<JSObject> ext(JSObject::cast(function_context->extension()));
6306 
6307  Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
6308  DCHECK(maybe.has_value);
6309  if (maybe.value) {
6310  // We don't expect this to do anything except replacing
6311  // property value.
6312  Runtime::SetObjectProperty(isolate, ext, variable_name, new_value,
6313  SLOPPY).Assert();
6314  return true;
6315  }
6316  }
6317  }
6318  }
6319 
6320  return default_result;
6321 }
6322 
6323 
6324 // Create a plain JSObject which materializes the closure content for the
6325 // context.
6327  Isolate* isolate, Handle<Context> context) {
6328  DCHECK(context->IsFunctionContext());
6329 
6330  Handle<SharedFunctionInfo> shared(context->closure()->shared());
6331  Handle<ScopeInfo> scope_info(shared->scope_info());
6332 
6333  // Allocate and initialize a JSObject with all the content of this function
6334  // closure.
6335  Handle<JSObject> closure_scope =
6336  isolate->factory()->NewJSObject(isolate->object_function());
6337 
6338  // Fill all context locals to the context extension.
6339  if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, context,
6340  closure_scope)) {
6341  return MaybeHandle<JSObject>();
6342  }
6343 
6344  // Finally copy any properties from the function context extension. This will
6345  // be variables introduced by eval.
6346  if (context->has_extension()) {
6347  Handle<JSObject> ext(JSObject::cast(context->extension()));
6351  JSObject);
6352 
6353  for (int i = 0; i < keys->length(); i++) {
6354  HandleScope scope(isolate);
6355  // Names of variables introduced by eval are strings.
6356  DCHECK(keys->get(i)->IsString());
6357  Handle<String> key(String::cast(keys->get(i)));
6358  Handle<Object> value;
6360  isolate, value, Object::GetPropertyOrElement(ext, key), JSObject);
6362  closure_scope, key, value, NONE),
6363  JSObject);
6364  }
6365  }
6366 
6367  return closure_scope;
6368 }
6369 
6370 
6371 // This method copies structure of MaterializeClosure method above.
6372 static bool SetClosureVariableValue(Isolate* isolate, Handle<Context> context,
6373  Handle<String> variable_name,
6374  Handle<Object> new_value) {
6375  DCHECK(context->IsFunctionContext());
6376 
6377  Handle<SharedFunctionInfo> shared(context->closure()->shared());
6378  Handle<ScopeInfo> scope_info(shared->scope_info());
6379 
6380  // Context locals to the context extension.
6381  if (SetContextLocalValue(isolate, scope_info, context, variable_name,
6382  new_value)) {
6383  return true;
6384  }
6385 
6386  // Properties from the function context extension. This will
6387  // be variables introduced by eval.
6388  if (context->has_extension()) {
6389  Handle<JSObject> ext(JSObject::cast(context->extension()));
6390  Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
6391  DCHECK(maybe.has_value);
6392  if (maybe.value) {
6393  // We don't expect this to do anything except replacing property value.
6394  Runtime::DefineObjectProperty(ext, variable_name, new_value, NONE)
6395  .Assert();
6396  return true;
6397  }
6398  }
6399 
6400  return false;
6401 }
6402 
6403 
6404 // Create a plain JSObject which materializes the scope for the specified
6405 // catch context.
6407  Isolate* isolate, Handle<Context> context) {
6408  DCHECK(context->IsCatchContext());
6409  Handle<String> name(String::cast(context->extension()));
6410  Handle<Object> thrown_object(context->get(Context::THROWN_OBJECT_INDEX),
6411  isolate);
6412  Handle<JSObject> catch_scope =
6413  isolate->factory()->NewJSObject(isolate->object_function());
6415  catch_scope, name, thrown_object, NONE),
6416  JSObject);
6417  return catch_scope;
6418 }
6419 
6420 
6421 static bool SetCatchVariableValue(Isolate* isolate, Handle<Context> context,
6422  Handle<String> variable_name,
6423  Handle<Object> new_value) {
6424  DCHECK(context->IsCatchContext());
6425  Handle<String> name(String::cast(context->extension()));
6426  if (!String::Equals(name, variable_name)) {
6427  return false;
6428  }
6429  context->set(Context::THROWN_OBJECT_INDEX, *new_value);
6430  return true;
6431 }
6432 
6433 
6434 // Create a plain JSObject which materializes the block scope for the specified
6435 // block context.
6437  Isolate* isolate, Handle<Context> context) {
6438  DCHECK(context->IsBlockContext());
6439  Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension()));
6440 
6441  // Allocate and initialize a JSObject with all the arguments, stack locals
6442  // heap locals and extension properties of the debugged function.
6443  Handle<JSObject> block_scope =
6444  isolate->factory()->NewJSObject(isolate->object_function());
6445 
6446  // Fill all context locals.
6447  if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, context,
6448  block_scope)) {
6449  return MaybeHandle<JSObject>();
6450  }
6451 
6452  return block_scope;
6453 }
6454 
6455 
6456 // Create a plain JSObject which materializes the module scope for the specified
6457 // module context.
6459  Isolate* isolate, Handle<Context> context) {
6460  DCHECK(context->IsModuleContext());
6461  Handle<ScopeInfo> scope_info(ScopeInfo::cast(context->extension()));
6462 
6463  // Allocate and initialize a JSObject with all the members of the debugged
6464  // module.
6465  Handle<JSObject> module_scope =
6466  isolate->factory()->NewJSObject(isolate->object_function());
6467 
6468  // Fill all context locals.
6469  if (!ScopeInfo::CopyContextLocalsToScopeObject(scope_info, context,
6470  module_scope)) {
6471  return MaybeHandle<JSObject>();
6472  }
6473 
6474  return module_scope;
6475 }
6476 
6477 
6478 // Iterate over the actual scopes visible from a stack frame or from a closure.
6479 // The iteration proceeds from the innermost visible nested scope outwards.
6480 // All scopes are backed by an actual context except the local scope,
6481 // which is inserted "artificially" in the context chain.
6483  public:
6484  enum ScopeType {
6492  };
6493 
6495  int inlined_jsframe_index, bool ignore_nested_scopes = false)
6496  : isolate_(isolate),
6497  frame_(frame),
6498  inlined_jsframe_index_(inlined_jsframe_index),
6499  function_(frame->function()),
6500  context_(Context::cast(frame->context())),
6502  failed_(false) {
6503  // Catch the case when the debugger stops in an internal function.
6504  Handle<SharedFunctionInfo> shared_info(function_->shared());
6505  Handle<ScopeInfo> scope_info(shared_info->scope_info());
6506  if (shared_info->script() == isolate->heap()->undefined_value()) {
6507  while (context_->closure() == *function_) {
6508  context_ = Handle<Context>(context_->previous(), isolate_);
6509  }
6510  return;
6511  }
6512 
6513  // Get the debug info (create it if it does not exist).
6514  if (!isolate->debug()->EnsureDebugInfo(shared_info, function_)) {
6515  // Return if ensuring debug info failed.
6516  return;
6517  }
6518 
6519  // Currently it takes too much time to find nested scopes due to script
6520  // parsing. Sometimes we want to run the ScopeIterator as fast as possible
6521  // (for example, while collecting async call stacks on every
6522  // addEventListener call), even if we drop some nested scopes.
6523  // Later we may optimize getting the nested scopes (cache the result?)
6524  // and include nested scopes into the "fast" iteration case as well.
6525  if (!ignore_nested_scopes) {
6526  Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared_info);
6527 
6528  // Find the break point where execution has stopped.
6529  BreakLocationIterator break_location_iterator(debug_info,
6531  // pc points to the instruction after the current one, possibly a break
6532  // location as well. So the "- 1" to exclude it from the search.
6533  break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
6534 
6535  // Within the return sequence at the moment it is not possible to
6536  // get a source position which is consistent with the current scope chain.
6537  // Thus all nested with, catch and block contexts are skipped and we only
6538  // provide the function scope.
6539  ignore_nested_scopes = break_location_iterator.IsExit();
6540  }
6541 
6542  if (ignore_nested_scopes) {
6543  if (scope_info->HasContext()) {
6544  context_ = Handle<Context>(context_->declaration_context(), isolate_);
6545  } else {
6546  while (context_->closure() == *function_) {
6547  context_ = Handle<Context>(context_->previous(), isolate_);
6548  }
6549  }
6550  if (scope_info->scope_type() == FUNCTION_SCOPE) {
6551  nested_scope_chain_.Add(scope_info);
6552  }
6553  } else {
6554  // Reparse the code and analyze the scopes.
6555  Handle<Script> script(Script::cast(shared_info->script()));
6556  Scope* scope = NULL;
6557 
6558  // Check whether we are in global, eval or function code.
6559  Handle<ScopeInfo> scope_info(shared_info->scope_info());
6560  if (scope_info->scope_type() != FUNCTION_SCOPE) {
6561  // Global or eval code.
6562  CompilationInfoWithZone info(script);
6563  if (scope_info->scope_type() == GLOBAL_SCOPE) {
6564  info.MarkAsGlobal();
6565  } else {
6566  DCHECK(scope_info->scope_type() == EVAL_SCOPE);
6567  info.MarkAsEval();
6568  info.SetContext(Handle<Context>(function_->context()));
6569  }
6570  if (Parser::Parse(&info) && Scope::Analyze(&info)) {
6571  scope = info.function()->scope();
6572  }
6573  RetrieveScopeChain(scope, shared_info);
6574  } else {
6575  // Function code
6576  CompilationInfoWithZone info(shared_info);
6577  if (Parser::Parse(&info) && Scope::Analyze(&info)) {
6578  scope = info.function()->scope();
6579  }
6580  RetrieveScopeChain(scope, shared_info);
6581  }
6582  }
6583  }
6584 
6586  : isolate_(isolate),
6587  frame_(NULL),
6589  function_(function),
6590  context_(function->context()),
6591  failed_(false) {
6592  if (function->IsBuiltin()) {
6594  }
6595  }
6596 
6597  // More scopes?
6598  bool Done() {
6599  DCHECK(!failed_);
6600  return context_.is_null();
6601  }
6602 
6603  bool Failed() { return failed_; }
6604 
6605  // Move to the next scope.
6606  void Next() {
6607  DCHECK(!failed_);
6608  ScopeType scope_type = Type();
6609  if (scope_type == ScopeTypeGlobal) {
6610  // The global scope is always the last in the chain.
6611  DCHECK(context_->IsNativeContext());
6613  return;
6614  }
6615  if (nested_scope_chain_.is_empty()) {
6616  context_ = Handle<Context>(context_->previous(), isolate_);
6617  } else {
6618  if (nested_scope_chain_.last()->HasContext()) {
6619  DCHECK(context_->previous() != NULL);
6620  context_ = Handle<Context>(context_->previous(), isolate_);
6621  }
6622  nested_scope_chain_.RemoveLast();
6623  }
6624  }
6625 
6626  // Return the type of the current scope.
6628  DCHECK(!failed_);
6629  if (!nested_scope_chain_.is_empty()) {
6630  Handle<ScopeInfo> scope_info = nested_scope_chain_.last();
6631  switch (scope_info->scope_type()) {
6632  case FUNCTION_SCOPE:
6633  DCHECK(context_->IsFunctionContext() || !scope_info->HasContext());
6634  return ScopeTypeLocal;
6635  case MODULE_SCOPE:
6636  DCHECK(context_->IsModuleContext());
6637  return ScopeTypeModule;
6638  case GLOBAL_SCOPE:
6639  DCHECK(context_->IsNativeContext());
6640  return ScopeTypeGlobal;
6641  case WITH_SCOPE:
6642  DCHECK(context_->IsWithContext());
6643  return ScopeTypeWith;
6644  case CATCH_SCOPE:
6645  DCHECK(context_->IsCatchContext());
6646  return ScopeTypeCatch;
6647  case BLOCK_SCOPE:
6648  DCHECK(!scope_info->HasContext() || context_->IsBlockContext());
6649  return ScopeTypeBlock;
6650  case EVAL_SCOPE:
6651  UNREACHABLE();
6652  }
6653  }
6654  if (context_->IsNativeContext()) {
6655  DCHECK(context_->global_object()->IsGlobalObject());
6656  return ScopeTypeGlobal;
6657  }
6658  if (context_->IsFunctionContext()) {
6659  return ScopeTypeClosure;
6660  }
6661  if (context_->IsCatchContext()) {
6662  return ScopeTypeCatch;
6663  }
6664  if (context_->IsBlockContext()) {
6665  return ScopeTypeBlock;
6666  }
6667  if (context_->IsModuleContext()) {
6668  return ScopeTypeModule;
6669  }
6670  DCHECK(context_->IsWithContext());
6671  return ScopeTypeWith;
6672  }
6673 
6674  // Return the JavaScript object with the content of the current scope.
6676  DCHECK(!failed_);
6677  switch (Type()) {
6679  return Handle<JSObject>(CurrentContext()->global_object());
6681  // Materialize the content of the local scope into a JSObject.
6682  DCHECK(nested_scope_chain_.length() == 1);
6685  // Return the with object.
6686  return Handle<JSObject>(JSObject::cast(CurrentContext()->extension()));
6690  // Materialize the content of the closure scope into a JSObject.
6696  }
6697  UNREACHABLE();
6698  return Handle<JSObject>();
6699  }
6700 
6701  bool SetVariableValue(Handle<String> variable_name,
6702  Handle<Object> new_value) {
6703  DCHECK(!failed_);
6704  switch (Type()) {
6706  break;
6709  variable_name, new_value);
6711  break;
6713  return SetCatchVariableValue(isolate_, CurrentContext(), variable_name,
6714  new_value);
6717  variable_name, new_value);
6719  // TODO(2399): should we implement it?
6720  break;
6722  // TODO(2399): should we implement it?
6723  break;
6724  }
6725  return false;
6726  }
6727 
6729  DCHECK(!failed_);
6730  if (!nested_scope_chain_.is_empty()) {
6731  return nested_scope_chain_.last();
6732  } else if (context_->IsBlockContext()) {
6733  return Handle<ScopeInfo>(ScopeInfo::cast(context_->extension()));
6734  } else if (context_->IsFunctionContext()) {
6735  return Handle<ScopeInfo>(context_->closure()->shared()->scope_info());
6736  }
6737  return Handle<ScopeInfo>::null();
6738  }
6739 
6740  // Return the context for this scope. For the local context there might not
6741  // be an actual context.
6743  DCHECK(!failed_);
6744  if (Type() == ScopeTypeGlobal || nested_scope_chain_.is_empty()) {
6745  return context_;
6746  } else if (nested_scope_chain_.last()->HasContext()) {
6747  return context_;
6748  } else {
6749  return Handle<Context>();
6750  }
6751  }
6752 
6753 #ifdef DEBUG
6754  // Debug print of the content of the current scope.
6755  void DebugPrint() {
6756  OFStream os(stdout);
6757  DCHECK(!failed_);
6758  switch (Type()) {
6760  os << "Global:\n";
6761  CurrentContext()->Print(os);
6762  break;
6763 
6765  os << "Local:\n";
6766  function_->shared()->scope_info()->Print();
6767  if (!CurrentContext().is_null()) {
6768  CurrentContext()->Print(os);
6769  if (CurrentContext()->has_extension()) {
6770  Handle<Object> extension(CurrentContext()->extension(), isolate_);
6771  if (extension->IsJSContextExtensionObject()) {
6772  extension->Print(os);
6773  }
6774  }
6775  }
6776  break;
6777  }
6778 
6780  os << "With:\n";
6781  CurrentContext()->extension()->Print(os);
6782  break;
6783 
6785  os << "Catch:\n";
6786  CurrentContext()->extension()->Print(os);
6787  CurrentContext()->get(Context::THROWN_OBJECT_INDEX)->Print(os);
6788  break;
6789 
6791  os << "Closure:\n";
6792  CurrentContext()->Print(os);
6793  if (CurrentContext()->has_extension()) {
6794  Handle<Object> extension(CurrentContext()->extension(), isolate_);
6795  if (extension->IsJSContextExtensionObject()) {
6796  extension->Print(os);
6797  }
6798  }
6799  break;
6800 
6801  default:
6802  UNREACHABLE();
6803  }
6804  PrintF("\n");
6805  }
6806 #endif
6807 
6808  private:
6815  bool failed_;
6816 
6818  Handle<SharedFunctionInfo> shared_info) {
6819  if (scope != NULL) {
6820  int source_position = shared_info->code()->SourcePosition(frame_->pc());
6821  scope->GetNestedScopeChain(&nested_scope_chain_, source_position);
6822  } else {
6823  // A failed reparse indicates that the preparser has diverged from the
6824  // parser or that the preparse data given to the initial parse has been
6825  // faulty. We fail in debug mode but in release mode we only provide the
6826  // information we get from the context chain but nothing about
6827  // completely stack allocated scopes or stack allocated locals.
6828  // Or it could be due to stack overflow.
6830  failed_ = true;
6831  }
6832  }
6833 
6835 };
6836 
6837 
6838 RUNTIME_FUNCTION(Runtime_GetScopeCount) {
6839  HandleScope scope(isolate);
6840  DCHECK(args.length() == 2);
6841  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
6842  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
6843 
6844  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
6845 
6846  // Get the frame where the debugging is performed.
6847  StackFrame::Id id = UnwrapFrameId(wrapped_id);
6848  JavaScriptFrameIterator it(isolate, id);
6849  JavaScriptFrame* frame = it.frame();
6850 
6851  // Count the visible scopes.
6852  int n = 0;
6853  for (ScopeIterator it(isolate, frame, 0); !it.Done(); it.Next()) {
6854  n++;
6855  }
6856 
6857  return Smi::FromInt(n);
6858 }
6859 
6860 
6861 // Returns the list of step-in positions (text offset) in a function of the
6862 // stack frame in a range from the current debug break position to the end
6863 // of the corresponding statement.
6864 RUNTIME_FUNCTION(Runtime_GetStepInPositions) {
6865  HandleScope scope(isolate);
6866  DCHECK(args.length() == 2);
6867  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
6868  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
6869 
6870  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
6871 
6872  // Get the frame where the debugging is performed.
6873  StackFrame::Id id = UnwrapFrameId(wrapped_id);
6874  JavaScriptFrameIterator frame_it(isolate, id);
6875  RUNTIME_ASSERT(!frame_it.done());
6876 
6877  JavaScriptFrame* frame = frame_it.frame();
6878 
6881 
6882  if (!isolate->debug()->EnsureDebugInfo(shared, fun)) {
6883  return isolate->heap()->undefined_value();
6884  }
6885 
6886  Handle<DebugInfo> debug_info = Debug::GetDebugInfo(shared);
6887 
6888  int len = 0;
6889  Handle<JSArray> array(isolate->factory()->NewJSArray(10));
6890  // Find the break point where execution has stopped.
6891  BreakLocationIterator break_location_iterator(debug_info,
6893 
6894  break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
6895  int current_statement_pos = break_location_iterator.statement_position();
6896 
6897  while (!break_location_iterator.Done()) {
6898  bool accept;
6899  if (break_location_iterator.pc() > frame->pc()) {
6900  accept = true;
6901  } else {
6902  StackFrame::Id break_frame_id = isolate->debug()->break_frame_id();
6903  // The break point is near our pc. Could be a step-in possibility,
6904  // that is currently taken by active debugger call.
6905  if (break_frame_id == StackFrame::NO_ID) {
6906  // We are not stepping.
6907  accept = false;
6908  } else {
6909  JavaScriptFrameIterator additional_frame_it(isolate, break_frame_id);
6910  // If our frame is a top frame and we are stepping, we can do step-in
6911  // at this place.
6912  accept = additional_frame_it.frame()->id() == id;
6913  }
6914  }
6915  if (accept) {
6916  if (break_location_iterator.IsStepInLocation(isolate)) {
6917  Smi* position_value = Smi::FromInt(break_location_iterator.position());
6919  isolate, JSObject::SetElement(
6920  array, len, Handle<Object>(position_value, isolate),
6921  NONE, SLOPPY));
6922  len++;
6923  }
6924  }
6925  // Advance iterator.
6926  break_location_iterator.Next();
6927  if (current_statement_pos != break_location_iterator.statement_position()) {
6928  break;
6929  }
6930  }
6931  return *array;
6932 }
6933 
6934 
6935 static const int kScopeDetailsTypeIndex = 0;
6936 static const int kScopeDetailsObjectIndex = 1;
6937 static const int kScopeDetailsSize = 2;
6938 
6939 
6941  Isolate* isolate, ScopeIterator* it) {
6942  // Calculate the size of the result.
6943  int details_size = kScopeDetailsSize;
6944  Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);
6945 
6946  // Fill in scope details.
6947  details->set(kScopeDetailsTypeIndex, Smi::FromInt(it->Type()));
6948  Handle<JSObject> scope_object;
6949  ASSIGN_RETURN_ON_EXCEPTION(isolate, scope_object, it->ScopeObject(),
6950  JSObject);
6951  details->set(kScopeDetailsObjectIndex, *scope_object);
6952 
6953  return isolate->factory()->NewJSArrayWithElements(details);
6954 }
6955 
6956 
6957 // Return an array with scope details
6958 // args[0]: number: break id
6959 // args[1]: number: frame index
6960 // args[2]: number: inlined frame index
6961 // args[3]: number: scope index
6962 //
6963 // The array returned contains the following information:
6964 // 0: Scope type
6965 // 1: Scope object
6966 RUNTIME_FUNCTION(Runtime_GetScopeDetails) {
6967  HandleScope scope(isolate);
6968  DCHECK(args.length() == 4);
6969  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
6970  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
6971 
6972  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
6973  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
6974  CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
6975 
6976  // Get the frame where the debugging is performed.
6977  StackFrame::Id id = UnwrapFrameId(wrapped_id);
6978  JavaScriptFrameIterator frame_it(isolate, id);
6979  JavaScriptFrame* frame = frame_it.frame();
6980 
6981  // Find the requested scope.
6982  int n = 0;
6983  ScopeIterator it(isolate, frame, inlined_jsframe_index);
6984  for (; !it.Done() && n < index; it.Next()) {
6985  n++;
6986  }
6987  if (it.Done()) {
6988  return isolate->heap()->undefined_value();
6989  }
6990  Handle<JSObject> details;
6991  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details,
6992  MaterializeScopeDetails(isolate, &it));
6993  return *details;
6994 }
6995 
6996 
6997 // Return an array of scope details
6998 // args[0]: number: break id
6999 // args[1]: number: frame index
7000 // args[2]: number: inlined frame index
7001 // args[3]: boolean: ignore nested scopes
7002 //
7003 // The array returned contains arrays with the following information:
7004 // 0: Scope type
7005 // 1: Scope object
7006 RUNTIME_FUNCTION(Runtime_GetAllScopesDetails) {
7007  HandleScope scope(isolate);
7008  DCHECK(args.length() == 3 || args.length() == 4);
7009  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7010  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7011 
7012  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
7013  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
7014 
7015  bool ignore_nested_scopes = false;
7016  if (args.length() == 4) {
7018  ignore_nested_scopes = flag;
7019  }
7020 
7021  // Get the frame where the debugging is performed.
7022  StackFrame::Id id = UnwrapFrameId(wrapped_id);
7023  JavaScriptFrameIterator frame_it(isolate, id);
7024  JavaScriptFrame* frame = frame_it.frame();
7025 
7026  List<Handle<JSObject> > result(4);
7027  ScopeIterator it(isolate, frame, inlined_jsframe_index, ignore_nested_scopes);
7028  for (; !it.Done(); it.Next()) {
7029  Handle<JSObject> details;
7030  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details,
7031  MaterializeScopeDetails(isolate, &it));
7032  result.Add(details);
7033  }
7034 
7035  Handle<FixedArray> array = isolate->factory()->NewFixedArray(result.length());
7036  for (int i = 0; i < result.length(); ++i) {
7037  array->set(i, *result[i]);
7038  }
7039  return *isolate->factory()->NewJSArrayWithElements(array);
7040 }
7041 
7042 
7043 RUNTIME_FUNCTION(Runtime_GetFunctionScopeCount) {
7044  HandleScope scope(isolate);
7045  DCHECK(args.length() == 1);
7046 
7047  // Check arguments.
7049 
7050  // Count the visible scopes.
7051  int n = 0;
7052  for (ScopeIterator it(isolate, fun); !it.Done(); it.Next()) {
7053  n++;
7054  }
7055 
7056  return Smi::FromInt(n);
7057 }
7058 
7059 
7060 RUNTIME_FUNCTION(Runtime_GetFunctionScopeDetails) {
7061  HandleScope scope(isolate);
7062  DCHECK(args.length() == 2);
7063 
7064  // Check arguments.
7066  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
7067 
7068  // Find the requested scope.
7069  int n = 0;
7070  ScopeIterator it(isolate, fun);
7071  for (; !it.Done() && n < index; it.Next()) {
7072  n++;
7073  }
7074  if (it.Done()) {
7075  return isolate->heap()->undefined_value();
7076  }
7077 
7078  Handle<JSObject> details;
7079  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details,
7080  MaterializeScopeDetails(isolate, &it));
7081  return *details;
7082 }
7083 
7084 
7085 static bool SetScopeVariableValue(ScopeIterator* it, int index,
7086  Handle<String> variable_name,
7087  Handle<Object> new_value) {
7088  for (int n = 0; !it->Done() && n < index; it->Next()) {
7089  n++;
7090  }
7091  if (it->Done()) {
7092  return false;
7093  }
7094  return it->SetVariableValue(variable_name, new_value);
7095 }
7096 
7097 
7098 // Change variable value in closure or local scope
7099 // args[0]: number or JsFunction: break id or function
7100 // args[1]: number: frame index (when arg[0] is break id)
7101 // args[2]: number: inlined frame index (when arg[0] is break id)
7102 // args[3]: number: scope index
7103 // args[4]: string: variable name
7104 // args[5]: object: new value
7105 //
7106 // Return true if success and false otherwise
7107 RUNTIME_FUNCTION(Runtime_SetScopeVariableValue) {
7108  HandleScope scope(isolate);
7109  DCHECK(args.length() == 6);
7110 
7111  // Check arguments.
7112  CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
7113  CONVERT_ARG_HANDLE_CHECKED(String, variable_name, 4);
7114  CONVERT_ARG_HANDLE_CHECKED(Object, new_value, 5);
7115 
7116  bool res;
7117  if (args[0]->IsNumber()) {
7118  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7119  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7120 
7121  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
7122  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
7123 
7124  // Get the frame where the debugging is performed.
7125  StackFrame::Id id = UnwrapFrameId(wrapped_id);
7126  JavaScriptFrameIterator frame_it(isolate, id);
7127  JavaScriptFrame* frame = frame_it.frame();
7128 
7129  ScopeIterator it(isolate, frame, inlined_jsframe_index);
7130  res = SetScopeVariableValue(&it, index, variable_name, new_value);
7131  } else {
7133  ScopeIterator it(isolate, fun);
7134  res = SetScopeVariableValue(&it, index, variable_name, new_value);
7135  }
7136 
7137  return isolate->heap()->ToBoolean(res);
7138 }
7139 
7140 
7141 RUNTIME_FUNCTION(Runtime_DebugPrintScopes) {
7142  HandleScope scope(isolate);
7143  DCHECK(args.length() == 0);
7144 
7145 #ifdef DEBUG
7146  // Print the scopes for the top frame.
7147  StackFrameLocator locator(isolate);
7148  JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
7149  for (ScopeIterator it(isolate, frame, 0); !it.Done(); it.Next()) {
7150  it.DebugPrint();
7151  }
7152 #endif
7153  return isolate->heap()->undefined_value();
7154 }
7155 
7156 
7157 RUNTIME_FUNCTION(Runtime_GetThreadCount) {
7158  HandleScope scope(isolate);
7159  DCHECK(args.length() == 1);
7160  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7161  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7162 
7163  // Count all archived V8 threads.
7164  int n = 0;
7165  for (ThreadState* thread = isolate->thread_manager()->FirstThreadStateInUse();
7166  thread != NULL; thread = thread->Next()) {
7167  n++;
7168  }
7169 
7170  // Total number of threads is current thread and archived threads.
7171  return Smi::FromInt(n + 1);
7172 }
7173 
7174 
7176 static const int kThreadDetailsThreadIdIndex = 1;
7177 static const int kThreadDetailsSize = 2;
7178 
7179 // Return an array with thread details
7180 // args[0]: number: break id
7181 // args[1]: number: thread index
7182 //
7183 // The array returned contains the following information:
7184 // 0: Is current thread?
7185 // 1: Thread id
7186 RUNTIME_FUNCTION(Runtime_GetThreadDetails) {
7187  HandleScope scope(isolate);
7188  DCHECK(args.length() == 2);
7189  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7190  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7191 
7192  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
7193 
7194  // Allocate array for result.
7195  Handle<FixedArray> details =
7196  isolate->factory()->NewFixedArray(kThreadDetailsSize);
7197 
7198  // Thread index 0 is current thread.
7199  if (index == 0) {
7200  // Fill the details.
7201  details->set(kThreadDetailsCurrentThreadIndex,
7202  isolate->heap()->true_value());
7203  details->set(kThreadDetailsThreadIdIndex,
7204  Smi::FromInt(ThreadId::Current().ToInteger()));
7205  } else {
7206  // Find the thread with the requested index.
7207  int n = 1;
7208  ThreadState* thread = isolate->thread_manager()->FirstThreadStateInUse();
7209  while (index != n && thread != NULL) {
7210  thread = thread->Next();
7211  n++;
7212  }
7213  if (thread == NULL) {
7214  return isolate->heap()->undefined_value();
7215  }
7216 
7217  // Fill the details.
7218  details->set(kThreadDetailsCurrentThreadIndex,
7219  isolate->heap()->false_value());
7220  details->set(kThreadDetailsThreadIdIndex,
7221  Smi::FromInt(thread->id().ToInteger()));
7222  }
7223 
7224  // Convert to JS array and return.
7225  return *isolate->factory()->NewJSArrayWithElements(details);
7226 }
7227 
7228 
7229 // Sets the disable break state
7230 // args[0]: disable break state
7231 RUNTIME_FUNCTION(Runtime_SetDisableBreak) {
7232  HandleScope scope(isolate);
7233  DCHECK(args.length() == 1);
7234  CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 0);
7235  isolate->debug()->set_disable_break(disable_break);
7236  return isolate->heap()->undefined_value();
7237 }
7238 
7239 
7240 static bool IsPositionAlignmentCodeCorrect(int alignment) {
7241  return alignment == STATEMENT_ALIGNED || alignment == BREAK_POSITION_ALIGNED;
7242 }
7243 
7244 
7245 RUNTIME_FUNCTION(Runtime_GetBreakLocations) {
7246  HandleScope scope(isolate);
7247  DCHECK(args.length() == 2);
7248 
7250  CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[1]);
7251 
7252  if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
7253  return isolate->ThrowIllegalOperation();
7254  }
7255  BreakPositionAlignment alignment =
7256  static_cast<BreakPositionAlignment>(statement_aligned_code);
7257 
7258  Handle<SharedFunctionInfo> shared(fun->shared());
7259  // Find the number of break points
7260  Handle<Object> break_locations =
7261  Debug::GetSourceBreakLocations(shared, alignment);
7262  if (break_locations->IsUndefined()) return isolate->heap()->undefined_value();
7263  // Return array as JS array
7264  return *isolate->factory()->NewJSArrayWithElements(
7265  Handle<FixedArray>::cast(break_locations));
7266 }
7267 
7268 
7269 // Set a break point in a function.
7270 // args[0]: function
7271 // args[1]: number: break source position (within the function source)
7272 // args[2]: number: break point object
7273 RUNTIME_FUNCTION(Runtime_SetFunctionBreakPoint) {
7274  HandleScope scope(isolate);
7275  DCHECK(args.length() == 3);
7276  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
7277  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
7278  RUNTIME_ASSERT(source_position >= function->shared()->start_position() &&
7279  source_position <= function->shared()->end_position());
7280  CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 2);
7281 
7282  // Set break point.
7283  RUNTIME_ASSERT(isolate->debug()->SetBreakPoint(
7284  function, break_point_object_arg, &source_position));
7285 
7286  return Smi::FromInt(source_position);
7287 }
7288 
7289 
7290 // Changes the state of a break point in a script and returns source position
7291 // where break point was set. NOTE: Regarding performance see the NOTE for
7292 // GetScriptFromScriptData.
7293 // args[0]: script to set break point in
7294 // args[1]: number: break source position (within the script source)
7295 // args[2]: number, breakpoint position alignment
7296 // args[3]: number: break point object
7297 RUNTIME_FUNCTION(Runtime_SetScriptBreakPoint) {
7298  HandleScope scope(isolate);
7299  DCHECK(args.length() == 4);
7300  CONVERT_ARG_HANDLE_CHECKED(JSValue, wrapper, 0);
7301  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
7302  RUNTIME_ASSERT(source_position >= 0);
7303  CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[2]);
7304  CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 3);
7305 
7306  if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
7307  return isolate->ThrowIllegalOperation();
7308  }
7309  BreakPositionAlignment alignment =
7310  static_cast<BreakPositionAlignment>(statement_aligned_code);
7311 
7312  // Get the script from the script wrapper.
7313  RUNTIME_ASSERT(wrapper->value()->IsScript());
7314  Handle<Script> script(Script::cast(wrapper->value()));
7315 
7316  // Set break point.
7317  if (!isolate->debug()->SetBreakPointForScript(script, break_point_object_arg,
7318  &source_position, alignment)) {
7319  return isolate->heap()->undefined_value();
7320  }
7321 
7322  return Smi::FromInt(source_position);
7323 }
7324 
7325 
7326 // Clear a break point
7327 // args[0]: number: break point object
7328 RUNTIME_FUNCTION(Runtime_ClearBreakPoint) {
7329  HandleScope scope(isolate);
7330  DCHECK(args.length() == 1);
7331  CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 0);
7332 
7333  // Clear break point.
7334  isolate->debug()->ClearBreakPoint(break_point_object_arg);
7335 
7336  return isolate->heap()->undefined_value();
7337 }
7338 
7339 
7340 // Change the state of break on exceptions.
7341 // args[0]: Enum value indicating whether to affect caught/uncaught exceptions.
7342 // args[1]: Boolean indicating on/off.
7343 RUNTIME_FUNCTION(Runtime_ChangeBreakOnException) {
7344  HandleScope scope(isolate);
7345  DCHECK(args.length() == 2);
7346  CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
7347  CONVERT_BOOLEAN_ARG_CHECKED(enable, 1);
7348 
7349  // If the number doesn't match an enum value, the ChangeBreakOnException
7350  // function will default to affecting caught exceptions.
7351  ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
7352  // Update break point state.
7353  isolate->debug()->ChangeBreakOnException(type, enable);
7354  return isolate->heap()->undefined_value();
7355 }
7356 
7357 
7358 // Returns the state of break on exceptions
7359 // args[0]: boolean indicating uncaught exceptions
7360 RUNTIME_FUNCTION(Runtime_IsBreakOnException) {
7361  HandleScope scope(isolate);
7362  DCHECK(args.length() == 1);
7363  CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
7364 
7365  ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
7366  bool result = isolate->debug()->IsBreakOnException(type);
7367  return Smi::FromInt(result);
7368 }
7369 
7370 
7371 // Prepare for stepping
7372 // args[0]: break id for checking execution state
7373 // args[1]: step action from the enumeration StepAction
7374 // args[2]: number of times to perform the step, for step out it is the number
7375 // of frames to step down.
7376 RUNTIME_FUNCTION(Runtime_PrepareStep) {
7377  HandleScope scope(isolate);
7378  DCHECK(args.length() == 4);
7379  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7380  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7381 
7382  if (!args[1]->IsNumber() || !args[2]->IsNumber()) {
7383  return isolate->Throw(isolate->heap()->illegal_argument_string());
7384  }
7385 
7386  CONVERT_NUMBER_CHECKED(int, wrapped_frame_id, Int32, args[3]);
7387 
7388  StackFrame::Id frame_id;
7389  if (wrapped_frame_id == 0) {
7390  frame_id = StackFrame::NO_ID;
7391  } else {
7392  frame_id = UnwrapFrameId(wrapped_frame_id);
7393  }
7394 
7395  // Get the step action and check validity.
7396  StepAction step_action = static_cast<StepAction>(NumberToInt32(args[1]));
7397  if (step_action != StepIn && step_action != StepNext &&
7398  step_action != StepOut && step_action != StepInMin &&
7399  step_action != StepMin) {
7400  return isolate->Throw(isolate->heap()->illegal_argument_string());
7401  }
7402 
7403  if (frame_id != StackFrame::NO_ID && step_action != StepNext &&
7404  step_action != StepMin && step_action != StepOut) {
7405  return isolate->ThrowIllegalOperation();
7406  }
7407 
7408  // Get the number of steps.
7409  int step_count = NumberToInt32(args[2]);
7410  if (step_count < 1) {
7411  return isolate->Throw(isolate->heap()->illegal_argument_string());
7412  }
7413 
7414  // Clear all current stepping setup.
7415  isolate->debug()->ClearStepping();
7416 
7417  // Prepare step.
7418  isolate->debug()->PrepareStep(static_cast<StepAction>(step_action),
7419  step_count, frame_id);
7420  return isolate->heap()->undefined_value();
7421 }
7422 
7423 
7424 // Clear all stepping set by PrepareStep.
7425 RUNTIME_FUNCTION(Runtime_ClearStepping) {
7426  HandleScope scope(isolate);
7427  DCHECK(args.length() == 0);
7428  isolate->debug()->ClearStepping();
7429  return isolate->heap()->undefined_value();
7430 }
7431 
7432 
7433 // Helper function to find or create the arguments object for
7434 // Runtime_DebugEvaluate.
7436  Isolate* isolate, Handle<JSObject> target, Handle<JSFunction> function) {
7437  // Do not materialize the arguments object for eval or top-level code.
7438  // Skip if "arguments" is already taken.
7439  if (!function->shared()->is_function()) return target;
7441  target, isolate->factory()->arguments_string());
7442  if (!maybe.has_value) return MaybeHandle<JSObject>();
7443  if (maybe.value) return target;
7444 
7445  // FunctionGetArguments can't throw an exception.
7446  Handle<JSObject> arguments =
7448  Handle<String> arguments_str = isolate->factory()->arguments_string();
7450  target, arguments_str, arguments, NONE),
7451  JSObject);
7452  return target;
7453 }
7454 
7455 
7456 // Compile and evaluate source for the given context.
7458  Handle<Context> context,
7459  Handle<Object> context_extension,
7460  Handle<Object> receiver,
7461  Handle<String> source) {
7462  if (context_extension->IsJSObject()) {
7463  Handle<JSObject> extension = Handle<JSObject>::cast(context_extension);
7464  Handle<JSFunction> closure(context->closure(), isolate);
7465  context = isolate->factory()->NewWithContext(closure, context, extension);
7466  }
7467 
7468  Handle<JSFunction> eval_fun;
7470  isolate, eval_fun, Compiler::GetFunctionFromEval(source, context, SLOPPY,
7473  Object);
7474 
7475  Handle<Object> result;
7477  isolate, result, Execution::Call(isolate, eval_fun, receiver, 0, NULL),
7478  Object);
7479 
7480  // Skip the global proxy as it has no properties and always delegates to the
7481  // real global object.
7482  if (result->IsJSGlobalProxy()) {
7483  PrototypeIterator iter(isolate, result);
7484  // TODO(verwaest): This will crash when the global proxy is detached.
7486  }
7487 
7488  // Clear the oneshot breakpoints so that the debugger does not step further.
7489  isolate->debug()->ClearStepping();
7490  return result;
7491 }
7492 
7493 
7495  Handle<JSObject> result =
7496  isolate->factory()->NewJSObject(isolate->object_function());
7497  Handle<Map> new_map = Map::Copy(Handle<Map>(result->map()));
7498  new_map->set_prototype(*isolate->factory()->null_value());
7499  JSObject::MigrateToMap(result, new_map);
7500  return result;
7501 }
7502 
7503 
7504 // Evaluate a piece of JavaScript in the context of a stack frame for
7505 // debugging. Things that need special attention are:
7506 // - Parameters and stack-allocated locals need to be materialized. Altered
7507 // values need to be written back to the stack afterwards.
7508 // - The arguments object needs to materialized.
7509 RUNTIME_FUNCTION(Runtime_DebugEvaluate) {
7510  HandleScope scope(isolate);
7511 
7512  // Check the execution state and decode arguments frame and source to be
7513  // evaluated.
7514  DCHECK(args.length() == 6);
7515  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7516  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7517 
7518  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
7519  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
7520  CONVERT_ARG_HANDLE_CHECKED(String, source, 3);
7521  CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 4);
7522  CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 5);
7523 
7524  // Handle the processing of break.
7525  DisableBreak disable_break_scope(isolate->debug(), disable_break);
7526 
7527  // Get the frame where the debugging is performed.
7528  StackFrame::Id id = UnwrapFrameId(wrapped_id);
7529  JavaScriptFrameIterator it(isolate, id);
7530  JavaScriptFrame* frame = it.frame();
7531  FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
7532  Handle<JSFunction> function(JSFunction::cast(frame_inspector.GetFunction()));
7533 
7534  // Traverse the saved contexts chain to find the active context for the
7535  // selected frame.
7536  SaveContext* save = FindSavedContextForFrame(isolate, frame);
7537 
7538  SaveContext savex(isolate);
7539  isolate->set_context(*(save->context()));
7540 
7541  // Materialize stack locals and the arguments object.
7542  Handle<JSObject> materialized = NewJSObjectWithNullProto(isolate);
7543 
7545  isolate, materialized,
7546  MaterializeStackLocalsWithFrameInspector(isolate, materialized, function,
7547  &frame_inspector));
7548 
7550  isolate, materialized,
7551  MaterializeArgumentsObject(isolate, materialized, function));
7552 
7553  // At this point, the lookup chain may look like this:
7554  // [inner context] -> [function stack]+[function context] -> [outer context]
7555  // The function stack is not an actual context, it complements the function
7556  // context. In order to have the same lookup chain when debug-evaluating,
7557  // we materialize the stack and insert it into the context chain as a
7558  // with-context before the function context.
7559  // [inner context] -> [with context] -> [function context] -> [outer context]
7560  // Ordering the with-context before the function context forces a dynamic
7561  // lookup instead of a static lookup that could fail as the scope info is
7562  // outdated and may expect variables to still be stack-allocated.
7563  // Afterwards, we write changes to the with-context back to the stack
7564  // and remove it from the context chain.
7565  // This could cause lookup failures if debug-evaluate creates a closure that
7566  // uses this temporary context chain.
7567 
7568  Handle<Context> eval_context(Context::cast(frame_inspector.GetContext()));
7569  DCHECK(!eval_context.is_null());
7570  Handle<Context> function_context = eval_context;
7571  Handle<Context> outer_context(function->context(), isolate);
7572  Handle<Context> inner_context;
7573  // We iterate to find the function's context. If the function has no
7574  // context-allocated variables, we iterate until we hit the outer context.
7575  while (!function_context->IsFunctionContext() &&
7576  !function_context.is_identical_to(outer_context)) {
7577  inner_context = function_context;
7578  function_context = Handle<Context>(function_context->previous(), isolate);
7579  }
7580 
7581  Handle<Context> materialized_context = isolate->factory()->NewWithContext(
7582  function, function_context, materialized);
7583 
7584  if (inner_context.is_null()) {
7585  // No inner context. The with-context is now inner-most.
7586  eval_context = materialized_context;
7587  } else {
7588  inner_context->set_previous(*materialized_context);
7589  }
7590 
7591  Handle<Object> receiver(frame->receiver(), isolate);
7592  MaybeHandle<Object> maybe_result =
7593  DebugEvaluate(isolate, eval_context, context_extension, receiver, source);
7594 
7595  // Remove with-context if it was inserted in between.
7596  if (!inner_context.is_null()) inner_context->set_previous(*function_context);
7597 
7598  Handle<Object> result;
7599  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, maybe_result);
7600 
7601  // Write back potential changes to materialized stack locals to the stack.
7602  UpdateStackLocalsFromMaterializedObject(isolate, materialized, function,
7603  frame, inlined_jsframe_index);
7604 
7605  return *result;
7606 }
7607 
7608 
7609 RUNTIME_FUNCTION(Runtime_DebugEvaluateGlobal) {
7610  HandleScope scope(isolate);
7611 
7612  // Check the execution state and decode arguments frame and source to be
7613  // evaluated.
7614  DCHECK(args.length() == 4);
7615  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
7616  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
7617 
7618  CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
7619  CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 2);
7620  CONVERT_ARG_HANDLE_CHECKED(Object, context_extension, 3);
7621 
7622  // Handle the processing of break.
7623  DisableBreak disable_break_scope(isolate->debug(), disable_break);
7624 
7625  // Enter the top context from before the debugger was invoked.
7626  SaveContext save(isolate);
7627  SaveContext* top = &save;
7628  while (top != NULL && *top->context() == *isolate->debug()->debug_context()) {
7629  top = top->prev();
7630  }
7631  if (top != NULL) {
7632  isolate->set_context(*top->context());
7633  }
7634 
7635  // Get the native context now set to the top context from before the
7636  // debugger was invoked.
7637  Handle<Context> context = isolate->native_context();
7638  Handle<JSObject> receiver(context->global_proxy());
7639  Handle<Object> result;
7641  isolate, result,
7642  DebugEvaluate(isolate, context, context_extension, receiver, source));
7643  return *result;
7644 }
7645 
7646 
7647 RUNTIME_FUNCTION(Runtime_DebugGetLoadedScripts) {
7648  HandleScope scope(isolate);
7649  DCHECK(args.length() == 0);
7650 
7651  // Fill the script objects.
7652  Handle<FixedArray> instances = isolate->debug()->GetLoadedScripts();
7653 
7654  // Convert the script objects to proper JS objects.
7655  for (int i = 0; i < instances->length(); i++) {
7656  Handle<Script> script = Handle<Script>(Script::cast(instances->get(i)));
7657  // Get the script wrapper in a local handle before calling GetScriptWrapper,
7658  // because using
7659  // instances->set(i, *GetScriptWrapper(script))
7660  // is unsafe as GetScriptWrapper might call GC and the C++ compiler might
7661  // already have dereferenced the instances handle.
7662  Handle<JSObject> wrapper = Script::GetWrapper(script);
7663  instances->set(i, *wrapper);
7664  }
7665 
7666  // Return result as a JS array.
7667  Handle<JSObject> result =
7668  isolate->factory()->NewJSObject(isolate->array_function());
7669  JSArray::SetContent(Handle<JSArray>::cast(result), instances);
7670  return *result;
7671 }
7672 
7673 
7674 // Helper function used by Runtime_DebugReferencedBy below.
7675 static int DebugReferencedBy(HeapIterator* iterator, JSObject* target,
7676  Object* instance_filter, int max_references,
7677  FixedArray* instances, int instances_size,
7678  JSFunction* arguments_function) {
7679  Isolate* isolate = target->GetIsolate();
7680  SealHandleScope shs(isolate);
7681  DisallowHeapAllocation no_allocation;
7682 
7683  // Iterate the heap.
7684  int count = 0;
7685  JSObject* last = NULL;
7686  HeapObject* heap_obj = NULL;
7687  while (((heap_obj = iterator->next()) != NULL) &&
7688  (max_references == 0 || count < max_references)) {
7689  // Only look at all JSObjects.
7690  if (heap_obj->IsJSObject()) {
7691  // Skip context extension objects and argument arrays as these are
7692  // checked in the context of functions using them.
7693  JSObject* obj = JSObject::cast(heap_obj);
7694  if (obj->IsJSContextExtensionObject() ||
7695  obj->map()->constructor() == arguments_function) {
7696  continue;
7697  }
7698 
7699  // Check if the JS object has a reference to the object looked for.
7700  if (obj->ReferencesObject(target)) {
7701  // Check instance filter if supplied. This is normally used to avoid
7702  // references from mirror objects (see Runtime_IsInPrototypeChain).
7703  if (!instance_filter->IsUndefined()) {
7704  for (PrototypeIterator iter(isolate, obj); !iter.IsAtEnd();
7705  iter.Advance()) {
7706  if (iter.GetCurrent() == instance_filter) {
7707  obj = NULL; // Don't add this object.
7708  break;
7709  }
7710  }
7711  }
7712 
7713  if (obj != NULL) {
7714  // Valid reference found add to instance array if supplied an update
7715  // count.
7716  if (instances != NULL && count < instances_size) {
7717  instances->set(count, obj);
7718  }
7719  last = obj;
7720  count++;
7721  }
7722  }
7723  }
7724  }
7725 
7726  // Check for circular reference only. This can happen when the object is only
7727  // referenced from mirrors and has a circular reference in which case the
7728  // object is not really alive and would have been garbage collected if not
7729  // referenced from the mirror.
7730  if (count == 1 && last == target) {
7731  count = 0;
7732  }
7733 
7734  // Return the number of referencing objects found.
7735  return count;
7736 }
7737 
7738 
7739 // Scan the heap for objects with direct references to an object
7740 // args[0]: the object to find references to
7741 // args[1]: constructor function for instances to exclude (Mirror)
7742 // args[2]: the the maximum number of objects to return
7743 RUNTIME_FUNCTION(Runtime_DebugReferencedBy) {
7744  HandleScope scope(isolate);
7745  DCHECK(args.length() == 3);
7746 
7747  // Check parameters.
7749  CONVERT_ARG_HANDLE_CHECKED(Object, instance_filter, 1);
7750  RUNTIME_ASSERT(instance_filter->IsUndefined() ||
7751  instance_filter->IsJSObject());
7752  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]);
7753  RUNTIME_ASSERT(max_references >= 0);
7754 
7755 
7756  // Get the constructor function for context extension and arguments array.
7757  Handle<JSFunction> arguments_function(
7758  JSFunction::cast(isolate->sloppy_arguments_map()->constructor()));
7759 
7760  // Get the number of referencing objects.
7761  int count;
7762  // First perform a full GC in order to avoid dead objects and to make the heap
7763  // iterable.
7764  Heap* heap = isolate->heap();
7765  heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy");
7766  {
7767  HeapIterator heap_iterator(heap);
7768  count = DebugReferencedBy(&heap_iterator, *target, *instance_filter,
7769  max_references, NULL, 0, *arguments_function);
7770  }
7771 
7772  // Allocate an array to hold the result.
7773  Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count);
7774 
7775  // Fill the referencing objects.
7776  {
7777  HeapIterator heap_iterator(heap);
7778  count = DebugReferencedBy(&heap_iterator, *target, *instance_filter,
7779  max_references, *instances, count,
7780  *arguments_function);
7781  }
7782 
7783  // Return result as JS array.
7784  Handle<JSFunction> constructor = isolate->array_function();
7785 
7786  Handle<JSObject> result = isolate->factory()->NewJSObject(constructor);
7787  JSArray::SetContent(Handle<JSArray>::cast(result), instances);
7788  return *result;
7789 }
7790 
7791 
7792 // Helper function used by Runtime_DebugConstructedBy below.
7793 static int DebugConstructedBy(HeapIterator* iterator, JSFunction* constructor,
7794  int max_references, FixedArray* instances,
7795  int instances_size) {
7796  DisallowHeapAllocation no_allocation;
7797 
7798  // Iterate the heap.
7799  int count = 0;
7800  HeapObject* heap_obj = NULL;
7801  while (((heap_obj = iterator->next()) != NULL) &&
7802  (max_references == 0 || count < max_references)) {
7803  // Only look at all JSObjects.
7804  if (heap_obj->IsJSObject()) {
7805  JSObject* obj = JSObject::cast(heap_obj);
7806  if (obj->map()->constructor() == constructor) {
7807  // Valid reference found add to instance array if supplied an update
7808  // count.
7809  if (instances != NULL && count < instances_size) {
7810  instances->set(count, obj);
7811  }
7812  count++;
7813  }
7814  }
7815  }
7816 
7817  // Return the number of referencing objects found.
7818  return count;
7819 }
7820 
7821 
7822 // Scan the heap for objects constructed by a specific function.
7823 // args[0]: the constructor to find instances of
7824 // args[1]: the the maximum number of objects to return
7825 RUNTIME_FUNCTION(Runtime_DebugConstructedBy) {
7826  HandleScope scope(isolate);
7827  DCHECK(args.length() == 2);
7828 
7829 
7830  // Check parameters.
7831  CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, 0);
7832  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]);
7833  RUNTIME_ASSERT(max_references >= 0);
7834 
7835  // Get the number of referencing objects.
7836  int count;
7837  // First perform a full GC in order to avoid dead objects and to make the heap
7838  // iterable.
7839  Heap* heap = isolate->heap();
7840  heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "%DebugConstructedBy");
7841  {
7842  HeapIterator heap_iterator(heap);
7843  count = DebugConstructedBy(&heap_iterator, *constructor, max_references,
7844  NULL, 0);
7845  }
7846 
7847  // Allocate an array to hold the result.
7848  Handle<FixedArray> instances = isolate->factory()->NewFixedArray(count);
7849 
7850  // Fill the referencing objects.
7851  {
7852  HeapIterator heap_iterator2(heap);
7853  count = DebugConstructedBy(&heap_iterator2, *constructor, max_references,
7854  *instances, count);
7855  }
7856 
7857  // Return result as JS array.
7858  Handle<JSFunction> array_function = isolate->array_function();
7859  Handle<JSObject> result = isolate->factory()->NewJSObject(array_function);
7860  JSArray::SetContent(Handle<JSArray>::cast(result), instances);
7861  return *result;
7862 }
7863 
7864 
7865 // Find the effective prototype object as returned by __proto__.
7866 // args[0]: the object to find the prototype for.
7867 RUNTIME_FUNCTION(Runtime_DebugGetPrototype) {
7868  HandleScope shs(isolate);
7869  DCHECK(args.length() == 1);
7871  return *GetPrototypeSkipHiddenPrototypes(isolate, obj);
7872 }
7873 
7874 
7875 // Patches script source (should be called upon BeforeCompile event).
7876 RUNTIME_FUNCTION(Runtime_DebugSetScriptSource) {
7877  HandleScope scope(isolate);
7878  DCHECK(args.length() == 2);
7879 
7880  CONVERT_ARG_HANDLE_CHECKED(JSValue, script_wrapper, 0);
7881  CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
7882 
7883  RUNTIME_ASSERT(script_wrapper->value()->IsScript());
7884  Handle<Script> script(Script::cast(script_wrapper->value()));
7885 
7886  int compilation_state = script->compilation_state();
7887  RUNTIME_ASSERT(compilation_state == Script::COMPILATION_STATE_INITIAL);
7888  script->set_source(*source);
7889 
7890  return isolate->heap()->undefined_value();
7891 }
7892 
7893 
7894 RUNTIME_FUNCTION(Runtime_DebugDisassembleFunction) {
7895  HandleScope scope(isolate);
7896 #ifdef DEBUG
7897  DCHECK(args.length() == 1);
7898  // Get the function and make sure it is compiled.
7901  return isolate->heap()->exception();
7902  }
7903  OFStream os(stdout);
7904  func->code()->Print(os);
7905  os << endl;
7906 #endif // DEBUG
7907  return isolate->heap()->undefined_value();
7908 }
7909 
7910 
7911 RUNTIME_FUNCTION(Runtime_DebugDisassembleConstructor) {
7912  HandleScope scope(isolate);
7913 #ifdef DEBUG
7914  DCHECK(args.length() == 1);
7915  // Get the function and make sure it is compiled.
7918  return isolate->heap()->exception();
7919  }
7920  OFStream os(stdout);
7921  func->shared()->construct_stub()->Print(os);
7922  os << endl;
7923 #endif // DEBUG
7924  return isolate->heap()->undefined_value();
7925 }
7926 
7927 
7928 RUNTIME_FUNCTION(Runtime_FunctionGetInferredName) {
7929  SealHandleScope shs(isolate);
7930  DCHECK(args.length() == 1);
7931 
7933  return f->shared()->inferred_name();
7934 }
7935 
7936 
7937 static int FindSharedFunctionInfosForScript(HeapIterator* iterator,
7938  Script* script,
7939  FixedArray* buffer) {
7940  DisallowHeapAllocation no_allocation;
7941  int counter = 0;
7942  int buffer_size = buffer->length();
7943  for (HeapObject* obj = iterator->next(); obj != NULL;
7944  obj = iterator->next()) {
7945  DCHECK(obj != NULL);
7946  if (!obj->IsSharedFunctionInfo()) {
7947  continue;
7948  }
7949  SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
7950  if (shared->script() != script) {
7951  continue;
7952  }
7953  if (counter < buffer_size) {
7954  buffer->set(counter, shared);
7955  }
7956  counter++;
7957  }
7958  return counter;
7959 }
7960 
7961 
7962 // For a script finds all SharedFunctionInfo's in the heap that points
7963 // to this script. Returns JSArray of SharedFunctionInfo wrapped
7964 // in OpaqueReferences.
7965 RUNTIME_FUNCTION(Runtime_LiveEditFindSharedFunctionInfosForScript) {
7966  HandleScope scope(isolate);
7967  CHECK(isolate->debug()->live_edit_enabled());
7968  DCHECK(args.length() == 1);
7969  CONVERT_ARG_CHECKED(JSValue, script_value, 0);
7970 
7971  RUNTIME_ASSERT(script_value->value()->IsScript());
7972  Handle<Script> script = Handle<Script>(Script::cast(script_value->value()));
7973 
7974  const int kBufferSize = 32;
7975 
7976  Handle<FixedArray> array;
7977  array = isolate->factory()->NewFixedArray(kBufferSize);
7978  int number;
7979  Heap* heap = isolate->heap();
7980  {
7981  HeapIterator heap_iterator(heap);
7982  Script* scr = *script;
7983  FixedArray* arr = *array;
7984  number = FindSharedFunctionInfosForScript(&heap_iterator, scr, arr);
7985  }
7986  if (number > kBufferSize) {
7987  array = isolate->factory()->NewFixedArray(number);
7988  HeapIterator heap_iterator(heap);
7989  Script* scr = *script;
7990  FixedArray* arr = *array;
7991  FindSharedFunctionInfosForScript(&heap_iterator, scr, arr);
7992  }
7993 
7994  Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(array);
7995  result->set_length(Smi::FromInt(number));
7996 
7998 
7999  return *result;
8000 }
8001 
8002 
8003 // For a script calculates compilation information about all its functions.
8004 // The script source is explicitly specified by the second argument.
8005 // The source of the actual script is not used, however it is important that
8006 // all generated code keeps references to this particular instance of script.
8007 // Returns a JSArray of compilation infos. The array is ordered so that
8008 // each function with all its descendant is always stored in a continues range
8009 // with the function itself going first. The root function is a script function.
8010 RUNTIME_FUNCTION(Runtime_LiveEditGatherCompileInfo) {
8011  HandleScope scope(isolate);
8012  CHECK(isolate->debug()->live_edit_enabled());
8013  DCHECK(args.length() == 2);
8014  CONVERT_ARG_CHECKED(JSValue, script, 0);
8015  CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
8016 
8017  RUNTIME_ASSERT(script->value()->IsScript());
8018  Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));
8019 
8020  Handle<JSArray> result;
8022  isolate, result, LiveEdit::GatherCompileInfo(script_handle, source));
8023  return *result;
8024 }
8025 
8026 
8027 // Changes the source of the script to a new_source.
8028 // If old_script_name is provided (i.e. is a String), also creates a copy of
8029 // the script with its original source and sends notification to debugger.
8030 RUNTIME_FUNCTION(Runtime_LiveEditReplaceScript) {
8031  HandleScope scope(isolate);
8032  CHECK(isolate->debug()->live_edit_enabled());
8033  DCHECK(args.length() == 3);
8034  CONVERT_ARG_CHECKED(JSValue, original_script_value, 0);
8035  CONVERT_ARG_HANDLE_CHECKED(String, new_source, 1);
8036  CONVERT_ARG_HANDLE_CHECKED(Object, old_script_name, 2);
8037 
8038  RUNTIME_ASSERT(original_script_value->value()->IsScript());
8039  Handle<Script> original_script(Script::cast(original_script_value->value()));
8040 
8042  original_script, new_source, old_script_name);
8043 
8044  if (old_script->IsScript()) {
8045  Handle<Script> script_handle = Handle<Script>::cast(old_script);
8046  return *Script::GetWrapper(script_handle);
8047  } else {
8048  return isolate->heap()->null_value();
8049  }
8050 }
8051 
8052 
8053 RUNTIME_FUNCTION(Runtime_LiveEditFunctionSourceUpdated) {
8054  HandleScope scope(isolate);
8055  CHECK(isolate->debug()->live_edit_enabled());
8056  DCHECK(args.length() == 1);
8057  CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 0);
8059 
8060  LiveEdit::FunctionSourceUpdated(shared_info);
8061  return isolate->heap()->undefined_value();
8062 }
8063 
8064 
8065 // Replaces code of SharedFunctionInfo with a new one.
8066 RUNTIME_FUNCTION(Runtime_LiveEditReplaceFunctionCode) {
8067  HandleScope scope(isolate);
8068  CHECK(isolate->debug()->live_edit_enabled());
8069  DCHECK(args.length() == 2);
8070  CONVERT_ARG_HANDLE_CHECKED(JSArray, new_compile_info, 0);
8071  CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_info, 1);
8073 
8074  LiveEdit::ReplaceFunctionCode(new_compile_info, shared_info);
8075  return isolate->heap()->undefined_value();
8076 }
8077 
8078 
8079 // Connects SharedFunctionInfo to another script.
8080 RUNTIME_FUNCTION(Runtime_LiveEditFunctionSetScript) {
8081  HandleScope scope(isolate);
8082  CHECK(isolate->debug()->live_edit_enabled());
8083  DCHECK(args.length() == 2);
8084  CONVERT_ARG_HANDLE_CHECKED(Object, function_object, 0);
8085  CONVERT_ARG_HANDLE_CHECKED(Object, script_object, 1);
8086 
8087  if (function_object->IsJSValue()) {
8088  Handle<JSValue> function_wrapper = Handle<JSValue>::cast(function_object);
8089  if (script_object->IsJSValue()) {
8090  RUNTIME_ASSERT(JSValue::cast(*script_object)->value()->IsScript());
8091  Script* script = Script::cast(JSValue::cast(*script_object)->value());
8092  script_object = Handle<Object>(script, isolate);
8093  }
8094  RUNTIME_ASSERT(function_wrapper->value()->IsSharedFunctionInfo());
8095  LiveEdit::SetFunctionScript(function_wrapper, script_object);
8096  } else {
8097  // Just ignore this. We may not have a SharedFunctionInfo for some functions
8098  // and we check it in this function.
8099  }
8100 
8101  return isolate->heap()->undefined_value();
8102 }
8103 
8104 
8105 // In a code of a parent function replaces original function as embedded object
8106 // with a substitution one.
8107 RUNTIME_FUNCTION(Runtime_LiveEditReplaceRefToNestedFunction) {
8108  HandleScope scope(isolate);
8109  CHECK(isolate->debug()->live_edit_enabled());
8110  DCHECK(args.length() == 3);
8111 
8112  CONVERT_ARG_HANDLE_CHECKED(JSValue, parent_wrapper, 0);
8113  CONVERT_ARG_HANDLE_CHECKED(JSValue, orig_wrapper, 1);
8114  CONVERT_ARG_HANDLE_CHECKED(JSValue, subst_wrapper, 2);
8115  RUNTIME_ASSERT(parent_wrapper->value()->IsSharedFunctionInfo());
8116  RUNTIME_ASSERT(orig_wrapper->value()->IsSharedFunctionInfo());
8117  RUNTIME_ASSERT(subst_wrapper->value()->IsSharedFunctionInfo());
8118 
8119  LiveEdit::ReplaceRefToNestedFunction(parent_wrapper, orig_wrapper,
8120  subst_wrapper);
8121  return isolate->heap()->undefined_value();
8122 }
8123 
8124 
8125 // Updates positions of a shared function info (first parameter) according
8126 // to script source change. Text change is described in second parameter as
8127 // array of groups of 3 numbers:
8128 // (change_begin, change_end, change_end_new_position).
8129 // Each group describes a change in text; groups are sorted by change_begin.
8130 RUNTIME_FUNCTION(Runtime_LiveEditPatchFunctionPositions) {
8131  HandleScope scope(isolate);
8132  CHECK(isolate->debug()->live_edit_enabled());
8133  DCHECK(args.length() == 2);
8134  CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0);
8135  CONVERT_ARG_HANDLE_CHECKED(JSArray, position_change_array, 1);
8137 
8138  LiveEdit::PatchFunctionPositions(shared_array, position_change_array);
8139  return isolate->heap()->undefined_value();
8140 }
8141 
8142 
8143 // For array of SharedFunctionInfo's (each wrapped in JSValue)
8144 // checks that none of them have activations on stacks (of any thread).
8145 // Returns array of the same length with corresponding results of
8146 // LiveEdit::FunctionPatchabilityStatus type.
8147 RUNTIME_FUNCTION(Runtime_LiveEditCheckAndDropActivations) {
8148  HandleScope scope(isolate);
8149  CHECK(isolate->debug()->live_edit_enabled());
8150  DCHECK(args.length() == 2);
8151  CONVERT_ARG_HANDLE_CHECKED(JSArray, shared_array, 0);
8152  CONVERT_BOOLEAN_ARG_CHECKED(do_drop, 1);
8153  RUNTIME_ASSERT(shared_array->length()->IsSmi());
8154  RUNTIME_ASSERT(shared_array->HasFastElements())
8155  int array_length = Smi::cast(shared_array->length())->value();
8156  for (int i = 0; i < array_length; i++) {
8157  Handle<Object> element =
8158  Object::GetElement(isolate, shared_array, i).ToHandleChecked();
8160  element->IsJSValue() &&
8161  Handle<JSValue>::cast(element)->value()->IsSharedFunctionInfo());
8162  }
8163 
8164  return *LiveEdit::CheckAndDropActivations(shared_array, do_drop);
8165 }
8166 
8167 
8168 // Compares 2 strings line-by-line, then token-wise and returns diff in form
8169 // of JSArray of triplets (pos1, pos1_end, pos2_end) describing list
8170 // of diff chunks.
8171 RUNTIME_FUNCTION(Runtime_LiveEditCompareStrings) {
8172  HandleScope scope(isolate);
8173  CHECK(isolate->debug()->live_edit_enabled());
8174  DCHECK(args.length() == 2);
8177 
8178  return *LiveEdit::CompareStrings(s1, s2);
8179 }
8180 
8181 
8182 // Restarts a call frame and completely drops all frames above.
8183 // Returns true if successful. Otherwise returns undefined or an error message.
8184 RUNTIME_FUNCTION(Runtime_LiveEditRestartFrame) {
8185  HandleScope scope(isolate);
8186  CHECK(isolate->debug()->live_edit_enabled());
8187  DCHECK(args.length() == 2);
8188  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
8189  RUNTIME_ASSERT(CheckExecutionState(isolate, break_id));
8190 
8191  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
8192  Heap* heap = isolate->heap();
8193 
8194  // Find the relevant frame with the requested index.
8195  StackFrame::Id id = isolate->debug()->break_frame_id();
8196  if (id == StackFrame::NO_ID) {
8197  // If there are no JavaScript stack frames return undefined.
8198  return heap->undefined_value();
8199  }
8200 
8201  JavaScriptFrameIterator it(isolate, id);
8202  int inlined_jsframe_index = FindIndexedNonNativeFrame(&it, index);
8203  if (inlined_jsframe_index == -1) return heap->undefined_value();
8204  // We don't really care what the inlined frame index is, since we are
8205  // throwing away the entire frame anyways.
8206  const char* error_message = LiveEdit::RestartFrame(it.frame());
8207  if (error_message) {
8208  return *(isolate->factory()->InternalizeUtf8String(error_message));
8209  }
8210  return heap->true_value();
8211 }
8212 
8213 
8214 // A testing entry. Returns statement position which is the closest to
8215 // source_position.
8216 RUNTIME_FUNCTION(Runtime_GetFunctionCodePositionFromSource) {
8217  HandleScope scope(isolate);
8218  CHECK(isolate->debug()->live_edit_enabled());
8219  DCHECK(args.length() == 2);
8220  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8221  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
8222 
8223  Handle<Code> code(function->code(), isolate);
8224 
8225  if (code->kind() != Code::FUNCTION &&
8226  code->kind() != Code::OPTIMIZED_FUNCTION) {
8227  return isolate->heap()->undefined_value();
8228  }
8229 
8231  int closest_pc = 0;
8232  int distance = kMaxInt;
8233  while (!it.done()) {
8234  int statement_position = static_cast<int>(it.rinfo()->data());
8235  // Check if this break point is closer that what was previously found.
8236  if (source_position <= statement_position &&
8237  statement_position - source_position < distance) {
8238  closest_pc =
8239  static_cast<int>(it.rinfo()->pc() - code->instruction_start());
8240  distance = statement_position - source_position;
8241  // Check whether we can't get any closer.
8242  if (distance == 0) break;
8243  }
8244  it.next();
8245  }
8246 
8247  return Smi::FromInt(closest_pc);
8248 }
8249 
8250 
8251 // Calls specified function with or without entering the debugger.
8252 // This is used in unit tests to run code as if debugger is entered or simply
8253 // to have a stack with C++ frame in the middle.
8254 RUNTIME_FUNCTION(Runtime_ExecuteInDebugContext) {
8255  HandleScope scope(isolate);
8256  DCHECK(args.length() == 2);
8257  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
8258  CONVERT_BOOLEAN_ARG_CHECKED(without_debugger, 1);
8259 
8260  MaybeHandle<Object> maybe_result;
8261  if (without_debugger) {
8262  maybe_result = Execution::Call(isolate, function,
8263  handle(function->global_proxy()), 0, NULL);
8264  } else {
8265  DebugScope debug_scope(isolate->debug());
8266  maybe_result = Execution::Call(isolate, function,
8267  handle(function->global_proxy()), 0, NULL);
8268  }
8269  Handle<Object> result;
8270  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, maybe_result);
8271  return *result;
8272 }
8273 
8274 
8275 // Performs a GC.
8276 // Presently, it only does a full GC.
8277 RUNTIME_FUNCTION(Runtime_CollectGarbage) {
8278  SealHandleScope shs(isolate);
8279  DCHECK(args.length() == 1);
8280  isolate->heap()->CollectAllGarbage(Heap::kNoGCFlags, "%CollectGarbage");
8281  return isolate->heap()->undefined_value();
8282 }
8283 
8284 
8285 // Gets the current heap usage.
8286 RUNTIME_FUNCTION(Runtime_GetHeapUsage) {
8287  SealHandleScope shs(isolate);
8288  DCHECK(args.length() == 0);
8289  int usage = static_cast<int>(isolate->heap()->SizeOfObjects());
8290  if (!Smi::IsValid(usage)) {
8291  return *isolate->factory()->NewNumberFromInt(usage);
8292  }
8293  return Smi::FromInt(usage);
8294 }
8295 
8296 
8297 // Finds the script object from the script data. NOTE: This operation uses
8298 // heap traversal to find the function generated for the source position
8299 // for the requested break point. For lazily compiled functions several heap
8300 // traversals might be required rendering this operation as a rather slow
8301 // operation. However for setting break points which is normally done through
8302 // some kind of user interaction the performance is not crucial.
8304  Handle<String> script_name) {
8305  // Scan the heap for Script objects to find the script with the requested
8306  // script data.
8307  Handle<Script> script;
8308  Factory* factory = script_name->GetIsolate()->factory();
8309  Heap* heap = script_name->GetHeap();
8310  HeapIterator iterator(heap);
8311  HeapObject* obj = NULL;
8312  while (script.is_null() && ((obj = iterator.next()) != NULL)) {
8313  // If a script is found check if it has the script data requested.
8314  if (obj->IsScript()) {
8315  if (Script::cast(obj)->name()->IsString()) {
8316  if (String::cast(Script::cast(obj)->name())->Equals(*script_name)) {
8317  script = Handle<Script>(Script::cast(obj));
8318  }
8319  }
8320  }
8321  }
8322 
8323  // If no script with the requested script data is found return undefined.
8324  if (script.is_null()) return factory->undefined_value();
8325 
8326  // Return the script found.
8327  return Script::GetWrapper(script);
8328 }
8329 
8330 
8331 // Get the script object from script data. NOTE: Regarding performance
8332 // see the NOTE for GetScriptFromScriptData.
8333 // args[0]: script data for the script to find the source for
8334 RUNTIME_FUNCTION(Runtime_GetScript) {
8335  HandleScope scope(isolate);
8336 
8337  DCHECK(args.length() == 1);
8338 
8339  CONVERT_ARG_CHECKED(String, script_name, 0);
8340 
8341  // Find the requested script.
8342  Handle<Object> result =
8344  return *result;
8345 }
8346 
8347 
8348 // Collect the raw data for a stack trace. Returns an array of 4
8349 // element segments each containing a receiver, function, code and
8350 // native code offset.
8351 RUNTIME_FUNCTION(Runtime_CollectStackTrace) {
8352  HandleScope scope(isolate);
8353  DCHECK(args.length() == 2);
8354  CONVERT_ARG_HANDLE_CHECKED(JSObject, error_object, 0);
8355  CONVERT_ARG_HANDLE_CHECKED(Object, caller, 1);
8356 
8357  if (!isolate->bootstrapper()->IsActive()) {
8358  // Optionally capture a more detailed stack trace for the message.
8359  isolate->CaptureAndSetDetailedStackTrace(error_object);
8360  // Capture a simple stack trace for the stack property.
8361  isolate->CaptureAndSetSimpleStackTrace(error_object, caller);
8362  }
8363  return isolate->heap()->undefined_value();
8364 }
8365 
8366 
8367 // Returns V8 version as a string.
8368 RUNTIME_FUNCTION(Runtime_GetV8Version) {
8369  HandleScope scope(isolate);
8370  DCHECK(args.length() == 0);
8371 
8372  const char* version_string = v8::V8::GetVersion();
8373 
8374  return *isolate->factory()->NewStringFromAsciiChecked(version_string);
8375 }
8376 
8377 
8378 // Returns function of generator activation.
8379 RUNTIME_FUNCTION(Runtime_GeneratorGetFunction) {
8380  HandleScope scope(isolate);
8381  DCHECK(args.length() == 1);
8383 
8384  return generator->function();
8385 }
8386 
8387 
8388 // Returns context of generator activation.
8389 RUNTIME_FUNCTION(Runtime_GeneratorGetContext) {
8390  HandleScope scope(isolate);
8391  DCHECK(args.length() == 1);
8393 
8394  return generator->context();
8395 }
8396 
8397 
8398 // Returns receiver of generator activation.
8399 RUNTIME_FUNCTION(Runtime_GeneratorGetReceiver) {
8400  HandleScope scope(isolate);
8401  DCHECK(args.length() == 1);
8403 
8404  return generator->receiver();
8405 }
8406 
8407 
8408 // Returns generator continuation as a PC offset, or the magic -1 or 0 values.
8409 RUNTIME_FUNCTION(Runtime_GeneratorGetContinuation) {
8410  HandleScope scope(isolate);
8411  DCHECK(args.length() == 1);
8413 
8414  return Smi::FromInt(generator->continuation());
8415 }
8416 
8417 
8418 RUNTIME_FUNCTION(Runtime_GeneratorGetSourcePosition) {
8419  HandleScope scope(isolate);
8420  DCHECK(args.length() == 1);
8422 
8423  if (generator->is_suspended()) {
8424  Handle<Code> code(generator->function()->code(), isolate);
8425  int offset = generator->continuation();
8426 
8427  RUNTIME_ASSERT(0 <= offset && offset < code->Size());
8428  Address pc = code->address() + offset;
8429 
8430  return Smi::FromInt(code->SourcePosition(pc));
8431  }
8432 
8433  return isolate->heap()->undefined_value();
8434 }
8435 
8436 
8437 RUNTIME_FUNCTION(Runtime_LoadMutableDouble) {
8438  HandleScope scope(isolate);
8439  DCHECK(args.length() == 2);
8441  CONVERT_ARG_HANDLE_CHECKED(Smi, index, 1);
8442  RUNTIME_ASSERT((index->value() & 1) == 1);
8443  FieldIndex field_index =
8444  FieldIndex::ForLoadByFieldIndex(object->map(), index->value());
8445  if (field_index.is_inobject()) {
8446  RUNTIME_ASSERT(field_index.property_index() <
8447  object->map()->inobject_properties());
8448  } else {
8449  RUNTIME_ASSERT(field_index.outobject_array_index() <
8450  object->properties()->length());
8451  }
8452  Handle<Object> raw_value(object->RawFastPropertyAt(field_index), isolate);
8453  RUNTIME_ASSERT(raw_value->IsMutableHeapNumber());
8454  return *Object::WrapForRead(isolate, raw_value, Representation::Double());
8455 }
8456 
8457 
8458 RUNTIME_FUNCTION(Runtime_TryMigrateInstance) {
8459  HandleScope scope(isolate);
8460  DCHECK(args.length() == 1);
8461  CONVERT_ARG_HANDLE_CHECKED(Object, object, 0);
8462  if (!object->IsJSObject()) return Smi::FromInt(0);
8463  Handle<JSObject> js_object = Handle<JSObject>::cast(object);
8464  if (!js_object->map()->is_deprecated()) return Smi::FromInt(0);
8465  // This call must not cause lazy deopts, because it's called from deferred
8466  // code where we can't handle lazy deopts for lack of a suitable bailout
8467  // ID. So we just try migration and signal failure if necessary,
8468  // which will also trigger a deopt.
8469  if (!JSObject::TryMigrateInstance(js_object)) return Smi::FromInt(0);
8470  return *object;
8471 }
8472 
8473 
8474 RUNTIME_FUNCTION(Runtime_GetFromCache) {
8475  SealHandleScope shs(isolate);
8476  // This is only called from codegen, so checks might be more lax.
8478  CONVERT_ARG_CHECKED(Object, key, 1);
8479 
8480  {
8481  DisallowHeapAllocation no_alloc;
8482 
8483  int finger_index = cache->finger_index();
8484  Object* o = cache->get(finger_index);
8485  if (o == key) {
8486  // The fastest case: hit the same place again.
8487  return cache->get(finger_index + 1);
8488  }
8489 
8490  for (int i = finger_index - 2; i >= JSFunctionResultCache::kEntriesIndex;
8491  i -= 2) {
8492  o = cache->get(i);
8493  if (o == key) {
8494  cache->set_finger_index(i);
8495  return cache->get(i + 1);
8496  }
8497  }
8498 
8499  int size = cache->size();
8500  DCHECK(size <= cache->length());
8501 
8502  for (int i = size - 2; i > finger_index; i -= 2) {
8503  o = cache->get(i);
8504  if (o == key) {
8505  cache->set_finger_index(i);
8506  return cache->get(i + 1);
8507  }
8508  }
8509  }
8510 
8511  // There is no value in the cache. Invoke the function and cache result.
8512  HandleScope scope(isolate);
8513 
8514  Handle<JSFunctionResultCache> cache_handle(cache);
8515  Handle<Object> key_handle(key, isolate);
8516  Handle<Object> value;
8517  {
8518  Handle<JSFunction> factory(JSFunction::cast(
8519  cache_handle->get(JSFunctionResultCache::kFactoryIndex)));
8520  // TODO(antonm): consider passing a receiver when constructing a cache.
8521  Handle<JSObject> receiver(isolate->global_proxy());
8522  // This handle is nor shared, nor used later, so it's safe.
8523  Handle<Object> argv[] = {key_handle};
8525  isolate, value,
8526  Execution::Call(isolate, factory, receiver, arraysize(argv), argv));
8527  }
8528 
8529 #ifdef VERIFY_HEAP
8530  if (FLAG_verify_heap) {
8531  cache_handle->JSFunctionResultCacheVerify();
8532  }
8533 #endif
8534 
8535  // Function invocation may have cleared the cache. Reread all the data.
8536  int finger_index = cache_handle->finger_index();
8537  int size = cache_handle->size();
8538 
8539  // If we have spare room, put new data into it, otherwise evict post finger
8540  // entry which is likely to be the least recently used.
8541  int index = -1;
8542  if (size < cache_handle->length()) {
8543  cache_handle->set_size(size + JSFunctionResultCache::kEntrySize);
8544  index = size;
8545  } else {
8546  index = finger_index + JSFunctionResultCache::kEntrySize;
8547  if (index == cache_handle->length()) {
8549  }
8550  }
8551 
8552  DCHECK(index % 2 == 0);
8554  DCHECK(index < cache_handle->length());
8555 
8556  cache_handle->set(index, *key_handle);
8557  cache_handle->set(index + 1, *value);
8558  cache_handle->set_finger_index(index);
8559 
8560 #ifdef VERIFY_HEAP
8561  if (FLAG_verify_heap) {
8562  cache_handle->JSFunctionResultCacheVerify();
8563  }
8564 #endif
8565 
8566  return *value;
8567 }
8568 
8569 
8570 RUNTIME_FUNCTION(Runtime_MessageGetStartPosition) {
8571  SealHandleScope shs(isolate);
8572  DCHECK(args.length() == 1);
8573  CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
8574  return Smi::FromInt(message->start_position());
8575 }
8576 
8577 
8578 RUNTIME_FUNCTION(Runtime_MessageGetScript) {
8579  SealHandleScope shs(isolate);
8580  DCHECK(args.length() == 1);
8581  CONVERT_ARG_CHECKED(JSMessageObject, message, 0);
8582  return message->script();
8583 }
8584 
8585 
8586 #ifdef DEBUG
8587 // ListNatives is ONLY used by the fuzz-natives.js in debug mode
8588 // Exclude the code in release mode.
8589 RUNTIME_FUNCTION(Runtime_ListNatives) {
8590  HandleScope scope(isolate);
8591  DCHECK(args.length() == 0);
8592 #define COUNT_ENTRY(Name, argc, ressize) +1
8593  int entry_count =
8594  0 RUNTIME_FUNCTION_LIST(COUNT_ENTRY) INLINE_FUNCTION_LIST(COUNT_ENTRY)
8595  INLINE_OPTIMIZED_FUNCTION_LIST(COUNT_ENTRY);
8596 #undef COUNT_ENTRY
8597  Factory* factory = isolate->factory();
8598  Handle<FixedArray> elements = factory->NewFixedArray(entry_count);
8599  int index = 0;
8600  bool inline_runtime_functions = false;
8601 #define ADD_ENTRY(Name, argc, ressize) \
8602  { \
8603  HandleScope inner(isolate); \
8604  Handle<String> name; \
8605  /* Inline runtime functions have an underscore in front of the name. */ \
8606  if (inline_runtime_functions) { \
8607  name = factory->NewStringFromStaticChars("_" #Name); \
8608  } else { \
8609  name = factory->NewStringFromStaticChars(#Name); \
8610  } \
8611  Handle<FixedArray> pair_elements = factory->NewFixedArray(2); \
8612  pair_elements->set(0, *name); \
8613  pair_elements->set(1, Smi::FromInt(argc)); \
8614  Handle<JSArray> pair = factory->NewJSArrayWithElements(pair_elements); \
8615  elements->set(index++, *pair); \
8616  }
8617  inline_runtime_functions = false;
8618  RUNTIME_FUNCTION_LIST(ADD_ENTRY)
8620  inline_runtime_functions = true;
8621  INLINE_FUNCTION_LIST(ADD_ENTRY)
8622 #undef ADD_ENTRY
8623  DCHECK_EQ(index, entry_count);
8624  Handle<JSArray> result = factory->NewJSArrayWithElements(elements);
8625  return *result;
8626 }
8627 #endif
8628 
8629 
8630 RUNTIME_FUNCTION(Runtime_IS_VAR) {
8631  UNREACHABLE(); // implemented as macro in the parser
8632  return NULL;
8633 }
8634 
8635 
8636 #define TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, size) \
8637  RUNTIME_FUNCTION(Runtime_HasExternal##Type##Elements) { \
8638  CONVERT_ARG_CHECKED(JSObject, obj, 0); \
8639  return isolate->heap()->ToBoolean(obj->HasExternal##Type##Elements()); \
8640  }
8641 
8643 
8644 #undef TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
8645 
8646 
8647 #define FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, s) \
8648  RUNTIME_FUNCTION(Runtime_HasFixed##Type##Elements) { \
8649  CONVERT_ARG_CHECKED(JSObject, obj, 0); \
8650  return isolate->heap()->ToBoolean(obj->HasFixed##Type##Elements()); \
8651  }
8652 
8654 
8655 #undef FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION
8656 
8657 
8658 RUNTIME_FUNCTION(Runtime_IsJSGlobalProxy) {
8659  SealHandleScope shs(isolate);
8660  DCHECK(args.length() == 1);
8661  CONVERT_ARG_CHECKED(Object, obj, 0);
8662  return isolate->heap()->ToBoolean(obj->IsJSGlobalProxy());
8663 }
8664 
8665 
8666 RUNTIME_FUNCTION(Runtime_IsObserved) {
8667  SealHandleScope shs(isolate);
8668  DCHECK(args.length() == 1);
8669 
8670  if (!args[0]->IsJSReceiver()) return isolate->heap()->false_value();
8672  DCHECK(!obj->IsJSGlobalProxy() || !obj->map()->is_observed());
8673  return isolate->heap()->ToBoolean(obj->map()->is_observed());
8674 }
8675 
8676 
8677 RUNTIME_FUNCTION(Runtime_SetIsObserved) {
8678  HandleScope scope(isolate);
8679  DCHECK(args.length() == 1);
8681  RUNTIME_ASSERT(!obj->IsJSGlobalProxy());
8682  if (obj->IsJSProxy()) return isolate->heap()->undefined_value();
8683  RUNTIME_ASSERT(!obj->map()->is_observed());
8684 
8685  DCHECK(obj->IsJSObject());
8687  return isolate->heap()->undefined_value();
8688 }
8689 
8690 
8691 RUNTIME_FUNCTION(Runtime_EnqueueMicrotask) {
8692  HandleScope scope(isolate);
8693  DCHECK(args.length() == 1);
8694  CONVERT_ARG_HANDLE_CHECKED(JSFunction, microtask, 0);
8695  isolate->EnqueueMicrotask(microtask);
8696  return isolate->heap()->undefined_value();
8697 }
8698 
8699 
8700 RUNTIME_FUNCTION(Runtime_RunMicrotasks) {
8701  HandleScope scope(isolate);
8702  DCHECK(args.length() == 0);
8703  isolate->RunMicrotasks();
8704  return isolate->heap()->undefined_value();
8705 }
8706 
8707 
8708 RUNTIME_FUNCTION(Runtime_GetObservationState) {
8709  SealHandleScope shs(isolate);
8710  DCHECK(args.length() == 0);
8711  return isolate->heap()->observation_state();
8712 }
8713 
8714 
8716  Handle<Context> context2) {
8717  return context1->security_token() == context2->security_token();
8718 }
8719 
8720 
8721 RUNTIME_FUNCTION(Runtime_ObserverObjectAndRecordHaveSameOrigin) {
8722  HandleScope scope(isolate);
8723  DCHECK(args.length() == 3);
8724  CONVERT_ARG_HANDLE_CHECKED(JSFunction, observer, 0);
8727 
8728  Handle<Context> observer_context(observer->context()->native_context());
8729  Handle<Context> object_context(object->GetCreationContext());
8730  Handle<Context> record_context(record->GetCreationContext());
8731 
8732  return isolate->heap()->ToBoolean(
8733  ContextsHaveSameOrigin(object_context, observer_context) &&
8734  ContextsHaveSameOrigin(object_context, record_context));
8735 }
8736 
8737 
8738 RUNTIME_FUNCTION(Runtime_ObjectWasCreatedInCurrentOrigin) {
8739  HandleScope scope(isolate);
8740  DCHECK(args.length() == 1);
8742 
8743  Handle<Context> creation_context(object->GetCreationContext(), isolate);
8744  return isolate->heap()->ToBoolean(
8745  ContextsHaveSameOrigin(creation_context, isolate->native_context()));
8746 }
8747 
8748 
8749 RUNTIME_FUNCTION(Runtime_GetObjectContextObjectObserve) {
8750  HandleScope scope(isolate);
8751  DCHECK(args.length() == 1);
8753 
8754  Handle<Context> context(object->GetCreationContext(), isolate);
8755  return context->native_object_observe();
8756 }
8757 
8758 
8759 RUNTIME_FUNCTION(Runtime_GetObjectContextObjectGetNotifier) {
8760  HandleScope scope(isolate);
8761  DCHECK(args.length() == 1);
8763 
8764  Handle<Context> context(object->GetCreationContext(), isolate);
8765  return context->native_object_get_notifier();
8766 }
8767 
8768 
8769 RUNTIME_FUNCTION(Runtime_GetObjectContextNotifierPerformChange) {
8770  HandleScope scope(isolate);
8771  DCHECK(args.length() == 1);
8772  CONVERT_ARG_HANDLE_CHECKED(JSObject, object_info, 0);
8773 
8774  Handle<Context> context(object_info->GetCreationContext(), isolate);
8775  return context->native_object_notifier_perform_change();
8776 }
8777 
8778 
8780  Handle<JSFunction> constructor,
8782  Arguments* caller_args) {
8783  Factory* factory = isolate->factory();
8784 
8785  bool holey = false;
8786  bool can_use_type_feedback = true;
8787  if (caller_args->length() == 1) {
8788  Handle<Object> argument_one = caller_args->at<Object>(0);
8789  if (argument_one->IsSmi()) {
8790  int value = Handle<Smi>::cast(argument_one)->value();
8791  if (value < 0 || value >= JSObject::kInitialMaxFastElementArray) {
8792  // the array is a dictionary in this case.
8793  can_use_type_feedback = false;
8794  } else if (value != 0) {
8795  holey = true;
8796  }
8797  } else {
8798  // Non-smi length argument produces a dictionary
8799  can_use_type_feedback = false;
8800  }
8801  }
8802 
8803  Handle<JSArray> array;
8804  if (!site.is_null() && can_use_type_feedback) {
8805  ElementsKind to_kind = site->GetElementsKind();
8806  if (holey && !IsFastHoleyElementsKind(to_kind)) {
8807  to_kind = GetHoleyElementsKind(to_kind);
8808  // Update the allocation site info to reflect the advice alteration.
8809  site->SetElementsKind(to_kind);
8810  }
8811 
8812  // We should allocate with an initial map that reflects the allocation site
8813  // advice. Therefore we use AllocateJSObjectFromMap instead of passing
8814  // the constructor.
8815  Handle<Map> initial_map(constructor->initial_map(), isolate);
8816  if (to_kind != initial_map->elements_kind()) {
8817  initial_map = Map::AsElementsKind(initial_map, to_kind);
8818  }
8819 
8820  // If we don't care to track arrays of to_kind ElementsKind, then
8821  // don't emit a memento for them.
8822  Handle<AllocationSite> allocation_site;
8824  allocation_site = site;
8825  }
8826 
8827  array = Handle<JSArray>::cast(factory->NewJSObjectFromMap(
8828  initial_map, NOT_TENURED, true, allocation_site));
8829  } else {
8830  array = Handle<JSArray>::cast(factory->NewJSObject(constructor));
8831 
8832  // We might need to transition to holey
8833  ElementsKind kind = constructor->initial_map()->elements_kind();
8834  if (holey && !IsFastHoleyElementsKind(kind)) {
8835  kind = GetHoleyElementsKind(kind);
8836  JSObject::TransitionElementsKind(array, kind);
8837  }
8838  }
8839 
8840  factory->NewJSArrayStorage(array, 0, 0, DONT_INITIALIZE_ARRAY_ELEMENTS);
8841 
8842  ElementsKind old_kind = array->GetElementsKind();
8844  isolate, ArrayConstructInitializeElements(array, caller_args));
8845  if (!site.is_null() &&
8846  (old_kind != array->GetElementsKind() || !can_use_type_feedback)) {
8847  // The arguments passed in caused a transition. This kind of complexity
8848  // can't be dealt with in the inlined hydrogen array constructor case.
8849  // We must mark the allocationsite as un-inlinable.
8850  site->SetDoNotInlineCall();
8851  }
8852  return *array;
8853 }
8854 
8855 
8856 RUNTIME_FUNCTION(Runtime_ArrayConstructor) {
8857  HandleScope scope(isolate);
8858  // If we get 2 arguments then they are the stub parameters (constructor, type
8859  // info). If we get 4, then the first one is a pointer to the arguments
8860  // passed by the caller, and the last one is the length of the arguments
8861  // passed to the caller (redundant, but useful to check on the deoptimizer
8862  // with an assert).
8863  Arguments empty_args(0, NULL);
8864  bool no_caller_args = args.length() == 2;
8865  DCHECK(no_caller_args || args.length() == 4);
8866  int parameters_start = no_caller_args ? 0 : 1;
8867  Arguments* caller_args =
8868  no_caller_args ? &empty_args : reinterpret_cast<Arguments*>(args[0]);
8869  CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start);
8870  CONVERT_ARG_HANDLE_CHECKED(Object, type_info, parameters_start + 1);
8871 #ifdef DEBUG
8872  if (!no_caller_args) {
8873  CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 2);
8874  DCHECK(arg_count == caller_args->length());
8875  }
8876 #endif
8877 
8879  if (!type_info.is_null() &&
8880  *type_info != isolate->heap()->undefined_value()) {
8881  site = Handle<AllocationSite>::cast(type_info);
8882  DCHECK(!site->SitePointsToLiteral());
8883  }
8884 
8885  return ArrayConstructorCommon(isolate, constructor, site, caller_args);
8886 }
8887 
8888 
8889 RUNTIME_FUNCTION(Runtime_InternalArrayConstructor) {
8890  HandleScope scope(isolate);
8891  Arguments empty_args(0, NULL);
8892  bool no_caller_args = args.length() == 1;
8893  DCHECK(no_caller_args || args.length() == 3);
8894  int parameters_start = no_caller_args ? 0 : 1;
8895  Arguments* caller_args =
8896  no_caller_args ? &empty_args : reinterpret_cast<Arguments*>(args[0]);
8897  CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, parameters_start);
8898 #ifdef DEBUG
8899  if (!no_caller_args) {
8900  CONVERT_SMI_ARG_CHECKED(arg_count, parameters_start + 1);
8901  DCHECK(arg_count == caller_args->length());
8902  }
8903 #endif
8904  return ArrayConstructorCommon(isolate, constructor,
8905  Handle<AllocationSite>::null(), caller_args);
8906 }
8907 
8908 
8909 RUNTIME_FUNCTION(Runtime_NormalizeElements) {
8910  HandleScope scope(isolate);
8911  DCHECK(args.length() == 1);
8913  RUNTIME_ASSERT(!array->HasExternalArrayElements() &&
8914  !array->HasFixedTypedArrayElements());
8916  return *array;
8917 }
8918 
8919 
8920 RUNTIME_FUNCTION(Runtime_MaxSmi) {
8921  SealHandleScope shs(isolate);
8922  DCHECK(args.length() == 0);
8923  return Smi::FromInt(Smi::kMaxValue);
8924 }
8925 
8926 
8927 // TODO(dcarney): remove this function when TurboFan supports it.
8928 // Takes the object to be iterated over and the result of GetPropertyNamesFast
8929 // Returns pair (cache_array, cache_type).
8930 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInInit) {
8931  SealHandleScope scope(isolate);
8932  DCHECK(args.length() == 2);
8933  // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs.
8934  // Not worth creating a macro atm as this function should be removed.
8935  if (!args[0]->IsJSReceiver() || !args[1]->IsObject()) {
8936  Object* error = isolate->ThrowIllegalOperation();
8937  return MakePair(error, isolate->heap()->undefined_value());
8938  }
8939  Handle<JSReceiver> object = args.at<JSReceiver>(0);
8940  Handle<Object> cache_type = args.at<Object>(1);
8941  if (cache_type->IsMap()) {
8942  // Enum cache case.
8943  if (Map::EnumLengthBits::decode(Map::cast(*cache_type)->bit_field3()) ==
8944  0) {
8945  // 0 length enum.
8946  // Can't handle this case in the graph builder,
8947  // so transform it into the empty fixed array case.
8948  return MakePair(isolate->heap()->empty_fixed_array(), Smi::FromInt(1));
8949  }
8950  return MakePair(object->map()->instance_descriptors()->GetEnumCache(),
8951  *cache_type);
8952  } else {
8953  // FixedArray case.
8954  Smi* new_cache_type = Smi::FromInt(object->IsJSProxy() ? 0 : 1);
8955  return MakePair(*Handle<FixedArray>::cast(cache_type), new_cache_type);
8956  }
8957 }
8958 
8959 
8960 // TODO(dcarney): remove this function when TurboFan supports it.
8961 RUNTIME_FUNCTION(Runtime_ForInCacheArrayLength) {
8962  SealHandleScope shs(isolate);
8963  DCHECK(args.length() == 2);
8964  CONVERT_ARG_HANDLE_CHECKED(Object, cache_type, 0);
8966  int length = 0;
8967  if (cache_type->IsMap()) {
8968  length = Map::cast(*cache_type)->EnumLength();
8969  } else {
8970  DCHECK(cache_type->IsSmi());
8971  length = array->length();
8972  }
8973  return Smi::FromInt(length);
8974 }
8975 
8976 
8977 // TODO(dcarney): remove this function when TurboFan supports it.
8978 // Takes (the object to be iterated over,
8979 // cache_array from ForInInit,
8980 // cache_type from ForInInit,
8981 // the current index)
8982 // Returns pair (array[index], needs_filtering).
8983 RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ForInNext) {
8984  SealHandleScope scope(isolate);
8985  DCHECK(args.length() == 4);
8986  int32_t index;
8987  // This simulates CONVERT_ARG_HANDLE_CHECKED for calls returning pairs.
8988  // Not worth creating a macro atm as this function should be removed.
8989  if (!args[0]->IsJSReceiver() || !args[1]->IsFixedArray() ||
8990  !args[2]->IsObject() || !args[3]->ToInt32(&index)) {
8991  Object* error = isolate->ThrowIllegalOperation();
8992  return MakePair(error, isolate->heap()->undefined_value());
8993  }
8994  Handle<JSReceiver> object = args.at<JSReceiver>(0);
8995  Handle<FixedArray> array = args.at<FixedArray>(1);
8996  Handle<Object> cache_type = args.at<Object>(2);
8997  // Figure out first if a slow check is needed for this object.
8998  bool slow_check_needed = false;
8999  if (cache_type->IsMap()) {
9000  if (object->map() != Map::cast(*cache_type)) {
9001  // Object transitioned. Need slow check.
9002  slow_check_needed = true;
9003  }
9004  } else {
9005  // No slow check needed for proxies.
9006  slow_check_needed = Smi::cast(*cache_type)->value() == 1;
9007  }
9008  return MakePair(array->get(index),
9009  isolate->heap()->ToBoolean(slow_check_needed));
9010 }
9011 
9012 
9013 // ----------------------------------------------------------------------------
9014 // Reference implementation for inlined runtime functions. Only used when the
9015 // compiler does not support a certain intrinsic. Don't optimize these, but
9016 // implement the intrinsic in the respective compiler instead.
9017 
9018 // TODO(mstarzinger): These are place-holder stubs for TurboFan and will
9019 // eventually all have a C++ implementation and this macro will be gone.
9020 #define U(name) \
9021  RUNTIME_FUNCTION(RuntimeReference_##name) { \
9022  UNIMPLEMENTED(); \
9023  return NULL; \
9024  }
9025 
9026 U(IsStringWrapperSafeForDefaultValueOf)
9027 U(DebugBreakInOptimizedCode)
9028 
9029 #undef U
9030 
9031 
9032 RUNTIME_FUNCTION(RuntimeReference_IsSmi) {
9033  SealHandleScope shs(isolate);
9034  DCHECK(args.length() == 1);
9035  CONVERT_ARG_CHECKED(Object, obj, 0);
9036  return isolate->heap()->ToBoolean(obj->IsSmi());
9037 }
9038 
9039 
9040 RUNTIME_FUNCTION(RuntimeReference_IsNonNegativeSmi) {
9041  SealHandleScope shs(isolate);
9042  DCHECK(args.length() == 1);
9043  CONVERT_ARG_CHECKED(Object, obj, 0);
9044  return isolate->heap()->ToBoolean(obj->IsSmi() &&
9045  Smi::cast(obj)->value() >= 0);
9046 }
9047 
9048 
9049 RUNTIME_FUNCTION(RuntimeReference_IsArray) {
9050  SealHandleScope shs(isolate);
9051  DCHECK(args.length() == 1);
9052  CONVERT_ARG_CHECKED(Object, obj, 0);
9053  return isolate->heap()->ToBoolean(obj->IsJSArray());
9054 }
9055 
9056 
9057 RUNTIME_FUNCTION(RuntimeReference_IsRegExp) {
9058  SealHandleScope shs(isolate);
9059  DCHECK(args.length() == 1);
9060  CONVERT_ARG_CHECKED(Object, obj, 0);
9061  return isolate->heap()->ToBoolean(obj->IsJSRegExp());
9062 }
9063 
9064 
9065 RUNTIME_FUNCTION(RuntimeReference_IsConstructCall) {
9066  SealHandleScope shs(isolate);
9067  DCHECK(args.length() == 0);
9068  JavaScriptFrameIterator it(isolate);
9069  JavaScriptFrame* frame = it.frame();
9070  return isolate->heap()->ToBoolean(frame->IsConstructor());
9071 }
9072 
9073 
9074 RUNTIME_FUNCTION(RuntimeReference_CallFunction) {
9075  SealHandleScope shs(isolate);
9076  return __RT_impl_Runtime_Call(args, isolate);
9077 }
9078 
9079 
9080 RUNTIME_FUNCTION(RuntimeReference_ArgumentsLength) {
9081  SealHandleScope shs(isolate);
9082  DCHECK(args.length() == 0);
9083  JavaScriptFrameIterator it(isolate);
9084  JavaScriptFrame* frame = it.frame();
9085  return Smi::FromInt(frame->GetArgumentsLength());
9086 }
9087 
9088 
9089 RUNTIME_FUNCTION(RuntimeReference_Arguments) {
9090  SealHandleScope shs(isolate);
9091  return __RT_impl_Runtime_GetArgumentsProperty(args, isolate);
9092 }
9093 
9094 
9095 RUNTIME_FUNCTION(RuntimeReference_ValueOf) {
9096  SealHandleScope shs(isolate);
9097  DCHECK(args.length() == 1);
9098  CONVERT_ARG_CHECKED(Object, obj, 0);
9099  if (!obj->IsJSValue()) return obj;
9100  return JSValue::cast(obj)->value();
9101 }
9102 
9103 
9104 RUNTIME_FUNCTION(RuntimeReference_SetValueOf) {
9105  SealHandleScope shs(isolate);
9106  DCHECK(args.length() == 2);
9107  CONVERT_ARG_CHECKED(Object, obj, 0);
9108  CONVERT_ARG_CHECKED(Object, value, 1);
9109  if (!obj->IsJSValue()) return value;
9110  JSValue::cast(obj)->set_value(value);
9111  return value;
9112 }
9113 
9114 
9115 RUNTIME_FUNCTION(RuntimeReference_DateField) {
9116  SealHandleScope shs(isolate);
9117  DCHECK(args.length() == 2);
9118  CONVERT_ARG_CHECKED(Object, obj, 0);
9119  CONVERT_SMI_ARG_CHECKED(index, 1);
9120  if (!obj->IsJSDate()) {
9121  HandleScope scope(isolate);
9123  isolate,
9124  NewTypeError("not_date_object", HandleVector<Object>(NULL, 0)));
9125  }
9126  JSDate* date = JSDate::cast(obj);
9127  if (index == 0) return date->value();
9128  return JSDate::GetField(date, Smi::FromInt(index));
9129 }
9130 
9131 
9132 RUNTIME_FUNCTION(RuntimeReference_ObjectEquals) {
9133  SealHandleScope shs(isolate);
9134  DCHECK(args.length() == 2);
9135  CONVERT_ARG_CHECKED(Object, obj1, 0);
9136  CONVERT_ARG_CHECKED(Object, obj2, 1);
9137  return isolate->heap()->ToBoolean(obj1 == obj2);
9138 }
9139 
9140 
9141 RUNTIME_FUNCTION(RuntimeReference_IsObject) {
9142  SealHandleScope shs(isolate);
9143  DCHECK(args.length() == 1);
9144  CONVERT_ARG_CHECKED(Object, obj, 0);
9145  if (!obj->IsHeapObject()) return isolate->heap()->false_value();
9146  if (obj->IsNull()) return isolate->heap()->true_value();
9147  if (obj->IsUndetectableObject()) return isolate->heap()->false_value();
9148  Map* map = HeapObject::cast(obj)->map();
9149  bool is_non_callable_spec_object =
9150  map->instance_type() >= FIRST_NONCALLABLE_SPEC_OBJECT_TYPE &&
9151  map->instance_type() <= LAST_NONCALLABLE_SPEC_OBJECT_TYPE;
9152  return isolate->heap()->ToBoolean(is_non_callable_spec_object);
9153 }
9154 
9155 
9156 RUNTIME_FUNCTION(RuntimeReference_IsFunction) {
9157  SealHandleScope shs(isolate);
9158  DCHECK(args.length() == 1);
9159  CONVERT_ARG_CHECKED(Object, obj, 0);
9160  return isolate->heap()->ToBoolean(obj->IsJSFunction());
9161 }
9162 
9163 
9164 RUNTIME_FUNCTION(RuntimeReference_IsUndetectableObject) {
9165  SealHandleScope shs(isolate);
9166  DCHECK(args.length() == 1);
9167  CONVERT_ARG_CHECKED(Object, obj, 0);
9168  return isolate->heap()->ToBoolean(obj->IsUndetectableObject());
9169 }
9170 
9171 
9172 RUNTIME_FUNCTION(RuntimeReference_IsSpecObject) {
9173  SealHandleScope shs(isolate);
9174  DCHECK(args.length() == 1);
9175  CONVERT_ARG_CHECKED(Object, obj, 0);
9176  return isolate->heap()->ToBoolean(obj->IsSpecObject());
9177 }
9178 
9179 
9180 RUNTIME_FUNCTION(RuntimeReference_HasCachedArrayIndex) {
9181  SealHandleScope shs(isolate);
9182  DCHECK(args.length() == 1);
9183  return isolate->heap()->false_value();
9184 }
9185 
9186 
9187 RUNTIME_FUNCTION(RuntimeReference_GetCachedArrayIndex) {
9188  SealHandleScope shs(isolate);
9189  DCHECK(args.length() == 1);
9190  return isolate->heap()->undefined_value();
9191 }
9192 
9193 
9194 RUNTIME_FUNCTION(RuntimeReference_FastOneByteArrayJoin) {
9195  SealHandleScope shs(isolate);
9196  DCHECK(args.length() == 2);
9197  return isolate->heap()->undefined_value();
9198 }
9199 
9200 
9201 RUNTIME_FUNCTION(RuntimeReference_GeneratorNext) {
9202  UNREACHABLE(); // Optimization disabled in SetUpGenerators().
9203  return NULL;
9204 }
9205 
9206 
9207 RUNTIME_FUNCTION(RuntimeReference_GeneratorThrow) {
9208  UNREACHABLE(); // Optimization disabled in SetUpGenerators().
9209  return NULL;
9210 }
9211 
9212 
9213 RUNTIME_FUNCTION(RuntimeReference_ClassOf) {
9214  SealHandleScope shs(isolate);
9215  DCHECK(args.length() == 1);
9216  CONVERT_ARG_CHECKED(Object, obj, 0);
9217  if (!obj->IsJSReceiver()) return isolate->heap()->null_value();
9218  return JSReceiver::cast(obj)->class_name();
9219 }
9220 
9221 
9222 RUNTIME_FUNCTION(RuntimeReference_GetFromCache) {
9223  HandleScope scope(isolate);
9224  DCHECK(args.length() == 2);
9225  CONVERT_SMI_ARG_CHECKED(id, 0);
9226  args[0] = isolate->native_context()->jsfunction_result_caches()->get(id);
9227  return __RT_impl_Runtime_GetFromCache(args, isolate);
9228 }
9229 
9230 
9231 RUNTIME_FUNCTION(RuntimeReference_DebugIsActive) {
9232  SealHandleScope shs(isolate);
9233  return Smi::FromInt(isolate->debug()->is_active());
9234 }
9235 
9236 
9237 // ----------------------------------------------------------------------------
9238 // Implementation of Runtime
9239 
9240 #define F(name, number_of_args, result_size) \
9241  { \
9242  Runtime::k##name, Runtime::RUNTIME, #name, FUNCTION_ADDR(Runtime_##name), \
9243  number_of_args, result_size \
9244  } \
9245  ,
9246 
9247 
9248 #define I(name, number_of_args, result_size) \
9249  { \
9250  Runtime::kInline##name, Runtime::INLINE, "_" #name, \
9251  FUNCTION_ADDR(RuntimeReference_##name), number_of_args, result_size \
9252  } \
9253  ,
9254 
9255 
9256 #define IO(name, number_of_args, result_size) \
9257  { \
9258  Runtime::kInlineOptimized##name, Runtime::INLINE_OPTIMIZED, "_" #name, \
9259  FUNCTION_ADDR(Runtime_##name), number_of_args, result_size \
9260  } \
9261  ,
9262 
9263 
9267 
9268 #undef IO
9269 #undef I
9270 #undef F
9271 
9272 
9274  Handle<NameDictionary> dict) {
9275  DCHECK(dict->NumberOfElements() == 0);
9276  HandleScope scope(isolate);
9277  for (int i = 0; i < kNumFunctions; ++i) {
9278  const char* name = kIntrinsicFunctions[i].name;
9279  if (name == NULL) continue;
9281  dict, isolate->factory()->InternalizeUtf8String(name),
9282  Handle<Smi>(Smi::FromInt(i), isolate),
9283  PropertyDetails(NONE, NORMAL, Representation::None()));
9284  // The dictionary does not need to grow.
9285  CHECK(new_dict.is_identical_to(dict));
9286  }
9287 }
9288 
9289 
9291  Heap* heap = name->GetHeap();
9292  int entry = heap->intrinsic_function_names()->FindEntry(name);
9293  if (entry != kNotFound) {
9294  Object* smi_index = heap->intrinsic_function_names()->ValueAt(entry);
9295  int function_index = Smi::cast(smi_index)->value();
9296  return &(kIntrinsicFunctions[function_index]);
9297  }
9298  return NULL;
9299 }
9300 
9301 
9303  for (size_t i = 0; i < arraysize(kIntrinsicFunctions); ++i) {
9304  if (entry == kIntrinsicFunctions[i].entry) {
9305  return &(kIntrinsicFunctions[i]);
9306  }
9307  }
9308  return NULL;
9309 }
9310 
9311 
9313  return &(kIntrinsicFunctions[static_cast<int>(id)]);
9314 }
9315 }
9316 } // namespace v8::internal
A stack-allocated class that governs a number of local handles.
Definition: v8.h:802
An object reference managed by the v8 garbage collector.
Definition: v8.h:198
A JavaScript value representing a 32-bit signed integer.
Definition: v8.h:2191
Isolate represents an isolated instance of the V8 engine.
Definition: v8.h:4356
A JavaScript value representing a 32-bit unsigned integer.
Definition: v8.h:2202
static Local< Context > ToLocal(v8::internal::Handle< v8::internal::Context > obj)
static v8::internal::Handle< To > OpenHandle(v8::Local< From > handle)
Definition: api.h:288
static const char * GetVersion()
Get the version string.
Definition: api.cc:5146
static double TimeCurrentMillis()
Object * GetComponent(AccessorComponent component)
Definition: objects.cc:7912
static Handle< Object > FunctionSetPrototype(Handle< JSFunction > object, Handle< Object > value)
Definition: accessors.cc:924
static Handle< AccessorInfo > MakeModuleExport(Handle< String > name, int index, PropertyAttributes attributes)
Definition: accessors.cc:1402
static Handle< Object > FunctionGetArguments(Handle< JSFunction > object)
Definition: accessors.cc:1157
void ExitScope(Handle< AllocationSite > site, Handle< JSObject > object)
void ExitScope(Handle< AllocationSite > scope_site, Handle< JSObject > object)
static AllocationSiteMode GetMode(ElementsKind boilerplate_elements_kind)
Definition: objects-inl.h:1591
A simple visitor visits every element of Array's.
Definition: runtime.cc:4605
Handle< FixedArray > storage_
Definition: runtime.cc:4713
void visit(uint32_t i, Handle< Object > elm)
Definition: runtime.cc:4618
void set_storage(FixedArray *storage)
Definition: runtime.cc:4707
ArrayConcatVisitor(Isolate *isolate, Handle< FixedArray > storage, bool fast_elements)
Definition: runtime.cc:4607
void increase_index_offset(uint32_t delta)
Definition: runtime.cc:4649
Handle< JSArray > ToArray()
Definition: runtime.cc:4667
static T decode(U value)
Definition: utils.h:228
void FindBreakLocationFromAddress(Address pc)
Definition: debug.cc:187
bool IsStepInLocation(Isolate *isolate)
Definition: debug.cc:365
Code * builtin(Name name)
Definition: builtins.h:254
void SetContext(Handle< Context > context)
Definition: compiler.h:257
FunctionLiteral * function() const
Definition: compiler.h:107
static Handle< FixedArray > GetElements(Handle< FixedArray > value)
Definition: parser.cc:3369
static LiteralType GetLiteralType(Handle< FixedArray > value)
Definition: parser.cc:3362
static MUST_USE_RESULT MaybeHandle< JSFunction > GetFunctionFromEval(Handle< String > source, Handle< Context > context, StrictMode strict_mode, ParseRestriction restriction, int scope_position)
Definition: compiler.cc:1081
static bool EnsureCompiled(Handle< JSFunction > function, ClearExceptionFlag flag)
Definition: compiler.cc:876
static Context * cast(Object *context)
Definition: contexts.h:255
Context * previous()
Definition: contexts.h:419
Context * native_context()
Definition: contexts.cc:44
Context * global_context()
Definition: contexts.cc:35
GlobalObject * global_object()
Definition: contexts.h:437
Context * declaration_context()
Definition: contexts.cc:14
JSFunction * closure()
Definition: contexts.h:416
static const int64_t kMaxTimeInMs
Definition: date.h:28
int64_t ToUTC(int64_t time_ms)
Definition: date.h:120
static const int64_t kMaxTimeBeforeUTCInMs
Definition: date.h:33
static bool Parse(Vector< Char > str, FixedArray *output, UnicodeCache *cache)
bool StepInActive()
Definition: debug.h:402
bool EnsureDebugInfo(Handle< SharedFunctionInfo > shared, Handle< JSFunction > function)
Definition: debug.cc:2177
void HandleStepIn(Handle< JSFunction > function, Handle< Object > holder, Address fp, bool is_constructor)
Definition: debug.cc:1593
bool IsStepping()
Definition: debug.h:399
static Handle< DebugInfo > GetDebugInfo(Handle< SharedFunctionInfo > shared)
Definition: debug.cc:1069
static Handle< Object > GetSourceBreakLocations(Handle< SharedFunctionInfo > shared, BreakPositionAlignment position_aligment)
Definition: debug.cc:1551
void FloodWithOneShot(Handle< JSFunction > function)
Definition: debug.cc:1197
void ClearStepping()
Definition: debug.cc:1643
Handle< Context > debug_context()
Definition: debug.h:459
void ClearStepOut()
Definition: debug.cc:1692
Object * GetExpression(int index)
Definition: deoptimizer.h:954
Object * GetParameter(int index)
Definition: deoptimizer.h:948
static DeoptimizedFrameInfo * DebuggerInspectableFrame(JavaScriptFrame *frame, int jsframe_index, Isolate *isolate)
Definition: deoptimizer.cc:136
static void DeleteDebuggerInspectableFrame(DeoptimizedFrameInfo *info, Isolate *isolate)
Definition: deoptimizer.cc:224
static MUST_USE_RESULT Handle< SeededNumberDictionary > New(Isolate *isolate, int at_least_space_for, PretenureFlag pretenure=NOT_TENURED)
Definition: objects.cc:14899
Object * ValueAt(int entry)
Definition: objects.h:3491
static MUST_USE_RESULT Handle< NameDictionary > Add(Handle< NameDictionary > dictionary, Handle< Name > key, Handle< Object > value, PropertyDetails details)
Definition: objects.cc:15024
PropertyDetails DetailsAt(int entry)
Definition: objects.h:3501
virtual bool HasElement(Handle< Object > receiver, Handle< JSObject > holder, uint32_t key, Handle< FixedArrayBase > backing_store)=0
Object * get(int index)
Definition: objects-inl.h:2165
void set(int index, Object *value)
Definition: objects-inl.h:2190
static MUST_USE_RESULT MaybeHandle< FixedArray > UnionOfKeys(Handle< FixedArray > first, Handle< FixedArray > second)
Definition: objects.cc:7723
static const int kMaxLength
Definition: objects.h:2469
void set(int index, double value)
Definition: objects-inl.h:2244
double get_scalar(int index)
Definition: objects-inl.h:2217
static const int kMaxLength
Definition: objects.h:2554
void SetArgumentsFrame(JavaScriptFrame *frame)
Definition: runtime.cc:5759
JavaScriptFrame * frame_
Definition: runtime.cc:5767
Object * GetParameter(int index)
Definition: runtime.cc:5736
DISALLOW_COPY_AND_ASSIGN(FrameInspector)
DeoptimizedFrameInfo * deoptimized_frame_
Definition: runtime.cc:5768
Object * GetExpression(int index)
Definition: runtime.cc:5740
FrameInspector(JavaScriptFrame *frame, int inlined_jsframe_index, Isolate *isolate)
Definition: runtime.cc:5707
static void Destroy(Object **location)
Handle< Object > Create(Object *value)
Handle< T > CloseAndEscape(Handle< T > handle_value)
Definition: handles-inl.h:119
static Handle< T > cast(Handle< S > that)
Definition: handles.h:116
bool is_null() const
Definition: handles.h:124
static Handle< T > null()
Definition: handles.h:123
static const int kNotFound
Definition: objects.h:3283
static Object ** RawField(HeapObject *obj, int offset)
Definition: objects-inl.h:1311
Isolate * GetIsolate() const
Definition: objects-inl.h:1387
static const int kHeaderSize
Definition: objects.h:1428
bool InNewSpace(Object *object)
Definition: heap-inl.h:322
static const int kMakeHeapIterableMask
Definition: heap.h:721
Object * ToBoolean(bool condition)
Definition: heap-inl.h:706
static const int kNoGCFlags
Definition: heap.h:716
void CollectAllGarbage(int flags, const char *gc_reason=NULL, const GCCallbackFlags gc_callback_flags=kNoGCCallbackFlags)
Definition: heap.cc:724
void ReportFailedAccessCheck(Handle< JSObject > receiver, v8::AccessType type)
Definition: isolate.cc:634
Object * ThrowIllegalOperation()
Definition: isolate.cc:852
Builtins * builtins()
Definition: isolate.h:947
Object * Throw(Object *exception, MessageLocation *location=NULL)
Definition: isolate.cc:832
Context * context()
Definition: isolate.h:548
Counters * counters()
Definition: isolate.h:857
JSObject * global_proxy()
Definition: isolate.h:675
bool MayNamedAccess(Handle< JSObject > receiver, Handle< Object > key, v8::AccessType type)
Definition: isolate.cc:697
Factory * factory()
Definition: isolate.h:982
GlobalHandles * global_handles()
Definition: isolate.h:917
bool has_pending_exception()
Definition: isolate.h:581
static void SetContent(Handle< JSArray > array, Handle< FixedArrayBase > storage)
Definition: objects-inl.h:6986
static Object * GetField(Object *date, Smi *index)
Definition: objects.cc:16122
static const int kLiteralNativeContextIndex
Definition: objects.h:7389
static const int kBoundFunctionIndex
Definition: objects.h:7392
static const int kBoundThisIndex
Definition: objects.h:7393
static const int kBoundArgumentsStartIndex
Definition: objects.h:7394
static Handle< JSFunction > CloneClosure(Handle< JSFunction > function)
Definition: objects.cc:9160
static Context * NativeContextFromLiterals(FixedArray *literals)
Definition: objects.cc:9554
static const int kGeneratorClosed
Definition: objects.h:7120
static const int kGeneratorExecuting
Definition: objects.h:7119
static void SetMapAndElements(Handle< JSObject > object, Handle< Map > map, Handle< FixedArrayBase > elements)
Definition: objects-inl.h:1814
static void ResetElements(Handle< JSObject > object)
Definition: objects.cc:4416
static MUST_USE_RESULT MaybeHandle< AccessorPair > GetOwnElementAccessorPair(Handle< JSObject > object, uint32_t index)
Definition: objects.cc:11759
static void MigrateSlowToFast(Handle< JSObject > object, int unused_property_fields)
Definition: objects.cc:4279
static MUST_USE_RESULT MaybeHandle< Object > SetAccessor(Handle< JSObject > object, Handle< AccessorInfo > info)
Definition: objects.cc:6188
static MUST_USE_RESULT MaybeHandle< Object > GetElementWithInterceptor(Handle< JSObject > object, Handle< Object > receiver, uint32_t index)
Definition: objects.cc:12839
static void SetObserved(Handle< JSObject > object)
Definition: objects.cc:5340
static MUST_USE_RESULT MaybeHandle< Object > Freeze(Handle< JSObject > object)
Definition: objects.cc:5239
static void NormalizeProperties(Handle< JSObject > object, PropertyNormalizationMode mode, int expected_additional_properties)
Definition: objects.cc:4166
static void EnsureCanContainHeapObjectElements(Handle< JSObject > obj)
Definition: objects-inl.h:1725
static MUST_USE_RESULT MaybeHandle< Object > GetAccessor(Handle< JSObject > object, Handle< Name > name, AccessorComponent component)
Definition: objects.cc:6268
static MUST_USE_RESULT MaybeHandle< Object > SetFastElement(Handle< JSObject > object, uint32_t index, Handle< Object > value, StrictMode strict_mode, bool check_prototype)
Definition: objects.cc:11949
static void TransitionElementsKind(Handle< JSObject > object, ElementsKind to_kind)
Definition: objects.cc:12706
static MUST_USE_RESULT Maybe< bool > HasRealNamedProperty(Handle< JSObject > object, Handle< Name > key)
Definition: objects.cc:13205
static MUST_USE_RESULT MaybeHandle< Object > SetOwnElement(Handle< JSObject > object, uint32_t index, Handle< Object > value, StrictMode strict_mode)
Definition: objects.cc:12327
static const int kInitialMaxFastElementArray
Definition: objects.h:2180
static Handle< Object > FastPropertyAt(Handle< JSObject > object, Representation representation, FieldIndex index)
Definition: objects.cc:5362
bool ReferencesObject(Object *obj)
Definition: objects.cc:5047
static MUST_USE_RESULT MaybeHandle< Object > SetElement(Handle< JSObject > object, uint32_t index, Handle< Object > value, PropertyAttributes attributes, StrictMode strict_mode, bool check_prototype=true, SetPropertyMode set_mode=SET_PROPERTY)
Definition: objects.cc:12336
static void MigrateToMap(Handle< JSObject > object, Handle< Map > new_map)
Definition: objects.cc:1886
static MUST_USE_RESULT MaybeHandle< JSObject > GetKeysForIndexedInterceptor(Handle< JSObject > object, Handle< JSReceiver > receiver)
Definition: objects.cc:13181
static Handle< Object > GetDataProperty(Handle< JSObject > object, Handle< Name > key)
Definition: objects.cc:140
static const uint32_t kMaxElementCount
Definition: objects.h:2161
static bool TryMigrateInstance(Handle< JSObject > instance)
Definition: objects.cc:3740
static Handle< Map > GetElementsTransitionMap(Handle< JSObject > object, ElementsKind to_kind)
Definition: objects.cc:3385
static MUST_USE_RESULT MaybeHandle< Object > SetPrototype(Handle< JSObject > object, Handle< Object > value, bool from_javascript)
Definition: objects.cc:11658
static MUST_USE_RESULT MaybeHandle< Object > PreventExtensions(Handle< JSObject > object)
Definition: objects.cc:5159
static Handle< Object > SetHiddenProperty(Handle< JSObject > object, Handle< Name > key, Handle< Object > value)
Definition: objects.cc:4627
static MUST_USE_RESULT MaybeHandle< JSObject > DeepWalk(Handle< JSObject > object, AllocationSiteCreationContext *site_context)
Definition: objects.cc:5581
static void AddProperty(Handle< JSObject > object, Handle< Name > key, Handle< Object > value, PropertyAttributes attributes)
Definition: objects.cc:3786
static void EnqueueChangeRecord(Handle< JSObject > object, const char *type, Handle< Name > name, Handle< Object > old_value)
Definition: objects.cc:1809
static void ValidateElements(Handle< JSObject > object)
Definition: objects-inl.h:1561
static MaybeHandle< Object > DefineAccessor(Handle< JSObject > object, Handle< Name > name, Handle< Object > getter, Handle< Object > setter, PropertyAttributes attributes)
Definition: objects.cc:6095
static MUST_USE_RESULT MaybeHandle< JSObject > DeepCopy(Handle< JSObject > object, AllocationSiteUsageContext *site_context, DeepCopyHints hints=kNoHints)
Definition: objects.cc:5593
static bool HasHiddenProperties(Handle< JSObject > object)
Definition: objects.cc:4697
static MUST_USE_RESULT MaybeHandle< JSObject > GetKeysForNamedInterceptor(Handle< JSObject > object, Handle< JSReceiver > receiver)
Definition: objects.cc:13156
static Handle< SeededNumberDictionary > NormalizeElements(Handle< JSObject > object)
Definition: objects.cc:4459
static MUST_USE_RESULT MaybeHandle< Object > SetOwnPropertyIgnoreAttributes(Handle< JSObject > object, Handle< Name > key, Handle< Object > value, PropertyAttributes attributes, ExecutableAccessorInfoHandling handling=DEFAULT_HANDLING)
Definition: objects.cc:3808
static Handle< Object > PrepareElementsForSort(Handle< JSObject > object, uint32_t limit)
Definition: objects.cc:14245
static void Fix(Handle< JSProxy > proxy)
Definition: objects.cc:3655
static MUST_USE_RESULT Maybe< bool > HasOwnElement(Handle< JSReceiver > object, uint32_t index)
Definition: objects-inl.h:6730
static MUST_USE_RESULT Maybe< PropertyAttributes > GetPropertyAttributes(Handle< JSReceiver > object, Handle< Name > name)
Definition: objects-inl.h:6670
static MUST_USE_RESULT Maybe< bool > HasElement(Handle< JSReceiver > object, uint32_t index)
Definition: objects-inl.h:6718
static MUST_USE_RESULT Maybe< PropertyAttributes > GetOwnPropertyAttributes(Handle< JSReceiver > object, Handle< Name > name)
Definition: objects.cc:3983
static MUST_USE_RESULT MaybeHandle< Object > DeleteElement(Handle< JSReceiver > object, uint32_t index, DeleteMode mode=NORMAL_DELETION)
Definition: objects.cc:5002
static MUST_USE_RESULT Maybe< bool > HasOwnProperty(Handle< JSReceiver >, Handle< Name > name)
Definition: objects-inl.h:6658
static MUST_USE_RESULT MaybeHandle< FixedArray > GetKeys(Handle< JSReceiver > object, KeyCollectionType type)
Definition: objects.cc:5797
static MUST_USE_RESULT Maybe< PropertyAttributes > GetOwnElementAttribute(Handle< JSReceiver > object, uint32_t index)
Definition: objects-inl.h:6743
static MUST_USE_RESULT Maybe< bool > HasProperty(Handle< JSReceiver > object, Handle< Name > name)
Definition: objects-inl.h:6646
static MUST_USE_RESULT MaybeHandle< Object > DeleteProperty(Handle< JSReceiver > object, Handle< Name > name, DeleteMode mode=NORMAL_DELETION)
Definition: objects.cc:5013
void SetParameterValue(int index, Object *value) const
Definition: frames.cc:719
void RestoreOperandStack(FixedArray *store, int stack_handler_index)
Definition: frames.cc:875
Object * receiver() const
Definition: frames-inl.h:250
bool IsConstructor() const
Definition: frames.cc:724
virtual void GetFunctions(List< JSFunction * > *functions)
Definition: frames.cc:762
bool has_adapted_arguments() const
Definition: frames-inl.h:260
static void PrintTop(Isolate *isolate, FILE *file, bool print_args, bool print_line_number)
Definition: frames.cc:811
Address GetParameterSlot(int index) const
Definition: frames-inl.h:209
int GetArgumentsLength() const
Definition: frames.cc:734
Object * GetParameter(int index) const
Definition: frames-inl.h:217
JSFunction * function() const
Definition: frames-inl.h:265
void SaveOperandStack(FixedArray *store, int *stack_handler_index) const
Definition: frames.cc:842
int ComputeParametersCount() const
Definition: frames.h:562
int Lookup(Handle< Map > map, Handle< Name > name)
Definition: heap.cc:5906
void Update(Handle< Map > map, Handle< Name > name, int field_offset)
Definition: heap.cc:5919
void Add(const T &element, AllocationPolicy allocator=AllocationPolicy())
Definition: list-inl.h:17
void Sort(int(*cmp)(const T *x, const T *y))
Definition: list-inl.h:194
static const char * RestartFrame(JavaScriptFrame *frame)
Definition: liveedit.cc:2034
static Handle< JSArray > CheckAndDropActivations(Handle< JSArray > shared_info_array, bool do_drop)
Definition: liveedit.cc:1955
static MUST_USE_RESULT MaybeHandle< JSArray > GatherCompileInfo(Handle< Script > script, Handle< String > source)
Definition: liveedit.cc:843
static void ReplaceRefToNestedFunction(Handle< JSValue > parent_function_shared, Handle< JSValue > orig_function_shared, Handle< JSValue > subst_function_shared)
Definition: liveedit.cc:1495
static void ReplaceFunctionCode(Handle< JSArray > new_compile_info_array, Handle< JSArray > shared_info_array)
Definition: liveedit.cc:1187
static Handle< Object > ChangeScriptSource(Handle< Script > original_script, Handle< String > new_source, Handle< Object > old_script_name)
Definition: liveedit.cc:1471
static void WrapSharedFunctionInfos(Handle< JSArray > array)
Definition: liveedit.cc:909
static void PatchFunctionPositions(Handle< JSArray > shared_info_array, Handle< JSArray > position_change_array)
Definition: liveedit.cc:1415
static void FunctionSourceUpdated(Handle< JSArray > shared_info_array)
Definition: liveedit.cc:1233
static Handle< JSArray > CompareStrings(Handle< String > s1, Handle< String > s2)
Definition: liveedit.cc:556
static void SetFunctionScript(Handle< JSValue > function_wrapper, Handle< Object > script_handle)
Definition: liveedit.cc:1242
static Handle< Map > Create(Isolate *isolate, int inobject_properties)
Definition: objects.cc:6674
ElementsKind elements_kind()
Definition: objects.h:5730
static Handle< Map > AsElementsKind(Handle< Map > map, ElementsKind kind)
Definition: objects.cc:3374
bool is_undetectable()
Definition: objects.h:5705
static bool IsValidElementsTransition(ElementsKind from_kind, ElementsKind to_kind)
Definition: objects.cc:12775
InstanceType instance_type()
Definition: objects-inl.h:4323
static Handle< Map > Copy(Handle< Map > map)
Definition: objects.cc:6664
bool is_null() const
Definition: handles.h:66
static Object *& Object_at(Address addr)
Definition: v8memory.h:60
static ModuleInfo * cast(Object *description)
Definition: scopeinfo.h:119
int FindEntry(Handle< Name > key)
Definition: objects.cc:13784
static MUST_USE_RESULT MaybeHandle< Object > GetPropertyOrElement(Handle< Object > object, Handle< Name > key)
Definition: objects-inl.h:1124
static MaybeHandle< JSReceiver > ToObject(Isolate *isolate, Handle< Object > object)
Definition: objects-inl.h:1094
static MUST_USE_RESULT MaybeHandle< Object > GetElement(Isolate *isolate, Handle< Object > object, uint32_t index)
Definition: objects-inl.h:1113
static MUST_USE_RESULT MaybeHandle< Object > GetProperty(LookupIterator *it)
Definition: objects.cc:109
@ CERTAINLY_NOT_STORE_FROM_KEYED
Definition: objects.h:1007
void ShortPrint(FILE *out=stdout)
Definition: objects.cc:905
bool ToArrayIndex(uint32_t *index)
Definition: objects-inl.h:2116
static Handle< Object > WrapForRead(Isolate *isolate, Handle< Object > object, Representation representation)
Definition: objects-inl.h:296
static MUST_USE_RESULT MaybeHandle< Object > GetPropertyWithAccessor(Handle< Object > receiver, Handle< Name > name, Handle< JSObject > holder, Handle< Object > structure)
Definition: objects.cc:411
static MUST_USE_RESULT MaybeHandle< Object > SetProperty(Handle< Object > object, Handle< Name > key, Handle< Object > value, StrictMode strict_mode, StoreFromKeyed store_mode=MAY_BE_STORE_FROM_KEYED)
Definition: objects.cc:2798
static const int kMaxRegularHeapObjectSize
Definition: spaces.h:754
A class to uniformly access the prototype of any Object and walk its prototype chain.
Definition: prototype.h:25
bool IsAtEnd(WhereToEnd where_to_end=END_AT_NULL) const
Definition: prototype.h:99
Object * GetCurrent() const
Definition: prototype.h:62
static int ModeMask(Mode mode)
Definition: assembler.h:445
byte * pc() const
Definition: assembler.h:457
intptr_t data() const
Definition: assembler.h:460
static const int kNoPosition
Definition: assembler.h:317
static Representation Double()
static Representation None()
static const int kNotFound
Definition: runtime.h:807
static const Function * FunctionForId(FunctionId id)
Definition: runtime.cc:9312
static void InitializeIntrinsicFunctionNames(Isolate *isolate, Handle< NameDictionary > dict)
Definition: runtime.cc:9273
static MUST_USE_RESULT MaybeHandle< Object > HasObjectProperty(Isolate *isolate, Handle< JSReceiver > object, Handle< Object > key)
Definition: runtime.cc:1891
static MUST_USE_RESULT MaybeHandle< Object > SetObjectProperty(Isolate *isolate, Handle< Object > object, Handle< Object > key, Handle< Object > value, StrictMode strict_mode)
Definition: runtime.cc:2181
static const Function * FunctionForEntry(Address ref)
Definition: runtime.cc:9302
static MUST_USE_RESULT MaybeHandle< Object > GetObjectProperty(Isolate *isolate, Handle< Object > object, Handle< Object > key)
Definition: runtime.cc:1912
static MUST_USE_RESULT MaybeHandle< Object > GetElementOrCharAt(Isolate *isolate, Handle< Object > object, uint32_t index)
Definition: runtime.cc:1850
static MUST_USE_RESULT MaybeHandle< Object > CreateArrayLiteralBoilerplate(Isolate *isolate, Handle< FixedArray > literals, Handle< FixedArray > elements)
Definition: runtime.cc:248
static const Function * FunctionForName(Handle< String > name)
Definition: runtime.cc:9290
static MUST_USE_RESULT MaybeHandle< Object > DefineObjectProperty(Handle< JSObject > object, Handle< Object > key, Handle< Object > value, PropertyAttributes attr)
Definition: runtime.cc:2277
static MUST_USE_RESULT MaybeHandle< Object > DeleteObjectProperty(Isolate *isolate, Handle< JSReceiver > object, Handle< Object > key, JSReceiver::DeleteMode mode)
Definition: runtime.cc:2328
static int ContextSlotIndex(Handle< ScopeInfo > scope_info, Handle< String > name, VariableMode *mode, InitializationFlag *init_flag, MaybeAssignedFlag *maybe_assigned_flag)
Definition: scopeinfo.cc:296
static bool CopyContextLocalsToScopeObject(Handle< ScopeInfo > scope_info, Handle< Context > context, Handle< JSObject > scope_object)
Definition: scopeinfo.cc:371
static ScopeInfo * Empty(Isolate *isolate)
Definition: scopeinfo.cc:132
void RetrieveScopeChain(Scope *scope, Handle< SharedFunctionInfo > shared_info)
Definition: runtime.cc:6817
MaybeHandle< JSObject > ScopeObject()
Definition: runtime.cc:6675
bool SetVariableValue(Handle< String > variable_name, Handle< Object > new_value)
Definition: runtime.cc:6701
JavaScriptFrame * frame_
Definition: runtime.cc:6810
Handle< Context > context_
Definition: runtime.cc:6813
Handle< ScopeInfo > CurrentScopeInfo()
Definition: runtime.cc:6728
List< Handle< ScopeInfo > > nested_scope_chain_
Definition: runtime.cc:6814
ScopeIterator(Isolate *isolate, JavaScriptFrame *frame, int inlined_jsframe_index, bool ignore_nested_scopes=false)
Definition: runtime.cc:6494
Handle< Context > CurrentContext()
Definition: runtime.cc:6742
ScopeIterator(Isolate *isolate, Handle< JSFunction > function)
Definition: runtime.cc:6585
Handle< JSFunction > function_
Definition: runtime.cc:6812
DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeIterator)
static bool Analyze(CompilationInfo *info)
Definition: scopes.cc:260
void GetNestedScopeChain(List< Handle< ScopeInfo > > *chain, int statement_position)
Definition: scopes.cc:754
static Handle< JSObject > GetWrapper(Handle< Script > script)
Definition: objects.cc:9741
static MUST_USE_RESULT Handle< SeededNumberDictionary > AtNumberPut(Handle< SeededNumberDictionary > dictionary, uint32_t key, Handle< Object > value)
Definition: objects.cc:15108
static bool IsInstance(Handle< JSArray > array)
Definition: liveedit.h:347
static const int kMaxValue
Definition: objects.h:1272
static Smi * FromInt(int value)
Definition: objects-inl.h:1321
static bool IsValid(intptr_t value)
Definition: objects-inl.h:1334
StackFrame * frame() const
Definition: frames.h:842
Object * context() const
Definition: frames-inl.h:164
Object * GetExpression(int index) const
Definition: frames-inl.h:154
void SetExpression(int index, Object *value)
Definition: frames-inl.h:159
Vector< const uint8_t > ToOneByteVector()
Definition: objects.h:8639
Vector< const uc16 > ToUC16Vector()
Definition: objects.h:8645
static Handle< String > Flatten(Handle< String > string, PretenureFlag pretenure=NOT_TENURED)
Definition: objects-inl.h:3354
bool Equals(String *other)
Definition: objects-inl.h:3336
int ToInteger() const
Definition: isolate.h:202
static ThreadId Current()
Definition: isolate.h:185
ThreadState * Next()
Definition: v8threads.cc:236
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf map
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long enable alignment of csp to bytes on platforms which prefer the register to always be expose gc extension under the specified name show built in functions in stack traces use random jit cookie to mask large constants minimum length for automatic enable preparsing CPU profiler sampling interval in microseconds trace out of bounds accesses to external arrays default size of stack region v8 is allowed to maximum length of function source code printed in a stack trace min size of a semi the new space consists of two semi spaces print one trace line following each garbage collection do not print trace line after scavenger collection print cumulative GC statistics in only print modified registers Trace simulator debug messages Implied by trace sim abort randomize hashes to avoid predictable hash Fixed seed to use to hash property Print the time it takes to deserialize the snapshot A filename with extra code to be included in the A file to write the raw snapshot bytes to(mksnapshot only)") DEFINE_STRING(raw_context_file
enable harmony numeric enable harmony object literal extensions Optimize object size
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long enable alignment of csp to bytes on platforms which prefer the register to always be expose gc extension under the specified name show built in functions in stack traces use random jit cookie to mask large constants minimum length for automatic enable preparsing CPU profiler sampling interval in microseconds trace out of bounds accesses to external arrays default size of stack region v8 is allowed to maximum length of function source code printed in a stack trace min size of a semi the new space consists of two semi spaces print one trace line following each garbage collection do not print trace line after scavenger collection print cumulative GC statistics in name
enable harmony numeric literals(0o77, 0b11)") DEFINE_BOOL(harmony_object_literals
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long mode(MIPS only)") DEFINE_BOOL(enable_always_align_csp
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long enable alignment of csp to bytes on platforms which prefer the register to always be expose gc extension under the specified name show built in functions in stack traces use random jit cookie to mask large constants minimum length for automatic enable preparsing CPU profiler sampling interval in microseconds trace out of bounds accesses to external arrays default size of stack region v8 is allowed to maximum length of function source code printed in a stack trace min size of a semi the new space consists of two semi spaces print one trace line following each garbage collection do not print trace line after scavenger collection print cumulative GC statistics in only print modified registers Trace simulator debug messages Implied by trace sim abort randomize hashes to avoid predictable hash Fixed seed to use to hash property keys(0 means random)" "(with snapshots this option cannot override the baked-in seed)") DEFINE_BOOL(profile_deserialization
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction pairs(ARM only)") DEFINE_BOOL(enable_unaligned_accesses
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long enable alignment of csp to bytes on platforms which prefer the register to always be expose gc extension under the specified name show built in functions in stack traces use random jit cookie to mask large constants minimum length for automatic enable preparsing CPU profiler sampling interval in microseconds trace out of bounds accesses to external arrays default size of stack region v8 is allowed to maximum length of function source code printed in a stack trace min size of a semi space(in MBytes)
enable harmony numeric enable harmony object literal extensions Optimize object Array DOM strings and string trace pretenuring decisions of HAllocate instructions Enables optimizations which favor memory size over execution speed maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining trace the tracking of allocation sites deoptimize every n garbage collections perform array bounds checks elimination analyze liveness of environment slots and zap dead values flushes the cache of optimized code for closures on every GC allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes enable context specialization in TurboFan execution budget before interrupt is triggered max percentage of megamorphic generic ICs to allow optimization enable use of SAHF instruction if enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable use of MLS instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long enable alignment of csp to bytes on platforms which prefer the register to always be NULL
#define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate)
Definition: isolate.h:101
#define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call)
Definition: isolate.h:131
#define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value)
Definition: isolate.h:123
#define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call)
Definition: isolate.h:146
#define RETURN_FAILURE_ON_EXCEPTION(isolate, call)
Definition: isolate.h:162
#define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T)
Definition: isolate.h:135
#define RETURN_ON_EXCEPTION(isolate, call, T)
Definition: isolate.h:165
#define THROW_NEW_ERROR(isolate, call, T)
Definition: isolate.h:138
#define LOG(isolate, Call)
Definition: log.h:69
#define UNREACHABLE()
Definition: logging.h:30
#define CHECK(condition)
Definition: logging.h:36
#define DCHECK_GE(v1, v2)
Definition: logging.h:208
#define DCHECK(condition)
Definition: logging.h:205
#define DCHECK_LT(v1, v2)
Definition: logging.h:209
#define DCHECK_EQ(v1, v2)
Definition: logging.h:206
void USE(T)
Definition: macros.h:322
intptr_t OffsetFrom(T x)
Definition: macros.h:383
#define arraysize(array)
Definition: macros.h:86
#define MUST_USE_RESULT
Definition: macros.h:266
int int32_t
Definition: unicode.cc:24
Vector< const char > CStrVector(const char *data)
Definition: vector.h:158
RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ResolvePossiblyDirectEval)
const int kPointerSize
Definition: globals.h:129
static void UpdateStackLocalsFromMaterializedObject(Isolate *isolate, Handle< JSObject > target, Handle< JSFunction > function, JavaScriptFrame *frame, int inlined_jsframe_index)
Definition: runtime.cc:6132
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeStackLocalsWithFrameInspector(Isolate *isolate, Handle< JSObject > target, Handle< JSFunction > function, FrameInspector *frame_inspector)
Definition: runtime.cc:6092
bool IsFastHoleyElementsKind(ElementsKind kind)
static const int kFrameDetailsAtReturnIndex
Definition: runtime.cc:5785
static int OwnPrototypeChainLength(JSObject *obj)
Definition: runtime.cc:2844
T * NewArray(size_t size)
Definition: allocation.h:60
static int DebugReferencedBy(HeapIterator *iterator, JSObject *target, Object *instance_filter, int max_references, FixedArray *instances, int instances_size, JSFunction *arguments_function)
Definition: runtime.cc:7675
static bool IterateElements(Isolate *isolate, Handle< JSArray > receiver, ArrayConcatVisitor *visitor)
A helper function that visits elements of a JSArray in numerical order.
Definition: runtime.cc:4946
static const int kScopeDetailsObjectIndex
Definition: runtime.cc:6936
static const int kFrameDetailsConstructCallIndex
Definition: runtime.cc:5784
static const int kFrameDetailsSourcePositionIndex
Definition: runtime.cc:5783
InitializationFlag
Definition: globals.h:751
@ TRACK_ALLOCATION_SITE
Definition: objects.h:8085
static const int kFrameDetailsFlagsIndex
Definition: runtime.cc:5786
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeModuleScope(Isolate *isolate, Handle< Context > context)
Definition: runtime.cc:6458
@ KEEP_EXCEPTION
Definition: globals.h:761
@ CLEAR_EXCEPTION
Definition: globals.h:762
@ IMMUTABLE_CHECK_INITIALIZED
Definition: contexts.h:60
@ MUTABLE_IS_INITIALIZED
Definition: contexts.h:57
@ MISSING_BINDING
Definition: contexts.h:63
@ IMMUTABLE_CHECK_INITIALIZED_HARMONY
Definition: contexts.h:62
@ MUTABLE_CHECK_INITIALIZED
Definition: contexts.h:58
@ IMMUTABLE_IS_INITIALIZED_HARMONY
Definition: contexts.h:61
@ IMMUTABLE_IS_INITIALIZED
Definition: contexts.h:59
static bool SetClosureVariableValue(Isolate *isolate, Handle< Context > context, Handle< String > variable_name, Handle< Object > new_value)
Definition: runtime.cc:6372
static StackFrame::Id UnwrapFrameId(int wrapped)
Definition: runtime.cc:5442
static LifetimePosition Min(LifetimePosition a, LifetimePosition b)
@ DEFINE_PROPERTY
Definition: objects.h:1552
bool IsFastSmiOrObjectElementsKind(ElementsKind kind)
static Object * DeclareGlobals(Isolate *isolate, Handle< GlobalObject > global, Handle< String > name, Handle< Object > value, PropertyAttributes attr, bool is_var, bool is_const, bool is_function)
Definition: runtime.cc:1038
uint64_t ObjectPair
static MUST_USE_RESULT MaybeHandle< Name > ToName(Isolate *isolate, Handle< Object > key)
Definition: runtime.cc:1879
static const int kFrameDetailsReceiverIndex
Definition: runtime.cc:5779
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeLocalContext(Isolate *isolate, Handle< JSObject > target, Handle< JSFunction > function, JavaScriptFrame *frame)
Definition: runtime.cc:6173
static int DebugConstructedBy(HeapIterator *iterator, JSFunction *constructor, int max_references, FixedArray *instances, int instances_size)
Definition: runtime.cc:7793
bool IsMoreGeneralElementsKindTransition(ElementsKind from_kind, ElementsKind to_kind)
const SwVfpRegister s1
static ObjectPair LoadLookupSlotHelper(Arguments args, Isolate *isolate, bool throw_error)
Definition: runtime.cc:4133
static MUST_USE_RESULT MaybeHandle< Object > GetOwnProperty(Isolate *isolate, Handle< JSObject > obj, Handle< Name > name)
Definition: runtime.cc:757
static Handle< Map > ComputeObjectLiteralMap(Handle< Context > context, Handle< FixedArray > constant_properties, bool *is_result_from_cache)
Definition: runtime.cc:71
static const int kScopeDetailsSize
Definition: runtime.cc:6937
static void InstallBuiltin(Isolate *isolate, Handle< JSObject > holder, const char *name, Builtins::Name builtin_name)
Definition: runtime.cc:1374
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeCatchScope(Isolate *isolate, Handle< Context > context)
Definition: runtime.cc:6406
static MUST_USE_RESULT MaybeHandle< AllocationSite > GetLiteralAllocationSite(Isolate *isolate, Handle< FixedArray > literals, int literals_index, Handle< FixedArray > elements)
Definition: runtime.cc:392
const SwVfpRegister s2
static MaybeHandle< JSObject > CreateArrayLiteralImpl(Isolate *isolate, Handle< FixedArray > literals, int literals_index, Handle< FixedArray > elements, int flags)
Definition: runtime.cc:423
static const int kThreadDetailsSize
Definition: runtime.cc:7177
double DoubleToInteger(double x)
static const int kThreadDetailsThreadIdIndex
Definition: runtime.cc:7176
ElementsKind GetPackedElementsKind(ElementsKind holey_kind)
static int FindSharedFunctionInfosForScript(HeapIterator *iterator, Script *script, FixedArray *buffer)
Definition: runtime.cc:7937
static bool SetContextLocalValue(Isolate *isolate, Handle< ScopeInfo > scope_info, Handle< Context > context, Handle< String > variable_name, Handle< Object > new_value)
Definition: runtime.cc:6237
OStream & endl(OStream &os)
Definition: ostreams.cc:112
static Handle< Object > Runtime_GetScriptFromScriptName(Handle< String > script_name)
Definition: runtime.cc:8303
int ToNumber(Register reg)
const int kMaxInt
Definition: globals.h:109
static MUST_USE_RESULT MaybeHandle< Object > CreateObjectLiteralBoilerplate(Isolate *isolate, Handle< FixedArray > literals, Handle< FixedArray > constant_properties, bool should_have_fast_elements, bool has_function_literal)
Definition: runtime.cc:126
ExceptionBreakType
Definition: debug.h:45
static Object * ComputeReceiverForNonGlobal(Isolate *isolate, JSObject *holder)
Definition: runtime.cc:4114
@ OBJECT_TEMPLATE_INFO_TYPE
Definition: objects.h:704
@ LAST_NONCALLABLE_SPEC_OBJECT_TYPE
Definition: objects.h:785
@ FIRST_NONCALLABLE_SPEC_OBJECT_TYPE
Definition: objects.h:784
@ FIRST_NONSTRING_TYPE
Definition: objects.h:758
@ ODDBALL_TYPE
Definition: objects.h:663
@ JS_FUNCTION_TYPE
Definition: objects.h:749
@ JS_FUNCTION_PROXY_TYPE
Definition: objects.h:726
@ FUNCTION_TEMPLATE_INFO_TYPE
Definition: objects.h:703
@ EXTERNAL_UINT16_ELEMENTS
Definition: elements-kind.h:36
@ EXTERNAL_INT16_ELEMENTS
Definition: elements-kind.h:35
@ EXTERNAL_UINT8_ELEMENTS
Definition: elements-kind.h:34
@ EXTERNAL_INT32_ELEMENTS
Definition: elements-kind.h:37
@ FAST_HOLEY_DOUBLE_ELEMENTS
Definition: elements-kind.h:27
@ SLOPPY_ARGUMENTS_ELEMENTS
Definition: elements-kind.h:31
@ EXTERNAL_INT8_ELEMENTS
Definition: elements-kind.h:33
@ EXTERNAL_FLOAT32_ELEMENTS
Definition: elements-kind.h:39
@ EXTERNAL_FLOAT64_ELEMENTS
Definition: elements-kind.h:40
@ FAST_HOLEY_SMI_ELEMENTS
Definition: elements-kind.h:17
@ EXTERNAL_UINT32_ELEMENTS
Definition: elements-kind.h:38
@ EXTERNAL_UINT8_CLAMPED_ELEMENTS
Definition: elements-kind.h:41
bool IsFastDoubleElementsKind(ElementsKind kind)
Handle< T > handle(T *t, Isolate *isolate)
Definition: handles.h:146
static void IterateExternalArrayElements(Isolate *isolate, Handle< JSObject > receiver, bool elements_are_ints, bool elements_are_guaranteed_smis, ArrayConcatVisitor *visitor)
Definition: runtime.cc:4786
static MUST_USE_RESULT MaybeHandle< Object > CreateLiteralBoilerplate(Isolate *isolate, Handle< FixedArray > literals, Handle< FixedArray > constant_properties)
Definition: runtime.cc:321
double Floor(double x)
Definition: utils.h:159
static Handle< Object > InstantiateAccessorComponent(Isolate *isolate, Handle< Object > component)
Definition: runtime.cc:2068
bool IsImmutableVariableMode(VariableMode mode)
Definition: globals.h:715
static Object * HasOwnPropertyImplementation(Isolate *isolate, Handle< JSObject > object, Handle< Name > key)
Definition: runtime.cc:2695
bool IsFastPackedElementsKind(ElementsKind kind)
static Object * ArrayConstructorCommon(Isolate *isolate, Handle< JSFunction > constructor, Handle< AllocationSite > site, Arguments *caller_args)
Definition: runtime.cc:8779
BreakPositionAlignment
Definition: debug.h:60
@ STATEMENT_ALIGNED
Definition: debug.h:61
@ BREAK_POSITION_ALIGNED
Definition: debug.h:62
static const int kScopeDetailsTypeIndex
Definition: runtime.cc:6935
const Register pc
@ DYNAMIC_GLOBAL
Definition: globals.h:689
@ DYNAMIC_LOCAL
Definition: globals.h:693
@ CONST_LEGACY
Definition: globals.h:671
ElementsKind GetHoleyElementsKind(ElementsKind packed_kind)
static SaveContext * FindSavedContextForFrame(Isolate *isolate, JavaScriptFrame *frame)
Definition: runtime.cc:5790
static MUST_USE_RESULT MaybeHandle< Object > TransitionElements(Handle< Object > object, ElementsKind to_kind, Isolate *isolate)
Definition: runtime.cc:230
static const int kFrameDetailsFunctionIndex
Definition: runtime.cc:5780
int32_t NumberToInt32(Object *number)
Definition: conversions.h:189
byte * Address
Definition: globals.h:101
bool IsFastElementsKind(ElementsKind kind)
static bool IsValidAccessor(Handle< Object > obj)
Definition: runtime.cc:2062
static bool ContextsHaveSameOrigin(Handle< Context > context1, Handle< Context > context2)
Definition: runtime.cc:8715
void PrintF(const char *format,...)
Definition: utils.cc:80
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeBlockScope(Isolate *isolate, Handle< Context > context)
Definition: runtime.cc:6436
Vector< Handle< Object > > HandleVector(v8::internal::Handle< T > *elms, int length)
Definition: utils.h:1100
int32_t DoubleToInt32(double x)
static Handle< Object > GetCharAt(Handle< String > string, uint32_t index)
Definition: runtime.cc:1840
static Object * StoreToSuper(Isolate *isolate, Handle< JSObject > home_object, Handle< Object > receiver, Handle< Name > name, Handle< Object > value, StrictMode strict_mode)
Definition: runtime.cc:900
static SmartArrayPointer< Handle< Object > > GetCallerArguments(Isolate *isolate, int prefix_argc, int *total_argc)
Definition: runtime.cc:3506
@ StepMin
Definition: debug.h:38
@ StepNext
Definition: debug.h:35
@ StepInMin
Definition: debug.h:39
@ StepIn
Definition: debug.h:36
@ StepOut
Definition: debug.h:34
static void CollectElementIndices(Handle< JSObject > object, uint32_t range, List< uint32_t > *indices)
Definition: runtime.cc:4836
uint32_t NumberToUint32(Object *number)
Definition: conversions.h:195
kFeedbackVectorOffset flag
Definition: objects-inl.h:5418
static bool ParameterIsShadowedByContextLocal(Handle< ScopeInfo > info, Handle< String > parameter_name)
Definition: runtime.cc:6079
static Object * ThrowRedeclarationError(Isolate *isolate, Handle< String > name)
Definition: runtime.cc:1029
static bool IsPositionAlignmentCodeCorrect(int alignment)
Definition: runtime.cc:7240
static const int kFrameDetailsArgumentCountIndex
Definition: runtime.cc:5781
STATIC_ASSERT(sizeof(CPURegister)==sizeof(Register))
static bool SetLocalVariableValue(Isolate *isolate, JavaScriptFrame *frame, int inlined_jsframe_index, Handle< String > variable_name, Handle< Object > new_value)
Definition: runtime.cc:6258
@ NO_PARSE_RESTRICTION
Definition: compiler.h:22
static Object * Runtime_NewObjectHelper(Isolate *isolate, Handle< Object > constructor, Handle< AllocationSite > site)
Definition: runtime.cc:3676
const char * DoubleToCString(double v, Vector< char > buffer)
Definition: conversions.cc:121
PropertyDescriptorIndices
Definition: runtime.cc:745
@ DESCRIPTOR_SIZE
Definition: runtime.cc:753
@ WRITABLE_INDEX
Definition: runtime.cc:750
@ ENUMERABLE_INDEX
Definition: runtime.cc:751
@ CONFIGURABLE_INDEX
Definition: runtime.cc:752
@ IS_ACCESSOR_INDEX
Definition: runtime.cc:746
static int FindIndexedNonNativeFrame(JavaScriptFrameIterator *it, int index)
Definition: runtime.cc:5803
@ ALL_BREAK_LOCATIONS
Definition: debug.h:53
static const int kThreadDetailsCurrentThreadIndex
Definition: runtime.cc:7175
static uint32_t EstimateElementCount(Handle< JSArray > array)
Definition: runtime.cc:4722
static Smi * WrapFrameId(StackFrame::Id id)
Definition: runtime.cc:5436
static bool CheckExecutionState(Isolate *isolate, int break_id)
Definition: runtime.cc:5663
ContextLookupFlags
Definition: contexts.h:15
@ DONT_FOLLOW_CHAINS
Definition: contexts.h:19
@ FOLLOW_CHAINS
Definition: contexts.h:20
bool IsFastSmiElementsKind(ElementsKind kind)
static bool SetScopeVariableValue(ScopeIterator *it, int index, Handle< String > variable_name, Handle< Object > new_value)
Definition: runtime.cc:7085
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeLocalScope(Isolate *isolate, JavaScriptFrame *frame, int inlined_jsframe_index)
Definition: runtime.cc:6219
@ FUNCTION_SCOPE
Definition: globals.h:647
@ MODULE_SCOPE
Definition: globals.h:648
@ GLOBAL_SCOPE
Definition: globals.h:649
static MaybeHandle< Object > DebugEvaluate(Isolate *isolate, Handle< Context > context, Handle< Object > context_extension, Handle< Object > receiver, Handle< String > source)
Definition: runtime.cc:7457
static Handle< Object > DebugGetProperty(LookupIterator *it, bool *has_caught=NULL)
Definition: runtime.cc:5472
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeClosure(Isolate *isolate, Handle< Context > context)
Definition: runtime.cc:6326
static Handle< JSObject > NewJSObjectWithNullProto(Isolate *isolate)
Definition: runtime.cc:7494
bool IsAligned(T value, U alignment)
Definition: utils.h:123
static const int kFrameDetailsFirstDynamicIndex
Definition: runtime.cc:5787
@ ACCESSOR_GETTER
Definition: objects.h:1558
@ ACCESSOR_SETTER
Definition: objects.h:1559
static Handle< JSObject > NewStrictArguments(Isolate *isolate, Handle< JSFunction > callee, Object **parameters, int argument_count)
Definition: runtime.cc:3417
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeScopeDetails(Isolate *isolate, ScopeIterator *it)
Definition: runtime.cc:6940
static void PrintTransition(Isolate *isolate, Object *result)
Definition: runtime.cc:4385
static int compareUInt32(const uint32_t *ap, const uint32_t *bp)
Definition: runtime.cc:4829
static int StackSize(Isolate *isolate)
Definition: runtime.cc:4378
static ObjectPair MakePair(Object *x, Object *y)
static Handle< Object > GetPrototypeSkipHiddenPrototypes(Isolate *isolate, Handle< Object > receiver)
Definition: runtime.cc:670
@ DONT_INITIALIZE_ARRAY_ELEMENTS
Definition: heap.h:512
bool IsFastObjectElementsKind(ElementsKind kind)
static MUST_USE_RESULT MaybeHandle< JSObject > MaterializeArgumentsObject(Isolate *isolate, Handle< JSObject > target, Handle< JSFunction > function)
Definition: runtime.cc:7435
static const int kFrameDetailsFrameIdIndex
Definition: runtime.cc:5778
static Handle< JSObject > NewSloppyArguments(Isolate *isolate, Handle< JSFunction > callee, Object **parameters, int argument_count)
Definition: runtime.cc:3326
static const int kFrameDetailsLocalCountIndex
Definition: runtime.cc:5782
static const Runtime::Function kIntrinsicFunctions[]
Definition: runtime.cc:9264
MaybeHandle< Object > ArrayConstructInitializeElements(Handle< JSArray > array, Arguments *args)
Definition: elements.cc:1828
static bool SetCatchVariableValue(Isolate *isolate, Handle< Context > context, Handle< String > variable_name, Handle< Object > new_value)
Definition: runtime.cc:6421
@ RUNTIME_FUNCTION
Definition: serialize.h:23
@ KEEP_INOBJECT_PROPERTIES
Definition: objects.h:249
Debugger support for the V8 JavaScript engine.
Definition: accessors.cc:20
Maybe< T > maybe(T t)
Definition: v8.h:902
@ ACCESS_SET
Definition: v8.h:3521
@ ACCESS_KEYS
Definition: v8.h:3524
@ ACCESS_GET
Definition: v8.h:3520
#define TYPED_ARRAYS(V)
Definition: objects.h:4433
PropertyAttributes
@ DONT_ENUM
@ DONT_DELETE
@ ABSENT
@ SEALED
@ NONE
@ FROZEN
@ READ_ONLY
@ STRING
#define CONVERT_BOOLEAN_ARG_CHECKED(name, index)
Definition: runtime-utils.h:39
#define CONVERT_ARG_CHECKED(Type, name, index)
Definition: runtime-utils.h:24
#define RUNTIME_ASSERT(value)
Definition: runtime-utils.h:12
#define CONVERT_ARG_HANDLE_CHECKED(Type, name, index)
Definition: runtime-utils.h:28
#define CONVERT_NUMBER_CHECKED(type, name, Type, obj)
Definition: runtime-utils.h:60
#define RUNTIME_ASSERT_HANDLIFIED(value, T)
Definition: runtime-utils.h:15
#define CONVERT_DOUBLE_ARG_CHECKED(name, index)
Definition: runtime-utils.h:53
#define CONVERT_NUMBER_ARG_HANDLE_CHECKED(name, index)
Definition: runtime-utils.h:32
#define CONVERT_INT32_ARG_CHECKED(name, index)
Definition: runtime-utils.h:85
#define CONVERT_PROPERTY_DETAILS_CHECKED(name, index)
Definition: runtime-utils.h:68
#define CONVERT_STRICT_MODE_ARG_CHECKED(name, index)
Definition: runtime-utils.h:75
#define CONVERT_SMI_ARG_CHECKED(name, index)
Definition: runtime-utils.h:46
#define TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, size)
Definition: runtime.cc:8636
#define IO(name, number_of_args, result_size)
Definition: runtime.cc:9256
#define FIXED_TYPED_ARRAYS_CHECK_RUNTIME_FUNCTION(Type, type, TYPE, ctype, s)
Definition: runtime.cc:8647
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size)
#define RUNTIME_FUNCTION_LIST_RETURN_OBJECT(F)
Definition: runtime.h:642
#define RUNTIME_FUNCTION_LIST_RETURN_PAIR(F)
Definition: runtime.h:512
#define INLINE_OPTIMIZED_FUNCTION_LIST(F)
Definition: runtime.h:708
#define RUNTIME_FUNCTION_LIST(F)
Definition: runtime.h:651
#define INLINE_FUNCTION_LIST(F)
Definition: runtime.h:659
A simple Maybe type, representing an object which may or may not have a value.
Definition: v8.h:890