runtime-debug.cc 66.9 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

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

namespace v8 {
namespace internal {

RUNTIME_FUNCTION(Runtime_DebugBreak) {
26
  SealHandleScope shs(isolate);
27 28 29 30
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
  isolate->debug()->set_return_value(value);

31 32
  // Get the top-most JavaScript frame.
  JavaScriptFrameIterator it(isolate);
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
  isolate->debug()->Break(it.frame());

  isolate->debug()->SetAfterBreakTarget(it.frame());
  return *isolate->debug()->return_value();
}

RUNTIME_FUNCTION(Runtime_DebugBreakOnBytecode) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
  isolate->debug()->set_return_value(value);

  // Get the top-most JavaScript frame.
  JavaScriptFrameIterator it(isolate);
  isolate->debug()->Break(it.frame());

49
  // If live-edit has dropped frames, we are not going back to dispatch.
50
  if (LiveEdit::SetAfterBreakTarget(isolate->debug())) return Smi::kZero;
51

52 53 54 55 56 57 58 59 60 61 62
  // 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();
  interpreter::Bytecode bytecode =
      interpreter::Bytecodes::FromByte(bytecode_array->get(bytecode_offset));
  return isolate->interpreter()->GetBytecodeHandler(
      bytecode, interpreter::OperandScale::kSingle);
63 64 65 66
}


RUNTIME_FUNCTION(Runtime_HandleDebuggerStatement) {
67 68
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
69 70 71
  if (isolate->debug()->break_points_active()) {
    isolate->debug()->HandleDebugBreak();
  }
72 73 74 75 76 77 78 79 80 81 82
  return isolate->heap()->undefined_value();
}


// Adds a JavaScript function as a debug event listener.
// args[0]: debug event listener function to set or null or undefined for
//          clearing the event listener function
// args[1]: object supplied during callback
RUNTIME_FUNCTION(Runtime_SetDebugEventListener) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 2);
83 84
  CHECK(args[0]->IsJSFunction() || args[0]->IsUndefined(isolate) ||
        args[0]->IsNull(isolate));
85 86 87 88 89 90 91 92
  CONVERT_ARG_HANDLE_CHECKED(Object, callback, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, data, 1);
  isolate->debug()->SetEventListener(callback, data);

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


93
RUNTIME_FUNCTION(Runtime_ScheduleBreak) {
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
  isolate->stack_guard()->RequestDebugBreak();
  return isolate->heap()->undefined_value();
}


static Handle<Object> DebugGetProperty(LookupIterator* it,
                                       bool* has_caught = NULL) {
  for (; it->IsFound(); it->Next()) {
    switch (it->state()) {
      case LookupIterator::NOT_FOUND:
      case LookupIterator::TRANSITION:
        UNREACHABLE();
      case LookupIterator::ACCESS_CHECK:
        // Ignore access checks.
        break;
111
      case LookupIterator::INTEGER_INDEXED_EXOTIC:
112 113 114 115 116 117 118 119
      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();
        }
120
        MaybeHandle<Object> maybe_result =
121
            JSObject::GetPropertyWithAccessor(it);
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        Handle<Object> result;
        if (!maybe_result.ToHandle(&result)) {
          result = handle(it->isolate()->pending_exception(), it->isolate());
          it->isolate()->clear_pending_exception();
          if (has_caught != NULL) *has_caught = true;
        }
        return result;
      }

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

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


140 141 142 143 144 145 146 147 148 149 150 151
static Handle<Object> DebugGetProperty(Handle<Object> object,
                                       Handle<Name> name) {
  LookupIterator it(object, name);
  return DebugGetProperty(&it);
}


template <class IteratorType>
static MaybeHandle<JSArray> GetIteratorInternalProperties(
    Isolate* isolate, Handle<IteratorType> object) {
  Factory* factory = isolate->factory();
  Handle<IteratorType> iterator = Handle<IteratorType>::cast(object);
152
  CHECK(iterator->kind()->IsSmi());
153 154 155 156 157 158 159 160 161 162 163 164
  const char* kind = NULL;
  switch (Smi::cast(iterator->kind())->value()) {
    case IteratorType::kKindKeys:
      kind = "keys";
      break;
    case IteratorType::kKindValues:
      kind = "values";
      break;
    case IteratorType::kKindEntries:
      kind = "entries";
      break;
    default:
165
      UNREACHABLE();
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  }

  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();
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  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);
214 215 216 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
  } 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);
250
  } else if (object->IsJSPromise()) {
251 252 253
    Handle<JSObject> promise = Handle<JSObject>::cast(object);

    Handle<Object> status_obj =
254
        DebugGetProperty(promise, isolate->factory()->promise_state_symbol());
255
    CHECK(status_obj->IsSmi());
256 257 258
    const char* status = "rejected";
    int status_val = Handle<Smi>::cast(status_obj)->value();
    switch (status_val) {
259
      case kPromiseFulfilled:
260 261
        status = "resolved";
        break;
262
      case kPromisePending:
263 264 265
        status = "pending";
        break;
      default:
266
        DCHECK_EQ(kPromiseRejected, status_val);
267 268 269 270 271 272 273 274 275 276
    }

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

    Handle<Object> value_obj =
277
        DebugGetProperty(promise, isolate->factory()->promise_result_symbol());
278 279 280 281 282
    Handle<String> promise_value =
        factory->NewStringFromAsciiChecked("[[PromiseValue]]");
    result->set(2, *promise_value);
    result->set(3, *value_obj);
    return factory->NewJSArrayWithElements(result);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  } 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);
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  } 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);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
320 321
  RETURN_RESULT_OR_FAILURE(isolate,
                           Runtime::GetInternalProperties(isolate, obj));
322 323 324
}


325 326 327 328 329 330 331 332 333
// 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);
334
  DCHECK_EQ(2, args.length());
335
  CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
336 337 338 339 340 341
  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));
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

  // 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
  // into the embedding application can occour, and the embedding application
  // 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;
