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

5 6
#include "src/debug/debug.h"

7 8 9 10 11 12 13 14 15
#include "src/api.h"
#include "src/arguments.h"
#include "src/bootstrapper.h"
#include "src/code-stubs.h"
#include "src/codegen.h"
#include "src/compilation-cache.h"
#include "src/compiler.h"
#include "src/deoptimizer.h"
#include "src/execution.h"
16
#include "src/frames-inl.h"
17
#include "src/full-codegen/full-codegen.h"
18
#include "src/global-handles.h"
19
#include "src/isolate-inl.h"
20
#include "src/list.h"
21
#include "src/log.h"
22
#include "src/messages.h"
23
#include "src/snapshot/natives.h"
24

25
#include "include/v8-debug.h"
26

27 28
namespace v8 {
namespace internal {
29

30
Debug::Debug(Isolate* isolate)
31 32 33 34 35 36 37
    : debug_context_(Handle<Context>()),
      event_listener_(Handle<Object>()),
      event_listener_data_(Handle<Object>()),
      message_handler_(NULL),
      command_received_(0),
      command_queue_(isolate->logger(), kQueueInitialSize),
      is_active_(false),
38
      is_suppressed_(false),
39
      live_edit_enabled_(true),  // TODO(yangguo): set to false by default.
40
      break_disabled_(false),
41
      break_points_active_(true),
42
      in_debug_event_listener_(false),
43 44
      break_on_exception_(false),
      break_on_uncaught_exception_(false),
45
      debug_info_list_(NULL),
46
      feature_tracker_(isolate),
47
      isolate_(isolate) {
48
  ThreadInit();
49 50 51
}


52
static v8::Local<v8::Context> GetDebugEventContext(Isolate* isolate) {
53 54 55 56
  Handle<Context> context = isolate->debug()->debugger_entry()->GetContext();
  // Isolate::context() may have been NULL when "script collected" event
  // occured.
  if (context.is_null()) return v8::Local<v8::Context>();
57 58
  Handle<Context> native_context(context->native_context());
  return v8::Utils::ToLocal(native_context);
59 60
}

61
BreakLocation::BreakLocation(Handle<DebugInfo> debug_info, RelocInfo* rinfo,
62
                             int position, int statement_position)
63
    : debug_info_(debug_info),
64
      code_offset_(static_cast<int>(rinfo->pc() - debug_info->code()->entry())),
65 66 67
      rmode_(rinfo->rmode()),
      data_(rinfo->data()),
      position_(position),
68
      statement_position_(statement_position) {}
69

70 71 72
BreakLocation::Iterator::Iterator(Handle<DebugInfo> debug_info,
                                  BreakLocatorType type)
    : debug_info_(debug_info),
73
      reloc_iterator_(debug_info->code(), GetModeMask(type)),
74 75
      break_index_(-1),
      position_(1),
76
      statement_position_(1) {
77
  if (!Done()) Next();
78 79 80 81 82 83 84
}


int BreakLocation::Iterator::GetModeMask(BreakLocatorType type) {
  int mask = 0;
  mask |= RelocInfo::ModeMask(RelocInfo::POSITION);
  mask |= RelocInfo::ModeMask(RelocInfo::STATEMENT_POSITION);
85
  mask |= RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT_AT_RETURN);
86 87 88 89 90 91
  mask |= RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT_AT_CALL);
  if (type == ALL_BREAK_LOCATIONS) {
    mask |= RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT_AT_POSITION);
    mask |= RelocInfo::ModeMask(RelocInfo::DEBUGGER_STATEMENT);
  }
  return mask;
92 93 94
}


95
void BreakLocation::Iterator::Next() {
96
  DisallowHeapAllocation no_gc;
97
  DCHECK(!Done());
98 99 100

  // Iterate through reloc info for code and original code stopping at each
  // breakable code target.
101
  bool first = break_index_ == -1;
102 103
  while (!Done()) {
    if (!first) reloc_iterator_.next();
104
    first = false;
105
    if (Done()) return;
106

107 108
    // Whenever a statement position or (plain) position is passed update the
    // current value of these.
109 110
    if (RelocInfo::IsPosition(rmode())) {
      if (RelocInfo::IsStatementPosition(rmode())) {
111 112
        statement_position_ = static_cast<int>(
            rinfo()->data() - debug_info_->shared()->start_position());
113
      }
114 115
      // Always update the position as we don't want that to be before the
      // statement position.
116 117
      position_ = static_cast<int>(rinfo()->data() -
                                   debug_info_->shared()->start_position());
118 119
      DCHECK(position_ >= 0);
      DCHECK(statement_position_ >= 0);
120
      continue;
121 122
    }

123 124 125 126
    DCHECK(RelocInfo::IsDebugBreakSlot(rmode()) ||
           RelocInfo::IsDebuggerStatement(rmode()));

    if (RelocInfo::IsDebugBreakSlotAtReturn(rmode())) {
127 128 129 130 131 132 133 134 135 136
      // Set the positions to the end of the function.
      if (debug_info_->shared()->HasSourceCode()) {
        position_ = debug_info_->shared()->end_position() -
                    debug_info_->shared()->start_position() - 1;
      } else {
        position_ = 0;
      }
      statement_position_ = position_;
    }

137
    break;
138
  }
139
  break_index_++;
140 141 142
}


143 144
// Find the break point at the supplied address, or the closest one before
// the address.
145 146
BreakLocation BreakLocation::FromCodeOffset(Handle<DebugInfo> debug_info,
                                            int offset) {
147
  Iterator it(debug_info, ALL_BREAK_LOCATIONS);
148
  it.SkipTo(BreakIndexFromCodeOffset(debug_info, offset));
149
  return it.GetBreakLocation();
150 151
}

152 153 154 155 156 157 158
// Move GetFirstFrameSummary Definition to here as FromFrame use it.
FrameSummary GetFirstFrameSummary(JavaScriptFrame* frame) {
  List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
  frame->Summarize(&frames);
  return frames.first();
}

159 160 161 162
BreakLocation BreakLocation::FromFrame(Handle<DebugInfo> debug_info,
                                       JavaScriptFrame* frame) {
  // Code offset to the instruction after the current one, possibly a break
  // location as well. So the "- 1" to exclude it from the search.
163 164 165
  // Get code offset from the unoptimized code.
  FrameSummary summary = GetFirstFrameSummary(frame);
  return FromCodeOffset(debug_info, summary.code_offset() - 1);
166
}
167

168 169
// Find the break point at the supplied address, or the closest one before
// the address.
170 171 172
void BreakLocation::FromCodeOffsetSameStatement(
    Handle<DebugInfo> debug_info, int offset, List<BreakLocation>* result_out) {
  int break_index = BreakIndexFromCodeOffset(debug_info, offset);
173
  Iterator it(debug_info, ALL_BREAK_LOCATIONS);
174 175 176 177 178 179 180 181 182
  it.SkipTo(break_index);
  int statement_position = it.statement_position();
  while (!it.Done() && it.statement_position() == statement_position) {
    result_out->Add(it.GetBreakLocation());
    it.Next();
  }
}


183 184 185 186 187 188 189 190 191 192
void BreakLocation::AllForStatementPosition(Handle<DebugInfo> debug_info,
                                            int statement_position,
                                            List<BreakLocation>* result_out) {
  for (Iterator it(debug_info, ALL_BREAK_LOCATIONS); !it.Done(); it.Next()) {
    if (it.statement_position() == statement_position) {
      result_out->Add(it.GetBreakLocation());
    }
  }
}

193 194
int BreakLocation::BreakIndexFromCodeOffset(Handle<DebugInfo> debug_info,
                                            int offset) {
195
  // Run through all break points to locate the one closest to the address.
196
  int closest_break = 0;
197
  int distance = kMaxInt;
198 199 200
  Code* code = debug_info->code();
  DCHECK(0 <= offset && offset < code->instruction_size());
  Address pc = code->instruction_start() + offset;
201
  for (Iterator it(debug_info, ALL_BREAK_LOCATIONS); !it.Done(); it.Next()) {
202
    // Check if this break point is closer that what was previously found.
203 204 205
    if (it.pc() <= pc && pc - it.pc() < distance) {
      closest_break = it.break_index();
      distance = static_cast<int>(pc - it.pc());
206 207 208 209
      // Check whether we can't get any closer.
      if (distance == 0) break;
    }
  }
210
  return closest_break;
211 212 213
}


214
BreakLocation BreakLocation::FromPosition(Handle<DebugInfo> debug_info,
215
                                          int position,
216
                                          BreakPositionAlignment alignment) {
217 218
  // Run through all break points to locate the one closest to the source
  // position.
219
  int closest_break = 0;
220
  int distance = kMaxInt;
221

222
  for (Iterator it(debug_info, ALL_BREAK_LOCATIONS); !it.Done(); it.Next()) {
223
    int next_position;
224 225 226 227 228
    if (alignment == STATEMENT_ALIGNED) {
      next_position = it.statement_position();
    } else {
      DCHECK(alignment == BREAK_POSITION_ALIGNED);
      next_position = it.position();
229 230
    }
    if (position <= next_position && next_position - position < distance) {
231
      closest_break = it.break_index();
232
      distance = next_position - position;
233 234 235 236 237
      // Check whether we can't get any closer.
      if (distance == 0) break;
    }
  }

238
  Iterator it(debug_info, ALL_BREAK_LOCATIONS);
239 240
  it.SkipTo(closest_break);
  return it.GetBreakLocation();
241 242 243
}


244
void BreakLocation::SetBreakPoint(Handle<Object> break_point_object) {
245 246
  // If there is not already a real break point here patch code with debug
  // break.
247
  if (!HasBreakPoint()) SetDebugBreak();
248
  DCHECK(IsDebugBreak() || IsDebuggerStatement());
249
  // Set the break point information.
250
  DebugInfo::SetBreakPoint(debug_info_, code_offset_, position_,
251
                           statement_position_, break_point_object);
252 253 254
}


255
void BreakLocation::ClearBreakPoint(Handle<Object> break_point_object) {
256
  // Clear the break point information.
257
  DebugInfo::ClearBreakPoint(debug_info_, code_offset_, break_point_object);
258 259 260
  // If there are no more break points here remove the debug break.
  if (!HasBreakPoint()) {
    ClearDebugBreak();
261
    DCHECK(!IsDebugBreak());
262 263 264 265
  }
}


266
void BreakLocation::SetOneShot() {
267
  // Debugger statement always calls debugger. No need to modify it.
268
  if (IsDebuggerStatement()) return;
269

270 271
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
272
    DCHECK(IsDebugBreak());
273 274 275 276 277 278 279 280
    return;
  }

  // Patch code with debug break.
  SetDebugBreak();
}


281
void BreakLocation::ClearOneShot() {
282
  // Debugger statement always calls debugger. No need to modify it.
283
  if (IsDebuggerStatement()) return;
284

285 286
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
287
    DCHECK(IsDebugBreak());
288 289 290 291 292
    return;
  }

  // Patch code removing debug break.
  ClearDebugBreak();
293
  DCHECK(!IsDebugBreak());
294 295 296
}


297
void BreakLocation::SetDebugBreak() {
298
  // Debugger statement always calls debugger. No need to modify it.
299
  if (IsDebuggerStatement()) return;
300

301
  // If there is already a break point here just return. This might happen if
302
  // the same code is flooded with break points twice. Flooding the same
303 304
  // function twice might happen when stepping in a function with an exception
  // handler as the handler and the function is the same.
305
  if (IsDebugBreak()) return;
306

307
  DCHECK(IsDebugBreakSlot());
308 309
  Isolate* isolate = debug_info_->GetIsolate();
  Builtins* builtins = isolate->builtins();
310 311
  Handle<Code> target =
      IsReturn() ? builtins->Return_DebugBreak() : builtins->Slot_DebugBreak();
312
  DebugCodegen::PatchDebugBreakSlot(isolate, pc(), target);
313
  DCHECK(IsDebugBreak());
314 315 316
}


