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

5
#include "src/v8.h"
6

7 8 9 10 11 12 13 14 15 16 17 18 19 20
#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/debug.h"
#include "src/deoptimizer.h"
#include "src/execution.h"
#include "src/full-codegen.h"
#include "src/global-handles.h"
#include "src/isolate-inl.h"
#include "src/list.h"
21
#include "src/log.h"
22 23
#include "src/messages.h"
#include "src/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 38
    : debug_context_(Handle<Context>()),
      event_listener_(Handle<Object>()),
      event_listener_data_(Handle<Object>()),
      message_handler_(NULL),
      command_received_(0),
      command_queue_(isolate->logger(), kQueueInitialSize),
      event_command_queue_(isolate->logger(), kQueueInitialSize),
      is_active_(false),
39
      is_suppressed_(false),
40 41
      live_edit_enabled_(true),  // TODO(yangguo): set to false by default.
      has_break_points_(false),
42
      break_disabled_(false),
43 44
      break_on_exception_(false),
      break_on_uncaught_exception_(false),
45 46
      script_cache_(NULL),
      debug_info_list_(NULL),
47
      isolate_(isolate) {
48
  ThreadInit();
49 50 51 52 53 54 55 56
}


static v8::Handle<v8::Context> GetDebugEventContext(Isolate* isolate) {
  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
}


62 63 64 65 66 67 68 69 70 71 72
BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
                                             BreakLocatorType type) {
  debug_info_ = debug_info;
  type_ = type;
  reloc_iterator_ = NULL;
  reloc_iterator_original_ = NULL;
  Reset();  // Initialize the rest of the member variables.
}


BreakLocationIterator::~BreakLocationIterator() {
73 74
  DCHECK(reloc_iterator_ != NULL);
  DCHECK(reloc_iterator_original_ != NULL);
75 76 77 78 79
  delete reloc_iterator_;
  delete reloc_iterator_original_;
}


80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
// Check whether a code stub with the specified major key is a possible break
// point location when looking for source break locations.
static bool IsSourceBreakStub(Code* code) {
  CodeStub::Major major_key = CodeStub::GetMajorKey(code);
  return major_key == CodeStub::CallFunction;
}


// Check whether a code stub with the specified major key is a possible break
// location.
static bool IsBreakStub(Code* code) {
  CodeStub::Major major_key = CodeStub::GetMajorKey(code);
  return major_key == CodeStub::CallFunction;
}


96
void BreakLocationIterator::Next() {
97
  DisallowHeapAllocation no_gc;
98
  DCHECK(!RinfoDone());
99 100 101 102 103 104 105 106 107

  // Iterate through reloc info for code and original code stopping at each
  // breakable code target.
  bool first = break_point_ == -1;
  while (!RinfoDone()) {
    if (!first) RinfoNext();
    first = false;
    if (RinfoDone()) return;

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

123 124 125 126 127 128 129 130
    if (IsDebugBreakSlot()) {
      // There is always a possible break point at a debug break slot.
      break_point_++;
      return;
    } else if (RelocInfo::IsCodeTarget(rmode())) {
      // Check for breakable code target. Look in the original code as setting
      // break points can cause the code targets in the running (debugged) code
      // to be of a different kind than in the original code.
131
      Address target = original_rinfo()->target_address();
132
      Code* code = Code::GetCodeFromTargetAddress(target);
133
      if ((code->is_inline_cache_stub() &&
134
           !code->is_binary_op_stub() &&
135 136
           !code->is_compare_ic_stub() &&
           !code->is_to_boolean_ic_stub()) ||
137
          RelocInfo::IsConstructCall(rmode())) {
138 139 140 141
        break_point_++;
        return;
      }
      if (code->kind() == Code::STUB) {
142 143 144
        if (IsDebuggerStatement()) {
          break_point_++;
          return;
145 146
        } else if (type_ == ALL_BREAK_LOCATIONS) {
          if (IsBreakStub(code)) {
147 148 149 150
            break_point_++;
            return;
          }
        } else {
151
          DCHECK(type_ == SOURCE_BREAK_LOCATIONS);
152
          if (IsSourceBreakStub(code)) {
153 154 155 156 157 158 159 160
            break_point_++;
            return;
          }
        }
      }
    }

    // Check for break at return.
161
    if (RelocInfo::IsJSReturn(rmode())) {
162 163 164
      // Set the positions to the end of the function.
      if (debug_info_->shared()->HasSourceCode()) {
        position_ = debug_info_->shared()->end_position() -
165
                    debug_info_->shared()->start_position() - 1;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
      } else {
        position_ = 0;
      }
      statement_position_ = position_;
      break_point_++;
      return;
    }
  }
}


void BreakLocationIterator::Next(int count) {
  while (count > 0) {
    Next();
    count--;
  }
}


185 186
// Find the break point at the supplied address, or the closest one before
// the address.
187 188 189 190 191 192
void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
  // Run through all break points to locate the one closest to the address.
  int closest_break_point = 0;
  int distance = kMaxInt;
  while (!Done()) {
    // Check if this break point is closer that what was previously found.
193
    if (this->pc() <= pc && pc - this->pc() < distance) {
194
      closest_break_point = break_point();
195
      distance = static_cast<int>(pc - this->pc());
196 197 198 199 200 201 202 203 204 205 206 207 208
      // Check whether we can't get any closer.
      if (distance == 0) break;
    }
    Next();
  }

  // Move to the break point found.
  Reset();
  Next(closest_break_point);
}


// Find the break point closest to the supplied source position.
209 210
void BreakLocationIterator::FindBreakLocationFromPosition(int position,
    BreakPositionAlignment alignment) {
211 212 213 214
  // Run through all break points to locate the one closest to the source
  // position.
  int closest_break_point = 0;
  int distance = kMaxInt;
215

216
  while (!Done()) {
217 218 219 220 221 222 223 224 225 226 227 228
    int next_position;
    switch (alignment) {
    case STATEMENT_ALIGNED:
      next_position = this->statement_position();
      break;
    case BREAK_POSITION_ALIGNED:
      next_position = this->position();
      break;
    default:
      UNREACHABLE();
      next_position = this->statement_position();
    }
229
    // Check if this break point is closer that what was previously found.
230
    if (position <= next_position && next_position - position < distance) {
231
      closest_break_point = break_point();
232
      distance = next_position - position;
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
      // Check whether we can't get any closer.
      if (distance == 0) break;
    }
    Next();
  }

  // Move to the break point found.
  Reset();
  Next(closest_break_point);
}


void BreakLocationIterator::Reset() {
  // Create relocation iterators for the two code objects.
  if (reloc_iterator_ != NULL) delete reloc_iterator_;
  if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
249 250 251 252 253 254
  reloc_iterator_ = new RelocIterator(
      debug_info_->code(),
      ~RelocInfo::ModeMask(RelocInfo::CODE_AGE_SEQUENCE));
  reloc_iterator_original_ = new RelocIterator(
      debug_info_->original_code(),
      ~RelocInfo::ModeMask(RelocInfo::CODE_AGE_SEQUENCE));
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

  // Position at the first break point.
  break_point_ = -1;
  position_ = 1;
  statement_position_ = 1;
  Next();
}


bool BreakLocationIterator::Done() const {
  return RinfoDone();
}


void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
  // If there is not already a real break point here patch code with debug
  // break.
272
  if (!HasBreakPoint()) SetDebugBreak();
273
  DCHECK(IsDebugBreak() || IsDebuggerStatement());
274 275 276 277 278 279 280 281 282 283 284 285 286
  // Set the break point information.
  DebugInfo::SetBreakPoint(debug_info_, code_position(),
                           position(), statement_position(),
                           break_point_object);
}


void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
  // Clear the break point information.
  DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
  // If there are no more break points here remove the debug break.
  if (!HasBreakPoint()) {
    ClearDebugBreak();
287
    DCHECK(!IsDebugBreak());
288 289 290 291 292
  }
}


void BreakLocationIterator::SetOneShot() {
293
  // Debugger statement always calls debugger. No need to modify it.
294
  if (IsDebuggerStatement()) return;
295

296 297
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
298
    DCHECK(IsDebugBreak());
299 300 301 302 303 304 305 306 307
    return;
  }

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


void BreakLocationIterator::ClearOneShot() {
308
  // Debugger statement always calls debugger. No need to modify it.
309
  if (IsDebuggerStatement()) return;
310

311 312
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
313
    DCHECK(IsDebugBreak());
314 315 316 317 318
    return;
  }

  // Patch code removing debug break.
  ClearDebugBreak();
319
  DCHECK(!IsDebugBreak());
320 321 322 323
}


void BreakLocationIterator::SetDebugBreak() {
324
  // Debugger statement always calls debugger. No need to modify it.
325
  if (IsDebuggerStatement()) return;
326

327
  // If there is already a break point here just return. This might happen if
328
  // the same code is flooded with break points twice. Flooding the same
329 330
  // function twice might happen when stepping in a function with an exception
  // handler as the handler and the function is the same.
331
  if (IsDebugBreak()) return;
332

333
  if (RelocInfo::IsJSReturn(rmode())) {
334 335
    // Patch the frame exit code with a break point.
    SetDebugBreakAtReturn();
336 337 338
  } else if (IsDebugBreakSlot()) {
    // Patch the code in the break slot.
    SetDebugBreakAtSlot();
339
  } else {
340 341
    // Patch the IC call.
    SetDebugBreakAtIC();
342
  }
343
  DCHECK(IsDebugBreak());
344 345 346 347
}


void BreakLocationIterator::ClearDebugBreak() {
348
  // Debugger statement always calls debugger. No need to modify it.
349
  if (IsDebuggerStatement()) return;
350

351
  if (RelocInfo::IsJSReturn(rmode())) {
352 353
    // Restore the frame exit code.
    ClearDebugBreakAtReturn();
354 355 356
  } else if (IsDebugBreakSlot()) {
    // Restore the code in the break slot.
    ClearDebugBreakAtSlot();
357
  } else {
358 359
    // Patch the IC call.
    ClearDebugBreakAtIC();
360
  }
361
  DCHECK(!IsDebugBreak());
362 363 364
}


365
bool BreakLocationIterator::IsStepInLocation(Isolate* isolate) {
366
  if (RelocInfo::IsConstructCall(original_rmode())) {
367 368 369
    return true;
  } else if (RelocInfo::IsCodeTarget(rmode())) {
    HandleScope scope(debug_info_->GetIsolate());
370
    Address target = original_rinfo()->target_address();
371
    Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
372
    if (target_code->kind() == Code::STUB) {
373
      return CodeStub::GetMajorKey(*target_code) == CodeStub::CallFunction;
374
    }
375
    return target_code->is_call_stub();
376
  }
verwaest@chromium.org's avatar
verwaest@chromium.org committed
377
  return false;
378 379 380
}


381
void BreakLocationIterator::PrepareStepIn(Isolate* isolate) {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
382
#ifdef DEBUG
383
  HandleScope scope(isolate);
384 385
  // Step in can only be prepared if currently positioned on an IC call,
  // construct call or CallFunction stub call.
386
  Address target = rinfo()->target_address();
387
  Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
388 389 390 391 392 393 394 395 396 397
  // All the following stuff is needed only for assertion checks so the code
  // is wrapped in ifdef.
  Handle<Code> maybe_call_function_stub = target_code;
  if (IsDebugBreak()) {
    Address original_target = original_rinfo()->target_address();
    maybe_call_function_stub =
        Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
  }
  bool is_call_function_stub =
      (maybe_call_function_stub->kind() == Code::STUB &&
398 399
       CodeStub::GetMajorKey(*maybe_call_function_stub) ==
           CodeStub::CallFunction);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
400 401 402 403 404 405 406 407

  // Step in through construct call requires no changes to the running code.
  // Step in through getters/setters should already be prepared as well
  // because caller of this function (Debug::PrepareStep) is expected to
  // flood the top frame's function with one shot breakpoints.
  // Step in through CallFunction stub should also be prepared by caller of
  // this function (Debug::PrepareStep) which should flood target function
  // with breakpoints.
408
  DCHECK(RelocInfo::IsConstructCall(rmode()) ||
verwaest@chromium.org's avatar
verwaest@chromium.org committed
409 410
         target_code->is_inline_cache_stub() ||
         is_call_function_stub);
411
#endif
412 413 414 415 416
}


// Check whether the break point is at a position which will exit the function.
bool BreakLocationIterator::IsExit() const {
417
  return (RelocInfo::IsJSReturn(rmode()));
418 419 420 421 422 423 424 425 426 427
}


bool BreakLocationIterator::HasBreakPoint() {
  return debug_info_->HasBreakPoint(code_position());
}


// Check whether there is a debug break at the current position.
bool BreakLocationIterator::IsDebugBreak() {
428
  if (RelocInfo::IsJSReturn(rmode())) {
429
    return IsDebugBreakAtReturn();
430 431
  } else if (IsDebugBreakSlot()) {
    return IsDebugBreakAtSlot();
432 433 434 435 436 437
  } else {
    return Debug::IsDebugBreak(rinfo()->target_address());
  }
}


438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
// Find the builtin to use for invoking the debug break
static Handle<Code> DebugBreakForIC(Handle<Code> code, RelocInfo::Mode mode) {
  Isolate* isolate = code->GetIsolate();

  // Find the builtin debug break function matching the calling convention
  // used by the call site.
  if (code->is_inline_cache_stub()) {
    switch (code->kind()) {
      case Code::CALL_IC:
        return isolate->builtins()->CallICStub_DebugBreak();

      case Code::LOAD_IC:
        return isolate->builtins()->LoadIC_DebugBreak();

      case Code::STORE_IC:
        return isolate->builtins()->StoreIC_DebugBreak();

      case Code::KEYED_LOAD_IC:
        return isolate->builtins()->KeyedLoadIC_DebugBreak();

      case Code::KEYED_STORE_IC:
        return isolate->builtins()->KeyedStoreIC_DebugBreak();

      case Code::COMPARE_NIL_IC:
        return isolate->builtins()->CompareNilIC_DebugBreak();

      default:
        UNREACHABLE();
    }
  }
  if (RelocInfo::IsConstructCall(mode)) {
    if (code->has_function_cache()) {
      return isolate->builtins()->CallConstructStub_Recording_DebugBreak();
    } else {
      return isolate->builtins()->CallConstructStub_DebugBreak();
    }
  }
  if (code->kind() == Code::STUB) {
476
    DCHECK(CodeStub::GetMajorKey(*code) == CodeStub::CallFunction);
477 478 479 480 481 482 483 484
    return isolate->builtins()->CallFunctionStub_DebugBreak();
  }

  UNREACHABLE();
  return Handle<Code>::null();
}