357 358
  // TODO(verwaest): Make sure DebugGetProperty can handle arrays, and remove
  // this special case.
359 360 361
  if (name->AsArrayIndex(&index)) {
    Handle<FixedArray> details = isolate->factory()->NewFixedArray(2);
    Handle<Object> element_or_char;
362 363
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
        isolate, element_or_char, JSReceiver::GetElement(isolate, obj, index));
364
    details->set(0, *element_or_char);
365
    details->set(1, PropertyDetails::Empty().AsSmi());
366 367 368
    return *isolate->factory()->NewJSArrayWithElements(details);
  }

369
  LookupIterator it(obj, name, LookupIterator::OWN);
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  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
387
                          ? PropertyDetails::Empty()
388 389 390 391 392
                          : it.property_details();
  details->set(1, d.AsSmi());
  details->set(
      2, isolate->heap()->ToBoolean(it.state() == LookupIterator::INTERCEPTOR));
  if (has_js_accessors) {
393
    Handle<AccessorPair> accessors = Handle<AccessorPair>::cast(maybe_pair);
394
    details->set(3, isolate->heap()->ToBoolean(has_caught));
395 396 397 398 399 400
    Handle<Object> getter =
        AccessorPair::GetComponent(accessors, ACCESSOR_GETTER);
    Handle<Object> setter =
        AccessorPair::GetComponent(accessors, ACCESSOR_SETTER);
    details->set(4, *getter);
    details->set(5, *setter);
401 402 403 404 405 406 407 408 409 410 411
  }

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


RUNTIME_FUNCTION(Runtime_DebugGetProperty) {
  HandleScope scope(isolate);

  DCHECK(args.length() == 2);

412
  CONVERT_ARG_HANDLE_CHECKED(Object, obj, 0);
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  CONVERT_ARG_HANDLE_CHECKED(Name, name, 1);

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


// Return the property type calculated from the property details.
// args[0]: smi with property details.
RUNTIME_FUNCTION(Runtime_DebugPropertyTypeFromDetails) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
  return Smi::FromInt(static_cast<int>(details.type()));
}


// Return the property attribute calculated from the property details.
// args[0]: smi with property details.
RUNTIME_FUNCTION(Runtime_DebugPropertyAttributesFromDetails) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_PROPERTY_DETAILS_CHECKED(details, 0);
  return Smi::FromInt(static_cast<int>(details.attributes()));
}


RUNTIME_FUNCTION(Runtime_CheckExecutionState) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
444
  CHECK(isolate->debug()->CheckExecutionState(break_id));
445 446 447 448 449 450 451 452
  return isolate->heap()->true_value();
}


RUNTIME_FUNCTION(Runtime_GetFrameCount) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
453
  CHECK(isolate->debug()->CheckExecutionState(break_id));
454 455 456 457 458 459

  // 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.
460
    return Smi::kZero;
461 462
  }

463
  for (StackTraceFrameIterator it(isolate, id); !it.done(); it.Advance()) {
464
    List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
465 466 467 468 469 470 471 472
    if (it.is_wasm()) {
      n++;
    } else {
      it.javascript_frame()->Summarize(&frames);
      for (int i = frames.length() - 1; i >= 0; i--) {
        // Omit functions from native and extension scripts.
        if (frames[i].function()->shared()->IsSubjectToDebugging()) n++;
      }
473 474 475 476 477 478 479 480 481
    }
  }
  return Smi::FromInt(n);
}


static const int kFrameDetailsFrameIdIndex = 0;
static const int kFrameDetailsReceiverIndex = 1;
static const int kFrameDetailsFunctionIndex = 2;
482 483 484 485 486 487 488 489
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;
490 491 492 493 494 495 496 497 498

// 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
499 500 501 502 503 504 505
// 3: Script
// 4: Argument count
// 5: Local count
// 6: Source position
// 7: Constructor call
// 8: Is at return
// 9: Flags
506 507 508 509 510 511 512
// Arguments name, value
// Locals name, value
// Return value if any
RUNTIME_FUNCTION(Runtime_GetFrameDetails) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
513
  CHECK(isolate->debug()->CheckExecutionState(break_id));
514 515 516 517 518 519 520 521 522 523 524

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

525
  StackTraceFrameIterator it(isolate, id);
526
  // Inlined frame index in optimized frame, starting from outer function.
527 528
  int inlined_jsframe_index =
      DebugFrameHelper::FindIndexedNonNativeFrame(&it, index);
529 530 531 532 533 534
  if (inlined_jsframe_index == -1) return heap->undefined_value();

  FrameInspector frame_inspector(it.frame(), inlined_jsframe_index, isolate);

  // Traverse the saved contexts chain to find the active context for the
  // selected frame.
535 536
  SaveContext* save =
      DebugFrameHelper::FindSavedContextForFrame(isolate, it.frame());
537 538

  // Get the frame id.
539 540
  Handle<Object> frame_id(DebugFrameHelper::WrapFrameId(it.frame()->id()),
                          isolate);
541 542 543 544

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

