accessors.cc 31.6 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/builtins/accessors.h"
6

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

24 25
namespace v8 {
namespace internal {
26

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

54
static V8_INLINE bool CheckForName(Isolate* isolate, Handle<Name> name,
55 56 57
                                   Handle<String> property_name, int offset,
                                   FieldIndex::Encoding encoding,
                                   FieldIndex* index) {
58
  if (Name::Equals(isolate, name, property_name)) {
59
    *index = FieldIndex::ForInObjectOffset(offset, encoding);
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
//
// Accessors::ReconfigureToDataProperty
//
105 106
void Accessors::ReconfigureToDataProperty(
    v8::Local<v8::Name> key, v8::Local<v8::Value> val,
107
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
108
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
109
  RuntimeCallTimerScope stats_scope(
110
      isolate, RuntimeCallCounterId::kReconfigureToDataProperty);
111
  HandleScope scope(isolate);
112
  Handle<Object> receiver = Utils::OpenHandle(*info.This());
113 114 115 116
  Handle<JSObject> holder =
      Handle<JSObject>::cast(Utils::OpenHandle(*info.Holder()));
  Handle<Name> name = Utils::OpenHandle(*key);
  Handle<Object> value = Utils::OpenHandle(*val);
117 118
  MaybeHandle<Object> result =
      Accessors::ReplaceAccessorWithDataProperty(receiver, holder, name, value);
119 120 121 122 123
  if (result.is_null()) {
    isolate->OptionalRescheduleException(false);
  } else {
    info.GetReturnValue().Set(true);
  }
124
}
125

126 127 128 129 130 131 132 133 134
//
// 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);
135
  Object result = isolate->native_context()->array_values_iterator();
136 137 138
  info.GetReturnValue().Set(Utils::ToLocal(Handle<Object>(result, isolate)));
}

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

144 145 146 147
//
// Accessors::ArrayLength
//

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

160
void Accessors::ArrayLengthSetter(
161 162
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
163
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
164 165
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kArrayLengthSetter);
166
  HandleScope scope(isolate);
167

168 169
  DCHECK(Utils::OpenHandle(*name)->SameValue(
      ReadOnlyRoots(isolate).length_string()));
170

171
  Handle<JSReceiver> object = Utils::OpenHandle(*info.Holder());
172 173 174
  Handle<JSArray> array = Handle<JSArray>::cast(object);
  Handle<Object> length_obj = Utils::OpenHandle(*val);

175 176
  bool was_readonly = JSArray::HasReadOnlyLength(array);

177
  uint32_t length = 0;
178 179 180
  if (!JSArray::AnythingToArrayLength(isolate, length_obj, &length)) {
    isolate->OptionalRescheduleException(false);
    return;
181
  }
182

183
  if (!was_readonly && V8_UNLIKELY(JSArray::HasReadOnlyLength(array)) &&
184
      length != array->length().Number()) {
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    // 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;
  }

201
  JSArray::SetLength(array, length);
202

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

221
Handle<AccessorInfo> Accessors::MakeArrayLengthInfo(Isolate* isolate) {
222 223
  return MakeAccessor(isolate, isolate->factory()->length_string(),
                      &ArrayLengthGetter, &ArrayLengthSetter);
224 225 226 227 228 229 230 231 232 233
}

//
// 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);
234
  JSModuleNamespace holder =
235 236
      JSModuleNamespace::cast(*Utils::OpenHandle(*info.Holder()));
  Handle<Object> result;
237
  if (!holder.GetExport(isolate, Handle<String>::cast(Utils::OpenHandle(*name)))
238 239 240 241 242 243 244 245 246
           .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,
247
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
248 249 250 251 252 253 254 255 256 257 258 259
  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 {
260
    info.GetReturnValue().Set(false);
261 262 263
  }
}

264 265
Handle<AccessorInfo> Accessors::MakeModuleNamespaceEntryInfo(
    Isolate* isolate, Handle<String> name) {
266
  return MakeAccessor(isolate, name, &ModuleNamespaceEntryGetter,
267
                      &ModuleNamespaceEntrySetter);
268 269
}

270 271 272 273
//
// Accessors::StringLength
//

274
void Accessors::StringLengthGetter(
275
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
276
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
277 278
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kStringLengthGetter);
279 280
  DisallowHeapAllocation no_allocation;
  HandleScope scope(isolate);
281 282 283 284 285 286

  // 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.

287
  Object value = *Utils::OpenHandle(*v8::Local<v8::Value>(info.This()));
288
  if (!value.IsString()) {
289 290
    // Not a string value. That means that we either got a String wrapper or
    // a Value with a String wrapper in its prototype chain.
291 292
    value =
        JSPrimitiveWrapper::cast(*Utils::OpenHandle(*info.Holder())).value();
293
  }
294
  Object result = Smi::FromInt(String::cast(value).length());
295 296
  info.GetReturnValue().Set(Utils::ToLocal(Handle<Object>(result, isolate)));
}
297

298
Handle<AccessorInfo> Accessors::MakeStringLengthInfo(Isolate* isolate) {
299
  return MakeAccessor(isolate, isolate->factory()->length_string(),
300
                      &StringLengthGetter, nullptr);
301
}
302 303 304 305 306

//
// Accessors::FunctionPrototype
//

307 308 309
static Handle<Object> GetFunctionPrototype(Isolate* isolate,
                                           Handle<JSFunction> function) {
  if (!function->has_prototype()) {
310
    Handle<JSObject> proto = isolate->factory()->NewFunctionPrototype(function);
311 312 313 314 315
    JSFunction::SetPrototype(function, proto);
  }
  return Handle<Object>(function->prototype(), isolate);
}

316
void Accessors::FunctionPrototypeGetter(
317
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
318
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
319
  RuntimeCallTimerScope timer(isolate,
320
                              RuntimeCallCounterId::kFunctionPrototypeGetter);
321
  HandleScope scope(isolate);
322 323
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
324
  DCHECK(function->has_prototype_property());
325
  Handle<Object> result = GetFunctionPrototype(isolate, function);
326
  info.GetReturnValue().Set(Utils::ToLocal(result));
327 328
}

329
void Accessors::FunctionPrototypeSetter(
330 331
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
332
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
333
  RuntimeCallTimerScope timer(isolate,
334
                              RuntimeCallCounterId::kFunctionPrototypeSetter);
335 336
  HandleScope scope(isolate);
  Handle<Object> value = Utils::OpenHandle(*val);
337 338
  Handle<JSFunction> object =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
339
  DCHECK(object->has_prototype_property());
340 341
  JSFunction::SetPrototype(object, value);
  info.GetReturnValue().Set(true);
342 343
}

344
Handle<AccessorInfo> Accessors::MakeFunctionPrototypeInfo(Isolate* isolate) {
345 346
  return MakeAccessor(isolate, isolate->factory()->prototype_string(),
                      &FunctionPrototypeGetter, &FunctionPrototypeSetter);
347
}
348 349 350 351 352

//
// Accessors::FunctionLength
//

353
void Accessors::FunctionLengthGetter(
354
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
355
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
356 357
  RuntimeCallTimerScope timer(isolate,
                              RuntimeCallCounterId::kFunctionLengthGetter);
358
  HandleScope scope(isolate);
359 360
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
361
  int length = function->length();
362
  Handle<Object> result(Smi::FromInt(length), isolate);
363
  info.GetReturnValue().Set(Utils::ToLocal(result));
364 365
}

366
Handle<AccessorInfo> Accessors::MakeFunctionLengthInfo(Isolate* isolate) {
367
  return MakeAccessor(isolate, isolate->factory()->length_string(),
368
                      &FunctionLengthGetter, &ReconfigureToDataProperty);
369
}
370 371 372 373 374

//
// Accessors::FunctionName
//

375
void Accessors::FunctionNameGetter(
376
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
377 378
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
379 380
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
381
  Handle<Object> result = JSFunction::GetName(isolate, function);
382
  info.GetReturnValue().Set(Utils::ToLocal(result));
383 384
}

385
Handle<AccessorInfo> Accessors::MakeFunctionNameInfo(Isolate* isolate) {
386
  return MakeAccessor(isolate, isolate->factory()->name_string(),
387
                      &FunctionNameGetter, &ReconfigureToDataProperty);
388
}
389 390 391 392 393

//
// Accessors::FunctionArguments
//

394
namespace {
395

396 397 398
Handle<JSObject> ArgumentsForInlinedFunction(JavaScriptFrame* frame,
                                             int inlined_frame_index) {
  Isolate* isolate = frame->isolate();
399
  Factory* factory = isolate->factory();
jarin@chromium.org's avatar
jarin@chromium.org committed
400

401
  TranslatedState translated_values(frame);
402
  translated_values.Prepare(frame->fp());
403 404 405 406 407 408 409

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

410 411 412
  // Materialize the function.
  bool should_deoptimize = iter->IsMaterializedObject();
  Handle<JSFunction> function = Handle<JSFunction>::cast(iter->GetValue());
413 414
  iter++;

415 416 417 418
  // Skip the receiver.
  iter++;
  argument_count--;

419
  Handle<JSObject> arguments =
420
      factory->NewArgumentsObject(function, argument_count);
421 422
  Handle<FixedArray> array = factory->NewFixedArray(argument_count);
  for (int i = 0; i < argument_count; ++i) {
423 424
    // If we materialize any object, we should deoptimize the frame because we
    // might alias an object that was eliminated by escape analysis.
425 426
    should_deoptimize = should_deoptimize || iter->IsMaterializedObject();
    Handle<Object> value = iter->GetValue();
427
    array->set(i, *value);
428
    iter++;
429 430 431
  }
  arguments->set_elements(*array);

432
  if (should_deoptimize) {
433
    translated_values.StoreMaterializedValuesAndDeopt(frame);
434 435
  }

436
  // Return the freshly allocated arguments object.
437
  return arguments;
438 439
}

440
int FindFunctionInFrame(JavaScriptFrame* frame, Handle<JSFunction> function) {
441
  std::vector<FrameSummary> frames;
442
  frame->Summarize(&frames);
443 444 445 446
  for (size_t i = frames.size(); i != 0; i--) {
    if (*frames[i - 1].AsJavaScript().function() == *function) {
      return static_cast<int>(i) - 1;
    }
447 448 449 450
  }
  return -1;
}

451 452 453 454
Handle<JSObject> GetFrameArguments(Isolate* isolate,
                                   JavaScriptFrameIterator* it,
                                   int function_index) {
  JavaScriptFrame* frame = it->frame();
455

456 457 458 459 460 461 462
  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);
  }
463

464 465 466 467 468 469
  // 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();
470

471 472 473 474 475 476 477 478 479 480 481
  // 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++) {
482
    Object value = frame->GetParameter(i);
483
    if (value.IsTheHole(isolate)) {
484 485
      // Generators currently use holes as dummy arguments when resuming.  We
      // must not leak those.
486
      DCHECK(IsResumableFunction(function->shared().kind()));
487
      value = ReadOnlyRoots(isolate).undefined_value();
488
    }
489
    array->set(i, value);
490
  }
491
  arguments->set_elements(*array);
492

493 494
  // Return the freshly allocated arguments object.
  return arguments;
495 496
}