317
void BreakLocation::ClearDebugBreak() {
318
  // Debugger statement always calls debugger. No need to modify it.
319
  if (IsDebuggerStatement()) return;
320

321
  DCHECK(IsDebugBreakSlot());
322
  DebugCodegen::ClearDebugBreakSlot(debug_info_->GetIsolate(), pc());
323
  DCHECK(!IsDebugBreak());
324 325 326
}


327
bool BreakLocation::IsDebugBreak() const {
328 329 330
  if (IsDebuggerStatement()) return false;
  DCHECK(IsDebugBreakSlot());
  return rinfo().IsPatchedDebugBreakSlotSequence();
331 332 333
}


334
Handle<Object> BreakLocation::BreakPointObjects() const {
335
  return debug_info_->GetBreakPointObjects(code_offset_);
336 337 338
}


339 340 341 342 343 344 345 346 347
void DebugFeatureTracker::Track(DebugFeatureTracker::Feature feature) {
  uint32_t mask = 1 << feature;
  // Only count one sample per feature and isolate.
  if (bitfield_ & mask) return;
  isolate_->counters()->debug_feature_usage()->AddSample(feature);
  bitfield_ |= mask;
}


348 349
// Threading support.
void Debug::ThreadInit() {
350 351 352
  thread_local_.break_count_ = 0;
  thread_local_.break_id_ = 0;
  thread_local_.break_frame_id_ = StackFrame::NO_ID;
353
  thread_local_.last_step_action_ = StepNone;
354
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
355
  thread_local_.last_fp_ = 0;
356
  thread_local_.target_fp_ = 0;
357
  thread_local_.step_in_enabled_ = false;
358
  // TODO(isolates): frames_are_dropped_?
359
  base::NoBarrier_Store(&thread_local_.current_debug_scope_,
360
                        static_cast<base::AtomicWord>(0));
361 362 363 364 365
}


char* Debug::ArchiveDebug(char* storage) {
  char* to = storage;
366
  MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
367 368 369 370 371 372 373
  ThreadInit();
  return storage + ArchiveSpacePerThread();
}


char* Debug::RestoreDebug(char* storage) {
  char* from = storage;
374
  MemCopy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
375 376 377 378 379
  return storage + ArchiveSpacePerThread();
}


int Debug::ArchiveSpacePerThread() {
380
  return sizeof(ThreadLocal);
381 382 383
}


384 385
DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
  // Globalize the request debug info object and make it weak.
386
  GlobalHandles* global_handles = debug_info->GetIsolate()->global_handles();
dcarney's avatar
dcarney committed
387 388
  debug_info_ =
      Handle<DebugInfo>::cast(global_handles->Create(debug_info)).location();
389 390 391
}


392
DebugInfoListNode::~DebugInfoListNode() {
dcarney's avatar
dcarney committed
393 394 395
  if (debug_info_ == nullptr) return;
  GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_));
  debug_info_ = nullptr;
396 397 398
}


399 400
bool Debug::Load() {
  // Return if debugger is already loaded.
401
  if (is_loaded()) return true;
402

403 404
  // Bail out if we're already in the process of compiling the native
  // JavaScript source code for the debugger.
405 406
  if (is_suppressed_) return false;
  SuppressDebug while_loading(this);
407 408 409

  // Disable breakpoints and interrupts while compiling and running the
  // debugger scripts including the context creation code.
410
  DisableBreak disable(this, true);
411
  PostponeInterruptsScope postpone(isolate_);
412

413
  // Create the debugger context.
414
  HandleScope scope(isolate_);
415
  ExtensionConfiguration no_extensions;
416
  Handle<Context> context = isolate_->bootstrapper()->CreateEnvironment(
417 418
      MaybeHandle<JSGlobalProxy>(), v8::Local<ObjectTemplate>(), &no_extensions,
      DEBUG_CONTEXT);
419

420 421 422
  // Fail if no context could be created.
  if (context.is_null()) return false;

423 424
  debug_context_ = Handle<Context>::cast(
      isolate_->global_handles()->Create(*context));
425 426 427

  feature_tracker()->Track(DebugFeatureTracker::kActive);

428 429 430 431 432
  return true;
}


void Debug::Unload() {
433
  ClearAllBreakPoints();
434
  ClearStepping();
435

436
  // Return debugger is not loaded.
437
  if (!is_loaded()) return;
438 439

  // Clear debugger context global handle.
440
  GlobalHandles::Destroy(Handle<Object>::cast(debug_context_).location());
441 442 443 444
  debug_context_ = Handle<Context>();
}


445
void Debug::Break(Arguments args, JavaScriptFrame* frame) {
446
  HandleScope scope(isolate_);
447
  DCHECK(args.length() == 0);
448

449 450
  // Initialize LiveEdit.
  LiveEdit::InitializeThreadLocal(this);
451 452

  // Just continue if breaks are disabled or debugger cannot be loaded.
453
  if (break_disabled()) return;
454

455
  // Enter the debugger.
456 457
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
458

459
  // Postpone interrupt during breakpoint processing.
460
  PostponeInterruptsScope postpone(isolate_);
461 462

  // Get the debug info (create it if it does not exist).
463 464 465 466 467 468
  Handle<JSFunction> function(frame->function());
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
    // Return if we failed to retrieve the debug info.
    return;
  }
469
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
470

471
  // Find the break location where execution has stopped.
472
  BreakLocation location = BreakLocation::FromFrame(debug_info, frame);
473 474

  // Find actual break points, if any, and trigger debug break event.
475 476 477 478 479 480 481
  Handle<Object> break_points_hit = CheckBreakPoints(&location);
  if (!break_points_hit->IsUndefined()) {
    // Clear all current stepping setup.
    ClearStepping();
    // Notify the debug event listeners.
    OnDebugBreak(break_points_hit, false);
    return;
482 483
  }

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  // No break point. Check for stepping.
  StepAction step_action = last_step_action();
  Address current_fp = frame->UnpaddedFP();
  Address target_fp = thread_local_.target_fp_;
  Address last_fp = thread_local_.last_fp_;

  bool step_break = true;
  switch (step_action) {
    case StepNone:
      return;
    case StepOut:
      // Step out has not reached the target frame yet.
      if (current_fp < target_fp) return;
      break;
    case StepNext:
      // Step next should not break in a deeper frame.
      if (current_fp < target_fp) return;
    // Fall through.
502 503 504
    case StepIn: {
      int offset =
          static_cast<int>(frame->pc() - location.code()->instruction_start());
505 506
      step_break = location.IsReturn() || (current_fp != last_fp) ||
                   (thread_local_.last_statement_position_ !=
507
                    location.code()->SourceStatementPosition(offset));
508
      break;
509
    }
510 511 512
    case StepFrame:
      step_break = current_fp != last_fp;
      break;
513 514
  }

515 516 517 518
  // Clear all current stepping setup.
  ClearStepping();

  if (step_break) {
519
    // Notify the debug event listeners.
520 521 522 523
    OnDebugBreak(isolate_->factory()->undefined_value(), false);
  } else {
    // Re-prepare to continue.
    PrepareStep(step_action);
524 525 526 527
  }
}


528 529 530 531
// Find break point objects for this location, if any, and evaluate them.
// Return an array of break point objects that evaluated true.
Handle<Object> Debug::CheckBreakPoints(BreakLocation* location,
                                       bool* has_break_points) {
532
  Factory* factory = isolate_->factory();
533 534 535 536
  bool has_break_points_to_check =
      break_points_active_ && location->HasBreakPoint();
  if (has_break_points) *has_break_points = has_break_points_to_check;
  if (!has_break_points_to_check) return factory->undefined_value();
537

538
  Handle<Object> break_point_objects = location->BreakPointObjects();
539 540 541
  // Count the number of break points hit. If there are multiple break points
  // they are in a FixedArray.
  Handle<FixedArray> break_points_hit;
542
  int break_points_hit_count = 0;
543
  DCHECK(!break_point_objects->IsUndefined());
544 545
  if (break_point_objects->IsFixedArray()) {
    Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
546
    break_points_hit = factory->NewFixedArray(array->length());
547
    for (int i = 0; i < array->length(); i++) {
548 549 550
      Handle<Object> break_point_object(array->get(i), isolate_);
      if (CheckBreakPoint(break_point_object)) {
        break_points_hit->set(break_points_hit_count++, *break_point_object);
551 552 553
      }
    }
  } else {
554
    break_points_hit = factory->NewFixedArray(1);
555
    if (CheckBreakPoint(break_point_objects)) {
556
      break_points_hit->set(break_points_hit_count++, *break_point_objects);
557 558
    }
  }
559
  if (break_points_hit_count == 0) return factory->undefined_value();
560
  Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit);
561 562
  result->set_length(Smi::FromInt(break_points_hit_count));
  return result;
563 564 565
}


566
bool Debug::IsMutedAtCurrentLocation(JavaScriptFrame* frame) {
567 568 569 570 571
  // A break location is considered muted if break locations on the current
  // statement have at least one break point, and all of these break points
  // evaluate to false. Aside from not triggering a debug break event at the
  // break location, we also do not trigger one for debugger statements, nor
  // an exception event on exception at this location.
572 573 574 575 576 577 578 579 580
  Object* fun = frame->function();
  if (!fun->IsJSFunction()) return false;
  JSFunction* function = JSFunction::cast(fun);
  if (!function->shared()->HasDebugInfo()) return false;
  HandleScope scope(isolate_);
  Handle<DebugInfo> debug_info(function->shared()->GetDebugInfo());
  // Enter the debugger.
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return false;
581 582 583 584 585 586 587 588 589 590 591 592 593
  BreakLocation current_position = BreakLocation::FromFrame(debug_info, frame);
  List<BreakLocation> break_locations;
  BreakLocation::AllForStatementPosition(
      debug_info, current_position.statement_position(), &break_locations);
  bool has_break_points_at_all = false;
  for (int i = 0; i < break_locations.length(); i++) {
    bool has_break_points;
    Handle<Object> check_result =
        CheckBreakPoints(&break_locations[i], &has_break_points);
    has_break_points_at_all |= has_break_points;
    if (has_break_points && !check_result->IsUndefined()) return false;
  }
  return has_break_points_at_all;
594 595 596
}


597 598 599 600 601 602 603 604
MaybeHandle<Object> Debug::CallFunction(const char* name, int argc,
                                        Handle<Object> args[]) {
  PostponeInterruptsScope no_interrupts(isolate_);
  AssertDebugContext();
  Handle<Object> holder = isolate_->natives_utils_object();
  Handle<JSFunction> fun = Handle<JSFunction>::cast(
      Object::GetProperty(isolate_, holder, name, STRICT).ToHandleChecked());
  Handle<Object> undefined = isolate_->factory()->undefined_value();
605
  return Execution::TryCall(isolate_, fun, undefined, argc, args);
606 607 608
}


609 610
// Check whether a single break point object is triggered.
bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
611 612
  Factory* factory = isolate_->factory();
  HandleScope scope(isolate_);
613

614 615 616 617
  // Ignore check if break point object is not a JSObject.
  if (!break_point_object->IsJSObject()) return true;

  // Get the break id as an object.
618
  Handle<Object> break_id = factory->NewNumberFromInt(Debug::break_id());