485 486 487 488 489 490 491 492
void BreakLocationIterator::SetDebugBreakAtIC() {
  // Patch the original code with the current address as the current address
  // might have changed by the inline caching since the code was copied.
  original_rinfo()->set_target_address(rinfo()->target_address());

  RelocInfo::Mode mode = rmode();
  if (RelocInfo::IsCodeTarget(mode)) {
    Address target = rinfo()->target_address();
493
    Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
494 495 496

    // Patch the code to invoke the builtin debug break function matching the
    // calling convention used by the call site.
497
    Handle<Code> dbgbrk_code = DebugBreakForIC(target_code, mode);
498 499 500 501 502 503 504 505 506 507 508
    rinfo()->set_target_address(dbgbrk_code->entry());
  }
}


void BreakLocationIterator::ClearDebugBreakAtIC() {
  // Patch the code to the original invoke.
  rinfo()->set_target_address(original_rinfo()->target_address());
}


509
bool BreakLocationIterator::IsDebuggerStatement() {
serya@chromium.org's avatar
serya@chromium.org committed
510
  return RelocInfo::DEBUG_BREAK == rmode();
511 512 513
}


514 515 516 517 518
bool BreakLocationIterator::IsDebugBreakSlot() {
  return RelocInfo::DEBUG_BREAK_SLOT == rmode();
}


519 520 521 522 523
Object* BreakLocationIterator::BreakPointObjects() {
  return debug_info_->GetBreakPointObjects(code_position());
}


524 525 526 527 528 529 530 531 532 533 534
// 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.
void BreakLocationIterator::ClearAllDebugBreak() {
  while (!Done()) {
    ClearDebugBreak();
    Next();
  }
}


535
bool BreakLocationIterator::RinfoDone() const {
536
  DCHECK(reloc_iterator_->done() == reloc_iterator_original_->done());
537 538 539 540 541 542 543 544
  return reloc_iterator_->done();
}


void BreakLocationIterator::RinfoNext() {
  reloc_iterator_->next();
  reloc_iterator_original_->next();
#ifdef DEBUG
545
  DCHECK(reloc_iterator_->done() == reloc_iterator_original_->done());
546
  if (!reloc_iterator_->done()) {
547
    DCHECK(rmode() == original_rmode());
548 549 550 551 552 553 554
  }
#endif
}


// Threading support.
void Debug::ThreadInit() {
555 556 557
  thread_local_.break_count_ = 0;
  thread_local_.break_id_ = 0;
  thread_local_.break_frame_id_ = StackFrame::NO_ID;
558
  thread_local_.last_step_action_ = StepNone;
559
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
560 561
  thread_local_.step_count_ = 0;
  thread_local_.last_fp_ = 0;
562
  thread_local_.queued_step_count_ = 0;
563
  thread_local_.step_into_fp_ = 0;
564
  thread_local_.step_out_fp_ = 0;
565
  // TODO(isolates): frames_are_dropped_?
566
  thread_local_.current_debug_scope_ = NULL;
567
  thread_local_.restarter_frame_function_pointer_ = NULL;
568 569 570 571 572
}


char* Debug::ArchiveDebug(char* storage) {
  char* to = storage;
573
  MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
574 575 576 577 578 579 580
  ThreadInit();
  return storage + ArchiveSpacePerThread();
}


char* Debug::RestoreDebug(char* storage) {
  char* from = storage;
581
  MemCopy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
582 583 584 585 586
  return storage + ArchiveSpacePerThread();
}


int Debug::ArchiveSpacePerThread() {
587
  return sizeof(ThreadLocal);
588 589 590
}


591
ScriptCache::ScriptCache(Isolate* isolate) : HashMap(HashMap::PointersMatch),
592
                                             isolate_(isolate) {
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  Heap* heap = isolate_->heap();
  HandleScope scope(isolate_);

  // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
  // rid of all the cached script wrappers and the second gets rid of the
  // scripts which are no longer referenced.
  heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "ScriptCache");
  heap->CollectAllGarbage(Heap::kMakeHeapIterableMask, "ScriptCache");

  // Scan heap for Script objects.
  HeapIterator iterator(heap);
  DisallowHeapAllocation no_allocation;

  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
    if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
      Add(Handle<Script>(Script::cast(obj)));
    }
  }
}


614
void ScriptCache::Add(Handle<Script> script) {
615
  GlobalHandles* global_handles = isolate_->global_handles();
616
  // Create an entry in the hash map for the script.
617
  int id = script->id()->value();
618 619 620
  HashMap::Entry* entry =
      HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
  if (entry->value != NULL) {
621 622 623 624
#ifdef DEBUG
    // The code deserializer may introduce duplicate Script objects.
    // Assert that the Script objects with the same id have the same name.
    Handle<Script> found(reinterpret_cast<Script**>(entry->value));
625 626
    DCHECK(script->id() == found->id());
    DCHECK(!script->name()->IsString() ||
627 628
           String::cast(script->name())->Equals(String::cast(found->name())));
#endif
629
    return;
630
  }
631 632 633
  // Globalize the script object, make it weak and use the location of the
  // global handle as the value in the hash map.
  Handle<Script> script_ =
634 635 636 637
      Handle<Script>::cast(global_handles->Create(*script));
  GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
                          this,
                          ScriptCache::HandleWeakScript);
638
  entry->value = script_.location();
639 640 641
}


642
Handle<FixedArray> ScriptCache::GetScripts() {
643
  Factory* factory = isolate_->factory();
644
  Handle<FixedArray> instances = factory->NewFixedArray(occupancy());
645 646
  int count = 0;
  for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
647
    DCHECK(entry->value != NULL);
648 649 650 651 652 653
    if (entry->value != NULL) {
      instances->set(count, *reinterpret_cast<Script**>(entry->value));
      count++;
    }
  }
  return instances;
654 655 656
}


657 658 659
void ScriptCache::Clear() {
  // Iterate the script cache to get rid of all the weak handles.
  for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
660
    DCHECK(entry != NULL);
661
    Object** location = reinterpret_cast<Object**>(entry->value);
662
    DCHECK((*location)->IsScript());
663 664
    GlobalHandles::ClearWeakness(location);
    GlobalHandles::Destroy(location);
665 666 667 668 669 670
  }
  // Clear the content of the hash map.
  HashMap::Clear();
}


671 672 673 674 675 676 677
void ScriptCache::HandleWeakScript(
    const v8::WeakCallbackData<v8::Value, void>& data) {
  // Retrieve the script identifier.
  Handle<Object> object = Utils::OpenHandle(*data.GetValue());
  int id = Handle<Script>::cast(object)->id()->value();
  void* key = reinterpret_cast<void*>(id);
  uint32_t hash = Hash(id);
678

679 680 681 682 683 684
  // Remove the corresponding entry from the cache.
  ScriptCache* script_cache =
      reinterpret_cast<ScriptCache*>(data.GetParameter());
  HashMap::Entry* entry = script_cache->Lookup(key, hash, false);
  Object** location = reinterpret_cast<Object**>(entry->value);
  script_cache->Remove(key, hash);
685 686

  // Clear the weak handle.
687
  GlobalHandles::Destroy(location);
688 689 690
}


691 692 693 694 695
void Debug::HandleWeakDebugInfo(
    const v8::WeakCallbackData<v8::Value, void>& data) {
  Debug* debug = reinterpret_cast<Isolate*>(data.GetIsolate())->debug();
  DebugInfoListNode* node =
      reinterpret_cast<DebugInfoListNode*>(data.GetParameter());
696 697 698
  // We need to clear all breakpoints associated with the function to restore
  // original code and avoid patching the code twice later because
  // the function will live in the heap until next gc, and can be found by
699
  // Debug::FindSharedFunctionInfoInScript.
700 701
  BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
  it.ClearAllDebugBreak();
702
  debug->RemoveDebugInfo(node->debug_info());
703
#ifdef DEBUG
704 705 706
  for (DebugInfoListNode* n = debug->debug_info_list_;
       n != NULL;
       n = n->next()) {
707
    DCHECK(n != node);
708 709 710 711 712 713 714
  }
#endif
}


DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
  // Globalize the request debug info object and make it weak.
715 716 717 718 719
  GlobalHandles* global_handles = debug_info->GetIsolate()->global_handles();
  debug_info_ = Handle<DebugInfo>::cast(global_handles->Create(debug_info));
  GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
                          this,
                          Debug::HandleWeakDebugInfo);
720 721 722 723
}


DebugInfoListNode::~DebugInfoListNode() {
724
  GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
725 726 727
}


728
bool Debug::CompileDebuggerScript(Isolate* isolate, int index) {
729 730
  Factory* factory = isolate->factory();
  HandleScope scope(isolate);
731

732
  // Bail out if the index is invalid.
733
  if (index == -1) return false;
734 735

  // Find source and name for the requested script.
736
  Handle<String> source_code =
737
      isolate->bootstrapper()->NativesSourceLookup(index);
738
  Vector<const char> name = Natives::GetScriptName(index);
739 740
  Handle<String> script_name =
      factory->NewStringFromAscii(name).ToHandleChecked();
741
  Handle<Context> context = isolate->native_context();
742 743

  // Compile the script.
744
  Handle<SharedFunctionInfo> function_info;
745 746 747
  function_info = Compiler::CompileScript(
      source_code, script_name, 0, 0, false, context, NULL, NULL,
      ScriptCompiler::kNoCompileOptions, NATIVES_CODE);
748 749

  // Silently ignore stack overflows during compilation.
750
  if (function_info.is_null()) {
751
    DCHECK(isolate->has_pending_exception());
752
    isolate->clear_pending_exception();
753 754 755
    return false;
  }

756
  // Execute the shared function in the debugger context.
757
  Handle<JSFunction> function =
758
      factory->NewFunctionFromSharedFunctionInfo(function_info, context);
759

760 761 762
  MaybeHandle<Object> maybe_exception;
  MaybeHandle<Object> result = Execution::TryCall(
      function, handle(context->global_proxy()), 0, NULL, &maybe_exception);
763 764

  // Check for caught exceptions.
765
  if (result.is_null()) {
766
    DCHECK(!isolate->has_pending_exception());
767 768
    MessageLocation computed_location;
    isolate->ComputeLocation(&computed_location);
769
    Handle<Object> message = MessageHandler::MakeMessageObject(
770
        isolate, "error_loading_debugger", &computed_location,
771
        Vector<Handle<Object> >::empty(), Handle<JSArray>());
772
    DCHECK(!isolate->has_pending_exception());
773 774
    Handle<Object> exception;
    if (maybe_exception.ToHandle(&exception)) {
775
      isolate->set_pending_exception(*exception);
776
      MessageHandler::ReportMessage(isolate, NULL, message);
777 778
      isolate->clear_pending_exception();
    }
779 780 781
    return false;
  }

782 783
  // Mark this script as native and return successfully.
  Handle<Script> script(Script::cast(function->shared()->script()));
784
  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
785 786 787 788 789 790
  return true;
}


bool Debug::Load() {
  // Return if debugger is already loaded.
791
  if (is_loaded()) return true;
792

793 794
  // Bail out if we're already in the process of compiling the native
  // JavaScript source code for the debugger.
795 796
  if (is_suppressed_) return false;
  SuppressDebug while_loading(this);
797 798 799

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

803
  // Create the debugger context.
804
  HandleScope scope(isolate_);
805
  ExtensionConfiguration no_extensions;
806
  Handle<Context> context =
807
      isolate_->bootstrapper()->CreateEnvironment(
808
          MaybeHandle<JSGlobalProxy>(),
809
          v8::Handle<ObjectTemplate>(),
810
          &no_extensions);
811

812 813 814
  // Fail if no context could be created.
  if (context.is_null()) return false;

815
  // Use the debugger context.
816 817
  SaveContext save(isolate_);
  isolate_->set_context(*context);
818 819

  // Expose the builtins object in the debugger context.
820
  Handle<String> key = isolate_->factory()->InternalizeOneByteString(
821
      STATIC_CHAR_VECTOR("builtins"));
822 823 824 825
  Handle<GlobalObject> global =
      Handle<GlobalObject>(context->global_object(), isolate_);
  Handle<JSBuiltinsObject> builtin =
      Handle<JSBuiltinsObject>(global->builtins(), isolate_);
826
  RETURN_ON_EXCEPTION_VALUE(
827
      isolate_, Object::SetProperty(global, key, builtin, SLOPPY), false);
828 829

  // Compile the JavaScript for the debugger in the debugger context.
830
  bool caught_exception =
831 832
      !CompileDebuggerScript(isolate_, Natives::GetIndex("mirror")) ||
      !CompileDebuggerScript(isolate_, Natives::GetIndex("debug"));
833 834 835

  if (FLAG_enable_liveedit) {
    caught_exception = caught_exception ||
836
        !CompileDebuggerScript(isolate_, Natives::GetIndex("liveedit"));
837
  }
838 839
  // Check for caught exceptions.
  if (caught_exception) return false;
840

841 842
  debug_context_ = Handle<Context>::cast(
      isolate_->global_handles()->Create(*context));
843 844 845 846 847
  return true;
}


void Debug::Unload() {
848
  ClearAllBreakPoints();
849
  ClearStepping();
850

851
  // Return debugger is not loaded.
852
  if (!is_loaded()) return;
853

854
  // Clear the script cache.
855 856 857 858
  if (script_cache_ != NULL) {
    delete script_cache_;
    script_cache_ = NULL;
  }
859

860
  // Clear debugger context global handle.
861
  GlobalHandles::Destroy(Handle<Object>::cast(debug_context_).location());
862 863 864 865
  debug_context_ = Handle<Context>();
}