545 546 547 548 549 550 551 552 553
  if (it.is_wasm()) {
    // 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.
554 555
    Handle<Object> wasm_instance_or_undef(it.wasm_frame()->wasm_instance(),
                                          isolate);
556 557
    int func_index = it.wasm_frame()->function_index();
    Handle<String> func_name =
558
        wasm::GetWasmFunctionName(isolate, wasm_instance_or_undef, func_index);
559 560 561 562 563 564 565 566
    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.
567
    details->set(kFrameDetailsArgumentCountIndex, Smi::kZero);
568 569

    // Add the locals count
570
    details->set(kFrameDetailsLocalCountIndex, Smi::kZero);
571 572

    // Add the source position.
573 574 575 576
    // For wasm, it is function-local, so translate it to a module-relative
    // position, such that together with the script it uniquely identifies the
    // position.
    Handle<Object> positionValue;
577 578
    if (position != kNoSourcePosition &&
        !wasm_instance_or_undef->IsUndefined(isolate)) {
579
      int translated_position = position;
580
      if (!wasm::WasmIsAsmJs(*wasm_instance_or_undef, isolate)) {
581
        Handle<WasmCompiledModule> compiled_module(
582 583 584
            WasmInstanceObject::cast(*wasm_instance_or_undef)
                ->get_compiled_module(),
            isolate);
585 586 587 588 589
        translated_position +=
            wasm::GetFunctionCodeOffset(compiled_module, func_index);
      }
      details->set(kFrameDetailsSourcePositionIndex,
                   Smi::FromInt(translated_position));
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    }

    // 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
    int flags = 0;
    if (*save->context() == *isolate->debug()->debug_context()) {
      flags |= 1 << 0;
    }
    details->set(kFrameDetailsFlagsIndex, Smi::FromInt(flags));

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

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

614 615 616 617
  // Check for constructor frame.
  bool constructor = frame_inspector.IsConstructor();

  // Get scope info and read from it for local variable information.
618 619
  Handle<JSFunction> function =
      Handle<JSFunction>::cast(frame_inspector.GetFunction());
620
  CHECK(function->shared()->IsSubjectToDebugging());
621 622 623 624 625
  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.
626 627 628 629 630 631
  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) {
632 633
    // Hide compiler-introduced temporary variables, whether on the stack or on
    // the context.
634 635 636
    if (ScopeInfo::VariableIsSynthetic(scope_info->LocalName(slot))) {
      local_count--;
    }
637 638
  }

639
  List<Handle<Object>> locals;
640 641 642 643
  // Fill in the values of the locals.
  int i = 0;
  for (; i < scope_info->StackLocalCount(); ++i) {
    // Use the value from the stack.
644
    if (ScopeInfo::VariableIsSynthetic(scope_info->LocalName(i))) continue;
645
    locals.Add(Handle<String>(scope_info->LocalName(i), isolate));
646 647
    Handle<Object> value =
        frame_inspector.GetExpression(scope_info->StackLocalIndex(i));
648 649
    // TODO(yangguo): We convert optimized out values to {undefined} when they
    // are passed to the debugger. Eventually we should handle them somehow.
650 651 652
    if (value->IsOptimizedOut(isolate)) {
      value = isolate->factory()->undefined_value();
    }
653
    locals.Add(value);
654
  }
655
  if (locals.length() < local_count * 2) {
656
    // Get the context containing declarations.
657 658 659
    DCHECK(maybe_context->IsContext());
    Handle<Context> context(Context::cast(*maybe_context)->closure_context());

660 661
    for (; i < scope_info->LocalCount(); ++i) {
      Handle<String> name(scope_info->LocalName(i));
662
      if (ScopeInfo::VariableIsSynthetic(*name)) continue;
663 664 665
      VariableMode mode;
      InitializationFlag init_flag;
      MaybeAssignedFlag maybe_assigned_flag;
666
      locals.Add(name);
667
      int context_slot_index = ScopeInfo::ContextSlotIndex(
668
          scope_info, name, &mode, &init_flag, &maybe_assigned_flag);
669
      Object* value = context->get(context_slot_index);
670
      locals.Add(Handle<Object>(value, isolate));
671 672 673 674 675 676 677
    }
  }

  // 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) {
678
    at_return = isolate->debug()->IsBreakAtReturn(it.javascript_frame());
679 680 681 682 683 684
  }

  // 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) {
685
    return_value = isolate->debug()->return_value();
686 687 688 689 690 691
  }

  // 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.
692 693
  if ((inlined_jsframe_index == 0) &&
      it.javascript_frame()->has_adapted_arguments()) {
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
    it.AdvanceToArgumentsFrame();
    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).
714
  details->set(kFrameDetailsFunctionIndex, *(frame_inspector.GetFunction()));
715

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

721 722 723 724 725 726 727
  // 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
728
  if (position != kNoSourcePosition) {
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    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;
    flags |= inlined_jsframe_index << 2;
  }
  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.
769
      details->set(details_index++, *(frame_inspector.GetParameter(i)));
770 771 772 773 774 775
    } else {
      details->set(details_index++, heap->undefined_value());
    }
  }

  // Add locals name and value from the temporary copy from the function frame.
776
  for (const auto& local : locals) details->set(details_index++, *local);
777 778 779 780 781 782 783 784

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

  // Add the receiver (same as in function frame).
  Handle<Object> receiver(it.frame()->receiver(), isolate);
785
  DCHECK(function->shared()->IsUserJavaScript());
786
  DCHECK_IMPLIES(is_sloppy(shared->language_mode()), receiver->IsJSReceiver());
787 788 789 790 791 792 793 794 795 796 797
  details->set(kFrameDetailsReceiverIndex, *receiver);

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


RUNTIME_FUNCTION(Runtime_GetScopeCount) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
798
  CHECK(isolate->debug()->CheckExecutionState(break_id));
799 800 801 802

  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);

  // Get the frame where the debugging is performed.
803
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
804 805
  JavaScriptFrameIterator it(isolate, id);
  JavaScriptFrame* frame = it.frame();
806
  FrameInspector frame_inspector(frame, 0, isolate);
807 808 809

  // Count the visible scopes.
  int n = 0;
810
  for (ScopeIterator it(isolate, &frame_inspector); !it.Done(); it.Next()) {
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    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);
  DCHECK(args.length() == 4);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
831
  CHECK(isolate->debug()->CheckExecutionState(break_id));
832 833 834 835 836 837

  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.
838
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
839 840
  JavaScriptFrameIterator frame_it(isolate, id);
  JavaScriptFrame* frame = frame_it.frame();
841
  FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
842 843 844

  // Find the requested scope.
  int n = 0;
845
  ScopeIterator it(isolate, &frame_inspector);
846 847 848 849 850 851
  for (; !it.Done() && n < index; it.Next()) {
    n++;
  }
  if (it.Done()) {
    return isolate->heap()->undefined_value();
  }
