accessors.cc 30.8 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/accessors.h"
6

7
#include "src/api/api-inl.h"
8
#include "src/contexts.h"
9
#include "src/deoptimizer/deoptimizer.h"
10 11
#include "src/execution.h"
#include "src/frames-inl.h"
12
#include "src/heap/factory.h"
13
#include "src/isolate-inl.h"
14
#include "src/logging/counters.h"
15
#include "src/messages.h"
16
#include "src/objects/api-callbacks.h"
17
#include "src/objects/field-index-inl.h"
18
#include "src/objects/js-array-inl.h"
19
#include "src/objects/module-inl.h"
20 21
#include "src/objects/property-details.h"
#include "src/objects/prototype.h"
22

23 24
namespace v8 {
namespace internal {
25

26
Handle<AccessorInfo> Accessors::MakeAccessor(
27
    Isolate* isolate, Handle<Name> name, AccessorNameGetterCallback getter,
28
    AccessorNameBooleanSetterCallback setter) {
29
  Factory* factory = isolate->factory();
30
  Handle<AccessorInfo> info = factory->NewAccessorInfo();
31 32
  info->set_all_can_read(false);
  info->set_all_can_write(false);
33
  info->set_is_special_data_property(true);
34
  info->set_is_sloppy(false);
35
  info->set_replace_on_access(false);
36 37
  info->set_getter_side_effect_type(SideEffectType::kHasSideEffect);
  info->set_setter_side_effect_type(SideEffectType::kHasSideEffect);
38 39
  name = factory->InternalizeName(name);
  info->set_name(*name);
40
  Handle<Object> get = v8::FromCData(isolate, getter);
41
  if (setter == nullptr) setter = &ReconfigureToDataProperty;
42 43 44
  Handle<Object> set = v8::FromCData(isolate, setter);
  info->set_getter(*get);
  info->set_setter(*set);
45
  Address redirected = info->redirected_getter();
46
  if (redirected != kNullAddress) {
47 48 49
    Handle<Object> js_get = v8::FromCData(isolate, redirected);
    info->set_js_getter(*js_get);
  }
50 51 52
  return info;
}

53
static V8_INLINE bool CheckForName(Isolate* isolate, Handle<Name> name,
54 55 56
                                   Handle<String> property_name, int offset,
                                   FieldIndex::Encoding encoding,
                                   FieldIndex* index) {
57
  if (Name::Equals(isolate, name, property_name)) {
58
    *index = FieldIndex::ForInObjectOffset(offset, encoding);
59 60 61 62 63 64
    return true;
  }
  return false;
}


65 66
// Returns true for properties that are accessors to object fields.
// If true, *object_offset contains offset of object field.
67 68
bool Accessors::IsJSObjectFieldAccessor(Isolate* isolate, Handle<Map> map,
                                        Handle<Name> name, FieldIndex* index) {
69 70
  switch (map->instance_type()) {
    case JS_ARRAY_TYPE:
71
      return CheckForName(isolate, name, isolate->factory()->length_string(),
72
                          JSArray::kLengthOffset, FieldIndex::kTagged, index);
73 74
    default:
      if (map->instance_type() < FIRST_NONSTRING_TYPE) {
75
        return CheckForName(isolate, name, isolate->factory()->length_string(),
76
                            String::kLengthOffset, FieldIndex::kWord32, index);
77 78 79 80 81 82
      }

      return false;
  }
}

83
V8_WARN_UNUSED_RESULT MaybeHandle<Object>
84
Accessors::ReplaceAccessorWithDataProperty(Handle<Object> receiver,
85 86 87
                                           Handle<JSObject> holder,
                                           Handle<Name> name,
                                           Handle<Object> value) {
88 89 90 91 92 93 94 95
  LookupIterator it(receiver, name, holder,
                    LookupIterator::OWN_SKIP_INTERCEPTOR);
  // Skip any access checks we might hit. This accessor should never hit in a
  // situation where the caller does not have access.
  if (it.state() == LookupIterator::ACCESS_CHECK) {
    CHECK(it.HasAccess());
    it.Next();
  }
96
  DCHECK(holder.is_identical_to(it.GetHolder<JSObject>()));
97 98 99 100 101
  CHECK_EQ(LookupIterator::ACCESSOR, it.state());
  it.ReconfigureDataProperty(value, it.property_attributes());
  return value;
}

102

103 104 105
//
// Accessors::ReconfigureToDataProperty
//
106 107
void Accessors::ReconfigureToDataProperty(
    v8::Local<v8::Name> key, v8::Local<v8::Value> val,
108
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
109
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
110
  RuntimeCallTimerScope stats_scope(
111
      isolate, RuntimeCallCounterId::kReconfigureToDataProperty);
112
  HandleScope scope(isolate);
113
  Handle<Object> receiver = Utils::OpenHandle(*info.This());
114 115 116 117
  Handle<JSObject> holder =
      Handle<JSObject>::cast(Utils::OpenHandle(*info.Holder()));
  Handle<Name> name = Utils::OpenHandle(*key);
  Handle<Object> value = Utils::OpenHandle(*val);
118 119
  MaybeHandle<Object> result =
      Accessors::ReplaceAccessorWithDataProperty(receiver, holder, name, value);
120 121 122 123 124
  if (result.is_null()) {
    isolate->OptionalRescheduleException(false);
  } else {
    info.GetReturnValue().Set(true);
  }
125
}
126

127

128 129 130 131 132 133 134 135 136 137
//
// Accessors::ArgumentsIterator
//


void Accessors::ArgumentsIteratorGetter(
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  DisallowHeapAllocation no_allocation;
  HandleScope scope(isolate);
138
  Object result = isolate->native_context()->array_values_iterator();
139 140 141
  info.GetReturnValue().Set(Utils::ToLocal(Handle<Object>(result, isolate)));
}

142
Handle<AccessorInfo> Accessors::MakeArgumentsIteratorInfo(Isolate* isolate) {
143
  Handle<Name> name = isolate->factory()->iterator_symbol();
144
  return MakeAccessor(isolate, name, &ArgumentsIteratorGetter, nullptr);
145 146 147
}


148 149 150 151 152
//
// Accessors::ArrayLength
//


153
void Accessors::ArrayLengthGetter(
154
    v8::Local<v8::Name> name,
155 156
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
157 158
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kArrayLengthGetter);
159
  DisallowHeapAllocation no_allocation;
160
  HandleScope scope(isolate);
161
  JSArray holder = JSArray::cast(*Utils::OpenHandle(*info.Holder()));
162
  Object result = holder->length();
163 164
  info.GetReturnValue().Set(Utils::ToLocal(Handle<Object>(result, isolate)));
}
165

166
void Accessors::ArrayLengthSetter(
167 168
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
169
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
170 171
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kArrayLengthSetter);
172
  HandleScope scope(isolate);
173

174 175
  DCHECK(Utils::OpenHandle(*name)->SameValue(
      ReadOnlyRoots(isolate).length_string()));
176

177
  Handle<JSReceiver> object = Utils::OpenHandle(*info.Holder());
178 179 180
  Handle<JSArray> array = Handle<JSArray>::cast(object);
  Handle<Object> length_obj = Utils::OpenHandle(*val);

181 182
  bool was_readonly = JSArray::HasReadOnlyLength(array);

183
  uint32_t length = 0;
184 185 186
  if (!JSArray::AnythingToArrayLength(isolate, length_obj, &length)) {
    isolate->OptionalRescheduleException(false);
    return;
187
  }
188

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
  if (!was_readonly && V8_UNLIKELY(JSArray::HasReadOnlyLength(array)) &&
      length != array->length()->Number()) {
    // AnythingToArrayLength() may have called setter re-entrantly and modified
    // its property descriptor. Don't perform this check if "length" was
    // previously readonly, as this may have been called during
    // DefineOwnPropertyIgnoreAttributes().
    if (info.ShouldThrowOnError()) {
      Factory* factory = isolate->factory();
      isolate->Throw(*factory->NewTypeError(
          MessageTemplate::kStrictReadOnlyProperty, Utils::OpenHandle(*name),
          i::Object::TypeOf(isolate, object), object));
      isolate->OptionalRescheduleException(false);
    } else {
      info.GetReturnValue().Set(false);
    }
    return;
  }

207
  JSArray::SetLength(array, length);
208

209 210 211 212 213
  uint32_t actual_new_len = 0;
  CHECK(array->length()->ToArrayLength(&actual_new_len));
  // Fail if there were non-deletable elements.
  if (actual_new_len != length) {
    if (info.ShouldThrowOnError()) {
214 215 216 217 218
      Factory* factory = isolate->factory();
      isolate->Throw(*factory->NewTypeError(
          MessageTemplate::kStrictDeleteProperty,
          factory->NewNumberFromUint(actual_new_len - 1), array));
      isolate->OptionalRescheduleException(false);
219 220
    } else {
      info.GetReturnValue().Set(false);
221
    }
222 223
  } else {
    info.GetReturnValue().Set(true);
224
  }
225 226
}

