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

5
#include "src/runtime/runtime-utils.h"
6

7 8
#include <vector>

9
#include "src/arguments.h"
10
#include "src/compiler.h"
11
#include "src/debug/debug-coverage.h"
12 13 14
#include "src/debug/debug-evaluate.h"
#include "src/debug/debug-frames.h"
#include "src/debug/debug-scopes.h"
15
#include "src/debug/debug.h"
16
#include "src/debug/liveedit.h"
17
#include "src/frames-inl.h"
yangguo's avatar
yangguo committed
18
#include "src/globals.h"
19 20
#include "src/interpreter/bytecodes.h"
#include "src/interpreter/interpreter.h"
21
#include "src/isolate-inl.h"
22
#include "src/objects/debug-objects-inl.h"
23
#include "src/runtime/runtime.h"
24
#include "src/snapshot/snapshot.h"
25
#include "src/wasm/wasm-objects-inl.h"
26 27 28 29

namespace v8 {
namespace internal {

30
RUNTIME_FUNCTION_RETURN_PAIR(Runtime_DebugBreakOnBytecode) {
31 32 33 34
  using interpreter::Bytecode;
  using interpreter::Bytecodes;
  using interpreter::OperandScale;

35
  SealHandleScope shs(isolate);
36
  DCHECK_EQ(1, args.length());
37
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
38
  HandleScope scope(isolate);
39 40
  // Return value can be changed by debugger. Last set value will be used as
  // return value.
41
  ReturnValueScope result_scope(isolate->debug());
42
  isolate->debug()->set_return_value(*value);
43 44 45

  // Get the top-most JavaScript frame.
  JavaScriptFrameIterator it(isolate);
46
  isolate->debug()->Break(it.frame(), handle(it.frame()->function()));
47 48 49 50 51 52 53 54

  // Return the handler from the original bytecode array.
  DCHECK(it.frame()->is_interpreted());
  InterpretedFrame* interpreted_frame =
      reinterpret_cast<InterpretedFrame*>(it.frame());
  SharedFunctionInfo* shared = interpreted_frame->function()->shared();
  BytecodeArray* bytecode_array = shared->bytecode_array();
  int bytecode_offset = interpreted_frame->GetBytecodeOffset();
55
  Bytecode bytecode = Bytecodes::FromByte(bytecode_array->get(bytecode_offset));
56 57 58 59 60
  if (Bytecodes::Returns(bytecode)) {
    // If we are returning (or suspending), reset the bytecode array on the
    // interpreted stack frame to the non-debug variant so that the interpreter
    // entry trampoline sees the return/suspend bytecode rather than the
    // DebugBreak.
61 62
    interpreted_frame->PatchBytecodeArray(bytecode_array);
  }
63

64 65 66
  // We do not have to deal with operand scale here. If the bytecode at the
  // break is prefixed by operand scaling, we would have patched over the
  // scaling prefix. We now simply dispatch to the handler for the prefix.
67 68
  // We need to deserialize now to ensure we don't hit the debug break again
  // after deserializing.
69
  OperandScale operand_scale = OperandScale::kSingle;
70 71
  isolate->interpreter()->GetAndMaybeDeserializeBytecodeHandler(bytecode,
                                                                operand_scale);
72

73 74
  return MakePair(isolate->debug()->return_value(),
                  Smi::FromInt(static_cast<uint8_t>(bytecode)));
75 76
}

77 78 79 80 81 82 83 84 85 86 87 88
RUNTIME_FUNCTION(Runtime_DebugBreakAtEntry) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
  USE(function);

  DCHECK(function->shared()->HasDebugInfo());
  DCHECK(function->shared()->GetDebugInfo()->BreakAtEntry());

  // Get the top-most JavaScript frame.
  JavaScriptFrameIterator it(isolate);
  DCHECK_EQ(*function, it.frame()->function());
89
  isolate->debug()->Break(it.frame(), function);
90 91 92

  return isolate->heap()->undefined_value();
}
93 94

RUNTIME_FUNCTION(Runtime_HandleDebuggerStatement) {
95
  SealHandleScope shs(isolate);
96
  DCHECK_EQ(0, args.length());
97
  if (isolate->debug()->break_points_active()) {
98
    isolate->debug()->HandleDebugBreak(kIgnoreIfTopFrameBlackboxed);
99
  }
100 101 102 103
  return isolate->heap()->undefined_value();
}


104
RUNTIME_FUNCTION(Runtime_ScheduleBreak) {
105
  SealHandleScope shs(isolate);
106
  DCHECK_EQ(0, args.length());
107 108 109 110 111
  isolate->stack_guard()->RequestDebugBreak();
  return isolate->heap()->undefined_value();
}

static Handle<Object> DebugGetProperty(LookupIterator* it,
112
                                       bool* has_caught = nullptr) {
113 114 115 116 117 118 119 120
  for (; it->IsFound(); it->Next()) {
    switch (it->state()) {
      case LookupIterator::NOT_FOUND:
      case LookupIterator::TRANSITION:
        UNREACHABLE();
      case LookupIterator::ACCESS_CHECK:
        // Ignore access checks.
        break;
121
      case LookupIterator::INTEGER_INDEXED_EXOTIC:
122 123 124 125 126 127 128 129
      case LookupIterator::INTERCEPTOR:
      case LookupIterator::JSPROXY:
        return it->isolate()->factory()->undefined_value();
      case LookupIterator::ACCESSOR: {
        Handle<Object> accessors = it->GetAccessors();
        if (!accessors->IsAccessorInfo()) {
          return it->isolate()->factory()->undefined_value();
        }
130
        MaybeHandle<Object> maybe_result =
131
            JSObject::GetPropertyWithAccessor(it);
132 133 134 135
        Handle<Object> result;
        if (!maybe_result.ToHandle(&result)) {
          result = handle(it->isolate()->pending_exception(), it->isolate());
          it->isolate()->clear_pending_exception();
136
          if (has_caught != nullptr) *has_caught = true;
137 138 139 140 141 142 143 144 145 146 147 148
        }
        return result;
      }

      case LookupIterator::DATA:
        return it->GetDataValue();
    }
  }

  return it->isolate()->factory()->undefined_value();
}

149 150 151 152 153
template <class IteratorType>
static MaybeHandle<JSArray> GetIteratorInternalProperties(
    Isolate* isolate, Handle<IteratorType> object) {
  Factory* factory = isolate->factory();
  Handle<IteratorType> iterator = Handle<IteratorType>::cast(object);
154
  const char* kind = nullptr;
155 156
  switch (iterator->map()->instance_type()) {
    case JS_MAP_KEY_ITERATOR_TYPE:
157 158
      kind = "keys";
      break;
159 160
    case JS_MAP_KEY_VALUE_ITERATOR_TYPE:
    case JS_SET_KEY_VALUE_ITERATOR_TYPE:
161 162
      kind = "entries";
      break;
163 164 165 166
    case JS_MAP_VALUE_ITERATOR_TYPE:
    case JS_SET_VALUE_ITERATOR_TYPE:
      kind = "values";
      break;
167
    default:
168
      UNREACHABLE();
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  }

  Handle<FixedArray> result = factory->NewFixedArray(2 * 3);
  Handle<String> has_more =
      factory->NewStringFromAsciiChecked("[[IteratorHasMore]]");
  result->set(0, *has_more);
  result->set(1, isolate->heap()->ToBoolean(iterator->HasMore()));

  Handle<String> index =
      factory->NewStringFromAsciiChecked("[[IteratorIndex]]");
  result->set(2, *index);
  result->set(3, iterator->index());

  Handle<String> iterator_kind =
      factory->NewStringFromAsciiChecked("[[IteratorKind]]");
  result->set(4, *iterator_kind);
  Handle<String> kind_str = factory->NewStringFromAsciiChecked(kind);
  result->set(5, *kind_str);
  return factory->NewJSArrayWithElements(result);
}


MaybeHandle<JSArray> Runtime::GetInternalProperties(Isolate* isolate,
                                                    Handle<Object> object) {
  Factory* factory = isolate->factory();
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  if (object->IsJSBoundFunction()) {
    Handle<JSBoundFunction> function = Handle<JSBoundFunction>::cast(object);

    Handle<FixedArray> result = factory->NewFixedArray(2 * 3);
    Handle<String> target =
        factory->NewStringFromAsciiChecked("[[TargetFunction]]");
    result->set(0, *target);
    result->set(1, function->bound_target_function());

    Handle<String> bound_this =
        factory->NewStringFromAsciiChecked("[[BoundThis]]");
    result->set(2, *bound_this);
    result->set(3, function->bound_this());

    Handle<String> bound_args =
        factory->NewStringFromAsciiChecked("[[BoundArgs]]");
    result->set(4, *bound_args);
    Handle<FixedArray> bound_arguments =
        factory->CopyFixedArray(handle(function->bound_arguments(), isolate));
    Handle<JSArray> arguments_array =
        factory->NewJSArrayWithElements(bound_arguments);
    result->set(5, *arguments_array);
    return factory->NewJSArrayWithElements(result);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  } else if (object->IsJSMapIterator()) {
    Handle<JSMapIterator> iterator = Handle<JSMapIterator>::cast(object);
    return GetIteratorInternalProperties(isolate, iterator);
  } else if (object->IsJSSetIterator()) {
    Handle<JSSetIterator> iterator = Handle<JSSetIterator>::cast(object);
    return GetIteratorInternalProperties(isolate, iterator);
  } else if (object->IsJSGeneratorObject()) {
    Handle<JSGeneratorObject> generator =
        Handle<JSGeneratorObject>::cast(object);

    const char* status = "suspended";
    if (generator->is_closed()) {
      status = "closed";
    } else if (generator->is_executing()) {
      status = "running";
    } else {
      DCHECK(generator->is_suspended());
    }

    Handle<FixedArray> result = factory->NewFixedArray(2 * 3);
    Handle<String> generator_status =
        factory->NewStringFromAsciiChecked("[[GeneratorStatus]]");
    result->set(0, *generator_status);
    Handle<String> status_str = factory->NewStringFromAsciiChecked(status);
    result->set(1, *status_str);

    Handle<String> function =
        factory->NewStringFromAsciiChecked("[[GeneratorFunction]]");
    result->set(2, *function);
    result->set(3, generator->function());

    Handle<String> receiver =
        factory->NewStringFromAsciiChecked("[[GeneratorReceiver]]");
    result->set(4, *receiver);
    result->set(5, generator->receiver());
    return factory->NewJSArrayWithElements(result);
253
  } else if (object->IsJSPromise()) {
254 255
    Handle<JSPromise> promise = Handle<JSPromise>::cast(object);
    const char* status = JSPromise::Status(promise->status());
256 257 258 259 260 261 262
    Handle<FixedArray> result = factory->NewFixedArray(2 * 2);
    Handle<String> promise_status =
        factory->NewStringFromAsciiChecked("[[PromiseStatus]]");
    result->set(0, *promise_status);
    Handle<String> status_str = factory->NewStringFromAsciiChecked(status);
    result->set(1, *status_str);

263 264 265 266
    Handle<Object> value_obj(promise->status() == Promise::kPending
                                 ? isolate->heap()->undefined_value()
                                 : promise->result(),
                             isolate);
267 268 269 270 271
    Handle<String> promise_value =
        factory->NewStringFromAsciiChecked("[[PromiseValue]]");
    result->set(2, *promise_value);
    result->set(3, *value_obj);
    return factory->NewJSArrayWithElements(result);
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  } else if (object->IsJSProxy()) {
    Handle<JSProxy> js_proxy = Handle<JSProxy>::cast(object);
    Handle<FixedArray> result = factory->NewFixedArray(3 * 2);

    Handle<String> handler_str =
        factory->NewStringFromAsciiChecked("[[Handler]]");
    result->set(0, *handler_str);
    result->set(1, js_proxy->handler());

    Handle<String> target_str =
        factory->NewStringFromAsciiChecked("[[Target]]");
    result->set(2, *target_str);
    result->set(3, js_proxy->target());

    Handle<String> is_revoked_str =
        factory->NewStringFromAsciiChecked("[[IsRevoked]]");
    result->set(4, *is_revoked_str);
    result->set(5, isolate->heap()->ToBoolean(js_proxy->IsRevoked()));
    return factory->NewJSArrayWithElements(result);
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  } else if (object->IsJSValue()) {
    Handle<JSValue> js_value = Handle<JSValue>::cast(object);

    Handle<FixedArray> result = factory->NewFixedArray(2);
    Handle<String> primitive_value =
        factory->NewStringFromAsciiChecked("[[PrimitiveValue]]");
    result->set(0, *primitive_value);
    result->set(1, js_value->value());
    return factory->NewJSArrayWithElements(result);
  }
  return factory->NewJSArray(0);
}


RUNTIME_FUNCTION(Runtime_DebugGetInternalProperties) {
  HandleScope scope(isolate);
307
  DCHECK_EQ(1, args.length());
308
  CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
309 310
  RETURN_RESULT_OR_FAILURE(isolate,
                           Runtime::GetInternalProperties(isolate, obj));
311 312 313
}


314 315 316 317 318 319 320 321 322
// Get debugger related details for an object property, in the following format:
// 0: Property value
// 1: Property details
// 2: Property value is exception
// 3: Getter function if defined
// 4: Setter function if defined
// Items 2-4 are only filled if the property has either a getter or a setter.
RUNTIME_FUNCTION(Runtime_DebugGetPropertyDetails) {
  HandleScope scope(isolate);
323
  DCHECK_EQ(2, args.length());
324
  CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
325 326 327 328 329 330
  CONVERT_ARG_HANDLE_CHECKED(Object, name_obj, 1);

  // Convert the {name_obj} to a Name.
  Handle<Name> name;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, name,
                                     Object::ToName(isolate, name_obj));
331 332 333 334