852
  RETURN_RESULT_OR_FAILURE(isolate, it.MaterializeScopeDetails());
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
}


// 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]);
869
  CHECK(isolate->debug()->CheckExecutionState(break_id));
870 871 872 873

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

874
  ScopeIterator::Option option = ScopeIterator::DEFAULT;
875 876
  if (args.length() == 4) {
    CONVERT_BOOLEAN_ARG_CHECKED(flag, 3);
877
    if (flag) option = ScopeIterator::IGNORE_NESTED_SCOPES;
878 879 880
  }

  // Get the frame where the debugging is performed.
881
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
882 883
  StackTraceFrameIterator frame_it(isolate, id);
  StandardFrame* frame = frame_it.frame();
884
  FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
885 886

  List<Handle<JSObject> > result(4);
887
  ScopeIterator it(isolate, &frame_inspector, option);
888 889 890
  for (; !it.Done(); it.Next()) {
    Handle<JSObject> details;
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, details,
891
                                       it.MaterializeScopeDetails());
892 893 894 895 896 897 898 899 900 901 902 903 904
    result.Add(details);
  }

  Handle<FixedArray> array = isolate->factory()->NewFixedArray(result.length());
  for (int i = 0; i < result.length(); ++i) {
    array->set(i, *result[i]);
  }
  return *isolate->factory()->NewJSArrayWithElements(array);
}


RUNTIME_FUNCTION(Runtime_GetFunctionScopeCount) {
  HandleScope scope(isolate);
905
  DCHECK_EQ(1, args.length());
906 907

  // Check arguments.
908
  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, function, 0);
909 910 911

  // Count the visible scopes.
  int n = 0;
912 913 914 915 916
  if (function->IsJSFunction()) {
    for (ScopeIterator it(isolate, Handle<JSFunction>::cast(function));
         !it.Done(); it.Next()) {
      n++;
    }
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  }

  return Smi::FromInt(n);
}


RUNTIME_FUNCTION(Runtime_GetFunctionScopeDetails) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);

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

941
  RETURN_RESULT_OR_FAILURE(isolate, it.MaterializeScopeDetails());
942 943
}

944 945 946 947
RUNTIME_FUNCTION(Runtime_GetGeneratorScopeCount) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());

948
  if (!args[0]->IsJSGeneratorObject()) return Smi::kZero;
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966

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

  // 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);
  DCHECK(args.length() == 2);

  if (!args[0]->IsJSGeneratorObject()) {
967
    return isolate->heap()->undefined_value();
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  }

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

  // 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());
}
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

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);
  DCHECK(args.length() == 6);

  // 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]);
1021
    CHECK(isolate->debug()->CheckExecutionState(break_id));
1022 1023 1024 1025 1026

    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.
1027
    StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
1028 1029
    JavaScriptFrameIterator frame_it(isolate, id);
    JavaScriptFrame* frame = frame_it.frame();
1030
    FrameInspector frame_inspector(frame, inlined_jsframe_index, isolate);
1031

1032
    ScopeIterator it(isolate, &frame_inspector);
1033
    res = SetScopeVariableValue(&it, index, variable_name, new_value);
1034
  } else if (args[0]->IsJSFunction()) {
1035 1036 1037
    CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
    ScopeIterator it(isolate, fun);
    res = SetScopeVariableValue(&it, index, variable_name, new_value);
1038 1039 1040 1041
  } else {
    CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, gen, 0);
    ScopeIterator it(isolate, gen);
    res = SetScopeVariableValue(&it, index, variable_name, new_value);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  }

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


RUNTIME_FUNCTION(Runtime_DebugPrintScopes) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 0);

#ifdef DEBUG
  // Print the scopes for the top frame.
  StackFrameLocator locator(isolate);
  JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
1056 1057 1058
  FrameInspector frame_inspector(frame, 0, isolate);

  for (ScopeIterator it(isolate, &frame_inspector); !it.Done(); it.Next()) {
1059 1060 1061 1062 1063 1064 1065 1066 1067
    it.DebugPrint();
  }
#endif
  return isolate->heap()->undefined_value();
}


// Sets the disable break state
// args[0]: disable break state
1068
RUNTIME_FUNCTION(Runtime_SetBreakPointsActive) {
1069 1070
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
1071 1072
  CONVERT_BOOLEAN_ARG_CHECKED(active, 0);
  isolate->debug()->set_break_points_active(active);
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
  return isolate->heap()->undefined_value();
}


static bool IsPositionAlignmentCodeCorrect(int alignment) {
  return alignment == STATEMENT_ALIGNED || alignment == BREAK_POSITION_ALIGNED;
}


RUNTIME_FUNCTION(Runtime_GetBreakLocations) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
1085
  CHECK(isolate->debug()->is_active());
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
  CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[1]);

  if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
    return isolate->ThrowIllegalOperation();
  }
  BreakPositionAlignment alignment =
      static_cast<BreakPositionAlignment>(statement_aligned_code);

  Handle<SharedFunctionInfo> shared(fun->shared());
  // Find the number of break points
  Handle<Object> break_locations =
      Debug::GetSourceBreakLocations(shared, alignment);
1099 1100 1101
  if (break_locations->IsUndefined(isolate)) {
    return isolate->heap()->undefined_value();
  }
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  // Return array as JS array
  return *isolate->factory()->NewJSArrayWithElements(
      Handle<FixedArray>::cast(break_locations));
}


// Set a break point in a function.
// args[0]: function
// args[1]: number: break source position (within the function source)
// args[2]: number: break point object
RUNTIME_FUNCTION(Runtime_SetFunctionBreakPoint) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 3);
1115
  CHECK(isolate->debug()->is_active());
1116 1117
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
1118 1119
  CHECK(source_position >= function->shared()->start_position() &&
        source_position <= function->shared()->end_position());
1120 1121 1122
  CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 2);

  // Set break point.