497 498
}  // namespace

499 500 501 502 503 504 505 506 507 508 509 510
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>();
511 512
}

513
void Accessors::FunctionArgumentsGetter(
514
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
515
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
516
  HandleScope scope(isolate);
517 518
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
519
  Handle<Object> result = isolate->factory()->null_value();
520
  if (!function->shared().native()) {
521 522 523 524 525 526 527 528 529 530
    // 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;
      }
    }
  }
531
  info.GetReturnValue().Set(Utils::ToLocal(result));
532 533
}

534
Handle<AccessorInfo> Accessors::MakeFunctionArgumentsInfo(Isolate* isolate) {
535
  return MakeAccessor(isolate, isolate->factory()->arguments_string(),
536
                      &FunctionArgumentsGetter, nullptr);
537
}
538 539 540 541 542

//
// Accessors::FunctionCaller
//

543
static inline bool AllowAccessToFunction(Context current_context,
544
                                         JSFunction function) {
545
  return current_context.HasSameSecurityTokenAs(function.context());
546 547
}

548 549
class FrameFunctionIterator {
 public:
550
  explicit FrameFunctionIterator(Isolate* isolate)
551
      : isolate_(isolate), frame_iterator_(isolate), inlined_frame_index_(-1) {
552
    GetFrames();
553
  }
554 555