866
void Debug::Break(Arguments args, JavaScriptFrame* frame) {
867 868
  Heap* heap = isolate_->heap();
  HandleScope scope(isolate_);
869
  DCHECK(args.length() == 0);
870

871 872
  // Initialize LiveEdit.
  LiveEdit::InitializeThreadLocal(this);
873 874

  // Just continue if breaks are disabled or debugger cannot be loaded.
875
  if (break_disabled_) return;
876

877
  // Enter the debugger.
878 879
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
880

881
  // Postpone interrupt during breakpoint processing.
882
  PostponeInterruptsScope postpone(isolate_);
883 884 885

  // Get the debug info (create it if it does not exist).
  Handle<SharedFunctionInfo> shared =
886
      Handle<SharedFunctionInfo>(frame->function()->shared());
887 888 889 890 891
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);

  // Find the break point where execution has stopped.
  BreakLocationIterator break_location_iterator(debug_info,
                                                ALL_BREAK_LOCATIONS);
892 893 894
  // pc points to the instruction after the current one, possibly a break
  // location as well. So the "- 1" to exclude it from the search.
  break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
895 896

  // Check whether step next reached a new statement.
897
  if (!StepNextContinue(&break_location_iterator, frame)) {
898
    // Decrease steps left if performing multiple steps.
899 900
    if (thread_local_.step_count_ > 0) {
      thread_local_.step_count_--;
901 902 903 904 905
    }
  }

  // If there is one or more real break points check whether any of these are
  // triggered.
906
  Handle<Object> break_points_hit(heap->undefined_value(), isolate_);
907 908
  if (break_location_iterator.HasBreakPoint()) {
    Handle<Object> break_point_objects =
909
        Handle<Object>(break_location_iterator.BreakPointObjects(), isolate_);
910
    break_points_hit = CheckBreakPoints(break_point_objects);
911 912
  }

913 914
  // If step out is active skip everything until the frame where we need to step
  // out to is reached, unless real breakpoint is hit.
915 916
  if (StepOutActive() &&
      frame->fp() != thread_local_.step_out_fp_ &&
917 918
      break_points_hit->IsUndefined() ) {
      // Step count should always be 0 for StepOut.
919
      DCHECK(thread_local_.step_count_ == 0);
920
  } else if (!break_points_hit->IsUndefined() ||
921 922
             (thread_local_.last_step_action_ != StepNone &&
              thread_local_.step_count_ == 0)) {
923 924 925
    // Notify debugger if a real break point is triggered or if performing
    // single stepping with no more steps to perform. Otherwise do another step.

926
    // Clear all current stepping setup.
927
    ClearStepping();
928

929 930 931 932 933 934 935
    if (thread_local_.queued_step_count_ > 0) {
      // Perform queued steps
      int step_count = thread_local_.queued_step_count_;

      // Clear queue
      thread_local_.queued_step_count_ = 0;

936
      PrepareStep(StepNext, step_count, StackFrame::NO_ID);
937 938
    } else {
      // Notify the debug event listeners.
939
      OnDebugBreak(break_points_hit, false);
940
    }
941
  } else if (thread_local_.last_step_action_ != StepNone) {
942 943
    // Hold on to last step action as it is cleared by the call to
    // ClearStepping.
944 945
    StepAction step_action = thread_local_.last_step_action_;
    int step_count = thread_local_.step_count_;
946

947 948 949 950 951 952
    // If StepNext goes deeper in code, StepOut until original frame
    // and keep step count queued up in the meantime.
    if (step_action == StepNext && frame->fp() < thread_local_.last_fp_) {
      // Count frames until target frame
      int count = 0;
      JavaScriptFrameIterator it(isolate_);
953
      while (!it.done() && it.frame()->fp() < thread_local_.last_fp_) {
954 955 956 957
        count++;
        it.Advance();
      }

958 959 960 961 962
      // Check that we indeed found the frame we are looking for.
      CHECK(!it.done() && (it.frame()->fp() == thread_local_.last_fp_));
      if (step_count > 1) {
        // Save old count and action to continue stepping after StepOut.
        thread_local_.queued_step_count_ = step_count - 1;
963 964
      }

965 966 967
      // Set up for StepOut to reach target frame.
      step_action = StepOut;
      step_count = count;
968 969
    }

970
    // Clear all current stepping setup.
971
    ClearStepping();
972 973

    // Set up for the remaining steps.
974
    PrepareStep(step_action, step_count, StackFrame::NO_ID);
975 976 977 978
  }
}


979
RUNTIME_FUNCTION(Debug_Break) {
980 981 982 983 984
  // Get the top-most JavaScript frame.
  JavaScriptFrameIterator it(isolate);
  isolate->debug()->Break(args, it.frame());
  isolate->debug()->SetAfterBreakTarget(it.frame());
  return isolate->heap()->undefined_value();
985 986 987
}


988 989 990 991
// Check the break point objects for whether one or more are actually
// triggered. This function returns a JSArray with the break point objects
// which is triggered.
Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
992 993
  Factory* factory = isolate_->factory();

994 995 996
  // Count the number of break points hit. If there are multiple break points
  // they are in a FixedArray.
  Handle<FixedArray> break_points_hit;
997
  int break_points_hit_count = 0;
998
  DCHECK(!break_point_objects->IsUndefined());
999 1000
  if (break_point_objects->IsFixedArray()) {
    Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
1001
    break_points_hit = factory->NewFixedArray(array->length());
1002
    for (int i = 0; i < array->length(); i++) {
1003
      Handle<Object> o(array->get(i), isolate_);
1004
      if (CheckBreakPoint(o)) {
1005
        break_points_hit->set(break_points_hit_count++, *o);
1006 1007 1008
      }
    }
  } else {
1009
    break_points_hit = factory->NewFixedArray(1);
1010
    if (CheckBreakPoint(break_point_objects)) {
1011
      break_points_hit->set(break_points_hit_count++, *break_point_objects);
1012 1013 1014
    }
  }

1015
  // Return undefined if no break points were triggered.
1016
  if (break_points_hit_count == 0) {
1017
    return factory->undefined_value();
1018
  }
1019
  // Return break points hit as a JSArray.
1020
  Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit);
1021 1022
  result->set_length(Smi::FromInt(break_points_hit_count));
  return result;
1023 1024 1025 1026 1027
}


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

1031 1032 1033
  // Ignore check if break point object is not a JSObject.
  if (!break_point_object->IsJSObject()) return true;

1034
  // Get the function IsBreakPointTriggered (defined in debug-debugger.js).
1035 1036
  Handle<String> is_break_point_triggered_string =
      factory->InternalizeOneByteString(
1037
          STATIC_CHAR_VECTOR("IsBreakPointTriggered"));
1038
  Handle<GlobalObject> debug_global(debug_context()->global_object());
1039
  Handle<JSFunction> check_break_point =
1040 1041
    Handle<JSFunction>::cast(Object::GetProperty(
        debug_global, is_break_point_triggered_string).ToHandleChecked());
1042 1043

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

  // Call HandleBreakPointx.
1047
  Handle<Object> argv[] = { break_id, break_point_object };
1048
  Handle<Object> result;
1049 1050
  if (!Execution::TryCall(check_break_point,
                          isolate_->js_builtins_object(),
1051
                          arraysize(argv),
1052 1053 1054
                          argv).ToHandle(&result)) {
    return false;
  }
1055 1056

  // Return whether the break point is triggered.
1057
  return result->IsTrue();
1058 1059 1060 1061 1062 1063 1064 1065 1066
}


// Check whether the function has debug information.
bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
  return !shared->debug_info()->IsUndefined();
}


1067 1068
// Return the debug info for this function. EnsureDebugInfo must be called
// prior to ensure the debug info has been generated for shared.
1069
Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
1070
  DCHECK(HasDebugInfo(shared));
1071 1072 1073 1074
  return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
}


1075
bool Debug::SetBreakPoint(Handle<JSFunction> function,
1076 1077
                          Handle<Object> break_point_object,
                          int* source_position) {
1078
  HandleScope scope(isolate_);
1079

1080 1081
  PrepareForBreakPoints();

1082 1083 1084
  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1085
    // Return if retrieving debug info failed.
1086
    return true;
1087 1088
  }

1089
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1090
  // Source positions starts with zero.
1091
  DCHECK(*source_position >= 0);
1092 1093 1094

  // Find the break point and change it.
  BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1095
  it.FindBreakLocationFromPosition(*source_position, STATEMENT_ALIGNED);
1096 1097
  it.SetBreakPoint(break_point_object);

1098 1099
  *source_position = it.position();

1100
  // At least one active break point now.
1101
  return debug_info->GetBreakPointCount() > 0;
1102 1103 1104
}


1105 1106
bool Debug::SetBreakPointForScript(Handle<Script> script,
                                   Handle<Object> break_point_object,
1107 1108
                                   int* source_position,
                                   BreakPositionAlignment alignment) {
1109 1110
  HandleScope scope(isolate_);

1111 1112 1113 1114
  PrepareForBreakPoints();

  // Obtain shared function info for the function.
  Object* result = FindSharedFunctionInfoInScript(script, *source_position);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  if (result->IsUndefined()) return false;

  // Make sure the function has set up the debug info.
  Handle<SharedFunctionInfo> shared(SharedFunctionInfo::cast(result));
  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();
  }

  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
  // Source positions starts with zero.
1135
  DCHECK(position >= 0);
1136 1137 1138

  // Find the break point and change it.
  BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1139
  it.FindBreakLocationFromPosition(position, alignment);
1140 1141 1142 1143 1144
  it.SetBreakPoint(break_point_object);

  *source_position = it.position() + shared->start_position();

  // At least one active break point now.
1145
  DCHECK(debug_info->GetBreakPointCount() > 0);
1146 1147 1148 1149
  return true;
}


1150
void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
1151
  HandleScope scope(isolate_);
1152

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
  DebugInfoListNode* node = debug_info_list_;
  while (node != NULL) {
    Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
                                                   break_point_object);
    if (!result->IsUndefined()) {
      // Get information in the break point.
      BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
      Handle<DebugInfo> debug_info = node->debug_info();

      // Find the break point and clear it.
      BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1164 1165
      it.FindBreakLocationFromAddress(debug_info->code()->entry() +
          break_point_info->code_position()->value());
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
      it.ClearBreakPoint(break_point_object);

      // If there are no more break points left remove the debug info for this
      // function.
      if (debug_info->GetBreakPointCount() == 0) {
        RemoveDebugInfo(debug_info);
      }

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


1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
void Debug::ClearAllBreakPoints() {
  DebugInfoListNode* node = debug_info_list_;
  while (node != NULL) {
    // Remove all debug break code.
    BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
    it.ClearAllDebugBreak();
    node = node->next();
  }

  // Remove all debug info.
  while (debug_info_list_ != NULL) {
    RemoveDebugInfo(debug_info_list_->debug_info());
  }
}


1197
void Debug::FloodWithOneShot(Handle<JSFunction> function) {
1198
  PrepareForBreakPoints();
1199 1200 1201 1202

  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1203 1204 1205
    // Return if we failed to retrieve the debug info.
    return;
  }
1206 1207

  // Flood the function with break points.
1208
  BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
1209 1210 1211 1212 1213 1214 1215
  while (!it.Done()) {
    it.SetOneShot();
    it.Next();
  }
}


1216 1217
void Debug::FloodBoundFunctionWithOneShot(Handle<JSFunction> function) {
  Handle<FixedArray> new_bindings(function->function_bindings());
1218 1219
  Handle<Object> bindee(new_bindings->get(JSFunction::kBoundFunctionIndex),
                        isolate_);
1220 1221

  if (!bindee.is_null() && bindee->IsJSFunction() &&
1222
      !JSFunction::cast(*bindee)->IsFromNativeScript()) {
1223 1224
    Handle<JSFunction> bindee_function(JSFunction::cast(*bindee));
    Debug::FloodWithOneShot(bindee_function);
1225 1226 1227 1228
  }
}


1229
void Debug::FloodHandlerWithOneShot() {
1230
  // Iterate through the JavaScript stack looking for handlers.
1231
  StackFrame::Id id = break_frame_id();
1232 1233 1234 1235
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack don't do anything.
    return;
  }
1236
  for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) {
1237 1238 1239
    JavaScriptFrame* frame = it.frame();
    if (frame->HasHandler()) {
      // Flood the function with the catch block with break points
1240
      FloodWithOneShot(Handle<JSFunction>(frame->function()));
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
      return;
    }
  }
}


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


1256 1257 1258 1259 1260 1261 1262 1263 1264
bool Debug::IsBreakOnException(ExceptionBreakType type) {
  if (type == BreakUncaughtException) {
    return break_on_uncaught_exception_;
  } else {
    return break_on_exception_;
  }
}


1265 1266 1267
bool Debug::PromiseHasRejectHandler(Handle<JSObject> promise) {
  Handle<JSFunction> fun = Handle<JSFunction>::cast(
      JSObject::GetDataProperty(isolate_->js_builtins_object(),
1268
                                isolate_->factory()->NewStringFromStaticChars(
1269 1270 1271 1272 1273 1274 1275
                                    "PromiseHasRejectHandler")));
  Handle<Object> result =
      Execution::Call(isolate_, fun, promise, 0, NULL).ToHandleChecked();
  return result->IsTrue();
}


1276 1277 1278
void Debug::PrepareStep(StepAction step_action,
                        int step_count,
                        StackFrame::Id frame_id) {
1279
  HandleScope scope(isolate_);
1280 1281 1282

  PrepareForBreakPoints();

1283
  DCHECK(in_debug_scope());
1284 1285 1286

  // Remember this step action and count.
  thread_local_.last_step_action_ = step_action;
1287 1288 1289 1290 1291 1292 1293
  if (step_action == StepOut) {
    // For step out target frame will be found on the stack so there is no need
    // to set step counter for it. It's expected to always be 0 for StepOut.
    thread_local_.step_count_ = 0;
  } else {
    thread_local_.step_count_ = step_count;
  }
1294 1295 1296 1297 1298

  // 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.
1299
  StackFrame::Id id = break_frame_id();
1300 1301 1302 1303
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack don't do anything.
    return;
  }