1123 1124
  CHECK(isolate->debug()->SetBreakPoint(function, break_point_object_arg,
                                        &source_position));
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

  return Smi::FromInt(source_position);
}


// Changes the state of a break point in a script and returns source position
// where break point was set. NOTE: Regarding performance see the NOTE for
// GetScriptFromScriptData.
// args[0]: script to set break point in
// args[1]: number: break source position (within the script source)
// args[2]: number, breakpoint position alignment
// args[3]: number: break point object
RUNTIME_FUNCTION(Runtime_SetScriptBreakPoint) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 4);
1140
  CHECK(isolate->debug()->is_active());
1141 1142
  CONVERT_ARG_HANDLE_CHECKED(JSValue, wrapper, 0);
  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
1143
  CHECK(source_position >= 0);
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  CONVERT_NUMBER_CHECKED(int32_t, statement_aligned_code, Int32, args[2]);
  CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 3);

  if (!IsPositionAlignmentCodeCorrect(statement_aligned_code)) {
    return isolate->ThrowIllegalOperation();
  }
  BreakPositionAlignment alignment =
      static_cast<BreakPositionAlignment>(statement_aligned_code);

  // Get the script from the script wrapper.
1154
  CHECK(wrapper->value()->IsScript());
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
  Handle<Script> script(Script::cast(wrapper->value()));

  // Set break point.
  if (!isolate->debug()->SetBreakPointForScript(script, break_point_object_arg,
                                                &source_position, alignment)) {
    return isolate->heap()->undefined_value();
  }

  return Smi::FromInt(source_position);
}


// Clear a break point
// args[0]: number: break point object
RUNTIME_FUNCTION(Runtime_ClearBreakPoint) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
1172
  CHECK(isolate->debug()->is_active());
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
  CONVERT_ARG_HANDLE_CHECKED(Object, break_point_object_arg, 0);

  // Clear break point.
  isolate->debug()->ClearBreakPoint(break_point_object_arg);

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


// 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);
  DCHECK(args.length() == 2);
  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);
  DCHECK(args.length() == 1);
  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);
1220
  DCHECK(args.length() == 2);
1221
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1222
  CHECK(isolate->debug()->CheckExecutionState(break_id));
1223

1224
  if (!args[1]->IsNumber()) {
1225 1226 1227 1228 1229 1230
    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 &&
1231
      step_action != StepOut && step_action != StepFrame) {
1232 1233 1234 1235 1236 1237 1238
    return isolate->Throw(isolate->heap()->illegal_argument_string());
  }

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

  // Prepare step.
1239
  isolate->debug()->PrepareStep(static_cast<StepAction>(step_action));
1240 1241 1242
  return isolate->heap()->undefined_value();
}

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
RUNTIME_FUNCTION(Runtime_PrepareStepFrame) {
  HandleScope scope(isolate);
  DCHECK_EQ(0, args.length());
  CHECK(isolate->debug()->CheckExecutionState());

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

  // Prepare step.
  isolate->debug()->PrepareStep(StepFrame);
  return isolate->heap()->undefined_value();
}
1255 1256 1257 1258 1259

// Clear all stepping set by PrepareStep.
RUNTIME_FUNCTION(Runtime_ClearStepping) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 0);
1260
  CHECK(isolate->debug()->is_active());
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
  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.
  DCHECK(args.length() == 6);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1273
  CHECK(isolate->debug()->CheckExecutionState(break_id));
1274 1275 1276 1277 1278

  CONVERT_SMI_ARG_CHECKED(wrapped_id, 1);
  CONVERT_NUMBER_CHECKED(int, inlined_jsframe_index, Int32, args[2]);
  CONVERT_ARG_HANDLE_CHECKED(String, source, 3);
  CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 4);
1279
  CONVERT_ARG_HANDLE_CHECKED(HeapObject, context_extension, 5);
1280

1281
  StackFrame::Id id = DebugFrameHelper::UnwrapFrameId(wrapped_id);
1282

1283 1284 1285
  RETURN_RESULT_OR_FAILURE(
      isolate, DebugEvaluate::Local(isolate, id, inlined_jsframe_index, source,
                                    disable_break, context_extension));
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
}


RUNTIME_FUNCTION(Runtime_DebugEvaluateGlobal) {
  HandleScope scope(isolate);

  // Check the execution state and decode arguments frame and source to be
  // evaluated.
  DCHECK(args.length() == 4);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
1296
  CHECK(isolate->debug()->CheckExecutionState(break_id));
1297 1298 1299

  CONVERT_ARG_HANDLE_CHECKED(String, source, 1);
  CONVERT_BOOLEAN_ARG_CHECKED(disable_break, 2);
1300
  CONVERT_ARG_HANDLE_CHECKED(HeapObject, context_extension, 3);
1301

1302 1303
  RETURN_RESULT_OR_FAILURE(
      isolate,
1304
      DebugEvaluate::Global(isolate, source, disable_break, context_extension));
1305 1306 1307 1308 1309 1310
}


RUNTIME_FUNCTION(Runtime_DebugGetLoadedScripts) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 0);
1311 1312 1313 1314

  // This runtime function is used by the debugger to determine whether the
  // debugger is active or not. Hence we fail gracefully here and don't crash.
  if (!isolate->debug()->is_active()) return isolate->ThrowIllegalOperation();
1315

1316 1317 1318
  Handle<FixedArray> instances;
  {
    DebugScope debug_scope(isolate->debug());
1319 1320 1321 1322
    if (debug_scope.failed()) {
      DCHECK(isolate->has_pending_exception());
      return isolate->heap()->exception();
    }
1323 1324 1325
    // Fill the script objects.
    instances = isolate->debug()->GetLoadedScripts();
  }
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

  // 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.
1340
  return *isolate->factory()->NewJSArrayWithElements(instances);
1341 1342
}