619

620
  // Call IsBreakPointTriggered.
621
  Handle<Object> argv[] = { break_id, break_point_object };
622
  Handle<Object> result;
623 624
  if (!CallFunction("IsBreakPointTriggered", arraysize(argv), argv)
           .ToHandle(&result)) {
625 626
    return false;
  }
627 628

  // Return whether the break point is triggered.
629
  return result->IsTrue();
630 631 632
}


633
bool Debug::SetBreakPoint(Handle<JSFunction> function,
634 635
                          Handle<Object> break_point_object,
                          int* source_position) {
636
  HandleScope scope(isolate_);
637

638 639 640
  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
641
    // Return if retrieving debug info failed.
642
    return true;
643 644
  }

645
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
646
  // Source positions starts with zero.
647
  DCHECK(*source_position >= 0);
648 649

  // Find the break point and change it.
650
  BreakLocation location = BreakLocation::FromPosition(
651
      debug_info, *source_position, STATEMENT_ALIGNED);
652 653
  *source_position = location.statement_position();
  location.SetBreakPoint(break_point_object);
654

655 656
  feature_tracker()->Track(DebugFeatureTracker::kBreakPoint);

657
  // At least one active break point now.
658
  return debug_info->GetBreakPointCount() > 0;
659 660 661
}


662 663
bool Debug::SetBreakPointForScript(Handle<Script> script,
                                   Handle<Object> break_point_object,
664 665
                                   int* source_position,
                                   BreakPositionAlignment alignment) {
666 667
  HandleScope scope(isolate_);

668
  // Obtain shared function info for the function.
669 670
  Handle<Object> result =
      FindSharedFunctionInfoInScript(script, *source_position);
671 672 673
  if (result->IsUndefined()) return false;

  // Make sure the function has set up the debug info.
674
  Handle<SharedFunctionInfo> shared = Handle<SharedFunctionInfo>::cast(result);
675 676 677 678 679 680 681 682 683 684 685 686 687 688
  if (!EnsureDebugInfo(shared, Handle<JSFunction>::null())) {
    // Return if retrieving debug info failed.
    return false;
  }

  // Find position within function. The script position might be before the
  // source position of the first function.
  int position;
  if (shared->start_position() > *source_position) {
    position = 0;
  } else {
    position = *source_position - shared->start_position();
  }

689
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
690
  // Source positions starts with zero.
691
  DCHECK(position >= 0);
692 693

  // Find the break point and change it.
694 695
  BreakLocation location =
      BreakLocation::FromPosition(debug_info, position, alignment);
696
  location.SetBreakPoint(break_point_object);
697

698 699
  feature_tracker()->Track(DebugFeatureTracker::kBreakPoint);

700 701
  position = (alignment == STATEMENT_ALIGNED) ? location.statement_position()
                                              : location.position();
702 703

  *source_position = position + shared->start_position();
704 705

  // At least one active break point now.
706
  DCHECK(debug_info->GetBreakPointCount() > 0);
707 708 709 710
  return true;
}


711
void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
712
  HandleScope scope(isolate_);
713

714 715
  DebugInfoListNode* node = debug_info_list_;
  while (node != NULL) {
716 717
    Handle<Object> result =
        DebugInfo::FindBreakPointInfo(node->debug_info(), break_point_object);
718 719
    if (!result->IsUndefined()) {
      // Get information in the break point.
720 721
      Handle<BreakPointInfo> break_point_info =
          Handle<BreakPointInfo>::cast(result);
722 723
      Handle<DebugInfo> debug_info = node->debug_info();

724 725
      BreakLocation location = BreakLocation::FromCodeOffset(
          debug_info, break_point_info->code_offset());
726
      location.ClearBreakPoint(break_point_object);
727 728 729 730

      // If there are no more break points left remove the debug info for this
      // function.
      if (debug_info->GetBreakPointCount() == 0) {
731
        RemoveDebugInfoAndClearFromShared(debug_info);
732 733 734 735 736 737 738 739 740
      }

      return;
    }
    node = node->next();
  }
}


741 742 743
// Clear out all the debug break code. This is ONLY supposed to be used when
// shutting down the debugger as it will leave the break point information in
// DebugInfo even though the code is patched back to the non break point state.
744
void Debug::ClearAllBreakPoints() {
745 746 747 748 749 750
  for (DebugInfoListNode* node = debug_info_list_; node != NULL;
       node = node->next()) {
    for (BreakLocation::Iterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
         !it.Done(); it.Next()) {
      it.GetBreakLocation().ClearDebugBreak();
    }
751 752 753
  }
  // Remove all debug info.
  while (debug_info_list_ != NULL) {
754
    RemoveDebugInfoAndClearFromShared(debug_info_list_->debug_info());
755 756 757 758
  }
}


759 760
void Debug::FloodWithOneShot(Handle<JSFunction> function,
                             BreakLocatorType type) {
761 762 763
  // Debug utility functions are not subject to debugging.
  if (function->native_context() == *debug_context()) return;

764 765 766 767 768 769 770
  if (!function->shared()->IsSubjectToDebugging()) {
    // Builtin functions are not subject to stepping, but need to be
    // deoptimized, because optimized code does not check for debug
    // step in at call sites.
    Deoptimizer::DeoptimizeFunction(*function);
    return;
  }
771 772 773
  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
774 775 776
    // Return if we failed to retrieve the debug info.
    return;
  }
777 778

  // Flood the function with break points.
779 780
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
  for (BreakLocation::Iterator it(debug_info, type); !it.Done(); it.Next()) {
781
    it.GetBreakLocation().SetOneShot();
782 783 784 785 786 787 788 789 790 791 792 793 794
  }
}


void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
  if (type == BreakUncaughtException) {
    break_on_uncaught_exception_ = enable;
  } else {
    break_on_exception_ = enable;
  }
}


795 796 797 798 799 800 801 802 803
bool Debug::IsBreakOnException(ExceptionBreakType type) {
  if (type == BreakUncaughtException) {
    return break_on_uncaught_exception_;
  } else {
    return break_on_exception_;
  }
}


804 805 806 807 808 809 810 811 812 813
void Debug::PrepareStepIn(Handle<JSFunction> function) {
  if (!is_active()) return;
  if (last_step_action() < StepIn) return;
  if (in_debug_scope()) return;
  if (thread_local_.step_in_enabled_) {
    FloodWithOneShot(function);
  }
}


814 815 816 817 818 819 820 821 822 823 824
void Debug::PrepareStepOnThrow() {
  if (!is_active()) return;
  if (last_step_action() == StepNone) return;
  if (in_debug_scope()) return;

  ClearOneShot();

  // Iterate through the JavaScript stack looking for handlers.
  JavaScriptFrameIterator it(isolate_);
  while (!it.done()) {
    JavaScriptFrame* frame = it.frame();
825
    if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) break;
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    it.Advance();
  }

  // Find the closest Javascript frame we can flood with one-shots.
  while (!it.done() &&
         !it.frame()->function()->shared()->IsSubjectToDebugging()) {
    it.Advance();
  }

  if (it.done()) return;  // No suitable Javascript catch handler.

  FloodWithOneShot(Handle<JSFunction>(it.frame()->function()));
}


841
void Debug::PrepareStep(StepAction step_action) {
842
  HandleScope scope(isolate_);
843

844
  DCHECK(in_debug_scope());
845 846 847 848 849

  // Get the frame where the execution has stopped and skip the debug frame if
  // any. The debug frame will only be present if execution was stopped due to
  // hitting a break point. In other situations (e.g. unhandled exception) the
  // debug frame is not present.
850 851 852 853 854
  StackFrame::Id frame_id = break_frame_id();
  // If there is no JavaScript stack don't do anything.
  if (frame_id == StackFrame::NO_ID) return;

  JavaScriptFrameIterator frames_it(isolate_, frame_id);
855 856
  JavaScriptFrame* frame = frames_it.frame();

857 858
  feature_tracker()->Track(DebugFeatureTracker::kStepping);

859 860 861 862 863
  // Remember this step action and count.
  thread_local_.last_step_action_ = step_action;
  STATIC_ASSERT(StepFrame > StepIn);
  thread_local_.step_in_enabled_ = (step_action >= StepIn);

864
  // If the function on the top frame is unresolved perform step out. This will
865
  // be the case when calling unknown function and having the debugger stopped
866 867 868 869 870 871
  // in an unhandled exception.
  if (!frame->function()->IsJSFunction()) {
    // Step out: Find the calling JavaScript frame and flood it with
    // breakpoints.
    frames_it.Advance();
    // Fill the function to return to with one-shot break points.
872
    JSFunction* function = frames_it.frame()->function();
873
    FloodWithOneShot(Handle<JSFunction>(function));
874 875 876 877
    return;
  }

  // Get the debug info (create it if it does not exist).
878
  FrameSummary summary = GetFirstFrameSummary(frame);
879
  Handle<JSFunction> function(summary.function());
880 881
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
882 883 884
    // Return if ensuring debug info failed.
    return;
  }
885

886 887
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
  // Refresh frame summary if the code has been recompiled for debugging.
888 889 890
  if (AbstractCode::cast(shared->code()) != *summary.abstract_code()) {
    summary = GetFirstFrameSummary(frame);
  }
891

892 893
  // PC points to the instruction after the current one, possibly a break
  // location as well. So the "- 1" to exclude it from the search.
894 895
  BreakLocation location =
      BreakLocation::FromCodeOffset(debug_info, summary.code_offset() - 1);
896

897 898
  // At a return statement we will step out either way.
  if (location.IsReturn()) step_action = StepOut;
899 900

  thread_local_.last_statement_position_ =
901
      debug_info->code()->SourceStatementPosition(summary.code_offset());
902
  thread_local_.last_fp_ = frame->UnpaddedFP();
903

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
  switch (step_action) {
    case StepNone:
      UNREACHABLE();
      break;
    case StepOut:
      // Advance to caller frame.
      frames_it.Advance();
      // Skip native and extension functions on the stack.
      while (!frames_it.done() &&
             !frames_it.frame()->function()->shared()->IsSubjectToDebugging()) {
        // Builtin functions are not subject to stepping, but need to be
        // deoptimized to include checks for step-in at call sites.
        Deoptimizer::DeoptimizeFunction(frames_it.frame()->function());
        frames_it.Advance();
      }
      if (frames_it.done()) {
        // Stepping out to the embedder. Disable step-in to avoid stepping into
        // the next (unrelated) call that the embedder makes.
        thread_local_.step_in_enabled_ = false;
      } else {
        // Fill the caller function to return to with one-shot break points.
        Handle<JSFunction> caller_function(frames_it.frame()->function());
        FloodWithOneShot(caller_function);
        thread_local_.target_fp_ = frames_it.frame()->UnpaddedFP();
      }
      // Clear last position info. For stepping out it does not matter.
      thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
      thread_local_.last_fp_ = 0;
      break;
    case StepNext:
      thread_local_.target_fp_ = frame->UnpaddedFP();
      FloodWithOneShot(function);
      break;
    case StepIn:
      FloodWithOneShot(function);
      break;
    case StepFrame:
      // No point in setting one-shot breaks at places where we are not about
      // to leave the current frame.
      FloodWithOneShot(function, CALLS_AND_RETURNS);
      break;
945 946 947 948 949 950
  }
}