1304 1305 1306
  if (frame_id != StackFrame::NO_ID) {
    id = frame_id;
  }
1307
  JavaScriptFrameIterator frames_it(isolate_, id);
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  JavaScriptFrame* frame = frames_it.frame();

  // First of all ensure there is one-shot break points in the top handler
  // if any.
  FloodHandlerWithOneShot();

  // If the function on the top frame is unresolved perform step out. This will
  // be the case when calling unknown functions and having the debugger stopped
  // 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.
1322
    JSFunction* function = frames_it.frame()->function();
1323
    FloodWithOneShot(Handle<JSFunction>(function));
1324 1325 1326 1327
    return;
  }

  // Get the debug info (create it if it does not exist).
1328
  Handle<JSFunction> function(frame->function());
1329 1330
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1331 1332 1333
    // Return if ensuring debug info failed.
    return;
  }
1334 1335 1336 1337
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);

  // Find the break location where execution has stopped.
  BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1338 1339 1340
  // pc points to the instruction after the current one, possibly a break
  // location as well. So the "- 1" to exclude it from the search.
  it.FindBreakLocationFromAddress(frame->pc() - 1);
1341 1342

  // Compute whether or not the target is a call target.
1343 1344
  bool is_load_or_store = false;
  bool is_inline_cache_stub = false;
1345
  bool is_at_restarted_function = false;
1346 1347
  Handle<Code> call_function_stub;

1348 1349 1350 1351 1352
  if (thread_local_.restarter_frame_function_pointer_ == NULL) {
    if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
      bool is_call_target = false;
      Address target = it.rinfo()->target_address();
      Code* code = Code::GetCodeFromTargetAddress(target);
1353 1354 1355
      if (code->is_call_stub()) {
        is_call_target = true;
      }
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
      if (code->is_inline_cache_stub()) {
        is_inline_cache_stub = true;
        is_load_or_store = !is_call_target;
      }

      // Check if target code is CallFunction stub.
      Code* maybe_call_function_stub = code;
      // If there is a breakpoint at this line look at the original code to
      // check if it is a CallFunction stub.
      if (it.IsDebugBreak()) {
        Address original_target = it.original_rinfo()->target_address();
        maybe_call_function_stub =
            Code::GetCodeFromTargetAddress(original_target);
      }
1370
      if ((maybe_call_function_stub->kind() == Code::STUB &&
1371 1372
           CodeStub::GetMajorKey(maybe_call_function_stub) ==
               CodeStub::CallFunction) ||
1373
          maybe_call_function_stub->kind() == Code::CALL_IC) {
1374 1375 1376 1377
        // Save reference to the code as we may need it to find out arguments
        // count for 'step in' later.
        call_function_stub = Handle<Code>(maybe_call_function_stub);
      }
1378
    }
1379 1380
  } else {
    is_at_restarted_function = true;
1381 1382
  }

1383
  // If this is the last break code target step out is the only possibility.
1384
  if (it.IsExit() || step_action == StepOut) {
1385 1386
    if (step_action == StepOut) {
      // Skip step_count frames starting with the current one.
ager@chromium.org's avatar
ager@chromium.org committed
1387
      while (step_count-- > 0 && !frames_it.done()) {
1388 1389 1390
        frames_it.Advance();
      }
    } else {
1391
      DCHECK(it.IsExit());
1392 1393 1394
      frames_it.Advance();
    }
    // Skip builtin functions on the stack.
1395 1396
    while (!frames_it.done() &&
           frames_it.frame()->function()->IsFromNativeScript()) {
1397 1398
      frames_it.Advance();
    }
1399 1400 1401 1402
    // Step out: If there is a JavaScript caller frame, we need to
    // flood it with breakpoints.
    if (!frames_it.done()) {
      // Fill the function to return to with one-shot break points.
1403
      JSFunction* function = frames_it.frame()->function();
1404
      FloodWithOneShot(Handle<JSFunction>(function));
1405 1406
      // Set target frame pointer.
      ActivateStepOut(frames_it.frame());
1407
    }
1408
  } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1409
               !call_function_stub.is_null() || is_at_restarted_function)
1410
             || step_action == StepNext || step_action == StepMin) {
1411 1412 1413
    // Step next or step min.

    // Fill the current function with one-shot break points.
1414
    FloodWithOneShot(function);
1415 1416 1417 1418

    // Remember source position and frame to handle step next.
    thread_local_.last_statement_position_ =
        debug_info->code()->SourceStatementPosition(frame->pc());
1419
    thread_local_.last_fp_ = frame->UnpaddedFP();
1420
  } else {
1421 1422 1423 1424 1425
    // If there's restarter frame on top of the stack, just get the pointer
    // to function which is going to be restarted.
    if (is_at_restarted_function) {
      Handle<JSFunction> restarted_function(
          JSFunction::cast(*thread_local_.restarter_frame_function_pointer_));
1426
      FloodWithOneShot(restarted_function);
1427 1428 1429
    } else if (!call_function_stub.is_null()) {
      // If it's CallFunction stub ensure target function is compiled and flood
      // it with one shot breakpoints.
1430
      bool is_call_ic = call_function_stub->kind() == Code::CALL_IC;
1431

1432
      // Find out number of arguments from the stub minor key.
1433
      uint32_t key = call_function_stub->stub_key();
1434 1435
      // Argc in the stub is the number of arguments passed - not the
      // expected arguments of the called function.
1436 1437 1438
      int call_function_arg_count = is_call_ic
          ? CallICStub::ExtractArgcFromMinorKey(CodeStub::MinorKeyFromKey(key))
          : CallFunctionStub::ExtractArgcFromMinorKey(
1439
              CodeStub::MinorKeyFromKey(key));
1440

1441
      DCHECK(is_call_ic ||
1442 1443
             CodeStub::GetMajorKey(*call_function_stub) ==
                 CodeStub::MajorKeyFromKey(key));
1444 1445

      // Find target function on the expression stack.
1446
      // Expression stack looks like this (top to bottom):
1447 1448 1449 1450 1451 1452
      // argN
      // ...
      // arg0
      // Receiver
      // Function to call
      int expressions_count = frame->ComputeExpressionsCount();
1453
      DCHECK(expressions_count - 2 - call_function_arg_count >= 0);
1454 1455
      Object* fun = frame->GetExpression(
          expressions_count - 2 - call_function_arg_count);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

      // Flood the actual target of call/apply.
      if (fun->IsJSFunction()) {
        Isolate* isolate = JSFunction::cast(fun)->GetIsolate();
        Code* apply = isolate->builtins()->builtin(Builtins::kFunctionApply);
        Code* call = isolate->builtins()->builtin(Builtins::kFunctionCall);
        while (fun->IsJSFunction()) {
          Code* code = JSFunction::cast(fun)->shared()->code();
          if (code != apply && code != call) break;
          fun = frame->GetExpression(
              expressions_count - 1 - call_function_arg_count);
        }
      }

1470 1471
      if (fun->IsJSFunction()) {
        Handle<JSFunction> js_function(JSFunction::cast(fun));
1472 1473
        if (js_function->shared()->bound()) {
          Debug::FloodBoundFunctionWithOneShot(js_function);
1474
        } else if (!js_function->IsFromNativeScript()) {
1475
          // Don't step into builtins.
1476
          // It will also compile target function if it's not compiled yet.
1477
          FloodWithOneShot(js_function);
1478 1479 1480 1481
        }
      }
    }

1482 1483
    // Fill the current function with one-shot break points even for step in on
    // a call target as the function called might be a native function for
1484 1485
    // which step in will not stop. It also prepares for stepping in
    // getters/setters.
1486
    FloodWithOneShot(function);
1487

1488 1489 1490
    if (is_load_or_store) {
      // Remember source position and frame to handle step in getter/setter. If
      // there is a custom getter/setter it will be handled in
1491
      // Object::Get/SetPropertyWithAccessor, otherwise the step action will be
1492 1493 1494
      // propagated on the next Debug::Break.
      thread_local_.last_statement_position_ =
          debug_info->code()->SourceStatementPosition(frame->pc());
1495
      thread_local_.last_fp_ = frame->UnpaddedFP();
1496 1497
    }

1498
    // Step in or Step in min
1499
    it.PrepareStepIn(isolate_);
1500 1501 1502 1503 1504 1505 1506 1507 1508
    ActivateStepIn(frame);
  }
}


// Check whether the current debug break should be reported to the debugger. It
// is used to have step next and step in only report break back to the debugger
// if on a different frame or in a different statement. In some situations
// there will be several break points in the same statement when the code is
1509
// flooded with one-shot break points. This function helps to perform several
1510 1511 1512
// steps before reporting break back to the debugger.
bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
                             JavaScriptFrame* frame) {
1513 1514 1515 1516 1517 1518 1519
  // StepNext and StepOut shouldn't bring us deeper in code, so last frame
  // shouldn't be a parent of current frame.
  if (thread_local_.last_step_action_ == StepNext ||
      thread_local_.last_step_action_ == StepOut) {
    if (frame->fp() < thread_local_.last_fp_) return true;
  }

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  // If the step last action was step next or step in make sure that a new
  // statement is hit.
  if (thread_local_.last_step_action_ == StepNext ||
      thread_local_.last_step_action_ == StepIn) {
    // Never continue if returning from function.
    if (break_location_iterator->IsExit()) return false;

    // Continue if we are still on the same frame and in the same statement.
    int current_statement_position =
        break_location_iterator->code()->SourceStatementPosition(frame->pc());
1530
    return thread_local_.last_fp_ == frame->UnpaddedFP() &&
1531
        thread_local_.last_statement_position_ == current_statement_position;
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
  }

  // No step next action - don't continue.
  return false;
}


// Check whether the code object at the specified address is a debug break code
// object.
bool Debug::IsDebugBreak(Address addr) {
1542
  Code* code = Code::GetCodeFromTargetAddress(addr);
1543
  return code->is_debug_stub() && code->extra_ic_state() == DEBUG_BREAK;
1544 1545 1546 1547 1548 1549 1550 1551
}





// Simple function for returning the source positions for active break points.
Handle<Object> Debug::GetSourceBreakLocations(
1552 1553
    Handle<SharedFunctionInfo> shared,
    BreakPositionAlignment position_alignment) {
1554
  Isolate* isolate = shared->GetIsolate();
1555
  Heap* heap = isolate->heap();
1556 1557 1558
  if (!HasDebugInfo(shared)) {
    return Handle<Object>(heap->undefined_value(), isolate);
  }
1559 1560
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
  if (debug_info->GetBreakPointCount() == 0) {
1561
    return Handle<Object>(heap->undefined_value(), isolate);
1562 1563
  }
  Handle<FixedArray> locations =
1564
      isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
1565 1566 1567 1568 1569 1570
  int count = 0;
  for (int i = 0; i < debug_info->break_points()->length(); i++) {
    if (!debug_info->break_points()->get(i)->IsUndefined()) {
      BreakPointInfo* break_point_info =
          BreakPointInfo::cast(debug_info->break_points()->get(i));
      if (break_point_info->GetBreakPointCount() > 0) {
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
        Smi* position;
        switch (position_alignment) {
        case STATEMENT_ALIGNED:
          position = break_point_info->statement_position();
          break;
        case BREAK_POSITION_ALIGNED:
          position = break_point_info->source_position();
          break;
        default:
          UNREACHABLE();
          position = break_point_info->statement_position();
        }

        locations->set(count++, position);
1585 1586 1587 1588 1589 1590 1591
      }
    }
  }
  return locations;
}


1592 1593
// Handle stepping into a function.
void Debug::HandleStepIn(Handle<JSFunction> function,
1594
                         Handle<Object> holder,
1595 1596
                         Address fp,
                         bool is_constructor) {
1597
  Isolate* isolate = function->GetIsolate();
1598 1599
  // If the frame pointer is not supplied by the caller find it.
  if (fp == 0) {
1600
    StackFrameIterator it(isolate);
1601 1602 1603
    it.Advance();
    // For constructor functions skip another frame.
    if (is_constructor) {
1604
      DCHECK(it.frame()->is_construct());
1605 1606 1607 1608 1609 1610 1611
      it.Advance();
    }
    fp = it.frame()->fp();
  }

  // Flood the function with one-shot break points if it is called from where
  // step into was requested.
1612
  if (fp == thread_local_.step_into_fp_) {
1613 1614 1615
    if (function->shared()->bound()) {
      // Handle Function.prototype.bind
      Debug::FloodBoundFunctionWithOneShot(function);
1616
    } else if (!function->IsFromNativeScript()) {
1617
      // Don't allow step into functions in the native context.
1618
      if (function->shared()->code() ==
1619
          isolate->builtins()->builtin(Builtins::kFunctionApply) ||
1620
          function->shared()->code() ==
1621
          isolate->builtins()->builtin(Builtins::kFunctionCall)) {
1622 1623
        // Handle function.apply and function.call separately to flood the
        // function to be called and not the code for Builtins::FunctionApply or
1624 1625
        // Builtins::FunctionCall. The receiver of call/apply is the target
        // function.
1626
        if (!holder.is_null() && holder->IsJSFunction()) {
1627
          Handle<JSFunction> js_function = Handle<JSFunction>::cast(holder);
1628
          if (!js_function->IsFromNativeScript()) {
1629 1630 1631 1632 1633
            Debug::FloodWithOneShot(js_function);
          } else if (js_function->shared()->bound()) {
            // Handle Function.prototype.bind
            Debug::FloodBoundFunctionWithOneShot(js_function);
          }
1634 1635
        }
      } else {
1636
        Debug::FloodWithOneShot(function);
1637
      }
1638
    }
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
1639
  }
1640 1641 1642
}


1643 1644 1645 1646
void Debug::ClearStepping() {
  // Clear the various stepping setup.
  ClearOneShot();
  ClearStepIn();
1647
  ClearStepOut();
1648 1649 1650 1651 1652 1653
  ClearStepNext();

  // Clear multiple step counter.
  thread_local_.step_count_ = 0;
}

1654