1343 1344
static bool HasInPrototypeChainIgnoringProxies(Isolate* isolate,
                                               JSObject* object,
1345
                                               Object* proto) {
1346
  PrototypeIterator iter(isolate, object, kStartAtReceiver);
1347 1348 1349
  while (true) {
    iter.AdvanceIgnoringProxies();
    if (iter.IsAtEnd()) return false;
1350
    if (iter.GetCurrent() == proto) return true;
1351 1352 1353 1354
  }
}


1355 1356 1357 1358 1359 1360 1361 1362
// 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);
  DCHECK(args.length() == 3);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, target, 0);
1363
  CONVERT_ARG_HANDLE_CHECKED(Object, filter, 1);
1364
  CHECK(filter->IsUndefined(isolate) || filter->IsJSObject());
1365
  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]);
1366
  CHECK(max_references >= 0);
1367

1368
  List<Handle<JSObject> > instances;
1369 1370
  Heap* heap = isolate->heap();
  {
1371
    HeapIterator iterator(heap, HeapIterator::kFilterUnreachable);
1372 1373 1374 1375 1376
    // Get the constructor function for context extension and arguments array.
    Object* arguments_fun = isolate->sloppy_arguments_map()->GetConstructor();
    HeapObject* heap_obj;
    while ((heap_obj = iterator.next())) {
      if (!heap_obj->IsJSObject()) continue;
1377
      JSObject* obj = JSObject::cast(heap_obj);
1378 1379 1380 1381 1382
      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.
1383
      if (!filter->IsUndefined(isolate) &&
1384
          HasInPrototypeChainIgnoringProxies(isolate, obj, *filter)) {
1385 1386 1387 1388
        continue;
      }
      if (obj->IsJSGlobalObject()) {
        obj = JSGlobalObject::cast(obj)->global_proxy();
1389
      }
1390 1391 1392 1393 1394
      instances.Add(Handle<JSObject>(obj));
      if (instances.length() == max_references) break;
    }
    // Iterate the rest of the heap to satisfy HeapIterator constraints.
    while (iterator.next()) {
1395 1396 1397
    }
  }

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
  Handle<FixedArray> result;
  if (instances.length() == 1 && instances.last().is_identical_to(target)) {
    // 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 {
    result = isolate->factory()->NewFixedArray(instances.length());
    for (int i = 0; i < instances.length(); ++i) result->set(i, *instances[i]);
  }
  return *isolate->factory()->NewJSArrayWithElements(result);
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
}


// 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);
  DCHECK(args.length() == 2);
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, constructor, 0);
  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]);
1421
  CHECK(max_references >= 0);
1422

1423
  List<Handle<JSObject> > instances;
1424 1425
  Heap* heap = isolate->heap();
  {
1426
    HeapIterator iterator(heap, HeapIterator::kFilterUnreachable);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    HeapObject* heap_obj;
    while ((heap_obj = iterator.next())) {
      if (!heap_obj->IsJSObject()) continue;
      JSObject* obj = JSObject::cast(heap_obj);
      if (obj->map()->GetConstructor() != *constructor) continue;
      instances.Add(Handle<JSObject>(obj));
      if (instances.length() == max_references) break;
    }
    // Iterate the rest of the heap to satisfy HeapIterator constraints.
    while (iterator.next()) {
    }
1438 1439
  }

1440 1441 1442 1443
  Handle<FixedArray> result =
      isolate->factory()->NewFixedArray(instances.length());
  for (int i = 0; i < instances.length(); ++i) result->set(i, *instances[i]);
  return *isolate->factory()->NewJSArrayWithElements(result);
1444 1445 1446 1447 1448 1449 1450 1451 1452
}


// 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);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, obj, 0);
1453 1454
  // TODO(1543): Come up with a solution for clients to handle potential errors
  // thrown by an intermediate proxy.
1455
  RETURN_RESULT_OR_FAILURE(isolate, JSReceiver::GetPrototype(isolate, obj));
1456 1457 1458 1459
}


// Patches script source (should be called upon BeforeCompile event).
1460
// TODO(5530): Remove once uses in debug.js are gone.
1461 1462 1463 1464 1465 1466 1467
RUNTIME_FUNCTION(Runtime_DebugSetScriptSource) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);

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

1468
  CHECK(script_wrapper->value()->IsScript());
1469 1470
  Handle<Script> script(Script::cast(script_wrapper->value()));

1471 1472 1473 1474 1475 1476
  // 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();
  }

1477 1478 1479 1480 1481 1482 1483 1484
  script->set_source(*source);

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


RUNTIME_FUNCTION(Runtime_FunctionGetInferredName) {
  SealHandleScope shs(isolate);
1485
  DCHECK_EQ(1, args.length());
1486

1487 1488 1489 1490 1491
  CONVERT_ARG_CHECKED(Object, f, 0);
  if (f->IsJSFunction()) {
    return JSFunction::cast(f)->shared()->inferred_name();
  }
  return isolate->heap()->empty_string();
1492 1493 1494
}


1495 1496
RUNTIME_FUNCTION(Runtime_FunctionGetDebugName) {
  HandleScope scope(isolate);
1497 1498 1499
  DCHECK_EQ(1, args.length());

  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, function, 0);
1500

1501
  if (function->IsJSBoundFunction()) {
1502 1503 1504
    RETURN_RESULT_OR_FAILURE(
        isolate, JSBoundFunction::GetName(
                     isolate, Handle<JSBoundFunction>::cast(function)));
1505
  } else {
1506
    return *JSFunction::GetDebugName(Handle<JSFunction>::cast(function));
1507
  }
1508 1509 1510
}


1511 1512 1513 1514 1515
// Calls specified function with or without entering the debugger.
// This is used in unit tests to run code as if debugger is entered or simply
// to have a stack with C++ frame in the middle.
RUNTIME_FUNCTION(Runtime_ExecuteInDebugContext) {
  HandleScope scope(isolate);
1516
  DCHECK(args.length() == 1);
1517 1518
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);

1519
  DebugScope debug_scope(isolate->debug());