  // Make sure to set the current context to the context before the debugger was
  // entered (if the debugger is entered). The reason for switching context here
  // is that for some property lookups (accessors and interceptors) callbacks
335
  // into the embedding application can occur, and the embedding application
336 337 338 339 340 341 342 343 344 345
  // could have the assumption that its own native context is the current
  // context and not some internal debugger context.
  SaveContext save(isolate);
  if (isolate->debug()->in_debug_scope()) {
    isolate->set_context(*isolate->debug()->debugger_entry()->GetContext());
  }

  // Check if the name is trivially convertible to an index and get the element
  // if so.
  uint32_t index;
346 347
  // TODO(verwaest): Make sure DebugGetProperty can handle arrays, and remove
  // this special case.
348 349 350
  if (name->AsArrayIndex(&index)) {
    Handle<FixedArray> details = isolate->factory()->NewFixedArray(2);
    Handle<Object> element_or_char;
351 352
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
        isolate, element_or_char, JSReceiver::GetElement(isolate, obj, index));
353
    details->set(0, *element_or_char);
354
    details->set(1, PropertyDetails::Empty().AsSmi());
355 356 357
    return *isolate->factory()->NewJSArrayWithElements(details);
  }

358
  LookupIterator it(obj, name, LookupIterator::OWN);
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
  bool has_caught = false;
  Handle<Object> value = DebugGetProperty(&it, &has_caught);
  if (!it.IsFound()) return isolate->heap()->undefined_value();

  Handle<Object> maybe_pair;
  if (it.state() == LookupIterator::ACCESSOR) {
    maybe_pair = it.GetAccessors();
  }

  // If the callback object is a fixed array then it contains JavaScript
  // getter and/or setter.
  bool has_js_accessors = !maybe_pair.is_null() && maybe_pair->IsAccessorPair();
  Handle<FixedArray> details =
      isolate->factory()->NewFixedArray(has_js_accessors ? 6 : 3);
  details->set(0, *value);
  // TODO(verwaest): Get rid of this random way of handling interceptors.
  PropertyDetails d = it.state() == LookupIterator::INTERCEPTOR
376
                          ? PropertyDetails::Empty()
377 378 379 380 381
                          : it.property_details();
  details->set(1, d.AsSmi());
  details->set(
      2, isolate->heap()->ToBoolean(it.state() == LookupIterator::INTERCEPTOR));
  if (has_js_accessors) {
382
    Handle<AccessorPair> accessors = Handle<AccessorPair>::cast(maybe_pair);
383
    details->set(3, isolate->heap()->ToBoolean(has_caught));
384 385 386 387 388 389
    Handle<Object> getter =
        AccessorPair::GetComponent(accessors, ACCESSOR_GETTER);
    Handle<Object> setter =
        AccessorPair::GetComponent(accessors, ACCESSOR_SETTER);
    details->set(4, *getter);
    details->set(5, *setter);
390 391 392 393 394 395 396 397 398
  }

  return *isolate->factory()->NewJSArrayWithElements(details);
}


RUNTIME_FUNCTION(Runtime_DebugGetProperty) {
  HandleScope scope(isolate);

399
  DCHECK_EQ(2, args.length());
400

401
  CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
402 403 404 405 406 407
  CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);

  LookupIterator it(obj, name);
  return *DebugGetProperty(&it);
}

408
// Return the property kind calculated from the property details.
409
// args[0]: smi with property details.
410
RUNTIME_FUNCTION(Runtime_DebugPropertyKindFromDetails) {
411
  SealHandleScope shs(isolate);
412
  DCHECK_EQ(1, args.length());
413
  CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
414
  return Smi::FromInt(static_cast<int>(details.kind()));
415 416 417 418 419 420 421
}


// Return the property attribute calculated from the property details.
// args[0]: smi with property details.
RUNTIME_FUNCTION(Runtime_DebugPropertyAttributesFromDetails) {
  SealHandleScope shs(isolate);
422
  DCHECK_EQ(1, args.length());
423 424 425 426 427 428 429
  CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
  return Smi::FromInt(static_cast<int>(details.attributes()));
}


RUNTIME_FUNCTION(Runtime_CheckExecutionState) {
  SealHandleScope shs(isolate);
430
  DCHECK_EQ(1, args.length());
431
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
432
  CHECK(isolate->debug()->CheckExecutionState(break_id));
433 434 435 436 437 438
  return isolate->heap()->true_value();
}