1655 1656 1657 1658 1659
// 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
1660
  // last break point for a function is removed that function is automatically
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
  // removed from the list.

  DebugInfoListNode* node = debug_info_list_;
  while (node != NULL) {
    BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
    while (!it.Done()) {
      it.ClearOneShot();
      it.Next();
    }
    node = node->next();
  }
}


void Debug::ActivateStepIn(StackFrame* frame) {
1676
  DCHECK(!StepOutActive());
1677
  thread_local_.step_into_fp_ = frame->UnpaddedFP();
1678 1679 1680 1681 1682 1683 1684 1685
}


void Debug::ClearStepIn() {
  thread_local_.step_into_fp_ = 0;
}


1686
void Debug::ActivateStepOut(StackFrame* frame) {
1687
  DCHECK(!StepInActive());
1688
  thread_local_.step_out_fp_ = frame->UnpaddedFP();
1689 1690 1691 1692 1693 1694 1695 1696
}


void Debug::ClearStepOut() {
  thread_local_.step_out_fp_ = 0;
}


1697 1698
void Debug::ClearStepNext() {
  thread_local_.last_step_action_ = StepNone;
1699
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1700 1701 1702 1703
  thread_local_.last_fp_ = 0;
}


1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
static void CollectActiveFunctionsFromThread(
    Isolate* isolate,
    ThreadLocalTop* top,
    List<Handle<JSFunction> >* active_functions,
    Object* active_code_marker) {
  // Find all non-optimized code functions with activation frames
  // on the stack. This includes functions which have optimized
  // activations (including inlined functions) on the stack as the
  // non-optimized code is needed for the lazy deoptimization.
  for (JavaScriptFrameIterator it(isolate, top); !it.done(); it.Advance()) {
    JavaScriptFrame* frame = it.frame();
    if (frame->is_optimized()) {
1716
      List<JSFunction*> functions(FLAG_max_inlining_levels + 1);
1717 1718 1719 1720 1721 1722 1723
      frame->GetFunctions(&functions);
      for (int i = 0; i < functions.length(); i++) {
        JSFunction* function = functions[i];
        active_functions->Add(Handle<JSFunction>(function));
        function->shared()->code()->set_gc_metadata(active_code_marker);
      }
    } else if (frame->function()->IsJSFunction()) {
1724
      JSFunction* function = frame->function();
1725
      DCHECK(frame->LookupCode()->kind() == Code::FUNCTION);
1726 1727 1728 1729 1730 1731 1732
      active_functions->Add(Handle<JSFunction>(function));
      function->shared()->code()->set_gc_metadata(active_code_marker);
    }
  }
}


1733 1734 1735 1736 1737
// Figure out how many bytes of "pc_offset" correspond to actual code by
// subtracting off the bytes that correspond to constant/veneer pools.  See
// Assembler::CheckConstPool() and Assembler::CheckVeneerPool(). Note that this
// is only useful for architectures using constant pools or veneer pools.
static int ComputeCodeOffsetFromPcOffset(Code *code, int pc_offset) {
1738 1739 1740 1741
  DCHECK_EQ(code->kind(), Code::FUNCTION);
  DCHECK(!code->has_debug_break_slots());
  DCHECK_LE(0, pc_offset);
  DCHECK_LT(pc_offset, code->instruction_end() - code->instruction_start());
1742 1743 1744 1745 1746 1747 1748 1749

  int mask = RelocInfo::ModeMask(RelocInfo::CONST_POOL) |
             RelocInfo::ModeMask(RelocInfo::VENEER_POOL);
  byte *pc = code->instruction_start() + pc_offset;
  int code_offset = pc_offset;
  for (RelocIterator it(code, mask); !it.done(); it.next()) {
    RelocInfo* info = it.rinfo();
    if (info->pc() >= pc) break;
1750
    DCHECK(RelocInfo::IsConstPool(info->rmode()));
1751
    code_offset -= static_cast<int>(info->data());
1752
    DCHECK_LE(0, code_offset);
1753 1754 1755 1756 1757 1758 1759 1760
  }

  return code_offset;
}


// The inverse of ComputeCodeOffsetFromPcOffset.
static int ComputePcOffsetFromCodeOffset(Code *code, int code_offset) {
1761
  DCHECK_EQ(code->kind(), Code::FUNCTION);
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772

  int mask = RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT) |
             RelocInfo::ModeMask(RelocInfo::CONST_POOL) |
             RelocInfo::ModeMask(RelocInfo::VENEER_POOL);
  int reloc = 0;
  for (RelocIterator it(code, mask); !it.done(); it.next()) {
    RelocInfo* info = it.rinfo();
    if (info->pc() - code->instruction_start() - reloc >= code_offset) break;
    if (RelocInfo::IsDebugBreakSlot(info->rmode())) {
      reloc += Assembler::kDebugBreakSlotLength;
    } else {
1773
      DCHECK(RelocInfo::IsConstPool(info->rmode()));
1774 1775 1776 1777 1778 1779
      reloc += static_cast<int>(info->data());
    }
  }

  int pc_offset = code_offset + reloc;

1780
  DCHECK_LT(code->instruction_start() + pc_offset, code->instruction_end());
1781 1782 1783 1784 1785

  return pc_offset;
}


1786 1787 1788 1789 1790 1791 1792 1793
static void RedirectActivationsToRecompiledCodeOnThread(
    Isolate* isolate,
    ThreadLocalTop* top) {
  for (JavaScriptFrameIterator it(isolate, top); !it.done(); it.Advance()) {
    JavaScriptFrame* frame = it.frame();

    if (frame->is_optimized() || !frame->function()->IsJSFunction()) continue;

1794
    JSFunction* function = frame->function();
1795

1796
    DCHECK(frame->LookupCode()->kind() == Code::FUNCTION);
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806

    Handle<Code> frame_code(frame->LookupCode());
    if (frame_code->has_debug_break_slots()) continue;

    Handle<Code> new_code(function->shared()->code());
    if (new_code->kind() != Code::FUNCTION ||
        !new_code->has_debug_break_slots()) {
      continue;
    }

1807 1808 1809 1810
    int old_pc_offset =
        static_cast<int>(frame->pc() - frame_code->instruction_start());
    int code_offset = ComputeCodeOffsetFromPcOffset(*frame_code, old_pc_offset);
    int new_pc_offset = ComputePcOffsetFromCodeOffset(*new_code, code_offset);
1811 1812

    // Compute the equivalent pc in the new code.
1813
    byte* new_pc = new_code->instruction_start() + new_pc_offset;
1814

1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
    if (FLAG_trace_deopt) {
      PrintF("Replacing code %08" V8PRIxPTR " - %08" V8PRIxPTR " (%d) "
             "with %08" V8PRIxPTR " - %08" V8PRIxPTR " (%d) "
             "for debugging, "
             "changing pc from %08" V8PRIxPTR " to %08" V8PRIxPTR "\n",
             reinterpret_cast<intptr_t>(
                 frame_code->instruction_start()),
             reinterpret_cast<intptr_t>(
                 frame_code->instruction_start()) +
             frame_code->instruction_size(),
             frame_code->instruction_size(),
             reinterpret_cast<intptr_t>(new_code->instruction_start()),
             reinterpret_cast<intptr_t>(new_code->instruction_start()) +
             new_code->instruction_size(),
             new_code->instruction_size(),
             reinterpret_cast<intptr_t>(frame->pc()),
1831
             reinterpret_cast<intptr_t>(new_pc));
1832 1833
    }

1834 1835 1836 1837 1838
    if (FLAG_enable_ool_constant_pool) {
      // Update constant pool pointer for new code.
      frame->set_constant_pool(new_code->constant_pool());
    }

1839 1840
    // Patch the return address to return into the code with
    // debug break slots.
1841
    frame->set_pc(new_pc);
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
  }
}


class ActiveFunctionsCollector : public ThreadVisitor {
 public:
  explicit ActiveFunctionsCollector(List<Handle<JSFunction> >* active_functions,
                                    Object* active_code_marker)
      : active_functions_(active_functions),
        active_code_marker_(active_code_marker) { }

  void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
    CollectActiveFunctionsFromThread(isolate,
                                     top,
                                     active_functions_,
                                     active_code_marker_);
  }

 private:
  List<Handle<JSFunction> >* active_functions_;
  Object* active_code_marker_;
};


class ActiveFunctionsRedirector : public ThreadVisitor {
 public:
  void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
    RedirectActivationsToRecompiledCodeOnThread(isolate, top);
  }
};


1874
static void EnsureFunctionHasDebugBreakSlots(Handle<JSFunction> function) {
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
  if (function->code()->kind() == Code::FUNCTION &&
      function->code()->has_debug_break_slots()) {
    // Nothing to do. Function code already had debug break slots.
    return;
  }
  // Make sure that the shared full code is compiled with debug
  // break slots.
  if (!function->shared()->code()->has_debug_break_slots()) {
    MaybeHandle<Code> code = Compiler::GetCodeForDebugging(function);
    // Recompilation can fail.  In that case leave the code as it was.
1885 1886 1887 1888
    if (!code.is_null()) function->ReplaceCode(*code.ToHandleChecked());
  } else {
    // Simply use shared code if it has debug break slots.
    function->ReplaceCode(function->shared()->code());
1889
  }
1890 1891 1892
}


1893
static void RecompileAndRelocateSuspendedGenerators(
1894 1895 1896 1897
    const List<Handle<JSGeneratorObject> > &generators) {
  for (int i = 0; i < generators.length(); i++) {
    Handle<JSFunction> fun(generators[i]->function());

1898
    EnsureFunctionHasDebugBreakSlots(fun);
1899 1900 1901 1902 1903 1904 1905 1906

    int code_offset = generators[i]->continuation();
    int pc_offset = ComputePcOffsetFromCodeOffset(fun->code(), code_offset);
    generators[i]->set_continuation(pc_offset);
  }
}


1907 1908 1909 1910
void Debug::PrepareForBreakPoints() {
  // If preparing for the first break point make sure to deoptimize all
  // functions as debugging does not work with optimized code.
  if (!has_break_points_) {
1911
    if (isolate_->concurrent_recompilation_enabled()) {
1912 1913 1914
      isolate_->optimizing_compiler_thread()->Flush();
    }

1915
    Deoptimizer::DeoptimizeAll(isolate_);
1916

1917
    Handle<Code> lazy_compile = isolate_->builtins()->CompileUnoptimized();
1918

1919 1920 1921
    // There will be at least one break point when we are done.
    has_break_points_ = true;

1922 1923 1924 1925
    // Keep the list of activated functions in a handlified list as it
    // is used both in GC and non-GC code.
    List<Handle<JSFunction> > active_functions(100);

1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
    // A list of all suspended generators.
    List<Handle<JSGeneratorObject> > suspended_generators;

    // A list of all generator functions.  We need to recompile all functions,
    // but we don't know until after visiting the whole heap which generator
    // functions have suspended activations and which do not.  As in the case of
    // functions with activations on the stack, we need to be careful with
    // generator functions with suspended activations because although they
    // should be recompiled, recompilation can fail, and we need to avoid
    // leaving the heap in an inconsistent state.
    //
    // We could perhaps avoid this list and instead re-use the GC metadata
    // links.
    List<Handle<JSFunction> > generator_functions;

1941 1942 1943
    {
      // We are going to iterate heap to find all functions without
      // debug break slots.
1944 1945 1946
      Heap* heap = isolate_->heap();
      heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
                              "preparing for breakpoints");
1947
      HeapIterator iterator(heap);
1948

1949 1950
      // Ensure no GC in this scope as we are going to use gc_metadata
      // field in the Code object to mark active functions.
1951
      DisallowHeapAllocation no_allocation;
1952

1953
      Object* active_code_marker = heap->the_hole_value();
1954

1955 1956 1957 1958 1959 1960 1961 1962
      CollectActiveFunctionsFromThread(isolate_,
                                       isolate_->thread_local_top(),
                                       &active_functions,
                                       active_code_marker);
      ActiveFunctionsCollector active_functions_collector(&active_functions,
                                                          active_code_marker);
      isolate_->thread_manager()->IterateArchivedThreads(
          &active_functions_collector);
1963

1964 1965 1966
      // Scan the heap for all non-optimized functions which have no
      // debug break slots and are not active or inlined into an active
      // function and mark them for lazy compilation.
1967 1968 1969 1970
      HeapObject* obj = NULL;
      while (((obj = iterator.next()) != NULL)) {
        if (obj->IsJSFunction()) {
          JSFunction* function = JSFunction::cast(obj);
1971
          SharedFunctionInfo* shared = function->shared();
1972 1973 1974

          if (!shared->allows_lazy_compilation()) continue;
          if (!shared->script()->IsScript()) continue;
1975
          if (function->IsFromNativeScript()) continue;
1976 1977
          if (shared->code()->gc_metadata() == active_code_marker) continue;

1978 1979 1980 1981 1982
          if (shared->is_generator()) {
            generator_functions.Add(Handle<JSFunction>(function, isolate_));
            continue;
          }

1983 1984 1985
          Code::Kind kind = function->code()->kind();
          if (kind == Code::FUNCTION &&
              !function->code()->has_debug_break_slots()) {
1986 1987
            function->ReplaceCode(*lazy_compile);
            function->shared()->ReplaceCode(*lazy_compile);
1988
          } else if (kind == Code::BUILTIN &&
1989 1990 1991
              (function->IsInOptimizationQueue() ||
               function->IsMarkedForOptimization() ||
               function->IsMarkedForConcurrentOptimization())) {
1992 1993 1994 1995
            // Abort in-flight compilation.
            Code* shared_code = function->shared()->code();
            if (shared_code->kind() == Code::FUNCTION &&
                shared_code->has_debug_break_slots()) {
1996
              function->ReplaceCode(shared_code);
1997
            } else {
1998 1999
              function->ReplaceCode(*lazy_compile);
              function->shared()->ReplaceCode(*lazy_compile);
2000
            }
2001
          }
2002 2003 2004 2005 2006
        } else if (obj->IsJSGeneratorObject()) {
          JSGeneratorObject* gen = JSGeneratorObject::cast(obj);
          if (!gen->is_suspended()) continue;

          JSFunction* fun = gen->function();
2007
          DCHECK_EQ(fun->code()->kind(), Code::FUNCTION);
2008 2009 2010
          if (fun->code()->has_debug_break_slots()) continue;

          int pc_offset = gen->continuation();
2011
          DCHECK_LT(0, pc_offset);
2012 2013 2014 2015 2016 2017 2018 2019

          int code_offset =
              ComputeCodeOffsetFromPcOffset(fun->code(), pc_offset);

          // This will be fixed after we recompile the functions.
          gen->set_continuation(code_offset);

          suspended_generators.Add(Handle<JSGeneratorObject>(gen, isolate_));
2020
        }
2021
      }
2022

2023 2024 2025 2026 2027 2028
      // Clear gc_metadata field.
      for (int i = 0; i < active_functions.length(); i++) {
        Handle<JSFunction> function = active_functions[i];
        function->shared()->code()->set_gc_metadata(Smi::FromInt(0));
      }
    }
2029

2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
    // Recompile generator functions that have suspended activations, and
    // relocate those activations.
    RecompileAndRelocateSuspendedGenerators(suspended_generators);

    // Mark generator functions that didn't have suspended activations for lazy
    // recompilation.  Note that this set does not include any active functions.
    for (int i = 0; i < generator_functions.length(); i++) {
      Handle<JSFunction> &function = generator_functions[i];
      if (function->code()->kind() != Code::FUNCTION) continue;
      if (function->code()->has_debug_break_slots()) continue;
2040 2041
      function->ReplaceCode(*lazy_compile);
      function->shared()->ReplaceCode(*lazy_compile);
2042 2043
    }

2044
    // Now recompile all functions with activation frames and and
2045 2046 2047 2048
    // patch the return address to run in the new compiled code.  It could be
    // that some active functions were recompiled already by the suspended
    // generator recompilation pass above; a generator with suspended
    // activations could also have active activations.  That's fine.
2049 2050
    for (int i = 0; i < active_functions.length(); i++) {
      Handle<JSFunction> function = active_functions[i];
2051
      Handle<SharedFunctionInfo> shared(function->shared());
2052

2053
      // If recompilation is not possible just skip it.
2054 2055 2056
      if (shared->is_toplevel()) continue;
      if (!shared->allows_lazy_compilation()) continue;
      if (shared->code()->kind() == Code::BUILTIN) continue;
2057

2058
      EnsureFunctionHasDebugBreakSlots(function);
2059
    }
2060 2061 2062 2063 2064 2065 2066

    RedirectActivationsToRecompiledCodeOnThread(isolate_,
                                                isolate_->thread_local_top());

    ActiveFunctionsRedirector active_functions_redirector;
    isolate_->thread_manager()->IterateArchivedThreads(
          &active_functions_redirector);
2067 2068 2069 2070
  }
}