1520 1521 1522 1523 1524
  if (debug_scope.failed()) {
    DCHECK(isolate->has_pending_exception());
    return isolate->heap()->exception();
  }

1525 1526 1527
  RETURN_RESULT_OR_FAILURE(
      isolate, Execution::Call(isolate, function,
                               handle(function->global_proxy()), 0, NULL));
1528 1529 1530
}


1531 1532 1533
RUNTIME_FUNCTION(Runtime_GetDebugContext) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 0);
1534 1535 1536
  Handle<Context> context;
  {
    DebugScope debug_scope(isolate->debug());
1537 1538 1539 1540
    if (debug_scope.failed()) {
      DCHECK(isolate->has_pending_exception());
      return isolate->heap()->exception();
    }
1541 1542
    context = isolate->debug()->GetDebugContext();
  }
1543
  if (context.is_null()) return isolate->heap()->undefined_value();
1544 1545 1546 1547 1548
  context->set_security_token(isolate->native_context()->security_token());
  return context->global_proxy();
}


1549 1550 1551 1552 1553
// Performs a GC.
// Presently, it only does a full GC.
RUNTIME_FUNCTION(Runtime_CollectGarbage) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
1554 1555
  isolate->heap()->CollectAllGarbage(Heap::kNoGCFlags,
                                     GarbageCollectionReason::kRuntime);
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
  return isolate->heap()->undefined_value();
}


// Gets the current heap usage.
RUNTIME_FUNCTION(Runtime_GetHeapUsage) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 0);
  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);
  DCHECK(args.length() == 1);
1581
  CONVERT_ARG_HANDLE_CHECKED(String, script_name, 0);
1582

1583 1584
  Handle<Script> found;
  {
1585 1586 1587
    Script::Iterator iterator(isolate);
    Script* script = NULL;
    while ((script = iterator.Next()) != NULL) {
1588 1589 1590 1591 1592 1593 1594 1595
      if (!script->name()->IsString()) continue;
      String* name = String::cast(script->name());
      if (name->Equals(*script_name)) {
        found = Handle<Script>(script, isolate);
        break;
      }
    }
  }
1596

1597
  if (found.is_null()) return isolate->heap()->undefined_value();
1598
  return *Script::GetWrapper(found);
1599 1600
}

1601
// TODO(5530): Remove once uses in debug.js are gone.
1602 1603 1604 1605 1606
RUNTIME_FUNCTION(Runtime_ScriptLineCount) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_CHECKED(JSValue, script, 0);

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

1610 1611 1612 1613 1614
  if (script_handle->type() == Script::TYPE_WASM) {
    // Return 0 for now; this function will disappear soon anyway.
    return Smi::FromInt(0);
  }

1615 1616 1617 1618 1619 1620
  Script::InitLineEnds(script_handle);

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

1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
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())
        ->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;
  return Smi::cast(line_ends_array->get(line - 1))->value() + 1;
}

}  // namespace

1645
// TODO(5530): Remove once uses in debug.js are gone.
1646 1647 1648 1649 1650 1651
RUNTIME_FUNCTION(Runtime_ScriptLineStartPosition) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_ARG_CHECKED(JSValue, script, 0);
  CONVERT_NUMBER_CHECKED(int32_t, line, Int32, args[1]);

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

1655
  return Smi::FromInt(ScriptLinePosition(script_handle, line));
1656 1657
}

1658
// TODO(5530): Remove once uses in debug.js are gone.
1659 1660 1661 1662 1663 1664
RUNTIME_FUNCTION(Runtime_ScriptLineEndPosition) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_ARG_CHECKED(JSValue, script, 0);
  CONVERT_NUMBER_CHECKED(int32_t, line, Int32, args[1]);

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

1668 1669 1670 1671 1672
  if (script_handle->type() == Script::TYPE_WASM) {
    // Return zero for now; this function will disappear soon anyway.
    return Smi::FromInt(0);
  }

1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
  Script::InitLineEnds(script_handle);

  FixedArray* line_ends_array = FixedArray::cast(script_handle->line_ends());
  const int line_count = line_ends_array->length();

  if (line < 0 || line >= line_count) {
    return Smi::FromInt(-1);
  } else {
    return Smi::cast(line_ends_array->get(line));
  }
}

1685 1686 1687
static Handle<Object> GetJSPositionInfo(Handle<Script> script, int position,
                                        Script::OffsetFlag offset_flag,
                                        Isolate* isolate) {
1688
  Script::PositionInfo info;
1689
  if (!Script::GetPositionInfo(script, position, &info, offset_flag)) {
1690
    return isolate->factory()->null_value();
1691 1692
  }

1693
  Handle<String> source = handle(String::cast(script->source()), isolate);
1694 1695 1696 1697
  Handle<String> sourceText = script->type() == Script::TYPE_WASM
                                  ? isolate->factory()->empty_string()
                                  : isolate->factory()->NewSubString(
                                        source, info.line_start, info.line_end);
1698 1699 1700 1701

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

1702 1703
  JSObject::AddProperty(jsinfo, isolate->factory()->script_string(), script,
                        NONE);
1704 1705 1706 1707 1708 1709 1710 1711 1712
  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);

1713 1714 1715
  return jsinfo;
}

1716
namespace {
1717

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
int ScriptLinePositionWithOffset(Handle<Script> script, int line, int offset) {
  if (line < 0 || offset < 0) return -1;

  if (line == 0) return ScriptLinePosition(script, line) + offset;

  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);
}