RUNTIME_FUNCTION(Runtime_GetFrameCount) {
  HandleScope scope(isolate);
439
  DCHECK_EQ(1, args.length());
440
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
441
  CHECK(isolate->debug()->CheckExecutionState(break_id));
442 443 444 445 446 447

  // Count all frames which are relevant to debugging stack trace.
  int n = 0;
  StackFrame::Id id = isolate->debug()->break_frame_id();
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack frame count is 0.
448
    return Smi::kZero;
449 450
  }

451
  std::vector<FrameSummary> frames;
452
  for (StackTraceFrameIterator it(isolate, id); !it.done(); it.Advance()) {
453
    frames.clear();
454
    it.frame()->Summarize(&frames);
455
    for (size_t i = frames.size(); i != 0; i--) {
456
      // Omit functions from native and extension scripts.
457
      if (frames[i - 1].is_subject_to_debugging()) n++;
458 459 460 461 462 463 464 465
    }
  }
  return Smi::FromInt(n);
}

static const int kFrameDetailsFrameIdIndex = 0;
static const int kFrameDetailsReceiverIndex = 1;
static const int kFrameDetailsFunctionIndex = 2;
466 467 468 469 470 471 472 473
static const int kFrameDetailsScriptIndex = 3;
static const int kFrameDetailsArgumentCountIndex = 4;
static const int kFrameDetailsLocalCountIndex = 5;
static const int kFrameDetailsSourcePositionIndex = 6;
static const int kFrameDetailsConstructCallIndex = 7;
static const int kFrameDetailsAtReturnIndex = 8;
static const int kFrameDetailsFlagsIndex = 9;
static const int kFrameDetailsFirstDynamicIndex = 10;
474 475 476 477 478 479 480 481 482

// Return an array with frame details
// args[0]: number: break id
// args[1]: number: frame index
//
// The array returned contains the following information:
// 0: Frame id
// 1: Receiver
// 2: Function
483 484 485 486 487 488 489
// 3: Script
// 4: Argument count
// 5: Local count
// 6: Source position
// 7: Constructor call
// 8: Is at return
// 9: Flags
490 491 492 493 494
// Arguments name, value
// Locals name, value
// Return value if any
RUNTIME_FUNCTION(Runtime_GetFrameDetails) {
  HandleScope scope(isolate);
495
  DCHECK_EQ(2, args.length());
496
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
497
  CHECK(isolate->debug()->CheckExecutionState(break_id));
498 499 500 501 502 503 504 505 506 507 508

  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);
  Heap* heap = isolate->heap();

  // Find the relevant frame with the requested index.
  StackFrame::Id id = isolate->debug()->break_frame_id();
  if (id == StackFrame::NO_ID) {
    // If there are no JavaScript stack frames return undefined.
    return heap->undefined_value();
  }

509
  StackTraceFrameIterator it(isolate, id);
510
  // Inlined frame index in optimized frame, starting from outer function.
511
  int inlined_frame_index =
512
      DebugFrameHelper::FindIndexedNonNativeFrame(&it, index);
513
  if (inlined_frame_index == -1) return heap->undefined_value();
514

515
  FrameInspector frame_inspector(it.frame(), inlined_frame_index, isolate);
516 517 518

  // Traverse the saved contexts chain to find the active context for the
  // selected frame.
519 520
  SaveContext* save =
      DebugFrameHelper::FindSavedContextForFrame(isolate, it.frame());
521 522

  // Get the frame id.
523 524
  Handle<Object> frame_id(DebugFrameHelper::WrapFrameId(it.frame()->id()),
                          isolate);
525

526
  if (frame_inspector.IsWasm()) {
527 528 529 530 531 532 533 534
    // Create the details array (no dynamic information for wasm).
    Handle<FixedArray> details =
        isolate->factory()->NewFixedArray(kFrameDetailsFirstDynamicIndex);

    // Add the frame id.
    details->set(kFrameDetailsFrameIdIndex, *frame_id);

    // Add the function name.
535
    Handle<String> func_name = frame_inspector.GetFunctionName();
536 537 538 539 540 541 542 543
    details->set(kFrameDetailsFunctionIndex, *func_name);

    // Add the script wrapper
    Handle<Object> script_wrapper =
        Script::GetWrapper(frame_inspector.GetScript());
    details->set(kFrameDetailsScriptIndex, *script_wrapper);

    // Add the arguments count.
544
    details->set(kFrameDetailsArgumentCountIndex, Smi::kZero);
545 546

    // Add the locals count
547
    details->set(kFrameDetailsLocalCountIndex, Smi::kZero);
548 549

    // Add the source position.
550
    int position = frame_inspector.GetSourcePosition();
551
    details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position));
552 553 554 555 556 557 558 559 560 561 562

    // Add the constructor information.
    details->set(kFrameDetailsConstructCallIndex, heap->ToBoolean(false));

    // Add the at return information.
    details->set(kFrameDetailsAtReturnIndex, heap->ToBoolean(false));

    // Add flags to indicate information on whether this frame is
    //   bit 0: invoked in the debugger context.
    //   bit 1: optimized frame.
    //   bit 2: inlined in optimized frame
563
    int flags = inlined_frame_index << 2;
564 565 566 567 568 569 570 571
    if (*save->context() == *isolate->debug()->debug_context()) {
      flags |= 1 << 0;
    }
    details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags));

    return *isolate->factory()->NewJSArrayWithElements(details);
  }

572 573 574
  // Find source position in unoptimized code.
  int position = frame_inspector.GetSourcePosition();

575 576 577
  // Handle JavaScript frames.
  bool is_optimized = it.frame()->is_optimized();

578 579 580 581
  // Check for constructor frame.
  bool constructor = frame_inspector.IsConstructor();

  // Get scope info and read from it for local variable information.
582 583
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(frame_inspector.GetFunction());
584
  CHECK(function->shared()->IsSubjectToDebugging());
585 586 587 588 589
  Handle<SharedFunctionInfo> shared(function->shared());
  Handle<ScopeInfo> scope_info(shared->scope_info());
  DCHECK(*scope_info != ScopeInfo::Empty(isolate));

  // Get the locals names and values into a temporary array.
590 591 592 593 594 595
  Handle<Object> maybe_context = frame_inspector.GetContext();
  const int local_count_with_synthetic = maybe_context->IsContext()
                                             ? scope_info->LocalCount()
                                             : scope_info->StackLocalCount();
  int local_count = local_count_with_synthetic;
  for (int slot = 0; slot < local_count_with_synthetic; ++slot) {
596 597
    // Hide compiler-introduced temporary variables, whether on the stack or on
    // the context.
598 599 600
    if (ScopeInfo::VariableIsSynthetic(scope_info->LocalName(slot))) {
      local_count--;
    }
601 602
  }

603
  std::vector<Handle<Object>> locals;
604 605 606 607
  // Fill in the values of the locals.
  int i = 0;
  for (; i < scope_info->StackLocalCount(); ++i) {
    // Use the value from the stack.
608
    if (ScopeInfo::VariableIsSynthetic(scope_info->LocalName(i))) continue;
609
    locals.emplace_back(scope_info->LocalName(i), isolate);
610 611
    Handle<Object> value =
        frame_inspector.GetExpression(scope_info->StackLocalIndex(i));
612 613
    // TODO(yangguo): We convert optimized out values to {undefined} when they
    // are passed to the debugger. Eventually we should handle them somehow.
614 615 616
    if (value->IsOptimizedOut(isolate)) {
      value = isolate->factory()->undefined_value();
    }
617
    locals.push_back(value);
618
  }
619
  if (static_cast<int>(locals.size()) < local_count * 2) {
620
    // Get the context containing declarations.
621 622 623
    DCHECK(maybe_context->IsContext());
    Handle<Context> context(Context::cast(*maybe_context)->closure_context());

624 625
    for (; i < scope_info->LocalCount(); ++i) {
      Handle<String> name(scope_info->LocalName(i));
626
      if (ScopeInfo::VariableIsSynthetic(*name)) continue;
627 628 629
      VariableMode mode;
      InitializationFlag init_flag;
      MaybeAssignedFlag maybe_assigned_flag;
630
      locals.push_back(name);
631
      int context_slot_index = ScopeInfo::ContextSlotIndex(
632
          scope_info, name, &mode, &init_flag, &maybe_assigned_flag);
633
      Object* value = context->get(context_slot_index);
634
      locals.emplace_back(value, isolate);
635 636 637 638 639 640 641
    }
  }

  // Check whether this frame is positioned at return. If not top
  // frame or if the frame is optimized it cannot be at a return.
  bool at_return = false;
  if (!is_optimized && index == 0) {
642
    at_return = isolate->debug()->IsBreakAtReturn(it.javascript_frame());
643 644 645 646 647 648
  }

  // If positioned just before return find the value to be returned and add it
  // to the frame information.
  Handle<Object> return_value = isolate->factory()->undefined_value();
  if (at_return) {
649
    return_value = handle(isolate->debug()->return_value(), isolate);
650 651 652 653 654 655
  }

  // Now advance to the arguments adapter frame (if any). It contains all
  // the provided parameters whereas the function frame always have the number
  // of arguments matching the functions parameters. The rest of the
  // information (except for what is collected above) is the same.