// Simple function for returning the source positions for active break points.
Handle<Object> Debug::GetSourceBreakLocations(
951 952
    Handle<SharedFunctionInfo> shared,
    BreakPositionAlignment position_alignment) {
953
  Isolate* isolate = shared->GetIsolate();
954
  Heap* heap = isolate->heap();
955
  if (!shared->HasDebugInfo()) {
956 957
    return Handle<Object>(heap->undefined_value(), isolate);
  }
958
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
959
  if (debug_info->GetBreakPointCount() == 0) {
960
    return Handle<Object>(heap->undefined_value(), isolate);
961 962
  }
  Handle<FixedArray> locations =
963
      isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
964
  int count = 0;
965
  for (int i = 0; i < debug_info->break_points()->length(); ++i) {
966 967 968
    if (!debug_info->break_points()->get(i)->IsUndefined()) {
      BreakPointInfo* break_point_info =
          BreakPointInfo::cast(debug_info->break_points()->get(i));
969 970 971 972 973
      int break_points = break_point_info->GetBreakPointCount();
      if (break_points == 0) continue;
      Smi* position = NULL;
      switch (position_alignment) {
        case STATEMENT_ALIGNED:
974
          position = Smi::FromInt(break_point_info->statement_position());
975 976
          break;
        case BREAK_POSITION_ALIGNED:
977
          position = Smi::FromInt(break_point_info->source_position());
978
          break;
979
      }
980
      for (int j = 0; j < break_points; ++j) locations->set(count++, position);
981 982 983 984 985 986 987 988 989 990
    }
  }
  return locations;
}


void Debug::ClearStepping() {
  // Clear the various stepping setup.
  ClearOneShot();

991
  thread_local_.last_step_action_ = StepNone;
992
  thread_local_.step_in_enabled_ = false;
993 994
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
  thread_local_.last_fp_ = 0;
995
  thread_local_.target_fp_ = 0;
996 997
}

998

999 1000 1001 1002 1003
// Clears all the one-shot break points that are currently set. Normally this
// function is called each time a break point is hit as one shot break points
// are used to support stepping.
void Debug::ClearOneShot() {
  // The current implementation just runs through all the breakpoints. When the
1004
  // last break point for a function is removed that function is automatically
1005
  // removed from the list.
1006 1007 1008 1009 1010
  for (DebugInfoListNode* node = debug_info_list_; node != NULL;
       node = node->next()) {
    for (BreakLocation::Iterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
         !it.Done(); it.Next()) {
      it.GetBreakLocation().ClearOneShot();
1011 1012 1013 1014 1015
    }
  }
}


1016 1017 1018
void Debug::EnableStepIn() {
  STATIC_ASSERT(StepFrame > StepIn);
  thread_local_.step_in_enabled_ = (last_step_action() >= StepIn);
1019 1020 1021
}


1022 1023 1024 1025
bool MatchingCodeTargets(Code* target1, Code* target2) {
  if (target1 == target2) return true;
  if (target1->kind() != target2->kind()) return false;
  return target1->is_handler() || target1->is_inline_cache_stub();
1026 1027 1028
}


1029 1030 1031 1032 1033 1034 1035
// Count the number of calls before the current frame PC to find the
// corresponding PC in the newly recompiled code.
static Address ComputeNewPcForRedirect(Code* new_code, Code* old_code,
                                       Address old_pc) {
  DCHECK_EQ(old_code->kind(), Code::FUNCTION);
  DCHECK_EQ(new_code->kind(), Code::FUNCTION);
  DCHECK(new_code->has_debug_break_slots());
1036 1037 1038 1039
  static const int mask = RelocInfo::kCodeTargetMask;

  // Find the target of the current call.
  Code* target = NULL;
1040
  intptr_t delta = 0;
1041 1042
  for (RelocIterator it(old_code, mask); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
1043 1044 1045 1046
    Address current_pc = rinfo->pc();
    // The frame PC is behind the call instruction by the call instruction size.
    if (current_pc > old_pc) break;
    delta = old_pc - current_pc;
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    target = Code::GetCodeFromTargetAddress(rinfo->target_address());
  }

  // Count the number of calls to the same target before the current call.
  int index = 0;
  for (RelocIterator it(old_code, mask); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
    Address current_pc = rinfo->pc();
    if (current_pc > old_pc) break;
    Code* current = Code::GetCodeFromTargetAddress(rinfo->target_address());
    if (MatchingCodeTargets(target, current)) index++;
  }

  DCHECK(index > 0);

  // Repeat the count on the new code to find corresponding call.
  for (RelocIterator it(new_code, mask); !it.done(); it.next()) {
    RelocInfo* rinfo = it.rinfo();
    Code* current = Code::GetCodeFromTargetAddress(rinfo->target_address());
    if (MatchingCodeTargets(target, current)) index--;
    if (index == 0) return rinfo->pc() + delta;
1068 1069
  }

1070 1071
  UNREACHABLE();
  return NULL;
1072 1073 1074
}


1075 1076
// Count the number of continuations at which the current pc offset is at.
static int ComputeContinuationIndexFromPcOffset(Code* code, int pc_offset) {
1077
  DCHECK_EQ(code->kind(), Code::FUNCTION);
1078 1079 1080
  Address pc = code->instruction_start() + pc_offset;
  int mask = RelocInfo::ModeMask(RelocInfo::GENERATOR_CONTINUATION);
  int index = 0;
1081
  for (RelocIterator it(code, mask); !it.done(); it.next()) {
1082 1083 1084 1085 1086
    index++;
    RelocInfo* rinfo = it.rinfo();
    Address current_pc = rinfo->pc();
    if (current_pc == pc) break;
    DCHECK(current_pc < pc);
1087
  }
1088 1089
  return index;
}
1090 1091


1092 1093 1094 1095 1096 1097 1098 1099
// Find the pc offset for the given continuation index.
static int ComputePcOffsetFromContinuationIndex(Code* code, int index) {
  DCHECK_EQ(code->kind(), Code::FUNCTION);
  DCHECK(code->has_debug_break_slots());
  int mask = RelocInfo::ModeMask(RelocInfo::GENERATOR_CONTINUATION);
  RelocIterator it(code, mask);
  for (int i = 1; i < index; i++) it.next();
  return static_cast<int>(it.rinfo()->pc() - code->instruction_start());
1100 1101 1102
}


1103 1104 1105 1106 1107
class RedirectActiveFunctions : public ThreadVisitor {
 public:
  explicit RedirectActiveFunctions(SharedFunctionInfo* shared)
      : shared_(shared) {
    DCHECK(shared->HasDebugCode());
1108 1109
  }

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
    for (JavaScriptFrameIterator it(isolate, top); !it.done(); it.Advance()) {
      JavaScriptFrame* frame = it.frame();
      JSFunction* function = frame->function();
      if (frame->is_optimized()) continue;
      if (!function->Inlines(shared_)) continue;

      Code* frame_code = frame->LookupCode();
      DCHECK(frame_code->kind() == Code::FUNCTION);
      if (frame_code->has_debug_break_slots()) continue;

      Code* new_code = function->shared()->code();
      Address old_pc = frame->pc();
      Address new_pc = ComputeNewPcForRedirect(new_code, frame_code, old_pc);

      if (FLAG_trace_deopt) {
        PrintF("Replacing pc for debugging: %08" V8PRIxPTR " => %08" V8PRIxPTR
               "\n",
               reinterpret_cast<intptr_t>(old_pc),
               reinterpret_cast<intptr_t>(new_pc));
      }
1131

1132 1133 1134 1135
      if (FLAG_enable_embedded_constant_pool) {
        // Update constant pool pointer for new code.
        frame->set_constant_pool(new_code->constant_pool());
      }
1136

1137 1138 1139 1140
      // Patch the return address to return into the code with
      // debug break slots.
      frame->set_pc(new_pc);
    }
1141 1142 1143
  }

 private:
1144 1145
  SharedFunctionInfo* shared_;
  DisallowHeapAllocation no_gc_;
1146 1147 1148
};


1149 1150
bool Debug::PrepareFunctionForBreakPoints(Handle<SharedFunctionInfo> shared) {
  DCHECK(shared->is_compiled());
1151

1152 1153
  if (isolate_->concurrent_recompilation_enabled()) {
    isolate_->optimizing_compile_dispatcher()->Flush();
1154
  }
1155

1156 1157
  List<Handle<JSFunction> > functions;
  List<Handle<JSGeneratorObject> > suspended_generators;
1158

1159
  // Flush all optimized code maps. Note that the below heap iteration does not
1160 1161 1162 1163 1164
  // cover this, because the given function might have been inlined into code
  // for which no JSFunction exists.
  {
    SharedFunctionInfo::Iterator iterator(isolate_);
    while (SharedFunctionInfo* shared = iterator.Next()) {
1165 1166 1167
      if (!shared->OptimizedCodeMapIsCleared()) {
        shared->ClearOptimizedCodeMap();
      }
1168
    }
1169
  }
1170

1171
  // Make sure we abort incremental marking.
1172 1173
  isolate_->heap()->CollectAllGarbage(Heap::kMakeHeapIterableMask,
                                      "prepare for break points");
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  {
    HeapIterator iterator(isolate_->heap());
    HeapObject* obj;
    bool include_generators = shared->is_generator();

    while ((obj = iterator.next())) {
      if (obj->IsJSFunction()) {
        JSFunction* function = JSFunction::cast(obj);
        if (!function->Inlines(*shared)) continue;
        if (function->code()->kind() == Code::OPTIMIZED_FUNCTION) {
          Deoptimizer::DeoptimizeFunction(function);
1186
        }
1187
        if (function->shared() == *shared) functions.Add(handle(function));
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
      } else if (include_generators && obj->IsJSGeneratorObject()) {
        JSGeneratorObject* generator_obj = JSGeneratorObject::cast(obj);
        if (!generator_obj->is_suspended()) continue;
        JSFunction* function = generator_obj->function();
        if (!function->Inlines(*shared)) continue;
        int pc_offset = generator_obj->continuation();
        int index =
            ComputeContinuationIndexFromPcOffset(function->code(), pc_offset);
        generator_obj->set_continuation(index);
        suspended_generators.Add(handle(generator_obj));
1198 1199
      }
    }
1200
  }
1201

1202 1203
  if (!shared->HasDebugCode()) {
    DCHECK(functions.length() > 0);
1204
    if (!Compiler::CompileDebugCode(functions.first())) return false;
1205
  }
1206

1207 1208 1209
  for (Handle<JSFunction> const function : functions) {
    function->ReplaceCode(shared->code());
  }
1210

1211 1212 1213 1214 1215
  for (Handle<JSGeneratorObject> const generator_obj : suspended_generators) {
    int index = generator_obj->continuation();
    int pc_offset = ComputePcOffsetFromContinuationIndex(shared->code(), index);
    generator_obj->set_continuation(pc_offset);
  }
1216

1217 1218 1219 1220
  // Update PCs on the stack to point to recompiled code.
  RedirectActiveFunctions redirect_visitor(*shared);
  redirect_visitor.VisitThread(isolate_, isolate_->thread_local_top());
  isolate_->thread_manager()->IterateArchivedThreads(&redirect_visitor);
1221

1222
  return true;
1223 1224 1225
}


1226 1227 1228 1229 1230 1231 1232 1233 1234
class SharedFunctionInfoFinder {
 public:
  explicit SharedFunctionInfoFinder(int target_position)
      : current_candidate_(NULL),
        current_candidate_closure_(NULL),
        current_start_position_(RelocInfo::kNoPosition),
        target_position_(target_position) {}