227
Handle<AccessorInfo> Accessors::MakeArrayLengthInfo(Isolate* isolate) {
228 229
  return MakeAccessor(isolate, isolate->factory()->length_string(),
                      &ArrayLengthGetter, &ArrayLengthSetter);
230 231 232 233 234 235 236 237 238 239
}

//
// Accessors::ModuleNamespaceEntry
//

void Accessors::ModuleNamespaceEntryGetter(
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
240
  JSModuleNamespace holder =
241 242
      JSModuleNamespace::cast(*Utils::OpenHandle(*info.Holder()));
  Handle<Object> result;
243 244
  if (!holder
           ->GetExport(isolate, Handle<String>::cast(Utils::OpenHandle(*name)))
245 246 247 248 249 250 251 252 253
           .ToHandle(&result)) {
    isolate->OptionalRescheduleException(false);
  } else {
    info.GetReturnValue().Set(Utils::ToLocal(result));
  }
}

void Accessors::ModuleNamespaceEntrySetter(
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
254
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
255 256 257 258 259 260 261 262 263 264 265 266
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
  Factory* factory = isolate->factory();
  Handle<JSModuleNamespace> holder =
      Handle<JSModuleNamespace>::cast(Utils::OpenHandle(*info.Holder()));

  if (info.ShouldThrowOnError()) {
    isolate->Throw(*factory->NewTypeError(
        MessageTemplate::kStrictReadOnlyProperty, Utils::OpenHandle(*name),
        i::Object::TypeOf(isolate, holder), holder));
    isolate->OptionalRescheduleException(false);
  } else {
267
    info.GetReturnValue().Set(false);
268 269 270
  }
}