656
  if ((inlined_frame_index == 0) &&
657
      it.javascript_frame()->has_adapted_arguments()) {
658 659
    it.AdvanceOneFrame();
    DCHECK(it.frame()->is_arguments_adaptor());
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    frame_inspector.SetArgumentsFrame(it.frame());
  }

  // Find the number of arguments to fill. At least fill the number of
  // parameters for the function and fill more if more parameters are provided.
  int argument_count = scope_info->ParameterCount();
  if (argument_count < frame_inspector.GetParametersCount()) {
    argument_count = frame_inspector.GetParametersCount();
  }

  // Calculate the size of the result.
  int details_size = kFrameDetailsFirstDynamicIndex +
                     2 * (argument_count + local_count) + (at_return ? 1 : 0);
  Handle<FixedArray> details = isolate->factory()->NewFixedArray(details_size);

  // Add the frame id.
  details->set(kFrameDetailsFrameIdIndex, *frame_id);

  // Add the function (same as in function frame).
679
  details->set(kFrameDetailsFunctionIndex, *(frame_inspector.GetFunction()));
680

681 682 683 684 685
  // Add the script wrapper
  Handle<Object> script_wrapper =
      Script::GetWrapper(frame_inspector.GetScript());
  details->set(kFrameDetailsScriptIndex, *script_wrapper);

686 687 688 689 690 691 692
  // Add the arguments count.
  details->set(kFrameDetailsArgumentCountIndex, Smi::FromInt(argument_count));

  // Add the locals count
  details->set(kFrameDetailsLocalCountIndex, Smi::FromInt(local_count));

  // Add the source position.
yangguo's avatar
yangguo committed
693
  if (position != kNoSourcePosition) {
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position));
  } else {
    details->set(kFrameDetailsSourcePositionIndex, heap->undefined_value());
  }

  // Add the constructor information.
  details->set(kFrameDetailsConstructCallIndex, heap->ToBoolean(constructor));

  // Add the at return information.
  details->set(kFrameDetailsAtReturnIndex, heap->ToBoolean(at_return));

  // Add flags to indicate information on whether this frame is
  //   bit 0: invoked in the debugger context.
  //   bit 1: optimized frame.
  //   bit 2: inlined in optimized frame
  int flags = 0;
  if (*save->context() == *isolate->debug()->debug_context()) {
    flags |= 1 << 0;
  }
  if (is_optimized) {
    flags |= 1 << 1;
715
    flags |= inlined_frame_index << 2;
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
  }
  details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags));

  // Fill the dynamic part.
  int details_index = kFrameDetailsFirstDynamicIndex;

  // Add arguments name and value.
  for (int i = 0; i < argument_count; i++) {
    // Name of the argument.
    if (i < scope_info->ParameterCount()) {
      details->set(details_index++, scope_info->ParameterName(i));
    } else {
      details->set(details_index++, heap->undefined_value());
    }

    // Parameter value.
    if (i < frame_inspector.GetParametersCount()) {
      // Get the value from the stack.
734
      details->set(details_index++, *(frame_inspector.GetParameter(i)));
735 736 737 738 739 740
    } else {
      details->set(details_index++, heap->undefined_value());
    }
  }

  // Add locals name and value from the temporary copy from the function frame.
741
  for (const auto& local : locals) details->set(details_index++, *local);
742 743 744 745 746 747 748

  // Add the value being returned.
  if (at_return) {
    details->set(details_index++, *return_value);
  }

  // Add the receiver (same as in function frame).
749
  Handle<Object> receiver = frame_inspector.GetReceiver();
750
  DCHECK(function->shared()->IsUserJavaScript());
751 752 753 754
  // Optimized frames only restore the receiver as best-effort (see
  // OptimizedFrame::Summarize).
  DCHECK_IMPLIES(!is_optimized && is_sloppy(shared->language_mode()),
                 receiver->IsJSReceiver());
755 756 757 758 759 760 761 762 763
  details->set(kFrameDetailsReceiverIndex, *receiver);

  DCHECK_EQ(details_size, details_index);
  return *isolate->factory()->NewJSArrayWithElements(details);
}


RUNTIME_FUNCTION(Runtime_GetScopeCount) {
  HandleScope scope(isolate);
764
  DCHECK_EQ(2, args.length());
765
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
766
  CHECK(isolate->debug()->CheckExecutionState(break_id));
767 768 769 770

  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);

  // Get the frame where the debugging is performed.
771
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
772 773 774 775
  StackTraceFrameIterator it(isolate, id);
  StandardFrame* frame = it.frame();
  if (it.frame()->is_wasm()) return 0;

776
  FrameInspector frame_inspector(frame, 0, isolate);
777 778 779

  // Count the visible scopes.
  int n = 0;
780
  for (ScopeIterator it(isolate, &frame_inspector); !it.Done(); it.Next()) {
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
    n++;
  }

  return Smi::FromInt(n);
}


// Return an array with scope details
// args[0]: number: break id
// args[1]: number: frame index
// args[2]: number: inlined frame index
// args[3]: number: scope index
//
// The array returned contains the following information:
// 0: Scope type
// 1: Scope object
RUNTIME_FUNCTION(Runtime_GetScopeDetails) {
  HandleScope scope(isolate);
799
  DCHECK_EQ(4, args.length());
800
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
801
  CHECK(isolate->debug()->CheckExecutionState(break_id));
802 803 804 805 806 807

  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);

  // Get the frame where the debugging is performed.
808
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
809 810 811
  StackTraceFrameIterator frame_it(isolate, id);
  // Wasm has no scopes, this must be javascript.
  JavaScriptFrame* frame = JavaScriptFrame::cast(frame_it.frame());
812
  FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
813 814 815

  // Find the requested scope.
  int n = 0;
816
  ScopeIterator it(isolate, &frame_inspector);
817 818 819 820 821 822
  for (; !it.Done() && n < index; it.Next()) {
    n++;
  }
  if (it.Done()) {
    return isolate->heap()->undefined_value();
  }
823
  RETURN_RESULT_OR_FAILURE(isolate, it.MaterializeScopeDetails());
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
}


// Return an array of scope details
// args[0]: number: break id
// args[1]: number: frame index
// args[2]: number: inlined frame index
// args[3]: boolean: ignore nested scopes
//
// The array returned contains arrays with the following information:
// 0: Scope type
// 1: Scope object
RUNTIME_FUNCTION(Runtime_GetAllScopesDetails) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 3 || args.length() == 4);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
840
  CHECK(isolate->debug()->CheckExecutionState(break_id));
841 842

  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
843
  CONVERT_NUMBER_CHECKED(int, inlined_frame_index, Int32, args[2]);
844

845
  ScopeIterator::Option option = ScopeIterator::DEFAULT;
846 847
  if (args.length() == 4) {
    CONVERT_BOOLEAN_ARG_CHECKED(flag, 3);
848
    if (flag) option = ScopeIterator::IGNORE_NESTED_SCOPES;
849 850 851
  }

  // Get the frame where the debugging is performed.
852
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
853 854
  StackTraceFrameIterator frame_it(isolate, id);
  StandardFrame* frame = frame_it.frame();
855

856 857 858 859
  // Handle wasm frames specially. They provide exactly two scopes (global /
  // local).
  if (frame->is_wasm_interpreter_entry()) {
    Handle<WasmDebugInfo> debug_info(
860
        WasmInterpreterEntryFrame::cast(frame)->debug_info(), isolate);
861 862 863 864 865
    return *WasmDebugInfo::GetScopeDetails(debug_info, frame->fp(),
                                           inlined_frame_index);
  }

  FrameInspector frame_inspector(frame, inlined_frame_index, isolate);
866
  std::vector<Handle<JSObject>> result;
867
  ScopeIterator it(isolate, &frame_inspector, option);
868 869 870
  for (; !it.Done(); it.Next()) {
    Handle<JSObject> details;
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details,
871
                                       it.MaterializeScopeDetails());
872
    result.push_back(details);
873 874
  }

875 876 877
  int result_size = static_cast<int>(result.size());
  Handle<FixedArray> array = isolate->factory()->NewFixedArray(result_size);
  for (int i = 0; i < result_size; ++i) {
878 879 880 881 882 883 884 885
    array->set(i, *result[i]);
  }
  return *isolate->factory()->NewJSArrayWithElements(array);
}


RUNTIME_FUNCTION(Runtime_GetFunctionScopeCount) {
  HandleScope scope(isolate);
886
  DCHECK_EQ(1, args.length());
887 888

  // Check arguments.
889
  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, function, 0);
890 891 892

  // Count the visible scopes.
  int n = 0;
893 894 895 896 897
  if (function->IsJSFunction()) {
    for (ScopeIterator it(isolate, Handle<JSFunction>::cast(function));
         !it.Done(); it.Next()) {
      n++;
    }
898 899 900 901 902 903 904 905
  }

  return Smi::FromInt(n);
}


RUNTIME_FUNCTION(Runtime_GetFunctionScopeDetails) {
  HandleScope scope(isolate);
906
  DCHECK_EQ(2, args.length());
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921

  // Check arguments.
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);

  // Find the requested scope.
  int n = 0;
  ScopeIterator it(isolate, fun);
  for (; !it.Done() && n < index; it.Next()) {
    n++;
  }
  if (it.Done()) {
    return isolate->heap()->undefined_value();
  }

922
  RETURN_RESULT_OR_FAILURE(isolate, it.MaterializeScopeDetails());