  void NewCandidate(SharedFunctionInfo* shared, JSFunction* closure = NULL) {
1235
    if (!shared->IsSubjectToDebugging()) return;
1236 1237 1238 1239
    int start_position = shared->function_token_position();
    if (start_position == RelocInfo::kNoPosition) {
      start_position = shared->start_position();
    }
1240

1241 1242 1243 1244 1245 1246
    if (start_position > target_position_) return;
    if (target_position_ > shared->end_position()) return;

    if (current_candidate_ != NULL) {
      if (current_start_position_ == start_position &&
          shared->end_position() == current_candidate_->end_position()) {
1247 1248
        // If we already have a matching closure, do not throw it away.
        if (current_candidate_closure_ != NULL && closure == NULL) return;
1249 1250 1251
        // If a top-level function contains only one function
        // declaration the source for the top-level and the function
        // is the same. In that case prefer the non top-level function.
1252
        if (!current_candidate_->is_toplevel() && shared->is_toplevel()) return;
1253 1254 1255 1256 1257
      } else if (start_position < current_start_position_ ||
                 current_candidate_->end_position() < shared->end_position()) {
        return;
      }
    }
1258

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
    current_start_position_ = start_position;
    current_candidate_ = shared;
    current_candidate_closure_ = closure;
  }

  SharedFunctionInfo* Result() { return current_candidate_; }

  JSFunction* ResultClosure() { return current_candidate_closure_; }

 private:
  SharedFunctionInfo* current_candidate_;
  JSFunction* current_candidate_closure_;
  int current_start_position_;
  int target_position_;
  DisallowHeapAllocation no_gc_;
};
1275

1276

1277 1278 1279 1280 1281 1282
// We need to find a SFI for a literal that may not yet have been compiled yet,
// and there may not be a JSFunction referencing it. Find the SFI closest to
// the given position, compile it to reveal possible inner SFIs and repeat.
// While we are at this, also ensure code with debug break slots so that we do
// not have to compile a SFI without JSFunction, which is paifu for those that
// cannot be compiled without context (need to find outer compilable SFI etc.)
1283 1284
Handle<Object> Debug::FindSharedFunctionInfoInScript(Handle<Script> script,
                                                     int position) {
1285
  for (int iteration = 0;; iteration++) {
1286 1287
    // Go through all shared function infos associated with this script to
    // find the inner most function containing this position.
1288 1289
    // If there is no shared function info for this script at all, there is
    // no point in looking for it by walking the heap.
1290 1291 1292 1293 1294
    if (!script->shared_function_infos()->IsWeakFixedArray()) break;

    SharedFunctionInfo* shared;
    {
      SharedFunctionInfoFinder finder(position);
1295 1296 1297 1298
      WeakFixedArray::Iterator iterator(script->shared_function_infos());
      SharedFunctionInfo* candidate;
      while ((candidate = iterator.Next<SharedFunctionInfo>())) {
        finder.NewCandidate(candidate);
1299 1300 1301
      }
      shared = finder.Result();
      if (shared == NULL) break;
1302
      // We found it if it's already compiled and has debug code.
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
      if (shared->HasDebugCode()) {
        Handle<SharedFunctionInfo> shared_handle(shared);
        // If the iteration count is larger than 1, we had to compile the outer
        // function in order to create this shared function info. So there can
        // be no JSFunction referencing it. We can anticipate creating a debug
        // info while bypassing PrepareFunctionForBreakpoints.
        if (iteration > 1) {
          AllowHeapAllocation allow_before_return;
          CreateDebugInfo(shared_handle);
        }
        return shared_handle;
      }
1315
    }
1316 1317
    // If not, compile to reveal inner functions, if possible.
    if (shared->allows_lazy_compilation_without_context()) {
1318
      HandleScope scope(isolate_);
1319
      if (!Compiler::CompileDebugCode(handle(shared))) break;
1320
      continue;
1321
    }
1322

1323 1324 1325
    // If not possible, comb the heap for the best suitable compile target.
    JSFunction* closure;
    {
1326
      HeapIterator it(isolate_->heap());
1327 1328
      SharedFunctionInfoFinder finder(position);
      while (HeapObject* object = it.next()) {
1329 1330
        JSFunction* candidate_closure = NULL;
        SharedFunctionInfo* candidate = NULL;
1331
        if (object->IsJSFunction()) {
1332 1333
          candidate_closure = JSFunction::cast(object);
          candidate = candidate_closure->shared();
1334
        } else if (object->IsSharedFunctionInfo()) {
1335 1336
          candidate = SharedFunctionInfo::cast(object);
          if (!candidate->allows_lazy_compilation_without_context()) continue;
1337 1338 1339
        } else {
          continue;
        }
1340 1341 1342
        if (candidate->script() == *script) {
          finder.NewCandidate(candidate, candidate_closure);
        }
1343 1344 1345 1346
      }
      closure = finder.ResultClosure();
      shared = finder.Result();
    }
1347
    if (shared == NULL) break;
1348 1349
    HandleScope scope(isolate_);
    if (closure == NULL) {
1350
      if (!Compiler::CompileDebugCode(handle(shared))) break;
1351
    } else {
1352
      if (!Compiler::CompileDebugCode(handle(closure))) break;
1353 1354 1355
    }
  }
  return isolate_->factory()->undefined_value();
1356 1357 1358
}


1359
// Ensures the debug information is present for shared.
1360 1361
bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
                            Handle<JSFunction> function) {
1362
  if (!shared->IsSubjectToDebugging()) return false;
1363

1364
  // Return if we already have the debug info for shared.
1365
  if (shared->HasDebugInfo()) return true;
1366

1367
  if (function.is_null()) {
1368
    DCHECK(shared->HasDebugCode());
1369
  } else if (!Compiler::Compile(function, CLEAR_EXCEPTION)) {
1370 1371
    return false;
  }
1372

1373 1374
  if (!PrepareFunctionForBreakPoints(shared)) return false;

1375 1376 1377 1378 1379 1380 1381
  CreateDebugInfo(shared);

  return true;
}


void Debug::CreateDebugInfo(Handle<SharedFunctionInfo> shared) {
1382
  // Create the debug info object.
1383
  DCHECK(shared->HasDebugCode());
1384
  Handle<DebugInfo> debug_info = isolate_->factory()->NewDebugInfo(shared);
1385 1386 1387 1388 1389 1390 1391 1392

  // Add debug info to the list.
  DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
  node->set_next(debug_info_list_);
  debug_info_list_ = node;
}


1393 1394 1395
void Debug::RemoveDebugInfoAndClearFromShared(Handle<DebugInfo> debug_info) {
  HandleScope scope(isolate_);
  Handle<SharedFunctionInfo> shared(debug_info->shared());
1396

1397
  DCHECK_NOT_NULL(debug_info_list_);
1398 1399 1400 1401
  // Run through the debug info objects to find this one and remove it.
  DebugInfoListNode* prev = NULL;
  DebugInfoListNode* current = debug_info_list_;
  while (current != NULL) {
1402 1403 1404 1405 1406 1407 1408 1409 1410
    if (current->debug_info().is_identical_to(debug_info)) {
      // Unlink from list. If prev is NULL we are looking at the first element.
      if (prev == NULL) {
        debug_info_list_ = current->next();
      } else {
        prev->set_next(current->next());
      }
      delete current;
      shared->set_debug_info(isolate_->heap()->undefined_value());
1411 1412 1413 1414 1415 1416
      return;
    }
    // Move to next in list.
    prev = current;
    current = current->next();
  }
1417 1418 1419 1420 1421 1422

  UNREACHABLE();
}


void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
1423 1424 1425
  after_break_target_ = NULL;

  if (LiveEdit::SetAfterBreakTarget(this)) return;  // LiveEdit did the job.
1426

1427 1428
  // Continue just after the slot.
  after_break_target_ = frame->pc();
1429 1430 1431
}


1432
bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
1433
  HandleScope scope(isolate_);
1434 1435

  // Get the executing function in which the debug break occurred.
1436 1437
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
1438 1439 1440 1441

  // With no debug info there are no break points, so we can't be at a return.
  if (!shared->HasDebugInfo()) return false;
  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
1442 1443 1444
  Handle<Code> code(debug_info->code());
#ifdef DEBUG
  // Get the code which is actually executing.
1445
  Handle<Code> frame_code(frame->LookupCode());
1446
  DCHECK(frame_code.is_identical_to(code));
1447 1448
#endif

1449 1450 1451
  // Find the reloc info matching the start of the debug break slot.
  Address slot_pc = frame->pc() - Assembler::kDebugBreakSlotLength;
  int mask = RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT_AT_RETURN);
1452
  for (RelocIterator it(*code, mask); !it.done(); it.next()) {
1453
    if (it.rinfo()->pc() == slot_pc) return true;
1454 1455 1456 1457 1458
  }
  return false;
}


1459
void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
1460
                                  LiveEdit::FrameDropMode mode) {
1461
  if (mode != LiveEdit::CURRENTLY_SET_MODE) {
1462 1463
    thread_local_.frame_drop_mode_ = mode;
  }
1464 1465 1466 1467
  thread_local_.break_frame_id_ = new_break_frame_id;
}


1468
bool Debug::IsDebugGlobal(JSGlobalObject* global) {
1469
  return is_loaded() && global == debug_context()->global_object();
1470 1471 1472
}


1473
void Debug::ClearMirrorCache() {
1474
  PostponeInterruptsScope postpone(isolate_);
1475
  HandleScope scope(isolate_);
1476
  CallFunction("ClearMirrorCache", 0, NULL);
1477 1478 1479
}


1480
Handle<FixedArray> Debug::GetLoadedScripts() {
1481
  isolate_->heap()->CollectAllGarbage();
1482 1483 1484 1485 1486 1487 1488 1489
  Factory* factory = isolate_->factory();
  if (!factory->script_list()->IsWeakFixedArray()) {
    return factory->empty_fixed_array();
  }
  Handle<WeakFixedArray> array =
      Handle<WeakFixedArray>::cast(factory->script_list());
  Handle<FixedArray> results = factory->NewFixedArray(array->Length());
  int length = 0;
1490 1491 1492 1493 1494
  {
    Script::Iterator iterator(isolate_);
    Script* script;
    while ((script = iterator.Next())) {
      if (script->HasValidSource()) results->set(length++, script);
1495 1496 1497 1498
    }
  }
  results->Shrink(length);
  return results;
1499 1500 1501
}


1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
void Debug::GetStepinPositions(JavaScriptFrame* frame, StackFrame::Id frame_id,
                               List<int>* results_out) {
  FrameSummary summary = GetFirstFrameSummary(frame);

  Handle<JSFunction> fun = Handle<JSFunction>(summary.function());
  Handle<SharedFunctionInfo> shared = Handle<SharedFunctionInfo>(fun->shared());

  if (!EnsureDebugInfo(shared, fun)) return;

  Handle<DebugInfo> debug_info(shared->GetDebugInfo());
  // Refresh frame summary if the code has been recompiled for debugging.
1513 1514 1515
  if (AbstractCode::cast(shared->code()) != *summary.abstract_code()) {
    summary = GetFirstFrameSummary(frame);
  }
1516 1517

  // Find range of break points starting from the break point where execution
1518 1519 1520
  // has stopped. The code offset points to the instruction after the current
  // possibly a break location, too. Subtract one to exclude it from the search.
  int call_offset = summary.code_offset() - 1;
1521
  List<BreakLocation> locations;
1522 1523
  BreakLocation::FromCodeOffsetSameStatement(debug_info, call_offset,
                                             &locations);
1524 1525

  for (BreakLocation location : locations) {
1526
    if (location.code_offset() <= summary.code_offset()) {
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
      // The break point is near our pc. Could be a step-in possibility,
      // that is currently taken by active debugger call.
      if (break_frame_id() == StackFrame::NO_ID) {
        continue;  // We are not stepping.
      } else {
        JavaScriptFrameIterator frame_it(isolate_, break_frame_id());
        // If our frame is a top frame and we are stepping, we can do step-in
        // at this place.
        if (frame_it.frame()->id() != frame_id) continue;
      }
    }
1538
    if (location.IsCall()) results_out->Add(location.position());
1539 1540 1541 1542
  }
}