271 272
Handle<AccessorInfo> Accessors::MakeModuleNamespaceEntryInfo(
    Isolate* isolate, Handle<String> name) {
273
  return MakeAccessor(isolate, name, &ModuleNamespaceEntryGetter,
274
                      &ModuleNamespaceEntrySetter);
275 276
}

277 278 279 280 281

//
// Accessors::StringLength
//

282
void Accessors::StringLengthGetter(
283
    v8::Local<v8::Name> name,
284 285
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
286 287
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kStringLengthGetter);
288 289
  DisallowHeapAllocation no_allocation;
  HandleScope scope(isolate);
290 291 292 293 294 295

  // We have a slight impedance mismatch between the external API and the way we
  // use callbacks internally: Externally, callbacks can only be used with
  // v8::Object, but internally we have callbacks on entities which are higher
  // in the hierarchy, in this case for String values.

296
  Object value = *Utils::OpenHandle(*v8::Local<v8::Value>(info.This()));
297 298 299 300
  if (!value->IsString()) {
    // Not a string value. That means that we either got a String wrapper or
    // a Value with a String wrapper in its prototype chain.
    value = JSValue::cast(*Utils::OpenHandle(*info.Holder()))->value();
301
  }
302
  Object result = Smi::FromInt(String::cast(value)->length());
303 304
  info.GetReturnValue().Set(Utils::ToLocal(Handle<Object>(result, isolate)));
}
305

306
Handle<AccessorInfo> Accessors::MakeStringLengthInfo(Isolate* isolate) {
307
  return MakeAccessor(isolate, isolate->factory()->length_string(),
308
                      &StringLengthGetter, nullptr);
309
}
310 311 312 313 314

//
// Accessors::FunctionPrototype
//

315 316 317 318 319 320 321 322 323
static Handle<Object> GetFunctionPrototype(Isolate* isolate,
                                           Handle<JSFunction> function) {
  if (!function->has_prototype()) {
    Handle<Object> proto = isolate->factory()->NewFunctionPrototype(function);
    JSFunction::SetPrototype(function, proto);
  }
  return Handle<Object>(function->prototype(), isolate);
}