923 924
}

925 926 927 928
RUNTIME_FUNCTION(Runtime_GetGeneratorScopeCount) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());

929
  if (!args[0]->IsJSGeneratorObject()) return Smi::kZero;
930 931 932 933

  // Check arguments.
  CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, gen, 0);

934 935 936 937 938
  // Only inspect suspended generator scopes.
  if (!gen->is_suspended()) {
    return Smi::kZero;
  }

939 940 941 942 943 944 945 946 947 948 949
  // Count the visible scopes.
  int n = 0;
  for (ScopeIterator it(isolate, gen); !it.Done(); it.Next()) {
    n++;
  }

  return Smi::FromInt(n);
}

RUNTIME_FUNCTION(Runtime_GetGeneratorScopeDetails) {
  HandleScope scope(isolate);
950
  DCHECK_EQ(2, args.length());
951 952

  if (!args[0]->IsJSGeneratorObject()) {
953
    return isolate->heap()->undefined_value();
954 955 956 957 958 959
  }

  // Check arguments.
  CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, gen, 0);
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);

960 961 962 963 964
  // Only inspect suspended generator scopes.
  if (!gen->is_suspended()) {
    return isolate->heap()->undefined_value();
  }

965 966 967 968 969 970 971 972 973 974 975 976
  // Find the requested scope.
  int n = 0;
  ScopeIterator it(isolate, gen);
  for (; !it.Done() && n < index; it.Next()) {
    n++;
  }
  if (it.Done()) {
    return isolate->heap()->undefined_value();
  }

  RETURN_RESULT_OR_FAILURE(isolate, it.MaterializeScopeDetails());
}
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

static bool SetScopeVariableValue(ScopeIterator* it, int index,
                                  Handle<String> variable_name,
                                  Handle<Object> new_value) {
  for (int n = 0; !it->Done() && n < index; it->Next()) {
    n++;
  }
  if (it->Done()) {
    return false;
  }
  return it->SetVariableValue(variable_name, new_value);
}


// Change variable value in closure or local scope
// args[0]: number or JsFunction: break id or function
// args[1]: number: frame index (when arg[0] is break id)
// args[2]: number: inlined frame index (when arg[0] is break id)
// args[3]: number: scope index
// args[4]: string: variable name
// args[5]: object: new value
//
// Return true if success and false otherwise
RUNTIME_FUNCTION(Runtime_SetScopeVariableValue) {
  HandleScope scope(isolate);
1002
  DCHECK_EQ(6, args.length());
1003 1004 1005 1006 1007 1008 1009 1010 1011

  // Check arguments.
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[3]);
  CONVERT_ARG_HANDLE_CHECKED(String, variable_name, 4);
  CONVERT_ARG_HANDLE_CHECKED(Object, new_value, 5);

  bool res;
  if (args[0]->IsNumber()) {
    CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1012
    CHECK(isolate->debug()->CheckExecutionState(break_id));
1013 1014 1015 1016 1017

    CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
    CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);

    // Get the frame where the debugging is performed.
1018
    StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
1019 1020 1021
    StackTraceFrameIterator frame_it(isolate, id);
    // Wasm has no scopes, this must be javascript.
    JavaScriptFrame* frame = JavaScriptFrame::cast(frame_it.frame());
1022
    FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
1023

1024
    ScopeIterator it(isolate, &frame_inspector);
1025
    res = SetScopeVariableValue(&it, index, variable_name, new_value);
1026
  } else if (args[0]->IsJSFunction()) {
1027 1028 1029
    CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
    ScopeIterator it(isolate, fun);
    res = SetScopeVariableValue(&it, index, variable_name, new_value);
1030 1031 1032 1033
  } else {
    CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, gen, 0);
    ScopeIterator it(isolate, gen);
    res = SetScopeVariableValue(&it, index, variable_name, new_value);
1034 1035 1036 1037 1038 1039 1040 1041
  }

  return isolate->heap()->ToBoolean(res);
}


RUNTIME_FUNCTION(Runtime_GetBreakLocations) {
  HandleScope scope(isolate);
1042
  DCHECK_EQ(1, args.length());
1043
  CHECK(isolate->debug()->is_active());
1044 1045 1046 1047
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);

  Handle<SharedFunctionInfo> shared(fun->shared());
  // Find the number of break points
1048
  Handle<Object> break_locations = Debug::GetSourceBreakLocations(shared);
1049 1050 1051
  if (break_locations->IsUndefined(isolate)) {
    return isolate->heap()->undefined_value();
  }
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  // Return array as JS array
  return *isolate->factory()->NewJSArrayWithElements(
      Handle<FixedArray>::cast(break_locations));
}


// Change the state of break on exceptions.
// args[0]: Enum value indicating whether to affect caught/uncaught exceptions.
// args[1]: Boolean indicating on/off.
RUNTIME_FUNCTION(Runtime_ChangeBreakOnException) {
  HandleScope scope(isolate);
1063
  DCHECK_EQ(2, args.length());
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
  CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);
  CONVERT_BOOLEAN_ARG_CHECKED(enable, 1);

  // If the number doesn't match an enum value, the ChangeBreakOnException
  // function will default to affecting caught exceptions.
  ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
  // Update break point state.
  isolate->debug()->ChangeBreakOnException(type, enable);
  return isolate->heap()->undefined_value();
}


// Returns the state of break on exceptions
// args[0]: boolean indicating uncaught exceptions
RUNTIME_FUNCTION(Runtime_IsBreakOnException) {
  HandleScope scope(isolate);
1080
  DCHECK_EQ(1, args.length());
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  CONVERT_NUMBER_CHECKED(uint32_t, type_arg, Uint32, args[0]);

  ExceptionBreakType type = static_cast<ExceptionBreakType>(type_arg);
  bool result = isolate->debug()->IsBreakOnException(type);
  return Smi::FromInt(result);
}


// Prepare for stepping
// args[0]: break id for checking execution state
// args[1]: step action from the enumeration StepAction
// args[2]: number of times to perform the step, for step out it is the number
//          of frames to step down.
RUNTIME_FUNCTION(Runtime_PrepareStep) {
  HandleScope scope(isolate);
1096
  DCHECK_EQ(2, args.length());
1097
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1098
  CHECK(isolate->debug()->CheckExecutionState(break_id));
1099

1100
  if (!args[1]->IsNumber()) {
1101 1102 1103 1104 1105 1106
    return isolate->Throw(isolate->heap()->illegal_argument_string());
  }

  // Get the step action and check validity.
  StepAction step_action = static_cast<StepAction>(NumberToInt32(args[1]));
  if (step_action != StepIn && step_action != StepNext &&
1107
      step_action != StepOut) {
1108 1109 1110 1111 1112 1113 1114
    return isolate->Throw(isolate->heap()->illegal_argument_string());
  }

  // Clear all current stepping setup.
  isolate->debug()->ClearStepping();

  // Prepare step.
1115
  isolate->debug()->PrepareStep(static_cast<StepAction>(step_action));
1116 1117 1118 1119 1120 1121
  return isolate->heap()->undefined_value();
}

// Clear all stepping set by PrepareStep.
RUNTIME_FUNCTION(Runtime_ClearStepping) {
  HandleScope scope(isolate);
1122
  DCHECK_EQ(0, args.length());
1123
  CHECK(isolate->debug()->is_active());
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
  isolate->debug()->ClearStepping();
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_DebugEvaluate) {
  HandleScope scope(isolate);

  // Check the execution state and decode arguments frame and source to be
  // evaluated.
1134
  DCHECK_EQ(5, args.length());
1135
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1136
  CHECK(isolate->debug()->CheckExecutionState(break_id));
1137 1138 1139 1140

  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
  CONVERT_ARG_HANDLE_CHECKED(String, source, 3);
1141
  CONVERT_BOOLEAN_ARG_CHECKED(throw_on_side_effect, 4);
1142

1143
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
1144

1145
  RETURN_RESULT_OR_FAILURE(
1146 1147
      isolate, DebugEvaluate::Local(isolate, id, inlined_jsframe_index, source,
                                    throw_on_side_effect));
1148 1149 1150 1151 1152 1153 1154 1155
}


RUNTIME_FUNCTION(Runtime_DebugEvaluateGlobal) {
  HandleScope scope(isolate);

  // Check the execution state and decode arguments frame and source to be
  // evaluated.
1156
  DCHECK_EQ(2, args.length());
1157
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1158
  CHECK(isolate->debug()->CheckExecutionState(break_id));
1159 1160 1161

  CONVERT_ARG_HANDLE_CHECKED(String, source, 1);

1162 1163
  RETURN_RESULT_OR_FAILURE(isolate,
                           DebugEvaluate::Global(isolate, source, false));
1164 1165 1166 1167 1168
}