  // Iterate through functions until the first occurrence of 'function'.
556
  // Returns true if one is found, and false if the iterator ends before.
557 558
  bool Find(Handle<JSFunction> function) {
    do {
559 560 561 562 563 564 565 566 567 568
      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;
569
    } while (function_->shared().is_toplevel());
570 571 572 573 574 575 576 577
    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() {
578 579
    while (!function_->shared().native() &&
           !function_->shared().IsUserJavaScript()) {
580 581
      if (!next().ToHandle(&function_)) return false;
    }
582 583 584
    return true;
  }

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
  // 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);
  }

611
 private:
612 613
  MaybeHandle<JSFunction> next() {
    while (true) {
614
      if (inlined_frame_index_ <= 0) {
615 616 617
        if (!frame_iterator_.done()) {
          frame_iterator_.Advance();
          frames_.clear();
618
          inlined_frame_index_ = -1;
619 620 621 622
          GetFrames();
        }
        if (inlined_frame_index_ == -1) return MaybeHandle<JSFunction>();
      }
623 624

      --inlined_frame_index_;
625 626 627 628 629 630 631
      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;
    }
  }
632
  void GetFrames() {
633
    DCHECK_EQ(-1, inlined_frame_index_);
634 635
    if (frame_iterator_.done()) return;
    JavaScriptFrame* frame = frame_iterator_.frame();
636
    frame->Summarize(&frames_);
637 638
    inlined_frame_index_ = static_cast<int>(frames_.size());
    DCHECK_LT(0, inlined_frame_index_);
639
  }
640
  Isolate* isolate_;
641
  Handle<JSFunction> function_;
642
  JavaScriptFrameIterator frame_iterator_;
643
  std::vector<FrameSummary> frames_;
644
  int inlined_frame_index_;
645 646
};