324
void Accessors::FunctionPrototypeGetter(
325
    v8::Local<v8::Name> name,
326 327
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
328
  RuntimeCallTimerScope timer(isolate,
329
                              RuntimeCallCounterId::kFunctionPrototypeGetter);
330
  HandleScope scope(isolate);
331 332
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
333
  DCHECK(function->has_prototype_property());
334
  Handle<Object> result = GetFunctionPrototype(isolate, function);
335
  info.GetReturnValue().Set(Utils::ToLocal(result));
336 337
}

338
void Accessors::FunctionPrototypeSetter(
339 340
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
341
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
342
  RuntimeCallTimerScope timer(isolate,
343
                              RuntimeCallCounterId::kFunctionPrototypeSetter);
344 345
  HandleScope scope(isolate);
  Handle<Object> value = Utils::OpenHandle(*val);
346 347
  Handle<JSFunction> object =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
348
  DCHECK(object->has_prototype_property());
349 350
  JSFunction::SetPrototype(object, value);
  info.GetReturnValue().Set(true);
351 352
}

353
Handle<AccessorInfo> Accessors::MakeFunctionPrototypeInfo(Isolate* isolate) {
354 355
  return MakeAccessor(isolate, isolate->factory()->prototype_string(),
                      &FunctionPrototypeGetter, &FunctionPrototypeSetter);
356
}
357 358 359 360 361 362 363


//
// Accessors::FunctionLength
//


364
void Accessors::FunctionLengthGetter(
365
    v8::Local<v8::Name> name,
366 367
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
368 369
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kFunctionLengthGetter);
370
  HandleScope scope(isolate);
371 372
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
373
  int length = function->length();
374
  Handle<Object> result(Smi::FromInt(length), isolate);
375
  info.GetReturnValue().Set(Utils::ToLocal(result));
376 377
}

378
Handle<AccessorInfo> Accessors::MakeFunctionLengthInfo(Isolate* isolate) {
379
  return MakeAccessor(isolate, isolate->factory()->length_string(),
380
                      &FunctionLengthGetter, &ReconfigureToDataProperty);
381
}
382 383 384 385 386 387 388


//
// Accessors::FunctionName
//


389
void Accessors::FunctionNameGetter(
390
    v8::Local<v8::Name> name,
391 392 393
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
394 395
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
396
  Handle<Object> result = JSFunction::GetName(isolate, function);
397
  info.GetReturnValue().Set(Utils::ToLocal(result));
398 399
}

400
Handle<AccessorInfo> Accessors::MakeFunctionNameInfo(Isolate* isolate) {
401
  return MakeAccessor(isolate, isolate->factory()->name_string(),
402
                      &FunctionNameGetter, &ReconfigureToDataProperty);
403
}
404 405 406 407 408 409


//
// Accessors::FunctionArguments
//