1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
void Debug::RecordEvalCaller(Handle<Script> script) {
  script->set_compilation_type(Script::COMPILATION_TYPE_EVAL);
  // For eval scripts add information on the function from which eval was
  // called.
  StackTraceFrameIterator it(script->GetIsolate());
  if (!it.done()) {
    script->set_eval_from_shared(it.frame()->function()->shared());
    Code* code = it.frame()->LookupCode();
    int offset = static_cast<int>(
        it.frame()->pc() - code->instruction_start());
1553
    script->set_eval_from_instructions_offset(offset);
1554 1555 1556 1557
  }
}


1558
MaybeHandle<Object> Debug::MakeExecutionState() {
1559
  // Create the execution state object.
1560
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()) };
1561
  return CallFunction("MakeExecutionState", arraysize(argv), argv);
1562 1563 1564
}


1565
MaybeHandle<Object> Debug::MakeBreakEvent(Handle<Object> break_points_hit) {
1566
  // Create the new break event object.
1567 1568
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()),
                            break_points_hit };
1569
  return CallFunction("MakeBreakEvent", arraysize(argv), argv);
1570 1571 1572
}


1573
MaybeHandle<Object> Debug::MakeExceptionEvent(Handle<Object> exception,
1574 1575
                                              bool uncaught,
                                              Handle<Object> promise) {
1576
  // Create the new exception event object.
1577
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()),
1578
                            exception,
1579 1580
                            isolate_->factory()->ToBoolean(uncaught),
                            promise };
1581
  return CallFunction("MakeExceptionEvent", arraysize(argv), argv);
1582 1583 1584
}


1585
MaybeHandle<Object> Debug::MakeCompileEvent(Handle<Script> script,
1586
                                            v8::DebugEvent type) {
1587
  // Create the compile event object.
1588
  Handle<Object> script_wrapper = Script::GetWrapper(script);
1589
  Handle<Object> argv[] = { script_wrapper,
1590
                            isolate_->factory()->NewNumberFromInt(type) };
1591
  return CallFunction("MakeCompileEvent", arraysize(argv), argv);
1592 1593 1594
}


1595 1596 1597
MaybeHandle<Object> Debug::MakePromiseEvent(Handle<JSObject> event_data) {
  // Create the promise event object.
  Handle<Object> argv[] = { event_data };
1598
  return CallFunction("MakePromiseEvent", arraysize(argv), argv);
1599 1600 1601
}


1602 1603 1604
MaybeHandle<Object> Debug::MakeAsyncTaskEvent(Handle<JSObject> task_event) {
  // Create the async task event object.
  Handle<Object> argv[] = { task_event };
1605
  return CallFunction("MakeAsyncTaskEvent", arraysize(argv), argv);
1606 1607 1608
}


1609
void Debug::OnThrow(Handle<Object> exception) {
1610
  if (in_debug_scope() || ignore_events()) return;
1611
  PrepareStepOnThrow();
1612 1613
  // Temporarily clear any scheduled_exception to allow evaluating
  // JavaScript from the debug event handler.
1614
  HandleScope scope(isolate_);
1615 1616 1617 1618 1619
  Handle<Object> scheduled_exception;
  if (isolate_->has_scheduled_exception()) {
    scheduled_exception = handle(isolate_->scheduled_exception(), isolate_);
    isolate_->clear_scheduled_exception();
  }
1620
  OnException(exception, isolate_->GetPromiseOnStackOnThrow());
1621 1622 1623
  if (!scheduled_exception.is_null()) {
    isolate_->thread_local_top()->scheduled_exception_ = *scheduled_exception;
  }
1624 1625
}

1626

1627 1628
void Debug::OnPromiseReject(Handle<JSObject> promise, Handle<Object> value) {
  if (in_debug_scope() || ignore_events()) return;
1629
  HandleScope scope(isolate_);
1630 1631
  // Check whether the promise has been marked as having triggered a message.
  Handle<Symbol> key = isolate_->factory()->promise_debug_marker_symbol();
1632
  if (JSReceiver::GetDataProperty(promise, key)->IsUndefined()) {
1633
    OnException(value, promise);
1634 1635 1636 1637 1638 1639
  }
}


MaybeHandle<Object> Debug::PromiseHasUserDefinedRejectHandler(
    Handle<JSObject> promise) {
1640
  Handle<JSFunction> fun = isolate_->promise_has_user_defined_reject_handler();
1641
  return Execution::Call(isolate_, fun, promise, 0, NULL);
1642
}
1643

1644

1645
void Debug::OnException(Handle<Object> exception, Handle<Object> promise) {
1646
  // In our prediction, try-finally is not considered to catch.
1647 1648
  Isolate::CatchType catch_type = isolate_->PredictExceptionCatcher();
  bool uncaught = (catch_type == Isolate::NOT_CAUGHT);
1649
  if (promise->IsJSObject()) {
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    Handle<JSObject> jspromise = Handle<JSObject>::cast(promise);
    // Mark the promise as already having triggered a message.
    Handle<Symbol> key = isolate_->factory()->promise_debug_marker_symbol();
    JSObject::SetProperty(jspromise, key, key, STRICT).Assert();
    // Check whether the promise reject is considered an uncaught exception.
    Handle<Object> has_reject_handler;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(
        isolate_, has_reject_handler,
        PromiseHasUserDefinedRejectHandler(jspromise), /* void */);
    uncaught = has_reject_handler->IsFalse();
1660
  }
1661 1662 1663
  // Bail out if exception breaks are not active
  if (uncaught) {
    // Uncaught exceptions are reported by either flags.
1664
    if (!(break_on_uncaught_exception_ || break_on_exception_)) return;
1665 1666
  } else {
    // Caught exceptions are reported is activated.
1667
    if (!break_on_exception_) return;
1668 1669
  }

1670 1671 1672 1673 1674 1675
  {
    // Check whether the break location is muted.
    JavaScriptFrameIterator it(isolate_);
    if (!it.done() && IsMutedAtCurrentLocation(it.frame())) return;
  }

1676 1677
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
1678 1679 1680 1681

  // Create the event data object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
1682 1683 1684 1685
  if (!MakeExceptionEvent(
          exception, uncaught, promise).ToHandle(&event_data)) {
    return;
  }
1686

1687
  // Process debug event.
1688
  ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
1689 1690 1691 1692
  // Return to continue execution from where the exception was thrown.
}


1693
void Debug::OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue) {
1694 1695
  // The caller provided for DebugScope.
  AssertDebugContext();
1696
  // Bail out if there is no listener for this event
1697
  if (ignore_events()) return;
1698

1699
  HandleScope scope(isolate_);
1700 1701 1702
  // Create the event data object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
1703
  if (!MakeBreakEvent(break_points_hit).ToHandle(&event_data)) return;
1704

1705 1706 1707 1708
  // Process debug event.
  ProcessDebugEvent(v8::Break,
                    Handle<JSObject>::cast(event_data),
                    auto_continue);
1709 1710 1711
}


1712 1713 1714
void Debug::OnCompileError(Handle<Script> script) {
  ProcessCompileEvent(v8::CompileError, script);
}
1715 1716


1717 1718
void Debug::OnBeforeCompile(Handle<Script> script) {
  ProcessCompileEvent(v8::BeforeCompile, script);
1719 1720 1721 1722
}


// Handle debugger actions when a new script is compiled.
1723
void Debug::OnAfterCompile(Handle<Script> script) {
1724
  ProcessCompileEvent(v8::AfterCompile, script);
1725 1726 1727
}


1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
void Debug::OnPromiseEvent(Handle<JSObject> data) {
  if (in_debug_scope() || ignore_events()) return;

  HandleScope scope(isolate_);
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;

  // Create the script collected state object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
  if (!MakePromiseEvent(data).ToHandle(&event_data)) return;

  // Process debug event.
  ProcessDebugEvent(v8::PromiseEvent,
                    Handle<JSObject>::cast(event_data),
                    true);
}


1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
void Debug::OnAsyncTaskEvent(Handle<JSObject> data) {
  if (in_debug_scope() || ignore_events()) return;

  HandleScope scope(isolate_);
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;

  // Create the script collected state object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
  if (!MakeAsyncTaskEvent(data).ToHandle(&event_data)) return;

  // Process debug event.
  ProcessDebugEvent(v8::AsyncTaskEvent,
                    Handle<JSObject>::cast(event_data),
                    true);
}


1766 1767 1768
void Debug::ProcessDebugEvent(v8::DebugEvent event,
                              Handle<JSObject> event_data,
                              bool auto_continue) {
1769
  HandleScope scope(isolate_);
1770

1771
  // Create the execution state.
1772 1773
  Handle<Object> exec_state;
  // Bail out and don't call debugger if exception.
1774 1775
  if (!MakeExecutionState().ToHandle(&exec_state)) return;

1776 1777
  // First notify the message handler if any.
  if (message_handler_ != NULL) {
1778 1779 1780 1781
    NotifyMessageHandler(event,
                         Handle<JSObject>::cast(exec_state),
                         event_data,
                         auto_continue);
1782
  }
1783 1784 1785 1786 1787 1788
  // Notify registered debug event listener. This can be either a C or
  // a JavaScript function. Don't call event listener for v8::Break
  // here, if it's only a debug command -- they will be processed later.
  if ((event != v8::Break || !auto_continue) && !event_listener_.is_null()) {
    CallEventCallback(event, exec_state, event_data, NULL);
  }
1789 1790 1791
}


1792 1793 1794 1795
void Debug::CallEventCallback(v8::DebugEvent event,
                              Handle<Object> exec_state,
                              Handle<Object> event_data,
                              v8::Debug::ClientData* client_data) {
1796 1797 1798
  // Prevent other interrupts from triggering, for example API callbacks,
  // while dispatching event listners.
  PostponeInterruptsScope postpone(isolate_);
1799 1800
  bool previous = in_debug_event_listener_;
  in_debug_event_listener_ = true;
1801
  if (event_listener_->IsForeign()) {
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    // Invoke the C debug event listener.
    v8::Debug::EventCallback callback =
        FUNCTION_CAST<v8::Debug::EventCallback>(
            Handle<Foreign>::cast(event_listener_)->foreign_address());
    EventDetailsImpl event_details(event,
                                   Handle<JSObject>::cast(exec_state),
                                   Handle<JSObject>::cast(event_data),
                                   event_listener_data_,
                                   client_data);
    callback(event_details);
1812
    DCHECK(!isolate_->has_scheduled_exception());
1813
  } else {
1814
    // Invoke the JavaScript debug event listener.
1815
    DCHECK(event_listener_->IsJSFunction());
1816 1817 1818 1819
    Handle<Object> argv[] = { Handle<Object>(Smi::FromInt(event), isolate_),
                              exec_state,
                              event_data,
                              event_listener_data_ };
1820
    Handle<JSReceiver> global(isolate_->global_proxy());
1821
    Execution::TryCall(isolate_, Handle<JSFunction>::cast(event_listener_),
1822
                       global, arraysize(argv), argv);
1823
  }
1824
  in_debug_event_listener_ = previous;
1825 1826 1827
}