647 648
MaybeHandle<JSFunction> FindCaller(Isolate* isolate,
                                   Handle<JSFunction> function) {
649
  FrameFunctionIterator it(isolate);
650
  if (function->shared().native()) {
651 652
    return MaybeHandle<JSFunction>();
  }
653 654
  // Find the function from the frames. Return null in case no frame
  // corresponding to the given function was found.
655
  if (!it.Find(function)) {
656
    return MaybeHandle<JSFunction>();
657
  }
658
  // Find previously called non-toplevel function.
659 660
  if (!it.FindNextNonTopLevel()) {
    return MaybeHandle<JSFunction>();
661
  }
662 663 664 665
  // 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>();
666
  }
667 668 669 670 671 672 673

  // 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();

674
  // Censor if the caller is not a sloppy mode function.
675 676
  // Change from ES5, which used to throw, see:
  // https://bugs.ecmascript.org/show_bug.cgi?id=310
677
  if (is_strict(caller->shared().language_mode())) {
678 679
    return MaybeHandle<JSFunction>();
  }
680
  // Don't return caller from another security context.
681
  if (!AllowAccessToFunction(isolate->context(), *caller)) {
682 683
    return MaybeHandle<JSFunction>();
  }
684
  return caller;
685 686 687
}

void Accessors::FunctionCallerGetter(
688
    v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
689 690
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
691 692
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
693
  Handle<Object> result;
694 695 696 697 698
  MaybeHandle<JSFunction> maybe_caller;
  maybe_caller = FindCaller(isolate, function);
  Handle<JSFunction> caller;
  if (maybe_caller.ToHandle(&caller)) {
    result = caller;
699
  } else {
700
    result = isolate->factory()->null_value();
701
  }
702 703 704
  info.GetReturnValue().Set(Utils::ToLocal(result));
}

705
Handle<AccessorInfo> Accessors::MakeFunctionCallerInfo(Isolate* isolate) {
706
  return MakeAccessor(isolate, isolate->factory()->caller_string(),
707
                      &FunctionCallerGetter, nullptr);
708
}
709

710 711 712 713 714 715 716
//
// 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());
717
  RuntimeCallTimerScope timer(isolate,
718
                              RuntimeCallCounterId::kBoundFunctionLengthGetter);
719 720 721 722
  HandleScope scope(isolate);
  Handle<JSBoundFunction> function =
      Handle<JSBoundFunction>::cast(Utils::OpenHandle(*info.Holder()));