410
namespace {
411

412 413 414
Handle<JSObject> ArgumentsForInlinedFunction(JavaScriptFrame* frame,
                                             int inlined_frame_index) {
  Isolate* isolate = frame->isolate();
415
  Factory* factory = isolate->factory();
jarin@chromium.org's avatar
jarin@chromium.org committed
416

417
  TranslatedState translated_values(frame);
418
  translated_values.Prepare(frame->fp());
419 420 421 422 423 424 425

  int argument_count = 0;
  TranslatedFrame* translated_frame =
      translated_values.GetArgumentsInfoFromJSFrameIndex(inlined_frame_index,
                                                         &argument_count);
  TranslatedFrame::iterator iter = translated_frame->begin();

426 427 428
  // Materialize the function.
  bool should_deoptimize = iter->IsMaterializedObject();
  Handle<JSFunction> function = Handle<JSFunction>::cast(iter->GetValue());
429 430
  iter++;

431 432 433 434
  // Skip the receiver.
  iter++;
  argument_count--;

435
  Handle<JSObject> arguments =
436
      factory->NewArgumentsObject(function, argument_count);
437 438
  Handle<FixedArray> array = factory->NewFixedArray(argument_count);
  for (int i = 0; i < argument_count; ++i) {
439 440
    // If we materialize any object, we should deoptimize the frame because we
    // might alias an object that was eliminated by escape analysis.
441 442
    should_deoptimize = should_deoptimize || iter->IsMaterializedObject();
    Handle<Object> value = iter->GetValue();
443
    array->set(i, *value);
444
    iter++;
445 446 447
  }
  arguments->set_elements(*array);

448
  if (should_deoptimize) {
449
    translated_values.StoreMaterializedValuesAndDeopt(frame);
450 451
  }

452
  // Return the freshly allocated arguments object.
453
  return arguments;
454 455
}

456
int FindFunctionInFrame(JavaScriptFrame* frame, Handle<JSFunction> function) {
457
  std::vector<FrameSummary> frames;
458
  frame->Summarize(&frames);
459 460 461 462
  for (size_t i = frames.size(); i != 0; i--) {
    if (*frames[i - 1].AsJavaScript().function() == *function) {
      return static_cast<int>(i) - 1;
    }
463 464 465 466
  }
  return -1;
}

467 468 469 470
Handle<JSObject> GetFrameArguments(Isolate* isolate,
                                   JavaScriptFrameIterator* it,
                                   int function_index) {
  JavaScriptFrame* frame = it->frame();
471

472 473 474 475 476 477 478
  if (function_index > 0) {
    // The function in question was inlined.  Inlined functions have the
    // correct number of arguments and no allocated arguments object, so
    // we can construct a fresh one by interpreting the function's
    // deoptimization input data.
    return ArgumentsForInlinedFunction(frame, function_index);
  }
479

480 481 482 483 484 485
  // Find the frame that holds the actual arguments passed to the function.
  if (it->frame()->has_adapted_arguments()) {
    it->AdvanceOneFrame();
    DCHECK(it->frame()->is_arguments_adaptor());
  }
  frame = it->frame();
486

487 488 489 490 491 492 493 494 495 496 497
  // Get the number of arguments and construct an arguments object
  // mirror for the right frame and the underlying function.
  const int length = frame->ComputeParametersCount();
  Handle<JSFunction> function(frame->function(), isolate);
  Handle<JSObject> arguments =
      isolate->factory()->NewArgumentsObject(function, length);
  Handle<FixedArray> array = isolate->factory()->NewFixedArray(length);

  // Copy the parameters to the arguments object.
  DCHECK(array->length() == length);
  for (int i = 0; i < length; i++) {
498
    Object value = frame->GetParameter(i);
499 500 501 502
    if (value->IsTheHole(isolate)) {
      // Generators currently use holes as dummy arguments when resuming.  We
      // must not leak those.
      DCHECK(IsResumableFunction(function->shared()->kind()));
503
      value = ReadOnlyRoots(isolate).undefined_value();
504
    }
505
    array->set(i, value);
506
  }
507
  arguments->set_elements(*array);
508

509 510
  // Return the freshly allocated arguments object.
  return arguments;
511 512
}

513 514
}  // namespace

515 516 517 518 519 520 521 522 523 524 525 526
Handle<JSObject> Accessors::FunctionGetArguments(JavaScriptFrame* frame,
                                                 int inlined_jsframe_index) {
  Isolate* isolate = frame->isolate();
  Address requested_frame_fp = frame->fp();
  // Forward a frame iterator to the requested frame. This is needed because we
  // potentially need for advance it to the arguments adaptor frame later.
  for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) {
    if (it.frame()->fp() != requested_frame_fp) continue;
    return GetFrameArguments(isolate, &it, inlined_jsframe_index);
  }
  UNREACHABLE();  // Requested frame not found.
  return Handle<JSObject>();
527 528 529
}


530
void Accessors::FunctionArgumentsGetter(
531
    v8::Local<v8::Name> name,
532 533
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
534
  HandleScope scope(isolate);
535 536
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
537 538 539 540 541 542 543 544 545 546 547 548
  Handle<Object> result = isolate->factory()->null_value();
  if (!function->shared()->native()) {
    // Find the top invocation of the function by traversing frames.
    for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) {
      JavaScriptFrame* frame = it.frame();
      int function_index = FindFunctionInFrame(frame, function);
      if (function_index >= 0) {
        result = GetFrameArguments(isolate, &it, function_index);
        break;
      }
    }
  }
549
  info.GetReturnValue().Set(Utils::ToLocal(result));
550 551
}