RUNTIME_FUNCTION(Runtime_DebugGetLoadedScripts) {
  HandleScope scope(isolate);
1169
  DCHECK_EQ(0, args.length());
1170

1171 1172 1173
  Handle<FixedArray> instances;
  {
    DebugScope debug_scope(isolate->debug());
1174 1175 1176 1177
    if (debug_scope.failed()) {
      DCHECK(isolate->has_pending_exception());
      return isolate->heap()->exception();
    }
1178 1179 1180
    // Fill the script objects.
    instances = isolate->debug()->GetLoadedScripts();
  }
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194

  // Convert the script objects to proper JS objects.
  for (int i = 0; i < instances->length(); i++) {
    Handle<Script> script = Handle<Script>(Script::cast(instances->get(i)));
    // Get the script wrapper in a local handle before calling GetScriptWrapper,
    // because using
    //   instances->set(i, *GetScriptWrapper(script))
    // is unsafe as GetScriptWrapper might call GC and the C++ compiler might
    // already have dereferenced the instances handle.
    Handle<JSObject> wrapper = Script::GetWrapper(script);
    instances->set(i, *wrapper);
  }

  // Return result as a JS array.
1195
  return *isolate->factory()->NewJSArrayWithElements(instances);
1196 1197
}

1198 1199
static bool HasInPrototypeChainIgnoringProxies(Isolate* isolate,
                                               JSObject* object,
1200
                                               Object* proto) {
1201
  PrototypeIterator iter(isolate, object, kStartAtReceiver);
1202 1203 1204
  while (true) {
    iter.AdvanceIgnoringProxies();
    if (iter.IsAtEnd()) return false;
1205
    if (iter.GetCurrent() == proto) return true;
1206 1207 1208 1209
  }
}


1210 1211 1212 1213 1214 1215
// Scan the heap for objects with direct references to an object
// args[0]: the object to find references to
// args[1]: constructor function for instances to exclude (Mirror)
// args[2]: the the maximum number of objects to return
RUNTIME_FUNCTION(Runtime_DebugReferencedBy) {
  HandleScope scope(isolate);
1216
  DCHECK_EQ(3, args.length());
1217
  CONVERT_ARG_HANDLE_CHECKED(JSObject, target, 0);
1218
  CONVERT_ARG_HANDLE_CHECKED(Object, filter, 1);
1219
  CHECK(filter->IsUndefined(isolate) || filter->IsJSObject());
1220
  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]);
1221
  CHECK_GE(max_references, 0);
1222

1223
  std::vector<Handle<JSObject>> instances;
1224 1225
  Heap* heap = isolate->heap();
  {
1226
    HeapIterator iterator(heap, HeapIterator::kFilterUnreachable);
1227 1228 1229
    // Get the constructor function for context extension and arguments array.
    Object* arguments_fun = isolate->sloppy_arguments_map()->GetConstructor();
    HeapObject* heap_obj;
1230
    while ((heap_obj = iterator.next()) != nullptr) {
1231
      if (!heap_obj->IsJSObject()) continue;
1232
      JSObject* obj = JSObject::cast(heap_obj);
1233 1234 1235 1236 1237
      if (obj->IsJSContextExtensionObject()) continue;
      if (obj->map()->GetConstructor() == arguments_fun) continue;
      if (!obj->ReferencesObject(*target)) continue;
      // Check filter if supplied. This is normally used to avoid
      // references from mirror objects.
1238
      if (!filter->IsUndefined(isolate) &&
1239
          HasInPrototypeChainIgnoringProxies(isolate, obj, *filter)) {
1240 1241 1242 1243
        continue;
      }
      if (obj->IsJSGlobalObject()) {
        obj = JSGlobalObject::cast(obj)->global_proxy();
1244
      }
1245 1246
      instances.emplace_back(obj);
      if (static_cast<int32_t>(instances.size()) == max_references) break;
1247 1248 1249
    }
    // Iterate the rest of the heap to satisfy HeapIterator constraints.
    while (iterator.next()) {
1250 1251 1252
    }
  }

1253
  Handle<FixedArray> result;
1254
  if (instances.size() == 1 && instances.back().is_identical_to(target)) {
1255 1256 1257 1258 1259 1260
    // Check for circular reference only. This can happen when the object is
    // only referenced from mirrors and has a circular reference in which case
    // the object is not really alive and would have been garbage collected if
    // not referenced from the mirror.
    result = isolate->factory()->empty_fixed_array();
  } else {
1261 1262 1263
    int instances_size = static_cast<int>(instances.size());
    result = isolate->factory()->NewFixedArray(instances_size);
    for (int i = 0; i < instances_size; ++i) result->set(i, *instances[i]);
1264 1265
  }
  return *isolate->factory()->NewJSArrayWithElements(result);
1266 1267 1268 1269 1270 1271 1272 1273
}


// Scan the heap for objects constructed by a specific function.
// args[0]: the constructor to find instances of
// args[1]: the the maximum number of objects to return
RUNTIME_FUNCTION(Runtime_DebugConstructedBy) {
  HandleScope scope(isolate);
1274
  DCHECK_EQ(2, args.length());
1275 1276
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, 0);
  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]);
1277
  CHECK_GE(max_references, 0);
1278

1279
  std::vector<Handle<JSObject>> instances;
1280 1281
  Heap* heap = isolate->heap();
  {
1282
    HeapIterator iterator(heap, HeapIterator::kFilterUnreachable);
1283
    HeapObject* heap_obj;
1284
    while ((heap_obj = iterator.next()) != nullptr) {
1285 1286 1287
      if (!heap_obj->IsJSObject()) continue;
      JSObject* obj = JSObject::cast(heap_obj);
      if (obj->map()->GetConstructor() != *constructor) continue;
1288 1289
      instances.emplace_back(obj);
      if (static_cast<int32_t>(instances.size()) == max_references) break;
1290 1291 1292 1293
    }
    // Iterate the rest of the heap to satisfy HeapIterator constraints.
    while (iterator.next()) {
    }
1294 1295
  }

1296 1297 1298
  int instances_size = static_cast<int>(instances.size());
  Handle<FixedArray> result = isolate->factory()->NewFixedArray(instances_size);
  for (int i = 0; i < instances_size; ++i) result->set(i, *instances[i]);
1299
  return *isolate->factory()->NewJSArrayWithElements(result);
1300 1301 1302 1303 1304 1305 1306
}


// Find the effective prototype object as returned by __proto__.
// args[0]: the object to find the prototype for.
RUNTIME_FUNCTION(Runtime_DebugGetPrototype) {
  HandleScope shs(isolate);
1307
  DCHECK_EQ(1, args.length());
1308
  CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
1309 1310
  // TODO(1543): Come up with a solution for clients to handle potential errors
  // thrown by an intermediate proxy.
1311
  RETURN_RESULT_OR_FAILURE(isolate, JSReceiver::GetPrototype(isolate, obj));
1312 1313 1314 1315
}


// Patches script source (should be called upon BeforeCompile event).
1316
// TODO(5530): Remove once uses in debug.js are gone.
1317 1318
RUNTIME_FUNCTION(Runtime_DebugSetScriptSource) {
  HandleScope scope(isolate);
1319
  DCHECK_EQ(2, args.length());
1320 1321 1322 1323

  CONVERT_ARG_HANDLE_CHECKED(JSValue, script_wrapper, 0);
  CONVERT_ARG_HANDLE_CHECKED(String, source, 1);

1324
  CHECK(script_wrapper->value()->IsScript());
1325 1326
  Handle<Script> script(Script::cast(script_wrapper->value()));

1327 1328 1329 1330 1331 1332
  // The following condition is not guaranteed to hold and a failure is also
  // propagated to callers. Hence we fail gracefully here and don't crash.
  if (script->compilation_state() != Script::COMPILATION_STATE_INITIAL) {
    return isolate->ThrowIllegalOperation();
  }

1333 1334 1335 1336 1337 1338 1339 1340
  script->set_source(*source);

  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_FunctionGetInferredName) {
  SealHandleScope shs(isolate);
1341
  DCHECK_EQ(1, args.length());
1342

1343 1344 1345 1346 1347
  CONVERT_ARG_CHECKED(Object, f, 0);
  if (f->IsJSFunction()) {
    return JSFunction::cast(f)->shared()->inferred_name();
  }
  return isolate->heap()->empty_string();
1348 1349 1350
}


1351 1352
RUNTIME_FUNCTION(Runtime_FunctionGetDebugName) {
  HandleScope scope(isolate);
1353 1354 1355
  DCHECK_EQ(1, args.length());

  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, function, 0);
1356

1357
  if (function->IsJSBoundFunction()) {
1358 1359 1360
    RETURN_RESULT_OR_FAILURE(
        isolate, JSBoundFunction::GetName(
                     isolate, Handle<JSBoundFunction>::cast(function)));
1361
  } else {
1362
    return *JSFunction::GetDebugName(Handle<JSFunction>::cast(function));
1363
  }
1364 1365 1366
}


1367 1368
RUNTIME_FUNCTION(Runtime_GetDebugContext) {
  HandleScope scope(isolate);
1369
  DCHECK_EQ(0, args.length());
1370 1371 1372
  Handle<Context> context;
  {
    DebugScope debug_scope(isolate->debug());
1373 1374 1375 1376
    if (debug_scope.failed()) {
      DCHECK(isolate->has_pending_exception());
      return isolate->heap()->exception();
    }
1377 1378
    context = isolate->debug()->GetDebugContext();
  }
1379
  if (context.is_null()) return isolate->heap()->undefined_value();
1380 1381 1382 1383 1384
  context->set_security_token(isolate->native_context()->security_token());
  return context->global_proxy();
}