1828 1829 1830
void Debug::ProcessCompileEvent(v8::DebugEvent event, Handle<Script> script) {
  if (ignore_events()) return;
  SuppressDebug while_processing(this);
1831

1832 1833
  bool in_nested_debug_scope = in_debug_scope();
  HandleScope scope(isolate_);
1834 1835 1836
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;

1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
  if (event == v8::AfterCompile) {
    // If debugging there might be script break points registered for this
    // script. Make sure that these break points are set.
    Handle<Object> argv[] = {Script::GetWrapper(script)};
    if (CallFunction("UpdateScriptBreakPoints", arraysize(argv), argv)
            .is_null()) {
      return;
    }
  }

  // Create the compile state object.
1848 1849 1850 1851
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
  if (!MakeCompileEvent(script, event).ToHandle(&event_data)) return;

1852 1853 1854 1855 1856 1857 1858 1859
  // Don't call NotifyMessageHandler if already in debug scope to avoid running
  // nested command loop.
  if (in_nested_debug_scope) {
    if (event_listener_.is_null()) return;
    // Create the execution state.
    Handle<Object> exec_state;
    // Bail out and don't call debugger if exception.
    if (!MakeExecutionState().ToHandle(&exec_state)) return;
1860

1861 1862 1863 1864 1865
    CallEventCallback(event, exec_state, event_data, NULL);
  } else {
    // Process debug event.
    ProcessDebugEvent(event, Handle<JSObject>::cast(event_data), true);
  }
1866 1867 1868
}


1869
Handle<Context> Debug::GetDebugContext() {
1870
  if (!is_loaded()) return Handle<Context>();
1871
  DebugScope debug_scope(this);
1872
  if (debug_scope.failed()) return Handle<Context>();
1873
  // The global handle may be destroyed soon after.  Return it reboxed.
1874
  return handle(*debug_context(), isolate_);
1875 1876 1877
}


1878 1879 1880 1881
void Debug::NotifyMessageHandler(v8::DebugEvent event,
                                 Handle<JSObject> exec_state,
                                 Handle<JSObject> event_data,
                                 bool auto_continue) {
1882 1883 1884
  // Prevent other interrupts from triggering, for example API callbacks,
  // while dispatching message handler callbacks.
  PostponeInterruptsScope no_interrupts(isolate_);
1885
  DCHECK(is_active_);
1886
  HandleScope scope(isolate_);
1887
  // Process the individual events.
1888
  bool sendEventMessage = false;
1889 1890
  switch (event) {
    case v8::Break:
1891
      sendEventMessage = !auto_continue;
1892
      break;
1893
    case v8::NewFunction:
1894
    case v8::BeforeCompile:
1895 1896 1897
    case v8::CompileError:
    case v8::PromiseEvent:
    case v8::AsyncTaskEvent:
1898
      break;
1899
    case v8::Exception:
1900
    case v8::AfterCompile:
1901
      sendEventMessage = true;
1902 1903 1904
      break;
  }

1905 1906 1907
  // The debug command interrupt flag might have been set when the command was
  // added. It should be enough to clear the flag only once while we are in the
  // debugger.
1908
  DCHECK(in_debug_scope());
1909
  isolate_->stack_guard()->ClearDebugCommand();
1910 1911 1912 1913

  // Notify the debugger that a debug event has occurred unless auto continue is
  // active in which case no event is send.
  if (sendEventMessage) {
1914 1915 1916 1917 1918 1919
    MessageImpl message = MessageImpl::NewEvent(
        event,
        auto_continue,
        Handle<JSObject>::cast(exec_state),
        Handle<JSObject>::cast(event_data));
    InvokeMessageHandler(message);
1920
  }
1921 1922 1923 1924 1925

  // If auto continue don't make the event cause a break, but process messages
  // in the queue if any. For script collected events don't even process
  // messages in the queue as the execution state might not be what is expected
  // by the client.
1926
  if (auto_continue && !has_commands()) return;
1927

1928 1929 1930
  // DebugCommandProcessor goes here.
  bool running = auto_continue;

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
  Handle<Object> cmd_processor_ctor = Object::GetProperty(
      isolate_, exec_state, "debugCommandProcessor").ToHandleChecked();
  Handle<Object> ctor_args[] = { isolate_->factory()->ToBoolean(running) };
  Handle<Object> cmd_processor = Execution::Call(
      isolate_, cmd_processor_ctor, exec_state, 1, ctor_args).ToHandleChecked();
  Handle<JSFunction> process_debug_request = Handle<JSFunction>::cast(
      Object::GetProperty(
          isolate_, cmd_processor, "processDebugRequest").ToHandleChecked());
  Handle<Object> is_running = Object::GetProperty(
      isolate_, cmd_processor, "isRunning").ToHandleChecked();

1942
  // Process requests from the debugger.
1943
  do {
1944
    // Wait for new command in the queue.
1945
    command_received_.Wait();
1946 1947

    // Get the command from the queue.
1948
    CommandMessage command = command_queue_.Get();
1949 1950
    isolate_->logger()->DebugTag(
        "Got request from command queue, in interactive loop.");
1951
    if (!is_active()) {
1952 1953
      // Delete command text and user data.
      command.Dispose();
1954 1955 1956
      return;
    }

1957 1958 1959 1960 1961 1962 1963 1964
    Vector<const uc16> command_text(
        const_cast<const uc16*>(command.text().start()),
        command.text().length());
    Handle<String> request_text = isolate_->factory()->NewStringFromTwoByte(
        command_text).ToHandleChecked();
    Handle<Object> request_args[] = { request_text };
    Handle<Object> answer_value;
    Handle<String> answer;
1965 1966
    MaybeHandle<Object> maybe_exception;
    MaybeHandle<Object> maybe_result =
1967
        Execution::TryCall(isolate_, process_debug_request, cmd_processor, 1,
1968
                           request_args, &maybe_exception);
1969 1970 1971 1972

    if (maybe_result.ToHandle(&answer_value)) {
      if (answer_value->IsUndefined()) {
        answer = isolate_->factory()->empty_string();
1973
      } else {
1974
        answer = Handle<String>::cast(answer_value);
1975
      }
1976 1977 1978

      // Log the JSON request/response.
      if (FLAG_trace_debug_json) {
1979 1980
        PrintF("%s\n", request_text->ToCString().get());
        PrintF("%s\n", answer->ToCString().get());
1981 1982
      }

1983 1984 1985
      Handle<Object> is_running_args[] = { answer };
      maybe_result = Execution::Call(
          isolate_, is_running, cmd_processor, 1, is_running_args);
1986 1987 1988
      Handle<Object> result;
      if (!maybe_result.ToHandle(&result)) break;
      running = result->IsTrue();
1989
    } else {
1990 1991 1992
      Handle<Object> exception;
      if (!maybe_exception.ToHandle(&exception)) break;
      Handle<Object> result;
1993
      if (!Object::ToString(isolate_, exception).ToHandle(&result)) break;
1994
      answer = Handle<String>::cast(result);
1995 1996 1997
    }

    // Return the result.
1998
    MessageImpl message = MessageImpl::NewResponse(
1999
        event, running, exec_state, event_data, answer, command.client_data());
2000 2001
    InvokeMessageHandler(message);
    command.Dispose();
2002

2003
    // Return from debug event processing if either the VM is put into the
2004
    // running state (through a continue command) or auto continue is active
2005
    // and there are no more commands queued.
2006
  } while (!running || has_commands());
2007
  command_queue_.Clear();
2008 2009 2010
}


2011 2012
void Debug::SetEventListener(Handle<Object> callback,
                             Handle<Object> data) {
2013
  GlobalHandles* global_handles = isolate_->global_handles();
2014

2015 2016 2017 2018 2019
  // Remove existing entry.
  GlobalHandles::Destroy(event_listener_.location());
  event_listener_ = Handle<Object>();
  GlobalHandles::Destroy(event_listener_data_.location());
  event_listener_data_ = Handle<Object>();
2020

2021
  // Set new entry.
2022
  if (!callback->IsUndefined() && !callback->IsNull()) {
2023 2024 2025
    event_listener_ = global_handles->Create(*callback);
    if (data.is_null()) data = isolate_->factory()->undefined_value();
    event_listener_data_ = global_handles->Create(*data);
2026 2027
  }

2028
  UpdateState();
2029 2030 2031
}


2032
void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
2033
  message_handler_ = handler;
2034
  UpdateState();
2035
  if (handler == NULL && in_debug_scope()) {
2036 2037
    // Send an empty command to the debugger if in a break to make JavaScript
    // run again if the debugger is closed.
2038
    EnqueueCommandMessage(Vector<const uint16_t>::empty());
2039
  }
2040
}
2041

2042

2043 2044

void Debug::UpdateState() {
2045 2046
  bool is_active = message_handler_ != NULL || !event_listener_.is_null();
  if (is_active || in_debug_scope()) {
2047 2048
    // Note that the debug context could have already been loaded to
    // bootstrap test cases.
2049
    isolate_->compilation_cache()->Disable();
2050
    is_active = Load();
2051
  } else if (is_loaded()) {
2052
    isolate_->compilation_cache()->Enable();
2053
    Unload();
2054
  }
2055
  is_active_ = is_active;
2056 2057 2058 2059
}


// Calls the registered debug message handler. This callback is part of the
2060
// public API.
2061
void Debug::InvokeMessageHandler(MessageImpl message) {
2062
  if (message_handler_ != NULL) message_handler_(message);
2063 2064 2065
}


2066 2067 2068
// Puts a command coming from the public API on the queue.  Creates
// a copy of the command string managed by the debugger.  Up to this
// point, the command data was managed by the API client.  Called
2069
// by the API client thread.
2070 2071
void Debug::EnqueueCommandMessage(Vector<const uint16_t> command,
                                  v8::Debug::ClientData* client_data) {
2072
  // Need to cast away const.
2073
  CommandMessage message = CommandMessage::New(
2074
      Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
2075 2076
                       command.length()),
      client_data);
2077
  isolate_->logger()->DebugTag("Put command on command_queue.");
2078
  command_queue_.Put(message);
2079
  command_received_.Signal();
2080 2081

  // Set the debug command break flag to have the command processed.
2082
  if (!in_debug_scope()) isolate_->stack_guard()->RequestDebugCommand();
2083 2084 2085
}


2086
MaybeHandle<Object> Debug::Call(Handle<Object> fun, Handle<Object> data) {
2087 2088
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return isolate_->factory()->undefined_value();
2089 2090

  // Create the execution state.
2091
  Handle<Object> exec_state;
2092 2093 2094
  if (!MakeExecutionState().ToHandle(&exec_state)) {
    return isolate_->factory()->undefined_value();
  }
2095

2096
  Handle<Object> argv[] = { exec_state, data };
2097
  return Execution::Call(
2098
      isolate_,
2099
      fun,
2100
      Handle<Object>(debug_context()->global_proxy(), isolate_),
2101
      arraysize(argv),
2102
      argv);
2103 2104 2105
}