552
Handle<AccessorInfo> Accessors::MakeFunctionArgumentsInfo(Isolate* isolate) {
553
  return MakeAccessor(isolate, isolate->factory()->arguments_string(),
554
                      &FunctionArgumentsGetter, nullptr);
555
}
556 557 558 559 560 561


//
// Accessors::FunctionCaller
//

562
static inline bool AllowAccessToFunction(Context current_context,
563
                                         JSFunction function) {
564 565 566
  return current_context->HasSameSecurityTokenAs(function->context());
}

567 568
class FrameFunctionIterator {
 public:
569
  explicit FrameFunctionIterator(Isolate* isolate)
570
      : isolate_(isolate), frame_iterator_(isolate), inlined_frame_index_(-1) {
571
    GetFrames();
572
  }
573 574

  // Iterate through functions until the first occurrence of 'function'.
575
  // Returns true if one is found, and false if the iterator ends before.
576 577
  bool Find(Handle<JSFunction> function) {
    do {
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
      if (!next().ToHandle(&function_)) return false;
    } while (!function_.is_identical_to(function));
    return true;
  }

  // Iterate through functions until the next non-toplevel one is found.
  // Returns true if one is found, and false if the iterator ends before.
  bool FindNextNonTopLevel() {
    do {
      if (!next().ToHandle(&function_)) return false;
    } while (function_->shared()->is_toplevel());
    return true;
  }

  // Iterate through function until the first native or user-provided function
  // is found. Functions not defined in user-provided scripts are not visible
  // unless directly exposed, in which case the native flag is set on them.
  // Returns true if one is found, and false if the iterator ends before.
  bool FindFirstNativeOrUserJavaScript() {
    while (!function_->shared()->native() &&
           !function_->shared()->IsUserJavaScript()) {
      if (!next().ToHandle(&function_)) return false;
    }
601 602 603
    return true;
  }

604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
  // In case of inlined frames the function could have been materialized from
  // deoptimization information. If that is the case we need to make sure that
  // subsequent call will see the same function, since we are about to hand out
  // the value to JavaScript. Make sure to store the materialized value and
  // trigger a deoptimization of the underlying frame.
  Handle<JSFunction> MaterializeFunction() {
    if (inlined_frame_index_ == 0) return function_;

    JavaScriptFrame* frame = frame_iterator_.frame();
    TranslatedState translated_values(frame);
    translated_values.Prepare(frame->fp());

    TranslatedFrame* translated_frame =
        translated_values.GetFrameFromJSFrameIndex(inlined_frame_index_);
    TranslatedFrame::iterator iter = translated_frame->begin();

    // First value is the function.
    bool should_deoptimize = iter->IsMaterializedObject();
    Handle<Object> value = iter->GetValue();
    if (should_deoptimize) {
      translated_values.StoreMaterializedValuesAndDeopt(frame);
    }

    return Handle<JSFunction>::cast(value);
  }

630
 private:
631 632
  MaybeHandle<JSFunction> next() {
    while (true) {
633
      if (inlined_frame_index_ <= 0) {
634 635 636
        if (!frame_iterator_.done()) {
          frame_iterator_.Advance();
          frames_.clear();
637
          inlined_frame_index_ = -1;
638 639 640 641
          GetFrames();
        }
        if (inlined_frame_index_ == -1) return MaybeHandle<JSFunction>();
      }
642 643

      --inlined_frame_index_;
644 645 646 647 648 649 650
      Handle<JSFunction> next_function =
          frames_[inlined_frame_index_].AsJavaScript().function();
      // Skip functions from other origins.
      if (!AllowAccessToFunction(isolate_->context(), *next_function)) continue;
      return next_function;
    }
  }
651
  void GetFrames() {
652
    DCHECK_EQ(-1, inlined_frame_index_);
653 654
    if (frame_iterator_.done()) return;
    JavaScriptFrame* frame = frame_iterator_.frame();
655
    frame->Summarize(&frames_);
656 657
    inlined_frame_index_ = static_cast<int>(frames_.size());
    DCHECK_LT(0, inlined_frame_index_);
658
  }
659
  Isolate* isolate_;
660
  Handle<JSFunction> function_;
661
  JavaScriptFrameIterator frame_iterator_;
662
  std::vector<FrameSummary> frames_;
663
  int inlined_frame_index_;
664 665 666
};