723 724
  int length = 0;
  if (!JSBoundFunction::GetLength(isolate, function).To(&length)) {
725 726 727 728 729 730 731
    isolate->OptionalRescheduleException(false);
    return;
  }
  Handle<Object> result(Smi::FromInt(length), isolate);
  info.GetReturnValue().Set(Utils::ToLocal(result));
}

732
Handle<AccessorInfo> Accessors::MakeBoundFunctionLengthInfo(Isolate* isolate) {
733
  return MakeAccessor(isolate, isolate->factory()->length_string(),
734
                      &BoundFunctionLengthGetter, &ReconfigureToDataProperty);
735 736 737 738 739 740 741 742 743
}

//
// 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());
744
  RuntimeCallTimerScope timer(isolate,
745
                              RuntimeCallCounterId::kBoundFunctionNameGetter);
746 747 748 749 750 751 752 753 754 755 756
  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));
}

757
Handle<AccessorInfo> Accessors::MakeBoundFunctionNameInfo(Isolate* isolate) {
758
  return MakeAccessor(isolate, isolate->factory()->name_string(),
759
                      &BoundFunctionNameGetter, &ReconfigureToDataProperty);
760 761
}

jgruber's avatar
jgruber committed
762 763 764 765 766 767 768 769 770 771 772
//
// 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()));

773 774 775
  // 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
776 777 778 779

  Handle<Object> stack_trace;
  Handle<Symbol> stack_trace_symbol = isolate->factory()->stack_trace_symbol();
  MaybeHandle<Object> maybe_stack_trace =
780
      JSObject::GetProperty(isolate, holder, stack_trace_symbol);
jgruber's avatar
jgruber committed
781 782 783 784 785 786 787
  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;
  }

788 789 790 791 792 793 794 795 796
  // 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
797 798

  Handle<Object> formatted_stack_trace;
799
  if (!ErrorUtils::FormatStackTrace(isolate, holder, stack_trace)
jgruber's avatar
jgruber committed
800 801 802 803 804
           .ToHandle(&formatted_stack_trace)) {
    isolate->OptionalRescheduleException(false);
    return;
  }

805 806 807 808 809
  // 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
810 811 812 813 814 815 816 817 818
  if (result.is_null()) {
    isolate->OptionalRescheduleException(false);
    return;
  }

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

819 820 821
void Accessors::ErrorStackSetter(
    v8::Local<v8::Name> name, v8::Local<v8::Value> val,
    const v8::PropertyCallbackInfo<v8::Boolean>& info) {
jgruber's avatar
jgruber committed
822 823
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
824 825
  Handle<JSObject> obj = Handle<JSObject>::cast(
      Utils::OpenHandle(*v8::Local<v8::Value>(info.This())));
826
  Handle<Object> value = Handle<Object>::cast(Utils::OpenHandle(*val));
jgruber's avatar
jgruber committed
827

828 829 830 831 832 833 834 835
  // 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
836 837 838
  }
}

839
Handle<AccessorInfo> Accessors::MakeErrorStackInfo(Isolate* isolate) {
840 841
  return MakeAccessor(isolate, isolate->factory()->stack_string(),
                      &ErrorStackGetter, &ErrorStackSetter);
jgruber's avatar
jgruber committed
842
}
843

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
//
// Accessors::RegExpResultIndices
//

void Accessors::RegExpResultIndicesGetter(
    v8::Local<v8::Name> key, const v8::PropertyCallbackInfo<v8::Value>& info) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
  HandleScope scope(isolate);
  Handle<JSRegExpResult> regexp_result(
      Handle<JSRegExpResult>::cast(Utils::OpenHandle(*info.Holder())));
  Handle<Object> indices(
      JSRegExpResult::GetAndCacheIndices(isolate, regexp_result));
  info.GetReturnValue().Set(Utils::ToLocal(indices));
}

Handle<AccessorInfo> Accessors::MakeRegExpResultIndicesInfo(Isolate* isolate) {
  return MakeAccessor(isolate, isolate->factory()->indices_string(),
                      &RegExpResultIndicesGetter, nullptr);
}

864 865
}  // namespace internal
}  // namespace v8