2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
Object* Debug::FindSharedFunctionInfoInScript(Handle<Script> script,
                                              int position) {
  // Iterate the heap looking for SharedFunctionInfo generated from the
  // script. The inner most SharedFunctionInfo containing the source position
  // for the requested break point is found.
  // NOTE: This might require several heap iterations. If the SharedFunctionInfo
  // which is found is not compiled it is compiled and the heap is iterated
  // again as the compilation might create inner functions from the newly
  // compiled function and the actual requested break point might be in one of
  // these functions.
  // NOTE: The below fix-point iteration depends on all functions that cannot be
  // compiled lazily without a context to not be compiled at all. Compilation
  // will be triggered at points where we do not need a context.
  bool done = false;
  // The current candidate for the source position:
  int target_start_position = RelocInfo::kNoPosition;
  Handle<JSFunction> target_function;
  Handle<SharedFunctionInfo> target;
2089
  Heap* heap = isolate_->heap();
2090
  while (!done) {
2091
    { // Extra scope for iterator.
2092
      HeapIterator iterator(heap);
2093 2094 2095 2096 2097 2098 2099 2100
      for (HeapObject* obj = iterator.next();
           obj != NULL; obj = iterator.next()) {
        bool found_next_candidate = false;
        Handle<JSFunction> function;
        Handle<SharedFunctionInfo> shared;
        if (obj->IsJSFunction()) {
          function = Handle<JSFunction>(JSFunction::cast(obj));
          shared = Handle<SharedFunctionInfo>(function->shared());
2101
          DCHECK(shared->allows_lazy_compilation() || shared->is_compiled());
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
          found_next_candidate = true;
        } else if (obj->IsSharedFunctionInfo()) {
          shared = Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(obj));
          // Skip functions that we cannot compile lazily without a context,
          // which is not available here, because there is no closure.
          found_next_candidate = shared->is_compiled() ||
              shared->allows_lazy_compilation_without_context();
        }
        if (!found_next_candidate) continue;
        if (shared->script() == *script) {
          // If the SharedFunctionInfo found has the requested script data and
          // contains the source position it is a candidate.
          int start_position = shared->function_token_position();
          if (start_position == RelocInfo::kNoPosition) {
            start_position = shared->start_position();
          }
          if (start_position <= position &&
              position <= shared->end_position()) {
            // If there is no candidate or this function is within the current
            // candidate this is the new candidate.
            if (target.is_null()) {
              target_start_position = start_position;
              target_function = function;
              target = shared;
            } else {
              if (target_start_position == start_position &&
                  shared->end_position() == target->end_position()) {
                // 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.
                if (!shared->is_toplevel()) {
                  target_start_position = start_position;
                  target_function = function;
                  target = shared;
                }
              } else if (target_start_position <= start_position &&
                         shared->end_position() <= target->end_position()) {
                // This containment check includes equality as a function
                // inside a top-level function can share either start or end
                // position with the top-level function.
                target_start_position = start_position;
                target_function = function;
                target = shared;
              }
            }
          }
        }
      }  // End for loop.
    }  // End no-allocation scope.

2152
    if (target.is_null()) return heap->undefined_value();
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164

    // There will be at least one break point when we are done.
    has_break_points_ = true;

    // If the candidate found is compiled we are done.
    done = target->is_compiled();
    if (!done) {
      // If the candidate is not compiled, compile it to reveal any inner
      // functions which might contain the requested source position. This
      // will compile all inner functions that cannot be compiled without a
      // context, because Compiler::BuildFunctionInfo checks whether the
      // debugger is active.
2165
      MaybeHandle<Code> maybe_result = target_function.is_null()
2166 2167
          ? Compiler::GetUnoptimizedCode(target)
          : Compiler::GetUnoptimizedCode(target_function);
2168
      if (maybe_result.is_null()) return isolate_->heap()->undefined_value();
2169 2170 2171 2172 2173 2174 2175
    }
  }  // End while loop.

  return *target;
}


2176
// Ensures the debug information is present for shared.
2177 2178
bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
                            Handle<JSFunction> function) {
2179 2180
  Isolate* isolate = shared->GetIsolate();

2181
  // Return if we already have the debug info for shared.
2182
  if (HasDebugInfo(shared)) {
2183
    DCHECK(shared->is_compiled());
2184 2185
    return true;
  }
2186

2187 2188 2189 2190 2191
  // There will be at least one break point when we are done.
  has_break_points_ = true;

  // Ensure function is compiled. Return false if this failed.
  if (!function.is_null() &&
2192
      !Compiler::EnsureCompiled(function, CLEAR_EXCEPTION)) {
2193 2194
    return false;
  }
2195 2196

  // Create the debug info object.
2197
  Handle<DebugInfo> debug_info = isolate->factory()->NewDebugInfo(shared);
2198 2199 2200 2201 2202 2203

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

2204
  return true;
2205 2206 2207 2208
}


void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
2209
  DCHECK(debug_info_list_ != NULL);
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
  // Run through the debug info objects to find this one and remove it.
  DebugInfoListNode* prev = NULL;
  DebugInfoListNode* current = debug_info_list_;
  while (current != NULL) {
    if (*current->debug_info() == *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());
      }
2221 2222
      current->debug_info()->shared()->set_debug_info(
              isolate_->heap()->undefined_value());
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
      delete current;

      // If there are no more debug info objects there are not more break
      // points.
      has_break_points_ = debug_info_list_ != NULL;

      return;
    }
    // Move to next in list.
    prev = current;
    current = current->next();
  }
  UNREACHABLE();
}


void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
2240 2241 2242
  after_break_target_ = NULL;

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

2244
  HandleScope scope(isolate_);
2245 2246
  PrepareForBreakPoints();

2247
  // Get the executing function in which the debug break occurred.
2248 2249 2250
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
2251 2252 2253
    // Return if we failed to retrieve the debug info.
    return;
  }
2254 2255 2256 2257 2258
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
  Handle<Code> code(debug_info->code());
  Handle<Code> original_code(debug_info->original_code());
#ifdef DEBUG
  // Get the code which is actually executing.
2259
  Handle<Code> frame_code(frame->LookupCode());
2260
  DCHECK(frame_code.is_identical_to(code));
2261 2262 2263 2264 2265
#endif

  // Find the call address in the running code. This address holds the call to
  // either a DebugBreakXXX or to the debug break return entry code if the
  // break point is still active after processing the break point.
2266
  Address addr = Assembler::break_address_from_return_address(frame->pc());
2267

2268
  // Check if the location is at JS exit or debug break slot.
2269 2270
  bool at_js_return = false;
  bool break_at_js_return_active = false;
2271
  bool at_debug_break_slot = false;
2272
  RelocIterator it(debug_info->code());
2273
  while (!it.done() && !at_js_return && !at_debug_break_slot) {
2274
    if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
2275 2276
      at_js_return = (it.rinfo()->pc() ==
          addr - Assembler::kPatchReturnSequenceAddressOffset);
2277
      break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
2278
    }
2279 2280 2281 2282
    if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
      at_debug_break_slot = (it.rinfo()->pc() ==
          addr - Assembler::kPatchDebugBreakSlotAddressOffset);
    }
2283 2284 2285 2286 2287
    it.next();
  }

  // Handle the jump to continue execution after break point depending on the
  // break location.
2288 2289 2290 2291 2292
  if (at_js_return) {
    // If the break point as return is still active jump to the corresponding
    // place in the original code. If not the break point was removed during
    // break point processing.
    if (break_at_js_return_active) {
2293
      addr += original_code->instruction_start() - code->instruction_start();
2294 2295
    }

2296
    // Move back to where the call instruction sequence started.
2297
    after_break_target_ = addr - Assembler::kPatchReturnSequenceAddressOffset;
2298 2299 2300 2301 2302
  } else if (at_debug_break_slot) {
    // Address of where the debug break slot starts.
    addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;

    // Continue just after the slot.
2303
    after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
2304
  } else {
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
    addr = Assembler::target_address_from_return_address(frame->pc());
    if (IsDebugBreak(Assembler::target_address_at(addr, *code))) {
      // We now know that there is still a debug break call at the target
      // address, so the break point is still there and the original code will
      // hold the address to jump to in order to complete the call which is
      // replaced by a call to DebugBreakXXX.

      // Find the corresponding address in the original code.
      addr += original_code->instruction_start() - code->instruction_start();

      // Install jump to the call address in the original code. This will be the
      // call which was overwritten by the call to DebugBreakXXX.
      after_break_target_ = Assembler::target_address_at(addr, *original_code);
    } else {
      // There is no longer a break point present. Don't try to look in the
      // original code as the running code will have the right address. This
      // takes care of the case where the last break point is removed from the
      // function and therefore no "original code" is available.
      after_break_target_ = Assembler::target_address_at(addr, *code);
    }
2325 2326 2327 2328
  }
}


2329
bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
2330
  HandleScope scope(isolate_);
2331

2332 2333 2334 2335 2336 2337 2338
  // If there are no break points this cannot be break at return, as
  // the debugger statement and stack guard bebug break cannot be at
  // return.
  if (!has_break_points_) {
    return false;
  }

2339 2340
  PrepareForBreakPoints();

2341
  // Get the executing function in which the debug break occurred.
2342 2343 2344
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
2345 2346 2347 2348 2349 2350 2351
    // Return if we failed to retrieve the debug info.
    return false;
  }
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
  Handle<Code> code(debug_info->code());
#ifdef DEBUG
  // Get the code which is actually executing.
2352
  Handle<Code> frame_code(frame->LookupCode());
2353
  DCHECK(frame_code.is_identical_to(code));
2354 2355 2356
#endif

  // Find the call address in the running code.
2357
  Address addr = Assembler::break_address_from_return_address(frame->pc());
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371

  // Check if the location is at JS return.
  RelocIterator it(debug_info->code());
  while (!it.done()) {
    if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
      return (it.rinfo()->pc() ==
          addr - Assembler::kPatchReturnSequenceAddressOffset);
    }
    it.next();
  }
  return false;
}


2372
void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
2373
                                  LiveEdit::FrameDropMode mode,
2374
                                  Object** restarter_frame_function_pointer) {
2375
  if (mode != LiveEdit::CURRENTLY_SET_MODE) {
2376 2377
    thread_local_.frame_drop_mode_ = mode;
  }
2378
  thread_local_.break_frame_id_ = new_break_frame_id;
2379 2380
  thread_local_.restarter_frame_function_pointer_ =
      restarter_frame_function_pointer;
2381 2382 2383
}


2384
bool Debug::IsDebugGlobal(GlobalObject* global) {
2385
  return is_loaded() && global == debug_context()->global_object();
2386 2387 2388
}


2389
void Debug::ClearMirrorCache() {
2390
  PostponeInterruptsScope postpone(isolate_);
2391
  HandleScope scope(isolate_);
2392
  AssertDebugContext();
2393
  Factory* factory = isolate_->factory();
2394 2395
  Handle<GlobalObject> global(isolate_->global_object());
  JSObject::SetProperty(global,
2396 2397
                        factory->NewStringFromAsciiChecked("next_handle_"),
                        handle(Smi::FromInt(0), isolate_), SLOPPY).Check();
2398
  JSObject::SetProperty(global,
2399 2400
                        factory->NewStringFromAsciiChecked("mirror_cache_"),
                        factory->NewJSArray(0, FAST_ELEMENTS), SLOPPY).Check();
2401 2402 2403
}