667 668
MaybeHandle<JSFunction> FindCaller(Isolate* isolate,
                                   Handle<JSFunction> function) {
669
  FrameFunctionIterator it(isolate);
670 671 672
  if (function->shared()->native()) {
    return MaybeHandle<JSFunction>();
  }
673 674
  // Find the function from the frames. Return null in case no frame
  // corresponding to the given function was found.
675
  if (!it.Find(function)) {
676
    return MaybeHandle<JSFunction>();
677
  }
678
  // Find previously called non-toplevel function.
679 680
  if (!it.FindNextNonTopLevel()) {
    return MaybeHandle<JSFunction>();
681
  }
682 683 684 685
  // Find the first user-land JavaScript function (or the entry point into
  // native JavaScript builtins in case such a builtin was the caller).
  if (!it.FindFirstNativeOrUserJavaScript()) {
    return MaybeHandle<JSFunction>();
686
  }
687 688 689 690 691 692 693

  // Materialize the function that the iterator is currently sitting on. Note
  // that this might trigger deoptimization in case the function was actually
  // materialized. Identity of the function must be preserved because we are
  // going to return it to JavaScript after this point.
  Handle<JSFunction> caller = it.MaterializeFunction();

694
  // Censor if the caller is not a sloppy mode function.
695 696
  // Change from ES5, which used to throw, see:
  // https://bugs.ecmascript.org/show_bug.cgi?id=310
697
  if (is_strict(caller->shared()->language_mode())) {
698 699
    return MaybeHandle<JSFunction>();
  }
700
  // Don't return caller from another security context.
701
  if (!AllowAccessToFunction(isolate->context(), *caller)) {
702 703
    return MaybeHandle<JSFunction>();
  }
704
  return caller;
705 706 707 708
}


void Accessors::FunctionCallerGetter(
709
    v8::Local<v8::Name> name,
710 711 712
    const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
713 714
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
715
  Handle<Object> result;
716 717 718 719 720
  MaybeHandle<JSFunction> maybe_caller;
  maybe_caller = FindCaller(isolate, function);
  Handle<JSFunction> caller;
  if (maybe_caller.ToHandle(&caller)) {
    result = caller;
721
  } else {
722
    result = isolate->factory()->null_value();
723
  }
724 725 726
  info.GetReturnValue().Set(Utils::ToLocal(result));
}

727
Handle<AccessorInfo> Accessors::MakeFunctionCallerInfo(Isolate* isolate) {
728
  return MakeAccessor(isolate, isolate->factory()->caller_string(),
729
                      &FunctionCallerGetter, nullptr);
730
}
731 732


733 734 735 736 737 738 739
//
// Accessors::BoundFunctionLength
//

void Accessors::BoundFunctionLengthGetter(
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
740
  RuntimeCallTimerScope timer(isolate,
741
                              RuntimeCallCounterId::kBoundFunctionLengthGetter);
742 743 744 745
  HandleScope scope(isolate);
  Handle<JSBoundFunction> function =
      Handle<JSBoundFunction>::cast(Utils::OpenHandle(*info.Holder()));

746 747
  int length = 0;
  if (!JSBoundFunction::GetLength(isolate, function).To(&length)) {
748 749 750 751 752 753 754
    isolate->OptionalRescheduleException(false);
    return;
  }
  Handle<Object> result(Smi::FromInt(length), isolate);
  info.GetReturnValue().Set(Utils::ToLocal(result));
}

755
Handle<AccessorInfo> Accessors::MakeBoundFunctionLengthInfo(Isolate* isolate) {
756
  return MakeAccessor(isolate, isolate->factory()->length_string(),
757
                      &BoundFunctionLengthGetter, &ReconfigureToDataProperty);
758 759 760 761 762 763 764 765 766
}

//
// Accessors::BoundFunctionName
//

void Accessors::BoundFunctionNameGetter(
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
767
  RuntimeCallTimerScope timer(isolate,
768
                              RuntimeCallCounterId::kBoundFunctionNameGetter);
769 770 771 772 773 774 775 776 777 778 779
  HandleScope scope(isolate);
  Handle<JSBoundFunction> function =
      Handle<JSBoundFunction>::cast(Utils::OpenHandle(*info.Holder()));
  Handle<Object> result;
  if (!JSBoundFunction::GetName(isolate, function).ToHandle(&result)) {
    isolate->OptionalRescheduleException(false);
    return;
  }
  info.GetReturnValue().Set(Utils::ToLocal(result));
}