1385 1386 1387 1388
// Performs a GC.
// Presently, it only does a full GC.
RUNTIME_FUNCTION(Runtime_CollectGarbage) {
  SealHandleScope shs(isolate);
1389
  DCHECK_EQ(1, args.length());
1390
  isolate->heap()->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask,
1391
                                     GarbageCollectionReason::kRuntime);
1392 1393 1394 1395 1396 1397 1398
  return isolate->heap()->undefined_value();
}


// Gets the current heap usage.
RUNTIME_FUNCTION(Runtime_GetHeapUsage) {
  SealHandleScope shs(isolate);
1399
  DCHECK_EQ(0, args.length());
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
  int usage = static_cast<int>(isolate->heap()->SizeOfObjects());
  if (!Smi::IsValid(usage)) {
    return *isolate->factory()->NewNumberFromInt(usage);
  }
  return Smi::FromInt(usage);
}


// Finds the script object from the script data. NOTE: This operation uses
// heap traversal to find the function generated for the source position
// for the requested break point. For lazily compiled functions several heap
// traversals might be required rendering this operation as a rather slow
// operation. However for setting break points which is normally done through
// some kind of user interaction the performance is not crucial.
RUNTIME_FUNCTION(Runtime_GetScript) {
  HandleScope scope(isolate);
1416
  DCHECK_EQ(1, args.length());
1417
  CONVERT_ARG_HANDLE_CHECKED(String, script_name, 0);
1418

1419 1420
  Handle<Script> found;
  {
1421
    Script::Iterator iterator(isolate);
1422 1423
    Script* script = nullptr;
    while ((script = iterator.Next()) != nullptr) {
1424 1425 1426 1427 1428 1429 1430 1431
      if (!script->name()->IsString()) continue;
      String* name = String::cast(script->name());
      if (name->Equals(*script_name)) {
        found = Handle<Script>(script, isolate);
        break;
      }
    }
  }
1432

1433
  if (found.is_null()) return isolate->heap()->undefined_value();
1434
  return *Script::GetWrapper(found);
1435 1436
}

1437
// TODO(5530): Remove once uses in debug.js are gone.
1438 1439
RUNTIME_FUNCTION(Runtime_ScriptLineCount) {
  HandleScope scope(isolate);
1440
  DCHECK_EQ(1, args.length());
1441 1442
  CONVERT_ARG_CHECKED(JSValue, script, 0);

1443
  CHECK(script->value()->IsScript());
1444 1445
  Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));

1446 1447 1448 1449 1450
  if (script_handle->type() == Script::TYPE_WASM) {
    // Return 0 for now; this function will disappear soon anyway.
    return Smi::FromInt(0);
  }

1451 1452 1453 1454 1455 1456
  Script::InitLineEnds(script_handle);

  FixedArray* line_ends_array = FixedArray::cast(script_handle->line_ends());
  return Smi::FromInt(line_ends_array->length());
}

1457 1458 1459 1460 1461 1462 1463
namespace {

int ScriptLinePosition(Handle<Script> script, int line) {
  if (line < 0) return -1;

  if (script->type() == Script::TYPE_WASM) {
    return WasmCompiledModule::cast(script->wasm_compiled_module())
1464
        ->shared()
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
        ->GetFunctionOffset(line);
  }

  Script::InitLineEnds(script);

  FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
  const int line_count = line_ends_array->length();
  DCHECK_LT(0, line_count);

  if (line == 0) return 0;
  // If line == line_count, we return the first position beyond the last line.
  if (line > line_count) return -1;
jgruber's avatar
jgruber committed
1477
  return Smi::ToInt(line_ends_array->get(line - 1)) + 1;
1478 1479 1480 1481
}

}  // namespace

1482 1483 1484
static Handle<Object> GetJSPositionInfo(Handle<Script> script, int position,
                                        Script::OffsetFlag offset_flag,
                                        Isolate* isolate) {
1485
  Script::PositionInfo info;
1486
  if (!Script::GetPositionInfo(script, position, &info, offset_flag)) {
1487
    return isolate->factory()->null_value();
1488 1489
  }

1490
  Handle<String> source = handle(String::cast(script->source()), isolate);
1491 1492 1493 1494
  Handle<String> sourceText = script->type() == Script::TYPE_WASM
                                  ? isolate->factory()->empty_string()
                                  : isolate->factory()->NewSubString(
                                        source, info.line_start, info.line_end);
1495 1496 1497 1498

  Handle<JSObject> jsinfo =
      isolate->factory()->NewJSObject(isolate->object_function());

1499 1500
  JSObject::AddProperty(jsinfo, isolate->factory()->script_string(), script,
                        NONE);
1501 1502 1503 1504 1505 1506 1507 1508 1509
  JSObject::AddProperty(jsinfo, isolate->factory()->position_string(),
                        handle(Smi::FromInt(position), isolate), NONE);
  JSObject::AddProperty(jsinfo, isolate->factory()->line_string(),
                        handle(Smi::FromInt(info.line), isolate), NONE);
  JSObject::AddProperty(jsinfo, isolate->factory()->column_string(),
                        handle(Smi::FromInt(info.column), isolate), NONE);
  JSObject::AddProperty(jsinfo, isolate->factory()->sourceText_string(),
                        sourceText, NONE);

1510 1511 1512
  return jsinfo;
}

1513
namespace {
1514

1515 1516 1517
int ScriptLinePositionWithOffset(Handle<Script> script, int line, int offset) {
  if (line < 0 || offset < 0) return -1;

1518 1519
  if (line == 0 || offset == 0)
    return ScriptLinePosition(script, line) + offset;
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529

  Script::PositionInfo info;
  if (!Script::GetPositionInfo(script, offset, &info, Script::NO_OFFSET)) {
    return -1;
  }

  const int total_line = info.line + line;
  return ScriptLinePosition(script, total_line);
}

1530 1531 1532 1533
Handle<Object> ScriptLocationFromLine(Isolate* isolate, Handle<Script> script,
                                      Handle<Object> opt_line,
                                      Handle<Object> opt_column,
                                      int32_t offset) {
1534 1535 1536
  // Line and column are possibly undefined and we need to handle these cases,
  // additionally subtracting corresponding offsets.

1537
  int32_t line = 0;
1538
  if (!opt_line->IsNullOrUndefined(isolate)) {
1539 1540
    CHECK(opt_line->IsNumber());
    line = NumberToInt32(*opt_line) - script->line_offset();
1541 1542
  }

1543
  int32_t column = 0;
1544
  if (!opt_column->IsNullOrUndefined(isolate)) {
1545 1546 1547
    CHECK(opt_column->IsNumber());
    column = NumberToInt32(*opt_column);
    if (line == 0) column -= script->column_offset();
1548 1549
  }

1550 1551
  int line_position = ScriptLinePositionWithOffset(script, line, offset);
  if (line_position < 0 || column < 0) return isolate->factory()->null_value();
1552

1553 1554
  return GetJSPositionInfo(script, line_position + column, Script::NO_OFFSET,
                           isolate);
1555 1556 1557 1558 1559
}

// Slow traversal over all scripts on the heap.
bool GetScriptById(Isolate* isolate, int needle, Handle<Script>* result) {
  Script::Iterator iterator(isolate);
1560 1561
  Script* script = nullptr;
  while ((script = iterator.Next()) != nullptr) {
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
    if (script->id() == needle) {
      *result = handle(script);
      return true;
    }
  }

  return false;
}

}  // namespace

// Get information on a specific source line and column possibly offset by a
// fixed source position. This function is used to find a source position from
// a line and column position. The fixed source position offset is typically
// used to find a source position in a function based on a line and column in
// the source for the function alone. The offset passed will then be the
// start position of the source for the function within the full script source.
// Note that incoming line and column parameters may be undefined, and are
// assumed to be passed *with* offsets.
// TODO(5530): Remove once uses in debug.js are gone.
RUNTIME_FUNCTION(Runtime_ScriptLocationFromLine) {
  HandleScope scope(isolate);
1584
  DCHECK_EQ(4, args.length());
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
  CONVERT_ARG_HANDLE_CHECKED(JSValue, script, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, opt_line, 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, opt_column, 2);
  CONVERT_NUMBER_CHECKED(int32_t, offset, Int32, args[3]);

  CHECK(script->value()->IsScript());
  Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));

  return *ScriptLocationFromLine(isolate, script_handle, opt_line, opt_column,
                                 offset);
}

// TODO(5530): Rename once conflicting function has been deleted.
RUNTIME_FUNCTION(Runtime_ScriptLocationFromLine2) {
  HandleScope scope(isolate);
1600
  DCHECK_EQ(4, args.length());
1601 1602 1603 1604 1605 1606 1607 1608 1609
  CONVERT_NUMBER_CHECKED(int32_t, scriptid, Int32, args[0]);
  CONVERT_ARG_HANDLE_CHECKED(Object, opt_line, 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, opt_column, 2);
  CONVERT_NUMBER_CHECKED(int32_t, offset, Int32, args[3]);

  Handle<Script> script;
  CHECK(GetScriptById(isolate, scriptid, &script));

  return *ScriptLocationFromLine(isolate, script, opt_line, opt_column, offset);
1610 1611
}