1732 1733 1734 1735
Handle<Object> ScriptLocationFromLine(Isolate* isolate, Handle<Script> script,
                                      Handle<Object> opt_line,
                                      Handle<Object> opt_column,
                                      int32_t offset) {
1736 1737 1738
  // Line and column are possibly undefined and we need to handle these cases,
  // additionally subtracting corresponding offsets.

1739 1740
  int32_t line = 0;
  if (!opt_line->IsNull(isolate) && !opt_line->IsUndefined(isolate)) {
1741 1742
    CHECK(opt_line->IsNumber());
    line = NumberToInt32(*opt_line) - script->line_offset();
1743 1744
  }

1745 1746
  int32_t column = 0;
  if (!opt_column->IsNull(isolate) && !opt_column->IsUndefined(isolate)) {
1747 1748 1749
    CHECK(opt_column->IsNumber());
    column = NumberToInt32(*opt_column);
    if (line == 0) column -= script->column_offset();
1750 1751
  }

1752 1753
  int line_position = ScriptLinePositionWithOffset(script, line, offset);
  if (line_position < 0 || column < 0) return isolate->factory()->null_value();
1754

1755 1756
  return GetJSPositionInfo(script, line_position + column, Script::NO_OFFSET,
                           isolate);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
}

// Slow traversal over all scripts on the heap.
bool GetScriptById(Isolate* isolate, int needle, Handle<Script>* result) {
  Script::Iterator iterator(isolate);
  Script* script = NULL;
  while ((script = iterator.Next()) != NULL) {
    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);
  DCHECK(args.length() == 4);
  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);
  DCHECK(args.length() == 4);
  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);
1812 1813
}

1814
// TODO(5530): Remove once uses in debug.js are gone.
1815 1816 1817 1818 1819 1820 1821
RUNTIME_FUNCTION(Runtime_ScriptPositionInfo) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 3);
  CONVERT_ARG_CHECKED(JSValue, script, 0);
  CONVERT_NUMBER_CHECKED(int32_t, position, Int32, args[1]);
  CONVERT_BOOLEAN_ARG_CHECKED(with_offset, 2);

1822
  CHECK(script->value()->IsScript());
1823 1824 1825 1826 1827 1828 1829
  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);
}

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
// TODO(5530): Rename once conflicting function has been deleted.
RUNTIME_FUNCTION(Runtime_ScriptPositionInfo2) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 3);
  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);
}

1846 1847
// Returns the given line as a string, or null if line is out of bounds.
// The parameter line is expected to include the script's line offset.
1848
// TODO(5530): Remove once uses in debug.js are gone.
1849 1850 1851 1852 1853 1854
RUNTIME_FUNCTION(Runtime_ScriptSourceLine) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);
  CONVERT_ARG_CHECKED(JSValue, script, 0);
  CONVERT_NUMBER_CHECKED(int32_t, line, Int32, args[1]);

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

1858 1859 1860 1861 1862
  if (script_handle->type() == Script::TYPE_WASM) {
    // Return null for now; this function will disappear soon anyway.
    return isolate->heap()->null_value();
  }

1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
  Script::InitLineEnds(script_handle);

  FixedArray* line_ends_array = FixedArray::cast(script_handle->line_ends());
  const int line_count = line_ends_array->length();

  line -= script_handle->line_offset();
  if (line < 0 || line_count <= line) {
    return isolate->heap()->null_value();
  }

  const int start =
      (line == 0) ? 0 : Smi::cast(line_ends_array->get(line - 1))->value() + 1;
  const int end = Smi::cast(line_ends_array->get(line))->value();

  Handle<String> source =
      handle(String::cast(script_handle->source()), isolate);
  Handle<String> str = isolate->factory()->NewSubString(source, start, end);

  return *str;
1882
}
1883 1884

// Set one shot breakpoints for the callback function that is passed to a
1885 1886
// built-in function such as Array.forEach to enable stepping into the callback,
// if we are indeed stepping and the callback is subject to debugging.
1887 1888
RUNTIME_FUNCTION(Runtime_DebugPrepareStepInIfStepping) {
  HandleScope scope(isolate);
1889 1890
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, fun, 0);
1891
  isolate->debug()->PrepareStepIn(fun);
1892 1893 1894
  return isolate->heap()->undefined_value();
}

1895 1896 1897 1898 1899 1900
// 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();
1901 1902
}

1903
RUNTIME_FUNCTION(Runtime_DebugRecordGenerator) {
1904 1905 1906 1907
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(JSGeneratorObject, generator, 0);
  CHECK(isolate->debug()->last_step_action() >= StepNext);
1908
  isolate->debug()->RecordGenerator(generator);
1909
  return isolate->heap()->undefined_value();
1910
}
1911 1912

RUNTIME_FUNCTION(Runtime_DebugPushPromise) {
1913
  DCHECK(args.length() == 1);
1914 1915
  HandleScope scope(isolate);
  CONVERT_ARG_HANDLE_CHECKED(JSObject, promise, 0);
1916
  isolate->PushPromise(promise);
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_DebugPopPromise) {
  DCHECK(args.length() == 0);
  SealHandleScope shs(isolate);
  isolate->PopPromise();
  return isolate->heap()->undefined_value();
}

1928 1929 1930 1931 1932
RUNTIME_FUNCTION(Runtime_DebugNextMicrotaskId) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 0);
  return Smi::FromInt(isolate->GetNextDebugMicrotaskId());
}
1933 1934

RUNTIME_FUNCTION(Runtime_DebugAsyncTaskEvent) {
1935
  DCHECK(args.length() == 3);
1936
  HandleScope scope(isolate);
1937 1938 1939 1940
  CONVERT_ARG_HANDLE_CHECKED(String, type, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, id, 1);
  CONVERT_ARG_HANDLE_CHECKED(String, name, 2);
  isolate->debug()->OnAsyncTaskEvent(type, id, name);
1941 1942 1943 1944
  return isolate->heap()->undefined_value();
}


1945
RUNTIME_FUNCTION(Runtime_DebugIsActive) {
1946 1947 1948
  SealHandleScope shs(isolate);
  return Smi::FromInt(isolate->debug()->is_active());
}
1949 1950


1951
RUNTIME_FUNCTION(Runtime_DebugBreakInOptimizedCode) {
1952 1953 1954
  UNIMPLEMENTED();
  return NULL;
}
1955

1956 1957
}  // namespace internal
}  // namespace v8