2404 2405 2406
Handle<FixedArray> Debug::GetLoadedScripts() {
  // Create and fill the script cache when the loaded scripts is requested for
  // the first time.
2407
  if (script_cache_ == NULL) script_cache_ = new ScriptCache(isolate_);
2408 2409 2410

  // Perform GC to get unreferenced scripts evicted from the cache before
  // returning the content.
2411 2412
  isolate_->heap()->CollectAllGarbage(Heap::kNoGCFlags,
                                      "Debug::GetLoadedScripts");
2413 2414 2415 2416 2417 2418

  // Get the scripts from the cache.
  return script_cache_->GetScripts();
}


2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
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());
    script->set_eval_from_instructions_offset(Smi::FromInt(offset));
  }
}


2434 2435 2436
MaybeHandle<Object> Debug::MakeJSObject(const char* constructor_name,
                                        int argc,
                                        Handle<Object> argv[]) {
2437
  AssertDebugContext();
2438
  // Create the execution state object.
2439
  Handle<GlobalObject> global(isolate_->global_object());
2440
  Handle<Object> constructor = Object::GetProperty(
2441
      isolate_, global, constructor_name).ToHandleChecked();
2442
  DCHECK(constructor->IsJSFunction());
2443
  if (!constructor->IsJSFunction()) return MaybeHandle<Object>();
2444 2445
  // We do not handle interrupts here.  In particular, termination interrupts.
  PostponeInterruptsScope no_interrupts(isolate_);
2446
  return Execution::TryCall(Handle<JSFunction>::cast(constructor),
2447
                            handle(debug_context()->global_proxy()),
2448 2449
                            argc,
                            argv);
2450 2451 2452
}


2453
MaybeHandle<Object> Debug::MakeExecutionState() {
2454
  // Create the execution state object.
2455
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()) };
2456
  return MakeJSObject("MakeExecutionState", arraysize(argv), argv);
2457 2458 2459
}


2460
MaybeHandle<Object> Debug::MakeBreakEvent(Handle<Object> break_points_hit) {
2461
  // Create the new break event object.
2462 2463
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()),
                            break_points_hit };
2464
  return MakeJSObject("MakeBreakEvent", arraysize(argv), argv);
2465 2466 2467
}


2468
MaybeHandle<Object> Debug::MakeExceptionEvent(Handle<Object> exception,
2469 2470
                                              bool uncaught,
                                              Handle<Object> promise) {
2471
  // Create the new exception event object.
2472
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()),
2473
                            exception,
2474 2475
                            isolate_->factory()->ToBoolean(uncaught),
                            promise };
2476
  return MakeJSObject("MakeExceptionEvent", arraysize(argv), argv);
2477 2478 2479
}


2480
MaybeHandle<Object> Debug::MakeCompileEvent(Handle<Script> script,
2481
                                            v8::DebugEvent type) {
2482
  // Create the compile event object.
2483
  Handle<Object> script_wrapper = Script::GetWrapper(script);
2484
  Handle<Object> argv[] = { script_wrapper,
2485
                            isolate_->factory()->NewNumberFromInt(type) };
2486
  return MakeJSObject("MakeCompileEvent", arraysize(argv), argv);
2487 2488 2489
}


2490 2491 2492
MaybeHandle<Object> Debug::MakePromiseEvent(Handle<JSObject> event_data) {
  // Create the promise event object.
  Handle<Object> argv[] = { event_data };
2493
  return MakeJSObject("MakePromiseEvent", arraysize(argv), argv);
2494 2495 2496
}


2497 2498 2499
MaybeHandle<Object> Debug::MakeAsyncTaskEvent(Handle<JSObject> task_event) {
  // Create the async task event object.
  Handle<Object> argv[] = { task_event };
2500
  return MakeJSObject("MakeAsyncTaskEvent", arraysize(argv), argv);
2501 2502 2503
}


2504
void Debug::OnThrow(Handle<Object> exception, bool uncaught) {
2505
  if (in_debug_scope() || ignore_events()) return;
2506 2507
  // Temporarily clear any scheduled_exception to allow evaluating
  // JavaScript from the debug event handler.
2508
  HandleScope scope(isolate_);
2509 2510 2511 2512 2513
  Handle<Object> scheduled_exception;
  if (isolate_->has_scheduled_exception()) {
    scheduled_exception = handle(isolate_->scheduled_exception(), isolate_);
    isolate_->clear_scheduled_exception();
  }
2514
  OnException(exception, uncaught, isolate_->GetPromiseOnStackOnThrow());
2515 2516 2517
  if (!scheduled_exception.is_null()) {
    isolate_->thread_local_top()->scheduled_exception_ = *scheduled_exception;
  }
2518 2519
}

2520

2521 2522
void Debug::OnPromiseReject(Handle<JSObject> promise, Handle<Object> value) {
  if (in_debug_scope() || ignore_events()) return;
2523
  HandleScope scope(isolate_);
2524 2525
  OnException(value, false, promise);
}
2526

2527 2528 2529 2530 2531 2532

void Debug::OnException(Handle<Object> exception, bool uncaught,
                        Handle<Object> promise) {
  if (promise->IsJSObject()) {
    uncaught |= !PromiseHasRejectHandler(Handle<JSObject>::cast(promise));
  }
2533 2534 2535
  // Bail out if exception breaks are not active
  if (uncaught) {
    // Uncaught exceptions are reported by either flags.
2536
    if (!(break_on_uncaught_exception_ || break_on_exception_)) return;
2537 2538
  } else {
    // Caught exceptions are reported is activated.
2539
    if (!break_on_exception_) return;
2540 2541
  }

2542 2543
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2544 2545

  // Clear all current stepping setup.
2546
  ClearStepping();
2547

2548 2549 2550
  // Create the event data object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
2551 2552 2553 2554
  if (!MakeExceptionEvent(
          exception, uncaught, promise).ToHandle(&event_data)) {
    return;
  }
2555

2556
  // Process debug event.
2557
  ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2558 2559 2560 2561
  // Return to continue execution from where the exception was thrown.
}


2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
void Debug::OnCompileError(Handle<Script> script) {
  // No more to do if not debugging.
  if (in_debug_scope() || ignore_events()) return;

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

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

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


2580
void Debug::OnDebugBreak(Handle<Object> break_points_hit,
2581
                            bool auto_continue) {
2582 2583
  // The caller provided for DebugScope.
  AssertDebugContext();
2584
  // Bail out if there is no listener for this event
2585
  if (ignore_events()) return;
2586

2587
  HandleScope scope(isolate_);
2588 2589 2590
  // Create the event data object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
2591
  if (!MakeBreakEvent(break_points_hit).ToHandle(&event_data)) return;
2592

2593 2594 2595 2596
  // Process debug event.
  ProcessDebugEvent(v8::Break,
                    Handle<JSObject>::cast(event_data),
                    auto_continue);
2597 2598 2599
}


2600
void Debug::OnBeforeCompile(Handle<Script> script) {
2601
  if (in_debug_scope() || ignore_events()) return;
2602

2603
  HandleScope scope(isolate_);
2604 2605
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2606 2607

  // Create the event data object.
2608
  Handle<Object> event_data;
2609
  // Bail out and don't call debugger if exception.
2610 2611
  if (!MakeCompileEvent(script, v8::BeforeCompile).ToHandle(&event_data))
    return;
2612

2613 2614 2615 2616
  // Process debug event.
  ProcessDebugEvent(v8::BeforeCompile,
                    Handle<JSObject>::cast(event_data),
                    true);
2617 2618 2619 2620
}


// Handle debugger actions when a new script is compiled.
2621
void Debug::OnAfterCompile(Handle<Script> script) {
2622
  // Add the newly compiled script to the script cache.
2623
  if (script_cache_ != NULL) script_cache_->Add(script);
2624 2625

  // No more to do if not debugging.
2626
  if (in_debug_scope() || ignore_events()) return;
2627

2628
  HandleScope scope(isolate_);
2629 2630
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2631 2632 2633 2634

  // If debugging there might be script break points registered for this
  // script. Make sure that these break points are set.

2635
  // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
2636 2637
  Handle<String> update_script_break_points_string =
      isolate_->factory()->InternalizeOneByteString(
2638
          STATIC_CHAR_VECTOR("UpdateScriptBreakPoints"));
2639
  Handle<GlobalObject> debug_global(debug_context()->global_object());
2640
  Handle<Object> update_script_break_points =
2641 2642
      Object::GetProperty(
          debug_global, update_script_break_points_string).ToHandleChecked();
2643 2644 2645
  if (!update_script_break_points->IsJSFunction()) {
    return;
  }
2646
  DCHECK(update_script_break_points->IsJSFunction());
2647 2648 2649

  // Wrap the script object in a proper JS object before passing it
  // to JavaScript.
2650
  Handle<Object> wrapper = Script::GetWrapper(script);
2651 2652

  // Call UpdateScriptBreakPoints expect no exceptions.
2653
  Handle<Object> argv[] = { wrapper };
2654 2655
  if (Execution::TryCall(Handle<JSFunction>::cast(update_script_break_points),
                         isolate_->js_builtins_object(),
2656
                         arraysize(argv),
2657
                         argv).is_null()) {
2658 2659 2660 2661
    return;
  }

  // Create the compile state object.
2662
  Handle<Object> event_data;
2663
  // Bail out and don't call debugger if exception.
2664
  if (!MakeCompileEvent(script, v8::AfterCompile).ToHandle(&event_data)) return;
2665

2666
  // Process debug event.
2667
  ProcessDebugEvent(v8::AfterCompile, Handle<JSObject>::cast(event_data), true);
2668 2669 2670
}


2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
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);
}


2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
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);
}


2709 2710 2711
void Debug::ProcessDebugEvent(v8::DebugEvent event,
                              Handle<JSObject> event_data,
                              bool auto_continue) {
2712
  HandleScope scope(isolate_);
2713

2714
  // Create the execution state.
2715 2716
  Handle<Object> exec_state;
  // Bail out and don't call debugger if exception.
2717 2718
  if (!MakeExecutionState().ToHandle(&exec_state)) return;

2719 2720
  // First notify the message handler if any.
  if (message_handler_ != NULL) {
2721 2722 2723 2724
    NotifyMessageHandler(event,
                         Handle<JSObject>::cast(exec_state),
                         event_data,
                         auto_continue);
2725
  }
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
  // 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);
  }
  // Process pending debug commands.
  if (event == v8::Break) {
    while (!event_command_queue_.IsEmpty()) {
      CommandMessage command = event_command_queue_.Get();
      if (!event_listener_.is_null()) {
        CallEventCallback(v8::BreakForCommand,
                          exec_state,
                          event_data,
                          command.client_data());
      }
      command.Dispose();
2743 2744 2745 2746 2747
    }
  }
}


2748 2749 2750 2751
void Debug::CallEventCallback(v8::DebugEvent event,
                              Handle<Object> exec_state,
                              Handle<Object> event_data,
                              v8::Debug::ClientData* client_data) {
2752
  if (event_listener_->IsForeign()) {
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
    // 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);
2763
    DCHECK(!isolate_->has_scheduled_exception());
2764
  } else {
2765
    // Invoke the JavaScript debug event listener.
2766
    DCHECK(event_listener_->IsJSFunction());
2767 2768 2769 2770
    Handle<Object> argv[] = { Handle<Object>(Smi::FromInt(event), isolate_),
                              exec_state,
                              event_data,
                              event_listener_data_ };
2771
    Handle<JSReceiver> global(isolate_->global_proxy());
2772
    Execution::TryCall(Handle<JSFunction>::cast(event_listener_),
2773
                       global, arraysize(argv), argv);
2774 2775 2776 2777
  }
}


2778
Handle<Context> Debug::GetDebugContext() {
2779
  DebugScope debug_scope(this);
2780
  // The global handle may be destroyed soon after.  Return it reboxed.
2781
  return handle(*debug_context(), isolate_);
2782 2783 2784
}


2785 2786 2787 2788
void Debug::NotifyMessageHandler(v8::DebugEvent event,
                                 Handle<JSObject> exec_state,
                                 Handle<JSObject> event_data,
                                 bool auto_continue) {
2789 2790 2791
  // Prevent other interrupts from triggering, for example API callbacks,
  // while dispatching message handler callbacks.
  PostponeInterruptsScope no_interrupts(isolate_);
2792
  DCHECK(is_active_);
2793
  HandleScope scope(isolate_);
2794
  // Process the individual events.
2795
  bool sendEventMessage = false;
2796 2797
  switch (event) {
    case v8::Break:
2798
    case v8::BreakForCommand:
2799
      sendEventMessage = !auto_continue;
2800 2801
      break;
    case v8::Exception:
2802
      sendEventMessage = true;
2803 2804 2805 2806
      break;
    case v8::BeforeCompile:
      break;
    case v8::AfterCompile:
2807
      sendEventMessage = true;
2808 2809 2810 2811 2812 2813 2814
      break;
    case v8::NewFunction:
      break;
    default:
      UNREACHABLE();
  }

2815 2816 2817
  // 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.
2818
  DCHECK(in_debug_scope());
2819
  isolate_->stack_guard()->ClearDebugCommand();
2820 2821 2822 2823

  // Notify the debugger that a debug event has occurred unless auto continue is
  // active in which case no event is send.
  if (sendEventMessage) {
2824 2825 2826 2827 2828 2829
    MessageImpl message = MessageImpl::NewEvent(
        event,
        auto_continue,
        Handle<JSObject>::cast(exec_state),
        Handle<JSObject>::cast(event_data));
    InvokeMessageHandler(message);
2830
  }
2831 2832 2833 2834 2835

  // 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.
2836
  if (auto_continue && !has_commands()) return;
2837

2838 2839 2840
  // DebugCommandProcessor goes here.
  bool running = auto_continue;

2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
  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();

2852
  // Process requests from the debugger.
2853
  do {
2854
    // Wait for new command in the queue.
2855
    command_received_.Wait();
2856 2857

    // Get the command from the queue.
2858
    CommandMessage command = command_queue_.Get();
2859 2860
    isolate_->logger()->DebugTag(
        "Got request from command queue, in interactive loop.");
2861
    if (!is_active()) {
2862 2863
      // Delete command text and user data.
      command.Dispose();
2864 2865 2866
      return;
    }

2867 2868 2869 2870 2871 2872 2873 2874
    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;
2875 2876 2877 2878
    MaybeHandle<Object> maybe_exception;
    MaybeHandle<Object> maybe_result =
        Execution::TryCall(process_debug_request, cmd_processor, 1,
                           request_args, &maybe_exception);
2879 2880 2881 2882

    if (maybe_result.ToHandle(&answer_value)) {
      if (answer_value->IsUndefined()) {
        answer = isolate_->factory()->empty_string();
2883
      } else {
2884
        answer = Handle<String>::cast(answer_value);
2885
      }
2886 2887 2888

      // Log the JSON request/response.
      if (FLAG_trace_debug_json) {
2889 2890
        PrintF("%s\n", request_text->ToCString().get());
        PrintF("%s\n", answer->ToCString().get());
2891 2892
      }

2893 2894 2895
      Handle<Object> is_running_args[] = { answer };
      maybe_result = Execution::Call(
          isolate_, is_running, cmd_processor, 1, is_running_args);
2896 2897 2898
      Handle<Object> result;
      if (!maybe_result.ToHandle(&result)) break;
      running = result->IsTrue();
2899
    } else {
2900 2901 2902 2903 2904
      Handle<Object> exception;
      if (!maybe_exception.ToHandle(&exception)) break;
      Handle<Object> result;
      if (!Execution::ToString(isolate_, exception).ToHandle(&result)) break;
      answer = Handle<String>::cast(result);
2905 2906 2907
    }

    // Return the result.
2908
    MessageImpl message = MessageImpl::NewResponse(
2909
        event, running, exec_state, event_data, answer, command.client_data());
2910 2911
    InvokeMessageHandler(message);
    command.Dispose();
2912

2913
    // Return from debug event processing if either the VM is put into the
2914
    // running state (through a continue command) or auto continue is active
2915
    // and there are no more commands queued.
2916
  } while (!running || has_commands());
2917
  command_queue_.Clear();
2918 2919 2920
}