1612
// TODO(5530): Remove once uses in debug.js are gone.
1613 1614
RUNTIME_FUNCTION(Runtime_ScriptPositionInfo) {
  HandleScope scope(isolate);
1615
  DCHECK_EQ(3, args.length());
1616 1617 1618 1619
  CONVERT_ARG_CHECKED(JSValue, script, 0);
  CONVERT_NUMBER_CHECKED(int32_t, position, Int32, args[1]);
  CONVERT_BOOLEAN_ARG_CHECKED(with_offset, 2);

1620
  CHECK(script->value()->IsScript());
1621 1622 1623 1624 1625 1626 1627
  Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));

  const Script::OffsetFlag offset_flag =
      with_offset ? Script::WITH_OFFSET : Script::NO_OFFSET;
  return *GetJSPositionInfo(script_handle, position, offset_flag, isolate);
}

1628 1629 1630
// TODO(5530): Rename once conflicting function has been deleted.
RUNTIME_FUNCTION(Runtime_ScriptPositionInfo2) {
  HandleScope scope(isolate);
1631
  DCHECK_EQ(3, args.length());
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
  CONVERT_NUMBER_CHECKED(int32_t, scriptid, Int32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, position, Int32, args[1]);
  CONVERT_BOOLEAN_ARG_CHECKED(with_offset, 2);

  Handle<Script> script;
  CHECK(GetScriptById(isolate, scriptid, &script));

  const Script::OffsetFlag offset_flag =
      with_offset ? Script::WITH_OFFSET : Script::NO_OFFSET;
  return *GetJSPositionInfo(script, position, offset_flag, isolate);
}

1644 1645 1646
// On function call, depending on circumstances, prepare for stepping in,
// or perform a side effect check.
RUNTIME_FUNCTION(Runtime_DebugOnFunctionCall) {
1647
  HandleScope scope(isolate);
1648 1649
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
  if (isolate->debug()->needs_check_on_function_call()) {
    // Ensure that the callee will perform debug check on function call too.
    Deoptimizer::DeoptimizeFunction(*fun);
    if (isolate->debug()->last_step_action() >= StepIn) {
      isolate->debug()->PrepareStepIn(fun);
    }
    if (isolate->needs_side_effect_check() &&
        !isolate->debug()->PerformSideEffectCheck(fun)) {
      return isolate->heap()->exception();
    }
1660
  }
1661 1662 1663
  return isolate->heap()->undefined_value();
}

1664 1665 1666 1667 1668 1669
// Set one shot breakpoints for the suspended generator object.
RUNTIME_FUNCTION(Runtime_DebugPrepareStepInSuspendedGenerator) {
  HandleScope scope(isolate);
  DCHECK_EQ(0, args.length());
  isolate->debug()->PrepareStepInSuspendedGenerator();
  return isolate->heap()->undefined_value();
1670 1671
}

1672
RUNTIME_FUNCTION(Runtime_DebugPushPromise) {
1673
  DCHECK_EQ(1, args.length());
1674 1675
  HandleScope scope(isolate);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
1676
  isolate->PushPromise(promise);
1677 1678 1679 1680 1681
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_DebugPopPromise) {
1682
  DCHECK_EQ(0, args.length());
1683 1684 1685 1686 1687
  SealHandleScope shs(isolate);
  isolate->PopPromise();
  return isolate->heap()->undefined_value();
}

1688 1689
RUNTIME_FUNCTION(Runtime_DebugAsyncFunctionPromiseCreated) {
  DCHECK_EQ(1, args.length());
1690
  HandleScope scope(isolate);
1691 1692 1693 1694 1695 1696
  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
  isolate->PushPromise(promise);
  int id = isolate->debug()->NextAsyncTaskId(promise);
  Handle<Symbol> async_stack_id_symbol =
      isolate->factory()->promise_async_stack_id_symbol();
  JSObject::SetProperty(promise, async_stack_id_symbol,
1697 1698
                        handle(Smi::FromInt(id), isolate),
                        LanguageMode::kStrict)
1699
      .Assert();
1700 1701 1702
  return isolate->heap()->undefined_value();
}

1703
RUNTIME_FUNCTION(Runtime_DebugIsActive) {
1704 1705 1706
  SealHandleScope shs(isolate);
  return Smi::FromInt(isolate->debug()->is_active());
}
1707

1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
namespace {
Handle<JSObject> MakeRangeObject(Isolate* isolate, const CoverageBlock& range) {
  Factory* factory = isolate->factory();

  Handle<String> start_string = factory->InternalizeUtf8String("start");
  Handle<String> end_string = factory->InternalizeUtf8String("end");
  Handle<String> count_string = factory->InternalizeUtf8String("count");

  Handle<JSObject> range_obj = factory->NewJSObjectWithNullProto();
  JSObject::AddProperty(range_obj, start_string,
                        factory->NewNumberFromInt(range.start), NONE);
  JSObject::AddProperty(range_obj, end_string,
                        factory->NewNumberFromInt(range.end), NONE);
  JSObject::AddProperty(range_obj, count_string,
                        factory->NewNumberFromUint(range.count), NONE);

  return range_obj;
}
}  // namespace

1728 1729
RUNTIME_FUNCTION(Runtime_DebugCollectCoverage) {
  HandleScope scope(isolate);
1730
  DCHECK_EQ(0, args.length());
1731
  // Collect coverage data.
1732 1733
  std::unique_ptr<Coverage> coverage;
  if (isolate->is_best_effort_code_coverage()) {
1734
    coverage = Coverage::CollectBestEffort(isolate);
1735
  } else {
1736
    coverage = Coverage::CollectPrecise(isolate);
1737
  }
1738 1739 1740
  Factory* factory = isolate->factory();
  // Turn the returned data structure into JavaScript.
  // Create an array of scripts.
1741
  int num_scripts = static_cast<int>(coverage->size());
1742 1743
  // Prepare property keys.
  Handle<FixedArray> scripts_array = factory->NewFixedArray(num_scripts);
1744
  Handle<String> script_string = factory->NewStringFromStaticChars("script");
1745
  for (int i = 0; i < num_scripts; i++) {
1746
    const auto& script_data = coverage->at(i);
1747
    HandleScope inner_scope(isolate);
1748 1749

    std::vector<CoverageBlock> ranges;
1750 1751 1752
    int num_functions = static_cast<int>(script_data.functions.size());
    for (int j = 0; j < num_functions; j++) {
      const auto& function_data = script_data.functions[j];
1753 1754 1755 1756 1757 1758
      ranges.emplace_back(function_data.start, function_data.end,
                          function_data.count);
      for (size_t k = 0; k < function_data.blocks.size(); k++) {
        const auto& block_data = function_data.blocks[k];
        ranges.emplace_back(block_data.start, block_data.end, block_data.count);
      }
1759
    }
1760 1761 1762 1763 1764 1765 1766 1767

    int num_ranges = static_cast<int>(ranges.size());
    Handle<FixedArray> ranges_array = factory->NewFixedArray(num_ranges);
    for (int j = 0; j < num_ranges; j++) {
      Handle<JSObject> range_object = MakeRangeObject(isolate, ranges[j]);
      ranges_array->set(j, *range_object);
    }

1768
    Handle<JSArray> script_obj =
1769
        factory->NewJSArrayWithElements(ranges_array, PACKED_ELEMENTS);
1770
    Handle<JSObject> wrapper = Script::GetWrapper(script_data.script);
1771
    JSObject::AddProperty(script_obj, script_string, wrapper, NONE);
1772 1773
    scripts_array->set(i, *script_obj);
  }
1774
  return *factory->NewJSArrayWithElements(scripts_array, PACKED_ELEMENTS);
1775 1776
}

1777 1778 1779
RUNTIME_FUNCTION(Runtime_DebugTogglePreciseCoverage) {
  SealHandleScope shs(isolate);
  CONVERT_BOOLEAN_ARG_CHECKED(enable, 0);
1780 1781
  Coverage::SelectMode(isolate, enable ? debug::Coverage::kPreciseCount
                                       : debug::Coverage::kBestEffort);
1782 1783 1784
  return isolate->heap()->undefined_value();
}

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
RUNTIME_FUNCTION(Runtime_DebugToggleBlockCoverage) {
  SealHandleScope shs(isolate);
  CONVERT_BOOLEAN_ARG_CHECKED(enable, 0);
  Coverage::SelectMode(isolate, enable ? debug::Coverage::kBlockCount
                                       : debug::Coverage::kBestEffort);
  return isolate->heap()->undefined_value();
}

RUNTIME_FUNCTION(Runtime_IncBlockCounter) {
  SealHandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  CONVERT_SMI_ARG_CHECKED(coverage_array_slot_index, 1);

1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
  // It's quite possible that a function contains IncBlockCounter bytecodes, but
  // no coverage info exists. This happens e.g. by selecting the best-effort
  // coverage collection mode, which triggers deletion of all coverage infos in
  // order to avoid memory leaks.

  SharedFunctionInfo* shared = function->shared();
  if (shared->HasCoverageInfo()) {
    CoverageInfo* coverage_info = shared->GetCoverageInfo();
    coverage_info->IncrementBlockCount(coverage_array_slot_index);
  }
1809 1810 1811 1812

  return isolate->heap()->undefined_value();
}

1813 1814
}  // namespace internal
}  // namespace v8