780
Handle<AccessorInfo> Accessors::MakeBoundFunctionNameInfo(Isolate* isolate) {
781
  return MakeAccessor(isolate, isolate->factory()->name_string(),
782
                      &BoundFunctionNameGetter, &ReconfigureToDataProperty);
783 784
}

jgruber's avatar
jgruber committed
785 786 787 788 789 790 791 792 793 794 795
//
// Accessors::ErrorStack
//

void Accessors::ErrorStackGetter(
    v8::Local<v8::Name> key, const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
  Handle<JSObject> holder =
      Handle<JSObject>::cast(Utils::OpenHandle(*info.Holder()));

796 797 798
  // Retrieve the stack trace. It can either be structured data in the form of
  // a FrameArray, an already formatted stack trace (string) or whatever the
  // "prepareStackTrace" callback produced.
jgruber's avatar
jgruber committed
799 800 801 802

  Handle<Object> stack_trace;
  Handle<Symbol> stack_trace_symbol = isolate->factory()->stack_trace_symbol();
  MaybeHandle<Object> maybe_stack_trace =
803
      JSObject::GetProperty(isolate, holder, stack_trace_symbol);
jgruber's avatar
jgruber committed
804 805 806 807 808 809 810
  if (!maybe_stack_trace.ToHandle(&stack_trace) ||
      stack_trace->IsUndefined(isolate)) {
    Handle<Object> result = isolate->factory()->undefined_value();
    info.GetReturnValue().Set(Utils::ToLocal(result));
    return;
  }

811 812 813 814 815 816 817 818 819
  // Only format the stack-trace the first time around. The check for a
  // FixedArray is sufficient as the user callback can not create plain
  // FixedArrays and the result is a String in case we format the stack
  // trace ourselves.

  if (!stack_trace->IsFixedArray()) {
    info.GetReturnValue().Set(Utils::ToLocal(stack_trace));
    return;
  }
jgruber's avatar
jgruber committed
820 821

  Handle<Object> formatted_stack_trace;
822
  if (!ErrorUtils::FormatStackTrace(isolate, holder, stack_trace)
jgruber's avatar
jgruber committed
823 824 825 826 827
           .ToHandle(&formatted_stack_trace)) {
    isolate->OptionalRescheduleException(false);
    return;
  }

828 829 830 831 832
  // Replace the structured stack-trace with the formatting result.
  MaybeHandle<Object> result = Object::SetProperty(
      isolate, holder, isolate->factory()->stack_trace_symbol(),
      formatted_stack_trace, StoreOrigin::kMaybeKeyed,
      Just(ShouldThrow::kThrowOnError));
jgruber's avatar
jgruber committed
833 834 835 836 837 838 839 840 841
  if (result.is_null()) {
    isolate->OptionalRescheduleException(false);
    return;
  }

  v8::Local<v8::Value> value = Utils::ToLocal(formatted_stack_trace);
  info.GetReturnValue().Set(value);
}

842 843 844
void Accessors::ErrorStackSetter(
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
jgruber's avatar
jgruber committed
845 846
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
847 848
  Handle<JSObject> obj = Handle<JSObject>::cast(
      Utils::OpenHandle(*v8::Local<v8::Value>(info.This())));
849
  Handle<Object> value = Handle<Object>::cast(Utils::OpenHandle(*val));
jgruber's avatar
jgruber committed
850

851 852 853 854 855 856 857 858
  // Store the value in the internal symbol to avoid reconfiguration to
  // a data property.
  MaybeHandle<Object> result = Object::SetProperty(
      isolate, obj, isolate->factory()->stack_trace_symbol(), value,
      StoreOrigin::kMaybeKeyed, Just(ShouldThrow::kThrowOnError));
  if (result.is_null()) {
    isolate->OptionalRescheduleException(false);
    return;
jgruber's avatar
jgruber committed
859 860 861
  }
}

862
Handle<AccessorInfo> Accessors::MakeErrorStackInfo(Isolate* isolate) {
863 864
  return MakeAccessor(isolate, isolate->factory()->stack_string(),
                      &ErrorStackGetter, &ErrorStackSetter);
jgruber's avatar
jgruber committed
865
}
866

867 868
}  // namespace internal
}  // namespace v8