2106
void Debug::HandleDebugBreak() {
2107 2108 2109
  // Ignore debug break during bootstrapping.
  if (isolate_->bootstrapper()->IsActive()) return;
  // Just continue if breaks are disabled.
2110
  if (break_disabled()) return;
2111 2112 2113 2114 2115 2116 2117
  // Ignore debug break if debugger is not active.
  if (!is_active()) return;

  StackLimitCheck check(isolate_);
  if (check.HasOverflowed()) return;

  { JavaScriptFrameIterator it(isolate_);
2118
    DCHECK(!it.done());
2119 2120 2121
    Object* fun = it.frame()->function();
    if (fun && fun->IsJSFunction()) {
      // Don't stop in builtin functions.
2122
      if (!JSFunction::cast(fun)->shared()->IsSubjectToDebugging()) return;
2123 2124
      JSGlobalObject* global =
          JSFunction::cast(fun)->context()->global_object();
2125 2126
      // Don't stop in debugger functions.
      if (IsDebugGlobal(global)) return;
2127 2128
      // Don't stop if the break location is muted.
      if (IsMutedAtCurrentLocation(it.frame())) return;
2129 2130 2131 2132 2133 2134 2135 2136 2137
    }
  }

  // Collect the break state before clearing the flags.
  bool debug_command_only = isolate_->stack_guard()->CheckDebugCommand() &&
                            !isolate_->stack_guard()->CheckDebugBreak();

  isolate_->stack_guard()->ClearDebugBreak();

2138 2139 2140
  // Clear stepping to avoid duplicate breaks.
  ClearStepping();

2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
  ProcessDebugMessages(debug_command_only);
}


void Debug::ProcessDebugMessages(bool debug_command_only) {
  isolate_->stack_guard()->ClearDebugCommand();

  StackLimitCheck check(isolate_);
  if (check.HasOverflowed()) return;

  HandleScope scope(isolate_);
2152 2153
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2154 2155 2156 2157 2158 2159 2160

  // Notify the debug event listeners. Indicate auto continue if the break was
  // a debug command break.
  OnDebugBreak(isolate_->factory()->undefined_value(), debug_command_only);
}


2161 2162 2163 2164 2165 2166
DebugScope::DebugScope(Debug* debug)
    : debug_(debug),
      prev_(debug->debugger_entry()),
      save_(debug_->isolate_),
      no_termination_exceptons_(debug_->isolate_,
                                StackGuard::TERMINATE_EXECUTION) {
2167
  // Link recursive debugger entry.
2168 2169
  base::NoBarrier_Store(&debug_->thread_local_.current_debug_scope_,
                        reinterpret_cast<base::AtomicWord>(this));
2170 2171

  // Store the previous break id and frame id.
2172 2173
  break_id_ = debug_->break_id();
  break_frame_id_ = debug_->break_frame_id();
2174 2175 2176

  // Create the new break info. If there is no JavaScript frames there is no
  // break frame id.
2177
  JavaScriptFrameIterator it(isolate());
2178
  bool has_js_frames = !it.done();
2179 2180 2181
  debug_->thread_local_.break_frame_id_ = has_js_frames ? it.frame()->id()
                                                        : StackFrame::NO_ID;
  debug_->SetNextBreakId();
2182

2183
  debug_->UpdateState();
2184
  // Make sure that debugger is loaded and enter the debugger context.
2185
  // The previous context is kept in save_.
2186 2187
  failed_ = !debug_->is_loaded();
  if (!failed_) isolate()->set_context(*debug->debug_context());
2188 2189 2190
}


2191 2192
DebugScope::~DebugScope() {
  if (!failed_ && prev_ == NULL) {
2193 2194 2195 2196
    // Clear mirror cache when leaving the debugger. Skip this if there is a
    // pending exception as clearing the mirror cache calls back into
    // JavaScript. This can happen if the v8::Debug::Call is used in which
    // case the exception should end up in the calling code.
2197
    if (!isolate()->has_pending_exception()) debug_->ClearMirrorCache();
2198 2199 2200

    // If there are commands in the queue when leaving the debugger request
    // that these commands are processed.
2201
    if (debug_->has_commands()) isolate()->stack_guard()->RequestDebugCommand();
2202 2203
  }

2204
  // Leaving this debugger entry.
2205 2206
  base::NoBarrier_Store(&debug_->thread_local_.current_debug_scope_,
                        reinterpret_cast<base::AtomicWord>(prev_));
2207 2208 2209 2210

  // Restore to the previous break state.
  debug_->thread_local_.break_frame_id_ = break_frame_id_;
  debug_->thread_local_.break_id_ = break_id_;
2211

2212
  debug_->UpdateState();
2213 2214 2215
}


2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
MessageImpl MessageImpl::NewEvent(DebugEvent event,
                                  bool running,
                                  Handle<JSObject> exec_state,
                                  Handle<JSObject> event_data) {
  MessageImpl message(true, event, running,
                      exec_state, event_data, Handle<String>(), NULL);
  return message;
}


MessageImpl MessageImpl::NewResponse(DebugEvent event,
                                     bool running,
                                     Handle<JSObject> exec_state,
                                     Handle<JSObject> event_data,
                                     Handle<String> response_json,
                                     v8::Debug::ClientData* client_data) {
  MessageImpl message(false, event, running,
                      exec_state, event_data, response_json, client_data);
  return message;
}


MessageImpl::MessageImpl(bool is_event,
                         DebugEvent event,
                         bool running,
                         Handle<JSObject> exec_state,
                         Handle<JSObject> event_data,
                         Handle<String> response_json,
                         v8::Debug::ClientData* client_data)
    : is_event_(is_event),
      event_(event),
      running_(running),
      exec_state_(exec_state),
      event_data_(event_data),
      response_json_(response_json),
      client_data_(client_data) {}


bool MessageImpl::IsEvent() const {
  return is_event_;
}


bool MessageImpl::IsResponse() const {
  return !is_event_;
}


DebugEvent MessageImpl::GetEvent() const {
  return event_;
}


bool MessageImpl::WillStartRunning() const {
  return running_;
}


2274
v8::Local<v8::Object> MessageImpl::GetExecutionState() const {
2275 2276 2277 2278
  return v8::Utils::ToLocal(exec_state_);
}


2279 2280 2281 2282 2283
v8::Isolate* MessageImpl::GetIsolate() const {
  return reinterpret_cast<v8::Isolate*>(exec_state_->GetIsolate());
}


2284
v8::Local<v8::Object> MessageImpl::GetEventData() const {
2285 2286 2287 2288
  return v8::Utils::ToLocal(event_data_);
}


2289
v8::Local<v8::String> MessageImpl::GetJSON() const {
2290 2291
  Isolate* isolate = event_data_->GetIsolate();
  v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate));
2292 2293 2294

  if (IsEvent()) {
    // Call toJSONProtocol on the debug event object.
2295 2296
    Handle<Object> fun = Object::GetProperty(
        isolate, event_data_, "toJSONProtocol").ToHandleChecked();
2297
    if (!fun->IsJSFunction()) {
2298
      return v8::Local<v8::String>();
2299
    }
2300 2301

    MaybeHandle<Object> maybe_json =
2302
        Execution::TryCall(isolate, fun, event_data_, 0, NULL);
2303 2304
    Handle<Object> json;
    if (!maybe_json.ToHandle(&json) || !json->IsString()) {
2305
      return v8::Local<v8::String>();
2306
    }
2307
    return scope.Escape(v8::Utils::ToLocal(Handle<String>::cast(json)));
2308 2309 2310 2311 2312 2313
  } else {
    return v8::Utils::ToLocal(response_json_);
  }
}


2314
v8::Local<v8::Context> MessageImpl::GetEventContext() const {
2315
  Isolate* isolate = event_data_->GetIsolate();
2316
  v8::Local<v8::Context> context = GetDebugEventContext(isolate);
2317
  // Isolate::context() may be NULL when "script collected" event occurs.
2318
  DCHECK(!context.IsEmpty());
2319
  return context;
2320 2321 2322 2323 2324 2325 2326 2327
}


v8::Debug::ClientData* MessageImpl::GetClientData() const {
  return client_data_;
}


2328 2329 2330
EventDetailsImpl::EventDetailsImpl(DebugEvent event,
                                   Handle<JSObject> exec_state,
                                   Handle<JSObject> event_data,
2331 2332
                                   Handle<Object> callback_data,
                                   v8::Debug::ClientData* client_data)
2333 2334 2335
    : event_(event),
      exec_state_(exec_state),
      event_data_(event_data),
2336 2337
      callback_data_(callback_data),
      client_data_(client_data) {}
2338 2339 2340 2341 2342 2343 2344


DebugEvent EventDetailsImpl::GetEvent() const {
  return event_;
}


2345
v8::Local<v8::Object> EventDetailsImpl::GetExecutionState() const {
2346 2347 2348 2349
  return v8::Utils::ToLocal(exec_state_);
}


2350
v8::Local<v8::Object> EventDetailsImpl::GetEventData() const {
2351 2352 2353 2354
  return v8::Utils::ToLocal(event_data_);
}


2355
v8::Local<v8::Context> EventDetailsImpl::GetEventContext() const {
2356
  return GetDebugEventContext(exec_state_->GetIsolate());
2357 2358 2359
}


2360
v8::Local<v8::Value> EventDetailsImpl::GetCallbackData() const {
2361 2362 2363 2364
  return v8::Utils::ToLocal(callback_data_);
}


2365 2366 2367 2368 2369
v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
  return client_data_;
}


2370 2371
CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
                                   client_data_(NULL) {
2372 2373 2374
}


2375 2376
CommandMessage::CommandMessage(const Vector<uint16_t>& text,
                               v8::Debug::ClientData* data)
2377
    : text_(text),
2378
      client_data_(data) {
2379 2380 2381
}


2382
void CommandMessage::Dispose() {
2383 2384 2385 2386 2387 2388
  text_.Dispose();
  delete client_data_;
  client_data_ = NULL;
}


2389 2390 2391
CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
                                   v8::Debug::ClientData* data) {
  return CommandMessage(command.Clone(), data);
2392 2393 2394
}


2395 2396 2397
CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
                                                     size_(size) {
  messages_ = NewArray<CommandMessage>(size);
2398 2399 2400
}


2401
CommandMessageQueue::~CommandMessageQueue() {
2402
  while (!IsEmpty()) Get().Dispose();
2403 2404 2405 2406
  DeleteArray(messages_);
}


2407
CommandMessage CommandMessageQueue::Get() {
2408
  DCHECK(!IsEmpty());
2409 2410 2411 2412 2413 2414
  int result = start_;
  start_ = (start_ + 1) % size_;
  return messages_[result];
}


2415
void CommandMessageQueue::Put(const CommandMessage& message) {
2416 2417 2418 2419 2420 2421 2422 2423
  if ((end_ + 1) % size_ == start_) {
    Expand();
  }
  messages_[end_] = message;
  end_ = (end_ + 1) % size_;
}


2424 2425
void CommandMessageQueue::Expand() {
  CommandMessageQueue new_queue(size_ * 2);
2426 2427
  while (!IsEmpty()) {
    new_queue.Put(Get());
2428
  }
2429
  CommandMessage* array_to_free = messages_;
2430 2431
  *this = new_queue;
  new_queue.messages_ = array_to_free;
2432 2433
  // Make the new_queue empty so that it doesn't call Dispose on any messages.
  new_queue.start_ = new_queue.end_;
2434 2435 2436 2437
  // Automatic destructor called on new_queue, freeing array_to_free.
}


2438
LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size)
2439
    : logger_(logger), queue_(size) {}
2440 2441


2442
bool LockingCommandMessageQueue::IsEmpty() const {
2443
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2444
  return queue_.IsEmpty();
2445 2446
}

2447

2448
CommandMessage LockingCommandMessageQueue::Get() {
2449
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2450
  CommandMessage result = queue_.Get();
2451
  logger_->DebugEvent("Get", result.text());
2452 2453 2454 2455
  return result;
}


2456
void LockingCommandMessageQueue::Put(const CommandMessage& message) {
2457
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2458
  queue_.Put(message);
2459
  logger_->DebugEvent("Put", message.text());
2460 2461 2462
}


2463
void LockingCommandMessageQueue::Clear() {
2464
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
2465 2466 2467
  queue_.Clear();
}

2468 2469
}  // namespace internal
}  // namespace v8