2921 2922
void Debug::SetEventListener(Handle<Object> callback,
                             Handle<Object> data) {
2923
  GlobalHandles* global_handles = isolate_->global_handles();
2924

2925 2926 2927 2928 2929
  // Remove existing entry.
  GlobalHandles::Destroy(event_listener_.location());
  event_listener_ = Handle<Object>();
  GlobalHandles::Destroy(event_listener_data_.location());
  event_listener_data_ = Handle<Object>();
2930

2931
  // Set new entry.
2932
  if (!callback->IsUndefined() && !callback->IsNull()) {
2933 2934 2935
    event_listener_ = global_handles->Create(*callback);
    if (data.is_null()) data = isolate_->factory()->undefined_value();
    event_listener_data_ = global_handles->Create(*data);
2936 2937
  }

2938
  UpdateState();
2939 2940 2941
}


2942
void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
2943
  message_handler_ = handler;
2944
  UpdateState();
2945
  if (handler == NULL && in_debug_scope()) {
2946 2947
    // Send an empty command to the debugger if in a break to make JavaScript
    // run again if the debugger is closed.
2948
    EnqueueCommandMessage(Vector<const uint16_t>::empty());
2949
  }
2950
}
2951

2952

2953 2954

void Debug::UpdateState() {
2955
  is_active_ = message_handler_ != NULL || !event_listener_.is_null();
2956
  if (is_active_ || in_debug_scope()) {
2957 2958
    // Note that the debug context could have already been loaded to
    // bootstrap test cases.
2959
    isolate_->compilation_cache()->Disable();
2960
    is_active_ = Load();
2961
  } else if (is_loaded()) {
2962
    isolate_->compilation_cache()->Enable();
2963
    Unload();
2964
  }
2965 2966 2967 2968
}


// Calls the registered debug message handler. This callback is part of the
2969
// public API.
2970
void Debug::InvokeMessageHandler(MessageImpl message) {
2971
  if (message_handler_ != NULL) message_handler_(message);
2972 2973 2974
}


2975 2976 2977
// 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
2978
// by the API client thread.
2979 2980
void Debug::EnqueueCommandMessage(Vector<const uint16_t> command,
                                  v8::Debug::ClientData* client_data) {
2981
  // Need to cast away const.
2982
  CommandMessage message = CommandMessage::New(
2983
      Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
2984 2985
                       command.length()),
      client_data);
2986
  isolate_->logger()->DebugTag("Put command on command_queue.");
2987
  command_queue_.Put(message);
2988
  command_received_.Signal();
2989 2990

  // Set the debug command break flag to have the command processed.
2991
  if (!in_debug_scope()) isolate_->stack_guard()->RequestDebugCommand();
2992 2993 2994
}


2995
void Debug::EnqueueDebugCommand(v8::Debug::ClientData* client_data) {
2996 2997 2998 2999
  CommandMessage message = CommandMessage::New(Vector<uint16_t>(), client_data);
  event_command_queue_.Put(message);

  // Set the debug command break flag to have the command processed.
3000
  if (!in_debug_scope()) isolate_->stack_guard()->RequestDebugCommand();
3001 3002 3003
}


3004
MaybeHandle<Object> Debug::Call(Handle<JSFunction> fun, Handle<Object> data) {
3005 3006
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return isolate_->factory()->undefined_value();
3007 3008

  // Create the execution state.
3009
  Handle<Object> exec_state;
3010 3011 3012
  if (!MakeExecutionState().ToHandle(&exec_state)) {
    return isolate_->factory()->undefined_value();
  }
3013

3014
  Handle<Object> argv[] = { exec_state, data };
3015
  return Execution::Call(
3016
      isolate_,
3017
      fun,
3018
      Handle<Object>(debug_context()->global_proxy(), isolate_),
3019
      arraysize(argv),
3020
      argv);
3021 3022 3023
}


3024
void Debug::HandleDebugBreak() {
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
  // Ignore debug break during bootstrapping.
  if (isolate_->bootstrapper()->IsActive()) return;
  // Just continue if breaks are disabled.
  if (break_disabled_) return;
  // Ignore debug break if debugger is not active.
  if (!is_active()) return;

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

  { JavaScriptFrameIterator it(isolate_);
3036
    DCHECK(!it.done());
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
    Object* fun = it.frame()->function();
    if (fun && fun->IsJSFunction()) {
      // Don't stop in builtin functions.
      if (JSFunction::cast(fun)->IsBuiltin()) return;
      GlobalObject* global = JSFunction::cast(fun)->context()->global_object();
      // Don't stop in debugger functions.
      if (IsDebugGlobal(global)) return;
    }
  }

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

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

  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_);
3064 3065
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
3066 3067 3068 3069 3070 3071 3072

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


3073 3074 3075 3076 3077 3078
DebugScope::DebugScope(Debug* debug)
    : debug_(debug),
      prev_(debug->debugger_entry()),
      save_(debug_->isolate_),
      no_termination_exceptons_(debug_->isolate_,
                                StackGuard::TERMINATE_EXECUTION) {
3079
  // Link recursive debugger entry.
3080
  debug_->thread_local_.current_debug_scope_ = this;
3081 3082

  // Store the previous break id and frame id.
3083 3084
  break_id_ = debug_->break_id();
  break_frame_id_ = debug_->break_frame_id();
3085 3086 3087

  // Create the new break info. If there is no JavaScript frames there is no
  // break frame id.
3088
  JavaScriptFrameIterator it(isolate());
3089
  bool has_js_frames = !it.done();
3090 3091 3092
  debug_->thread_local_.break_frame_id_ = has_js_frames ? it.frame()->id()
                                                        : StackFrame::NO_ID;
  debug_->SetNextBreakId();
3093

3094
  debug_->UpdateState();
3095
  // Make sure that debugger is loaded and enter the debugger context.
3096
  // The previous context is kept in save_.
3097 3098
  failed_ = !debug_->is_loaded();
  if (!failed_) isolate()->set_context(*debug->debug_context());
3099 3100 3101 3102
}



3103 3104
DebugScope::~DebugScope() {
  if (!failed_ && prev_ == NULL) {
3105 3106 3107 3108
    // 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.
3109
    if (!isolate()->has_pending_exception()) debug_->ClearMirrorCache();
3110 3111 3112

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

3116
  // Leaving this debugger entry.
3117 3118 3119 3120 3121
  debug_->thread_local_.current_debug_scope_ = prev_;

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

3123
  debug_->UpdateState();
3124 3125 3126
}


3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
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_;
}


v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
  return v8::Utils::ToLocal(exec_state_);
}


3190 3191 3192 3193 3194
v8::Isolate* MessageImpl::GetIsolate() const {
  return reinterpret_cast<v8::Isolate*>(exec_state_->GetIsolate());
}


3195 3196 3197 3198 3199 3200
v8::Handle<v8::Object> MessageImpl::GetEventData() const {
  return v8::Utils::ToLocal(event_data_);
}


v8::Handle<v8::String> MessageImpl::GetJSON() const {
3201 3202
  Isolate* isolate = event_data_->GetIsolate();
  v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate));
3203 3204 3205

  if (IsEvent()) {
    // Call toJSONProtocol on the debug event object.
3206 3207
    Handle<Object> fun = Object::GetProperty(
        isolate, event_data_, "toJSONProtocol").ToHandleChecked();
3208 3209 3210
    if (!fun->IsJSFunction()) {
      return v8::Handle<v8::String>();
    }
3211 3212 3213 3214 3215

    MaybeHandle<Object> maybe_json =
        Execution::TryCall(Handle<JSFunction>::cast(fun), event_data_, 0, NULL);
    Handle<Object> json;
    if (!maybe_json.ToHandle(&json) || !json->IsString()) {
3216 3217
      return v8::Handle<v8::String>();
    }
3218
    return scope.Escape(v8::Utils::ToLocal(Handle<String>::cast(json)));
3219 3220 3221 3222 3223 3224 3225
  } else {
    return v8::Utils::ToLocal(response_json_);
  }
}


v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
3226
  Isolate* isolate = event_data_->GetIsolate();
3227 3228
  v8::Handle<v8::Context> context = GetDebugEventContext(isolate);
  // Isolate::context() may be NULL when "script collected" event occures.
3229
  DCHECK(!context.IsEmpty());
3230
  return context;
3231 3232 3233 3234 3235 3236 3237 3238
}


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


3239 3240 3241
EventDetailsImpl::EventDetailsImpl(DebugEvent event,
                                   Handle<JSObject> exec_state,
                                   Handle<JSObject> event_data,
3242 3243
                                   Handle<Object> callback_data,
                                   v8::Debug::ClientData* client_data)
3244 3245 3246
    : event_(event),
      exec_state_(exec_state),
      event_data_(event_data),
3247 3248
      callback_data_(callback_data),
      client_data_(client_data) {}
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266


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


v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
  return v8::Utils::ToLocal(exec_state_);
}


v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
  return v8::Utils::ToLocal(event_data_);
}


v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
3267
  return GetDebugEventContext(exec_state_->GetIsolate());
3268 3269 3270 3271 3272 3273 3274 3275
}


v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
  return v8::Utils::ToLocal(callback_data_);
}


3276 3277 3278 3279 3280
v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
  return client_data_;
}


3281 3282
CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
                                   client_data_(NULL) {
3283 3284 3285
}


3286 3287
CommandMessage::CommandMessage(const Vector<uint16_t>& text,
                               v8::Debug::ClientData* data)
3288
    : text_(text),
3289
      client_data_(data) {
3290 3291 3292
}


3293
void CommandMessage::Dispose() {
3294 3295 3296 3297 3298 3299
  text_.Dispose();
  delete client_data_;
  client_data_ = NULL;
}


3300 3301 3302
CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
                                   v8::Debug::ClientData* data) {
  return CommandMessage(command.Clone(), data);
3303 3304 3305
}


3306 3307 3308
CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
                                                     size_(size) {
  messages_ = NewArray<CommandMessage>(size);
3309 3310 3311
}


3312
CommandMessageQueue::~CommandMessageQueue() {
3313
  while (!IsEmpty()) Get().Dispose();
3314 3315 3316 3317
  DeleteArray(messages_);
}


3318
CommandMessage CommandMessageQueue::Get() {
3319
  DCHECK(!IsEmpty());
3320 3321 3322 3323 3324 3325
  int result = start_;
  start_ = (start_ + 1) % size_;
  return messages_[result];
}


3326
void CommandMessageQueue::Put(const CommandMessage& message) {
3327 3328 3329 3330 3331 3332 3333 3334
  if ((end_ + 1) % size_ == start_) {
    Expand();
  }
  messages_[end_] = message;
  end_ = (end_ + 1) % size_;
}


3335 3336
void CommandMessageQueue::Expand() {
  CommandMessageQueue new_queue(size_ * 2);
3337 3338
  while (!IsEmpty()) {
    new_queue.Put(Get());
3339
  }
3340
  CommandMessage* array_to_free = messages_;
3341 3342
  *this = new_queue;
  new_queue.messages_ = array_to_free;
3343 3344
  // Make the new_queue empty so that it doesn't call Dispose on any messages.
  new_queue.start_ = new_queue.end_;
3345 3346 3347 3348
  // Automatic destructor called on new_queue, freeing array_to_free.
}


3349
LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size)
3350
    : logger_(logger), queue_(size) {}
3351 3352


3353
bool LockingCommandMessageQueue::IsEmpty() const {
3354
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3355
  return queue_.IsEmpty();
3356 3357
}

3358

3359
CommandMessage LockingCommandMessageQueue::Get() {
3360
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3361
  CommandMessage result = queue_.Get();
3362
  logger_->DebugEvent("Get", result.text());
3363 3364 3365 3366
  return result;
}


3367
void LockingCommandMessageQueue::Put(const CommandMessage& message) {
3368
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3369
  queue_.Put(message);
3370
  logger_->DebugEvent("Put", message.text());
3371 3372 3373
}


3374
void LockingCommandMessageQueue::Clear() {
3375
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3376 3377 3378
  queue_.Clear();
}

3379
} }  // namespace v8::internal