debug.cc 118 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 131 132
    // Check for break at return.
    if (RelocInfo::IsJSReturn(rmode())) {
      // Set the positions to the end of the function.
      if (debug_info_->shared()->HasSourceCode()) {
        position_ = debug_info_->shared()->end_position() -
                    debug_info_->shared()->start_position() - 1;
      } else {
        position_ = 0;
      }
      statement_position_ = position_;
133 134
      break_point_++;
      return;
135 136 137
    }

    if (RelocInfo::IsCodeTarget(rmode())) {
138 139 140
      // 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.
141
      Address target = original_rinfo()->target_address();
142
      Code* code = Code::GetCodeFromTargetAddress(target);
143 144 145 146 147 148 149 150 151 152 153

      if (RelocInfo::IsConstructCall(rmode()) || code->is_call_stub()) {
        break_point_++;
        return;
      }

      // Skip below if we only want locations for calls and returns.
      if (type_ == CALLS_AND_RETURNS) continue;

      if ((code->is_inline_cache_stub() && !code->is_binary_op_stub() &&
           !code->is_compare_ic_stub() && !code->is_to_boolean_ic_stub())) {
154 155 156 157
        break_point_++;
        return;
      }
      if (code->kind() == Code::STUB) {
158 159 160
        if (IsDebuggerStatement()) {
          break_point_++;
          return;
161 162
        } else if (type_ == ALL_BREAK_LOCATIONS) {
          if (IsBreakStub(code)) {
163 164 165 166
            break_point_++;
            return;
          }
        } else {
167
          DCHECK(type_ == SOURCE_BREAK_LOCATIONS);
168
          if (IsSourceBreakStub(code)) {
169 170 171 172 173 174 175
            break_point_++;
            return;
          }
        }
      }
    }

176 177
    if (IsDebugBreakSlot() && type_ != CALLS_AND_RETURNS) {
      // There is always a possible break point at a debug break slot.
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
      break_point_++;
      return;
    }
  }
}


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


193 194
// Find the break point at the supplied address, or the closest one before
// the address.
195 196 197 198 199 200
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.
201
    if (this->pc() <= pc && pc - this->pc() < distance) {
202
      closest_break_point = break_point();
203
      distance = static_cast<int>(pc - this->pc());
204 205 206 207 208 209 210 211 212 213 214 215 216
      // 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.
217 218
void BreakLocationIterator::FindBreakLocationFromPosition(int position,
    BreakPositionAlignment alignment) {
219 220 221 222
  // Run through all break points to locate the one closest to the source
  // position.
  int closest_break_point = 0;
  int distance = kMaxInt;
223

224
  while (!Done()) {
225 226 227 228 229 230 231 232 233 234 235 236
    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();
    }
237
    // Check if this break point is closer that what was previously found.
238
    if (position <= next_position && next_position - position < distance) {
239
      closest_break_point = break_point();
240
      distance = next_position - position;
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
      // 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_;
257 258 259 260 261 262
  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));
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

  // 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.
280
  if (!HasBreakPoint()) SetDebugBreak();
281
  DCHECK(IsDebugBreak() || IsDebuggerStatement());
282 283 284 285 286 287 288 289 290 291 292 293 294
  // 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();
295
    DCHECK(!IsDebugBreak());
296 297 298 299 300
  }
}


void BreakLocationIterator::SetOneShot() {
301
  // Debugger statement always calls debugger. No need to modify it.
302
  if (IsDebuggerStatement()) return;
303

304 305
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
306
    DCHECK(IsDebugBreak());
307 308 309 310 311 312 313 314 315
    return;
  }

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


void BreakLocationIterator::ClearOneShot() {
316
  // Debugger statement always calls debugger. No need to modify it.
317
  if (IsDebuggerStatement()) return;
318

319 320
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
321
    DCHECK(IsDebugBreak());
322 323 324 325 326
    return;
  }

  // Patch code removing debug break.
  ClearDebugBreak();
327
  DCHECK(!IsDebugBreak());
328 329 330 331
}


void BreakLocationIterator::SetDebugBreak() {
332
  // Debugger statement always calls debugger. No need to modify it.
333
  if (IsDebuggerStatement()) return;
334

335
  // If there is already a break point here just return. This might happen if
336
  // the same code is flooded with break points twice. Flooding the same
337 338
  // function twice might happen when stepping in a function with an exception
  // handler as the handler and the function is the same.
339
  if (IsDebugBreak()) return;
340

341
  if (RelocInfo::IsJSReturn(rmode())) {
342 343
    // Patch the frame exit code with a break point.
    SetDebugBreakAtReturn();
344 345 346
  } else if (IsDebugBreakSlot()) {
    // Patch the code in the break slot.
    SetDebugBreakAtSlot();
347
  } else {
348 349
    // Patch the IC call.
    SetDebugBreakAtIC();
350
  }
351
  DCHECK(IsDebugBreak());
352 353 354 355
}


void BreakLocationIterator::ClearDebugBreak() {
356
  // Debugger statement always calls debugger. No need to modify it.
357
  if (IsDebuggerStatement()) return;
358

359
  if (RelocInfo::IsJSReturn(rmode())) {
360 361
    // Restore the frame exit code.
    ClearDebugBreakAtReturn();
362 363 364
  } else if (IsDebugBreakSlot()) {
    // Restore the code in the break slot.
    ClearDebugBreakAtSlot();
365
  } else {
366 367
    // Patch the IC call.
    ClearDebugBreakAtIC();
368
  }
369
  DCHECK(!IsDebugBreak());
370 371 372
}


373
bool BreakLocationIterator::IsStepInLocation(Isolate* isolate) {
374
  if (RelocInfo::IsConstructCall(original_rmode())) {
375 376 377
    return true;
  } else if (RelocInfo::IsCodeTarget(rmode())) {
    HandleScope scope(debug_info_->GetIsolate());
378
    Address target = original_rinfo()->target_address();
379
    Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
380
    if (target_code->kind() == Code::STUB) {
381
      return CodeStub::GetMajorKey(*target_code) == CodeStub::CallFunction;
382
    }
383
    return target_code->is_call_stub();
384
  }
verwaest@chromium.org's avatar
verwaest@chromium.org committed
385
  return false;
386 387 388
}


389
void BreakLocationIterator::PrepareStepIn(Isolate* isolate) {
verwaest@chromium.org's avatar
verwaest@chromium.org committed
390
#ifdef DEBUG
391
  HandleScope scope(isolate);
392 393
  // Step in can only be prepared if currently positioned on an IC call,
  // construct call or CallFunction stub call.
394
  Address target = rinfo()->target_address();
395
  Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
verwaest@chromium.org's avatar
verwaest@chromium.org committed
396 397 398 399 400 401 402 403 404 405
  // 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 &&
406 407
       CodeStub::GetMajorKey(*maybe_call_function_stub) ==
           CodeStub::CallFunction);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
408 409 410 411 412 413 414 415

  // 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.
416
  DCHECK(RelocInfo::IsConstructCall(rmode()) ||
verwaest@chromium.org's avatar
verwaest@chromium.org committed
417 418
         target_code->is_inline_cache_stub() ||
         is_call_function_stub);
419
#endif
420 421 422 423 424
}


// Check whether the break point is at a position which will exit the function.
bool BreakLocationIterator::IsExit() const {
425
  return (RelocInfo::IsJSReturn(rmode()));
426 427 428 429 430 431 432 433 434 435
}


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


// Check whether there is a debug break at the current position.
bool BreakLocationIterator::IsDebugBreak() {
436
  if (RelocInfo::IsJSReturn(rmode())) {
437
    return IsDebugBreakAtReturn();
438 439
  } else if (IsDebugBreakSlot()) {
    return IsDebugBreakAtSlot();
440 441 442 443 444 445
  } else {
    return Debug::IsDebugBreak(rinfo()->target_address());
  }
}


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 476 477 478 479 480 481 482 483
// 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) {
484
    DCHECK(CodeStub::GetMajorKey(*code) == CodeStub::CallFunction);
485 486 487 488 489 490 491 492
    return isolate->builtins()->CallFunctionStub_DebugBreak();
  }

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


493 494 495 496 497 498 499 500
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();
501
    Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
502 503 504

    // Patch the code to invoke the builtin debug break function matching the
    // calling convention used by the call site.
505
    Handle<Code> dbgbrk_code = DebugBreakForIC(target_code, mode);
506 507 508 509 510 511 512 513 514 515 516
    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());
}


517
bool BreakLocationIterator::IsDebuggerStatement() {
serya@chromium.org's avatar
serya@chromium.org committed
518
  return RelocInfo::DEBUG_BREAK == rmode();
519 520 521
}


522 523 524 525 526
bool BreakLocationIterator::IsDebugBreakSlot() {
  return RelocInfo::DEBUG_BREAK_SLOT == rmode();
}


527 528 529 530 531
Object* BreakLocationIterator::BreakPointObjects() {
  return debug_info_->GetBreakPointObjects(code_position());
}


532 533 534 535 536 537 538 539 540 541 542
// 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();
  }
}


543
bool BreakLocationIterator::RinfoDone() const {
544
  DCHECK(reloc_iterator_->done() == reloc_iterator_original_->done());
545 546 547 548 549 550 551 552
  return reloc_iterator_->done();
}


void BreakLocationIterator::RinfoNext() {
  reloc_iterator_->next();
  reloc_iterator_original_->next();
#ifdef DEBUG
553
  DCHECK(reloc_iterator_->done() == reloc_iterator_original_->done());
554
  if (!reloc_iterator_->done()) {
555
    DCHECK(rmode() == original_rmode());
556 557 558 559 560 561 562
  }
#endif
}


// Threading support.
void Debug::ThreadInit() {
563 564 565
  thread_local_.break_count_ = 0;
  thread_local_.break_id_ = 0;
  thread_local_.break_frame_id_ = StackFrame::NO_ID;
566
  thread_local_.last_step_action_ = StepNone;
567
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
568 569
  thread_local_.step_count_ = 0;
  thread_local_.last_fp_ = 0;
570
  thread_local_.queued_step_count_ = 0;
571
  thread_local_.step_into_fp_ = 0;
572
  thread_local_.step_out_fp_ = 0;
573
  // TODO(isolates): frames_are_dropped_?
574 575
  base::NoBarrier_Store(&thread_local_.current_debug_scope_,
                        static_cast<base::AtomicWord>(NULL));
576
  thread_local_.restarter_frame_function_pointer_ = NULL;
577 578 579 580 581
}


char* Debug::ArchiveDebug(char* storage) {
  char* to = storage;
582
  MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
583 584 585 586 587 588 589
  ThreadInit();
  return storage + ArchiveSpacePerThread();
}


char* Debug::RestoreDebug(char* storage) {
  char* from = storage;
590
  MemCopy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
591 592 593 594 595
  return storage + ArchiveSpacePerThread();
}


int Debug::ArchiveSpacePerThread() {
596
  return sizeof(ThreadLocal);
597 598 599
}


600
ScriptCache::ScriptCache(Isolate* isolate) : HashMap(HashMap::PointersMatch),
601
                                             isolate_(isolate) {
602 603 604
  Heap* heap = isolate_->heap();
  HandleScope scope(isolate_);

605
  // Perform a GC to get rid of all unreferenced scripts.
606 607 608 609 610 611 612 613 614 615 616 617 618 619
  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)));
    }
  }
}


620
void ScriptCache::Add(Handle<Script> script) {
621
  GlobalHandles* global_handles = isolate_->global_handles();
622
  // Create an entry in the hash map for the script.
623
  int id = script->id()->value();
624 625 626
  HashMap::Entry* entry =
      HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
  if (entry->value != NULL) {
627 628 629 630
#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));
631 632
    DCHECK(script->id() == found->id());
    DCHECK(!script->name()->IsString() ||
633 634
           String::cast(script->name())->Equals(String::cast(found->name())));
#endif
635
    return;
636
  }
637 638 639
  // 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_ =
640 641 642 643
      Handle<Script>::cast(global_handles->Create(*script));
  GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
                          this,
                          ScriptCache::HandleWeakScript);
644
  entry->value = script_.location();
645 646 647
}


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


663 664 665
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)) {
666
    DCHECK(entry != NULL);
667
    Object** location = reinterpret_cast<Object**>(entry->value);
668
    DCHECK((*location)->IsScript());
669 670
    GlobalHandles::ClearWeakness(location);
    GlobalHandles::Destroy(location);
671 672 673 674 675 676
  }
  // Clear the content of the hash map.
  HashMap::Clear();
}


677 678 679 680 681 682 683
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);
684

685 686 687 688 689 690
  // 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);
691 692

  // Clear the weak handle.
693
  GlobalHandles::Destroy(location);
694 695 696
}


697 698 699 700 701
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());
702
  debug->RemoveDebugInfo(node->debug_info().location());
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
  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()),
718 719
                          this, Debug::HandleWeakDebugInfo,
                          GlobalHandles::Phantom);
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
  *source_position = it.statement_position();
1099

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
  it.SetBreakPoint(break_point_object);

1142 1143 1144 1145
  position = (alignment == STATEMENT_ALIGNED) ? it.statement_position()
                                              : it.position();

  *source_position = position + shared->start_position();
1146 1147

  // At least one active break point now.
1148
  DCHECK(debug_info->GetBreakPointCount() > 0);
1149 1150 1151 1152
  return true;
}


1153
void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
1154
  HandleScope scope(isolate_);
1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  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);
1167 1168
      it.FindBreakLocationFromAddress(debug_info->code()->entry() +
          break_point_info->code_position()->value());
1169 1170 1171 1172 1173
      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) {
1174
        RemoveDebugInfoAndClearFromShared(debug_info);
1175 1176 1177 1178 1179 1180 1181 1182 1183
      }

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


1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
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) {
1195
    RemoveDebugInfoAndClearFromShared(debug_info_list_->debug_info());
1196 1197 1198 1199
  }
}


1200 1201
void Debug::FloodWithOneShot(Handle<JSFunction> function,
                             BreakLocatorType type) {
1202 1203 1204
  // Do not ever break in native functions.
  if (function->IsFromNativeScript()) return;

1205
  PrepareForBreakPoints();
1206 1207 1208 1209

  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1210 1211 1212
    // Return if we failed to retrieve the debug info.
    return;
  }
1213 1214

  // Flood the function with break points.
1215
  BreakLocationIterator it(GetDebugInfo(shared), type);
1216 1217 1218 1219 1220 1221 1222
  while (!it.Done()) {
    it.SetOneShot();
    it.Next();
  }
}


1223 1224
void Debug::FloodBoundFunctionWithOneShot(Handle<JSFunction> function) {
  Handle<FixedArray> new_bindings(function->function_bindings());
1225 1226
  Handle<Object> bindee(new_bindings->get(JSFunction::kBoundFunctionIndex),
                        isolate_);
1227 1228

  if (!bindee.is_null() && bindee->IsJSFunction() &&
1229
      !JSFunction::cast(*bindee)->IsFromNativeScript()) {
1230
    Handle<JSFunction> bindee_function(JSFunction::cast(*bindee));
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    FloodWithOneShotGeneric(bindee_function);
  }
}


void Debug::FloodDefaultConstructorWithOneShot(Handle<JSFunction> function) {
  DCHECK(function->shared()->is_default_constructor());
  // Instead of stepping into the function we directly step into the super class
  // constructor.
  Isolate* isolate = function->GetIsolate();
  PrototypeIterator iter(isolate, function);
  Handle<Object> proto = PrototypeIterator::GetCurrent(iter);
  if (!proto->IsJSFunction()) return;  // Object.prototype
  Handle<JSFunction> function_proto = Handle<JSFunction>::cast(proto);
  FloodWithOneShotGeneric(function_proto);
}


void Debug::FloodWithOneShotGeneric(Handle<JSFunction> function,
                                    Handle<Object> holder) {
  if (function->shared()->bound()) {
    FloodBoundFunctionWithOneShot(function);
  } else if (function->shared()->is_default_constructor()) {
    FloodDefaultConstructorWithOneShot(function);
1255
  } else {
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    Isolate* isolate = function->GetIsolate();
    // Don't allow step into functions in the native context.
    if (function->shared()->code() ==
            isolate->builtins()->builtin(Builtins::kFunctionApply) ||
        function->shared()->code() ==
            isolate->builtins()->builtin(Builtins::kFunctionCall)) {
      // Handle function.apply and function.call separately to flood the
      // function to be called and not the code for Builtins::FunctionApply or
      // Builtins::FunctionCall. The receiver of call/apply is the target
      // function.
      if (!holder.is_null() && holder->IsJSFunction()) {
        Handle<JSFunction> js_function = Handle<JSFunction>::cast(holder);
        FloodWithOneShotGeneric(js_function);
      }
    } else {
      FloodWithOneShot(function);
    }
1273 1274 1275 1276
  }
}


1277
void Debug::FloodHandlerWithOneShot() {
1278
  // Iterate through the JavaScript stack looking for handlers.
1279
  StackFrame::Id id = break_frame_id();
1280 1281 1282 1283
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack don't do anything.
    return;
  }
1284
  for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) {
1285 1286 1287
    JavaScriptFrame* frame = it.frame();
    if (frame->HasHandler()) {
      // Flood the function with the catch block with break points
1288
      FloodWithOneShot(Handle<JSFunction>(frame->function()));
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
      return;
    }
  }
}


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


1304 1305 1306 1307 1308 1309 1310 1311 1312
bool Debug::IsBreakOnException(ExceptionBreakType type) {
  if (type == BreakUncaughtException) {
    return break_on_uncaught_exception_;
  } else {
    return break_on_exception_;
  }
}


1313 1314 1315
void Debug::PrepareStep(StepAction step_action,
                        int step_count,
                        StackFrame::Id frame_id) {
1316
  HandleScope scope(isolate_);
1317 1318 1319

  PrepareForBreakPoints();

1320
  DCHECK(in_debug_scope());
1321 1322 1323

  // Remember this step action and count.
  thread_local_.last_step_action_ = step_action;
1324 1325 1326 1327 1328 1329 1330
  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;
  }
1331 1332 1333 1334 1335

  // 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.
1336
  StackFrame::Id id = break_frame_id();
1337 1338 1339 1340
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack don't do anything.
    return;
  }
1341 1342 1343
  if (frame_id != StackFrame::NO_ID) {
    id = frame_id;
  }
1344
  JavaScriptFrameIterator frames_it(isolate_, id);
1345 1346 1347 1348 1349 1350 1351
  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
1352
  // be the case when calling unknown function and having the debugger stopped
1353 1354 1355 1356 1357 1358
  // 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.
1359
    JSFunction* function = frames_it.frame()->function();
1360
    FloodWithOneShot(Handle<JSFunction>(function));
1361 1362 1363 1364
    return;
  }

  // Get the debug info (create it if it does not exist).
1365
  Handle<JSFunction> function(frame->function());
1366 1367
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1368 1369 1370
    // Return if ensuring debug info failed.
    return;
  }
1371 1372 1373 1374
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);

  // Find the break location where execution has stopped.
  BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1375 1376 1377
  // 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);
1378 1379

  // Compute whether or not the target is a call target.
1380 1381
  bool is_load_or_store = false;
  bool is_inline_cache_stub = false;
1382
  bool is_at_restarted_function = false;
1383 1384
  Handle<Code> call_function_stub;

1385 1386 1387 1388 1389
  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);
1390 1391 1392
      if (code->is_call_stub()) {
        is_call_target = true;
      }
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
      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);
      }
1407
      if ((maybe_call_function_stub->kind() == Code::STUB &&
1408 1409
           CodeStub::GetMajorKey(maybe_call_function_stub) ==
               CodeStub::CallFunction) ||
1410
          maybe_call_function_stub->is_call_stub()) {
1411 1412 1413 1414
        // 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);
      }
1415
    }
1416 1417
  } else {
    is_at_restarted_function = true;
1418 1419
  }

1420
  // If this is the last break code target step out is the only possibility.
1421
  if (it.IsExit() || step_action == StepOut) {
1422 1423
    if (step_action == StepOut) {
      // Skip step_count frames starting with the current one.
ager@chromium.org's avatar
ager@chromium.org committed
1424
      while (step_count-- > 0 && !frames_it.done()) {
1425 1426 1427
        frames_it.Advance();
      }
    } else {
1428
      DCHECK(it.IsExit());
1429 1430 1431
      frames_it.Advance();
    }
    // Skip builtin functions on the stack.
1432 1433
    while (!frames_it.done() &&
           frames_it.frame()->function()->IsFromNativeScript()) {
1434 1435
      frames_it.Advance();
    }
1436 1437 1438 1439
    // 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.
1440
      JSFunction* function = frames_it.frame()->function();
1441
      FloodWithOneShot(Handle<JSFunction>(function));
1442 1443
      // Set target frame pointer.
      ActivateStepOut(frames_it.frame());
1444
    }
1445
  } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1446
               !call_function_stub.is_null() || is_at_restarted_function)
1447
             || step_action == StepNext || step_action == StepMin) {
1448 1449 1450
    // Step next or step min.

    // Fill the current function with one-shot break points.
1451 1452 1453
    // If we are stepping into another frame, only fill calls and returns.
    FloodWithOneShot(function, step_action == StepFrame ? CALLS_AND_RETURNS
                                                        : ALL_BREAK_LOCATIONS);
1454 1455 1456 1457

    // Remember source position and frame to handle step next.
    thread_local_.last_statement_position_ =
        debug_info->code()->SourceStatementPosition(frame->pc());
1458
    thread_local_.last_fp_ = frame->UnpaddedFP();
1459
  } else {
1460 1461 1462 1463 1464
    // 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_));
1465
      FloodWithOneShot(restarted_function);
1466 1467 1468
    } else if (!call_function_stub.is_null()) {
      // If it's CallFunction stub ensure target function is compiled and flood
      // it with one shot breakpoints.
1469
      bool is_call_ic = call_function_stub->kind() == Code::CALL_IC;
1470

1471
      // Find out number of arguments from the stub minor key.
1472
      uint32_t key = call_function_stub->stub_key();
1473 1474
      // Argc in the stub is the number of arguments passed - not the
      // expected arguments of the called function.
1475 1476 1477
      int call_function_arg_count = is_call_ic
          ? CallICStub::ExtractArgcFromMinorKey(CodeStub::MinorKeyFromKey(key))
          : CallFunctionStub::ExtractArgcFromMinorKey(
1478
              CodeStub::MinorKeyFromKey(key));
1479

1480
      DCHECK(is_call_ic ||
1481 1482
             CodeStub::GetMajorKey(*call_function_stub) ==
                 CodeStub::MajorKeyFromKey(key));
1483 1484

      // Find target function on the expression stack.
1485
      // Expression stack looks like this (top to bottom):
1486 1487 1488 1489 1490 1491
      // argN
      // ...
      // arg0
      // Receiver
      // Function to call
      int expressions_count = frame->ComputeExpressionsCount();
1492
      DCHECK(expressions_count - 2 - call_function_arg_count >= 0);
1493 1494
      Object* fun = frame->GetExpression(
          expressions_count - 2 - call_function_arg_count);
verwaest@chromium.org's avatar
verwaest@chromium.org committed
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508

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

1509 1510
      if (fun->IsJSFunction()) {
        Handle<JSFunction> js_function(JSFunction::cast(fun));
1511
        FloodWithOneShotGeneric(js_function);
1512 1513 1514
      }
    }

1515 1516
    // 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
1517 1518
    // which step in will not stop. It also prepares for stepping in
    // getters/setters.
1519 1520 1521
    // If we are stepping into another frame, only fill calls and returns.
    FloodWithOneShot(function, step_action == StepFrame ? CALLS_AND_RETURNS
                                                        : ALL_BREAK_LOCATIONS);
1522

1523 1524 1525
    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
1526
      // Object::Get/SetPropertyWithAccessor, otherwise the step action will be
1527 1528 1529
      // propagated on the next Debug::Break.
      thread_local_.last_statement_position_ =
          debug_info->code()->SourceStatementPosition(frame->pc());
1530
      thread_local_.last_fp_ = frame->UnpaddedFP();
1531 1532
    }

1533
    // Step in or Step in min
1534
    it.PrepareStepIn(isolate_);
1535 1536 1537 1538 1539 1540 1541 1542 1543
    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
1544
// flooded with one-shot break points. This function helps to perform several
1545 1546 1547
// steps before reporting break back to the debugger.
bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
                             JavaScriptFrame* frame) {
1548 1549
  // StepNext and StepOut shouldn't bring us deeper in code, so last frame
  // shouldn't be a parent of current frame.
1550 1551 1552
  StepAction step_action = thread_local_.last_step_action_;

  if (step_action == StepNext || step_action == StepOut) {
1553 1554 1555
    if (frame->fp() < thread_local_.last_fp_) return true;
  }

1556 1557 1558 1559 1560
  // We stepped into a new frame if the frame pointer changed.
  if (step_action == StepFrame) {
    return frame->UnpaddedFP() == thread_local_.last_fp_;
  }

1561 1562
  // If the step last action was step next or step in make sure that a new
  // statement is hit.
1563
  if (step_action == StepNext || step_action == StepIn) {
1564 1565 1566 1567 1568 1569
    // 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());
1570
    return thread_local_.last_fp_ == frame->UnpaddedFP() &&
1571
        thread_local_.last_statement_position_ == current_statement_position;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
  }

  // 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) {
1582
  Code* code = Code::GetCodeFromTargetAddress(addr);
1583
  return code->is_debug_stub() && code->extra_ic_state() == DEBUG_BREAK;
1584 1585 1586 1587 1588 1589 1590 1591
}





// Simple function for returning the source positions for active break points.
Handle<Object> Debug::GetSourceBreakLocations(
1592 1593
    Handle<SharedFunctionInfo> shared,
    BreakPositionAlignment position_alignment) {
1594
  Isolate* isolate = shared->GetIsolate();
1595
  Heap* heap = isolate->heap();
1596 1597 1598
  if (!HasDebugInfo(shared)) {
    return Handle<Object>(heap->undefined_value(), isolate);
  }
1599 1600
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
  if (debug_info->GetBreakPointCount() == 0) {
1601
    return Handle<Object>(heap->undefined_value(), isolate);
1602 1603
  }
  Handle<FixedArray> locations =
1604
      isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
1605 1606 1607 1608 1609 1610
  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) {
1611
        Smi* position = NULL;
1612
        switch (position_alignment) {
1613 1614 1615 1616 1617 1618
          case STATEMENT_ALIGNED:
            position = break_point_info->statement_position();
            break;
          case BREAK_POSITION_ALIGNED:
            position = break_point_info->source_position();
            break;
1619 1620 1621
        }

        locations->set(count++, position);
1622 1623 1624 1625 1626 1627 1628
      }
    }
  }
  return locations;
}


1629
// Handle stepping into a function.
1630 1631 1632 1633 1634 1635 1636
void Debug::HandleStepIn(Handle<Object> function_obj, Handle<Object> holder,
                         Address fp, bool is_constructor) {
  // Flood getter/setter if we either step in or step to another frame.
  bool step_frame = thread_local_.last_step_action_ == StepFrame;
  if (!StepInActive() && !step_frame) return;
  if (!function_obj->IsJSFunction()) return;
  Handle<JSFunction> function = Handle<JSFunction>::cast(function_obj);
1637
  Isolate* isolate = function->GetIsolate();
1638 1639
  // If the frame pointer is not supplied by the caller find it.
  if (fp == 0) {
1640
    StackFrameIterator it(isolate);
1641 1642 1643
    it.Advance();
    // For constructor functions skip another frame.
    if (is_constructor) {
1644
      DCHECK(it.frame()->is_construct());
1645 1646 1647 1648 1649 1650
      it.Advance();
    }
    fp = it.frame()->fp();
  }

  // Flood the function with one-shot break points if it is called from where
1651 1652
  // step into was requested, or when stepping into a new frame.
  if (fp == thread_local_.step_into_fp_ || step_frame) {
1653
    FloodWithOneShotGeneric(function, holder);
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
1654
  }
1655 1656 1657
}


1658 1659 1660 1661
void Debug::ClearStepping() {
  // Clear the various stepping setup.
  ClearOneShot();
  ClearStepIn();
1662
  ClearStepOut();
1663 1664 1665 1666 1667 1668
  ClearStepNext();

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

1669

1670 1671 1672 1673 1674
// 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
1675
  // last break point for a function is removed that function is automatically
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
  // 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) {
1691
  DCHECK(!StepOutActive());
1692
  thread_local_.step_into_fp_ = frame->UnpaddedFP();
1693 1694 1695 1696 1697 1698 1699 1700
}


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


1701
void Debug::ActivateStepOut(StackFrame* frame) {
1702
  DCHECK(!StepInActive());
1703
  thread_local_.step_out_fp_ = frame->UnpaddedFP();
1704 1705 1706 1707 1708 1709 1710 1711
}


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


1712 1713
void Debug::ClearStepNext() {
  thread_local_.last_step_action_ = StepNone;
1714
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1715 1716 1717 1718
  thread_local_.last_fp_ = 0;
}


1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
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()) {
1731
      List<JSFunction*> functions(FLAG_max_inlining_levels + 1);
1732 1733 1734 1735 1736 1737 1738
      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()) {
1739
      JSFunction* function = frame->function();
1740
      DCHECK(frame->LookupCode()->kind() == Code::FUNCTION);
1741 1742 1743 1744 1745 1746 1747
      active_functions->Add(Handle<JSFunction>(function));
      function->shared()->code()->set_gc_metadata(active_code_marker);
    }
  }
}


1748 1749 1750 1751 1752
// 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) {
1753 1754 1755 1756
  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());
1757 1758 1759 1760 1761 1762 1763 1764

  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;
1765
    DCHECK(RelocInfo::IsConstPool(info->rmode()));
1766
    code_offset -= static_cast<int>(info->data());
1767
    DCHECK_LE(0, code_offset);
1768 1769 1770 1771 1772 1773 1774 1775
  }

  return code_offset;
}


// The inverse of ComputeCodeOffsetFromPcOffset.
static int ComputePcOffsetFromCodeOffset(Code *code, int code_offset) {
1776
  DCHECK_EQ(code->kind(), Code::FUNCTION);
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787

  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 {
1788
      DCHECK(RelocInfo::IsConstPool(info->rmode()));
1789 1790 1791 1792 1793 1794
      reloc += static_cast<int>(info->data());
    }
  }

  int pc_offset = code_offset + reloc;

1795
  DCHECK_LT(code->instruction_start() + pc_offset, code->instruction_end());
1796 1797 1798 1799 1800

  return pc_offset;
}


1801 1802 1803 1804 1805 1806 1807 1808
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;

1809
    JSFunction* function = frame->function();
1810

1811
    DCHECK(frame->LookupCode()->kind() == Code::FUNCTION);
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821

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

1822 1823 1824 1825
    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);
1826 1827

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

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
    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()),
1846
             reinterpret_cast<intptr_t>(new_pc));
1847 1848
    }

1849 1850 1851 1852 1853
    if (FLAG_enable_ool_constant_pool) {
      // Update constant pool pointer for new code.
      frame->set_constant_pool(new_code->constant_pool());
    }

1854 1855
    // Patch the return address to return into the code with
    // debug break slots.
1856
    frame->set_pc(new_pc);
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
  }
}


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


1889
static void EnsureFunctionHasDebugBreakSlots(Handle<JSFunction> function) {
1890 1891 1892 1893 1894 1895 1896 1897
  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()) {
1898
    MaybeHandle<Code> code = Compiler::GetDebugCode(function);
1899
    // Recompilation can fail.  In that case leave the code as it was.
1900 1901 1902 1903
    if (!code.is_null()) function->ReplaceCode(*code.ToHandleChecked());
  } else {
    // Simply use shared code if it has debug break slots.
    function->ReplaceCode(function->shared()->code());
1904
  }
1905 1906 1907
}


1908
static void RecompileAndRelocateSuspendedGenerators(
1909 1910 1911 1912
    const List<Handle<JSGeneratorObject> > &generators) {
  for (int i = 0; i < generators.length(); i++) {
    Handle<JSFunction> fun(generators[i]->function());

1913
    EnsureFunctionHasDebugBreakSlots(fun);
1914 1915 1916 1917 1918 1919 1920 1921

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


1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
static bool SkipSharedFunctionInfo(SharedFunctionInfo* shared,
                                   Object* active_code_marker) {
  if (!shared->allows_lazy_compilation()) return true;
  if (!shared->script()->IsScript()) return true;
  Object* script = shared->script();
  if (!script->IsScript()) return true;
  if (Script::cast(script)->type()->value() == Script::TYPE_NATIVE) return true;
  Code* shared_code = shared->code();
  return shared_code->gc_metadata() == active_code_marker;
}


static inline bool HasDebugBreakSlots(Code* code) {
  return code->kind() == Code::FUNCTION && code->has_debug_break_slots();
}


1939 1940 1941 1942
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_) {
1943
    if (isolate_->concurrent_recompilation_enabled()) {
1944 1945 1946
      isolate_->optimizing_compiler_thread()->Flush();
    }

1947
    Deoptimizer::DeoptimizeAll(isolate_);
1948

1949
    Handle<Code> lazy_compile = isolate_->builtins()->CompileLazy();
1950

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

1954 1955 1956 1957
    // 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);

1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
    // 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;

1973 1974 1975
    {
      // We are going to iterate heap to find all functions without
      // debug break slots.
1976 1977 1978
      Heap* heap = isolate_->heap();
      heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
                              "preparing for breakpoints");
1979
      HeapIterator iterator(heap);
1980

1981 1982
      // Ensure no GC in this scope as we are going to use gc_metadata
      // field in the Code object to mark active functions.
1983
      DisallowHeapAllocation no_allocation;
1984

1985
      Object* active_code_marker = heap->the_hole_value();
1986

1987 1988 1989 1990 1991 1992 1993 1994
      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);
1995

1996 1997 1998
      // 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.
1999 2000 2001 2002
      HeapObject* obj = NULL;
      while (((obj = iterator.next()) != NULL)) {
        if (obj->IsJSFunction()) {
          JSFunction* function = JSFunction::cast(obj);
2003
          SharedFunctionInfo* shared = function->shared();
2004
          if (SkipSharedFunctionInfo(shared, active_code_marker)) continue;
2005 2006 2007 2008
          if (shared->is_generator()) {
            generator_functions.Add(Handle<JSFunction>(function, isolate_));
            continue;
          }
2009 2010 2011
          if (HasDebugBreakSlots(function->code())) continue;
          Code* fallback = HasDebugBreakSlots(shared->code()) ? shared->code()
                                                              : *lazy_compile;
2012
          Code::Kind kind = function->code()->kind();
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
          if (kind == Code::FUNCTION ||
              (kind == Code::BUILTIN &&  // Abort in-flight compilation.
               (function->IsInOptimizationQueue() ||
                function->IsMarkedForOptimization() ||
                function->IsMarkedForConcurrentOptimization()))) {
            function->ReplaceCode(fallback);
          }
          if (kind == Code::OPTIMIZED_FUNCTION) {
            // Optimized code can only get here if DeoptimizeAll did not
            // deoptimize turbo fan code.
            DCHECK(!FLAG_turbo_deoptimization);
            DCHECK(function->code()->is_turbofanned());
            function->ReplaceCode(fallback);
2026
          }
2027 2028 2029 2030 2031
        } else if (obj->IsJSGeneratorObject()) {
          JSGeneratorObject* gen = JSGeneratorObject::cast(obj);
          if (!gen->is_suspended()) continue;

          JSFunction* fun = gen->function();
2032
          DCHECK_EQ(fun->code()->kind(), Code::FUNCTION);
2033 2034 2035
          if (fun->code()->has_debug_break_slots()) continue;

          int pc_offset = gen->continuation();
2036
          DCHECK_LT(0, pc_offset);
2037 2038 2039 2040 2041 2042 2043 2044

          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_));
2045 2046 2047 2048 2049 2050
        } else if (obj->IsSharedFunctionInfo()) {
          SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
          if (SkipSharedFunctionInfo(shared, active_code_marker)) continue;
          if (shared->is_generator()) continue;
          if (HasDebugBreakSlots(shared->code())) continue;
          shared->ReplaceCode(*lazy_compile);
2051
        }
2052
      }
2053

2054 2055 2056 2057 2058 2059
      // 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));
      }
    }
2060

2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
    // 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;
2071 2072
      function->ReplaceCode(*lazy_compile);
      function->shared()->ReplaceCode(*lazy_compile);
2073 2074
    }

2075
    // Now recompile all functions with activation frames and and
2076 2077 2078 2079
    // 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.
2080 2081
    for (int i = 0; i < active_functions.length(); i++) {
      Handle<JSFunction> function = active_functions[i];
2082
      Handle<SharedFunctionInfo> shared(function->shared());
2083

2084
      // If recompilation is not possible just skip it.
2085 2086 2087
      if (shared->is_toplevel()) continue;
      if (!shared->allows_lazy_compilation()) continue;
      if (shared->code()->kind() == Code::BUILTIN) continue;
2088

2089
      EnsureFunctionHasDebugBreakSlots(function);
2090
    }
2091 2092 2093 2094 2095 2096 2097

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

    ActiveFunctionsRedirector active_functions_redirector;
    isolate_->thread_manager()->IterateArchivedThreads(
          &active_functions_redirector);
2098 2099 2100 2101
  }
}


2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
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;
2120
  Heap* heap = isolate_->heap();
2121
  while (!done) {
2122
    { // Extra scope for iterator.
2123
      HeapIterator iterator(heap);
2124 2125 2126 2127 2128 2129 2130 2131
      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());
2132
          DCHECK(shared->allows_lazy_compilation() || shared->is_compiled());
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
          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.

2183
    if (target.is_null()) return heap->undefined_value();
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195

    // 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.
2196
      MaybeHandle<Code> maybe_result = target_function.is_null()
2197 2198
          ? Compiler::GetUnoptimizedCode(target)
          : Compiler::GetUnoptimizedCode(target_function);
2199
      if (maybe_result.is_null()) return isolate_->heap()->undefined_value();
2200 2201 2202 2203 2204 2205 2206
    }
  }  // End while loop.

  return *target;
}


2207
// Ensures the debug information is present for shared.
2208 2209
bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
                            Handle<JSFunction> function) {
2210 2211
  Isolate* isolate = shared->GetIsolate();

2212
  // Return if we already have the debug info for shared.
2213
  if (HasDebugInfo(shared)) {
2214
    DCHECK(shared->is_compiled());
2215 2216
    return true;
  }
2217

2218 2219 2220 2221 2222
  // 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() &&
2223
      !Compiler::EnsureCompiled(function, CLEAR_EXCEPTION)) {
2224 2225
    return false;
  }
2226 2227

  // Create the debug info object.
2228
  Handle<DebugInfo> debug_info = isolate->factory()->NewDebugInfo(shared);
2229 2230 2231 2232 2233 2234

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

2235
  return true;
2236 2237 2238
}


2239 2240 2241 2242 2243
// This uses the location of a handle to look up the debug info in the debug
// info list, but it doesn't use the actual debug info for anything.  Therefore
// if the debug info has been collected by the GC, we can be sure that this
// method will not attempt to resurrect it.
void Debug::RemoveDebugInfo(DebugInfo** debug_info) {
2244
  DCHECK(debug_info_list_ != NULL);
2245 2246 2247 2248
  // Run through the debug info objects to find this one and remove it.
  DebugInfoListNode* prev = NULL;
  DebugInfoListNode* current = debug_info_list_;
  while (current != NULL) {
2249
    if (current->debug_info().location() == debug_info) {
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
      // Unlink from list. If prev is NULL we are looking at the first element.
      if (prev == NULL) {
        debug_info_list_ = current->next();
      } else {
        prev->set_next(current->next());
      }
      delete current;

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


2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
void Debug::RemoveDebugInfoAndClearFromShared(Handle<DebugInfo> debug_info) {
  HandleScope scope(isolate_);
  Handle<SharedFunctionInfo> shared(debug_info->shared());

  RemoveDebugInfo(debug_info.location());

  shared->set_debug_info(isolate_->heap()->undefined_value());
}


2282
void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
2283 2284 2285
  after_break_target_ = NULL;

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

2287
  HandleScope scope(isolate_);
2288 2289
  PrepareForBreakPoints();

2290
  // Get the executing function in which the debug break occurred.
2291 2292 2293
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
2294 2295 2296
    // Return if we failed to retrieve the debug info.
    return;
  }
2297 2298 2299 2300 2301
  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.
2302
  Handle<Code> frame_code(frame->LookupCode());
2303
  DCHECK(frame_code.is_identical_to(code));
2304 2305 2306 2307 2308
#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.
2309
  Address addr = Assembler::break_address_from_return_address(frame->pc());
2310

2311
  // Check if the location is at JS exit or debug break slot.
2312 2313
  bool at_js_return = false;
  bool break_at_js_return_active = false;
2314
  bool at_debug_break_slot = false;
2315
  RelocIterator it(debug_info->code());
2316
  while (!it.done() && !at_js_return && !at_debug_break_slot) {
2317
    if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
2318 2319
      at_js_return = (it.rinfo()->pc() ==
          addr - Assembler::kPatchReturnSequenceAddressOffset);
2320
      break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
2321
    }
2322 2323 2324 2325
    if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
      at_debug_break_slot = (it.rinfo()->pc() ==
          addr - Assembler::kPatchDebugBreakSlotAddressOffset);
    }
2326 2327 2328 2329 2330
    it.next();
  }

  // Handle the jump to continue execution after break point depending on the
  // break location.
2331 2332 2333 2334 2335
  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) {
2336
      addr += original_code->instruction_start() - code->instruction_start();
2337 2338
    }

2339
    // Move back to where the call instruction sequence started.
2340
    after_break_target_ = addr - Assembler::kPatchReturnSequenceAddressOffset;
2341 2342 2343 2344 2345
  } else if (at_debug_break_slot) {
    // Address of where the debug break slot starts.
    addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;

    // Continue just after the slot.
2346
    after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
2347
  } else {
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
    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);
    }
2368 2369 2370 2371
  }
}


2372
bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
2373
  HandleScope scope(isolate_);
2374

2375
  // If there are no break points this cannot be break at return, as
2376
  // the debugger statement and stack guard debug break cannot be at
2377 2378 2379 2380 2381
  // return.
  if (!has_break_points_) {
    return false;
  }

2382 2383
  PrepareForBreakPoints();

2384
  // Get the executing function in which the debug break occurred.
2385 2386 2387
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
2388 2389 2390 2391 2392 2393 2394
    // 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.
2395
  Handle<Code> frame_code(frame->LookupCode());
2396
  DCHECK(frame_code.is_identical_to(code));
2397 2398 2399
#endif

  // Find the call address in the running code.
2400
  Address addr = Assembler::break_address_from_return_address(frame->pc());
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414

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


2415
void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
2416
                                  LiveEdit::FrameDropMode mode,
2417
                                  Object** restarter_frame_function_pointer) {
2418
  if (mode != LiveEdit::CURRENTLY_SET_MODE) {
2419 2420
    thread_local_.frame_drop_mode_ = mode;
  }
2421
  thread_local_.break_frame_id_ = new_break_frame_id;
2422 2423
  thread_local_.restarter_frame_function_pointer_ =
      restarter_frame_function_pointer;
2424 2425 2426
}


2427
bool Debug::IsDebugGlobal(GlobalObject* global) {
2428
  return is_loaded() && global == debug_context()->global_object();
2429 2430 2431
}


2432
void Debug::ClearMirrorCache() {
2433
  PostponeInterruptsScope postpone(isolate_);
2434
  HandleScope scope(isolate_);
2435
  AssertDebugContext();
2436
  Factory* factory = isolate_->factory();
2437 2438
  Handle<GlobalObject> global(isolate_->global_object());
  JSObject::SetProperty(global,
2439 2440
                        factory->NewStringFromAsciiChecked("next_handle_"),
                        handle(Smi::FromInt(0), isolate_), SLOPPY).Check();
2441
  JSObject::SetProperty(global,
2442 2443
                        factory->NewStringFromAsciiChecked("mirror_cache_"),
                        factory->NewJSArray(0, FAST_ELEMENTS), SLOPPY).Check();
2444 2445 2446
}


2447 2448 2449
Handle<FixedArray> Debug::GetLoadedScripts() {
  // Create and fill the script cache when the loaded scripts is requested for
  // the first time.
2450
  if (script_cache_ == NULL) script_cache_ = new ScriptCache(isolate_);
2451 2452 2453

  // Perform GC to get unreferenced scripts evicted from the cache before
  // returning the content.
2454 2455
  isolate_->heap()->CollectAllGarbage(Heap::kNoGCFlags,
                                      "Debug::GetLoadedScripts");
2456 2457 2458 2459 2460 2461

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


2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
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));
  }
}


2477 2478 2479
MaybeHandle<Object> Debug::MakeJSObject(const char* constructor_name,
                                        int argc,
                                        Handle<Object> argv[]) {
2480
  AssertDebugContext();
2481
  // Create the execution state object.
2482
  Handle<GlobalObject> global(isolate_->global_object());
2483
  Handle<Object> constructor = Object::GetProperty(
2484
      isolate_, global, constructor_name).ToHandleChecked();
2485
  DCHECK(constructor->IsJSFunction());
2486
  if (!constructor->IsJSFunction()) return MaybeHandle<Object>();
2487 2488
  // We do not handle interrupts here.  In particular, termination interrupts.
  PostponeInterruptsScope no_interrupts(isolate_);
2489
  return Execution::TryCall(Handle<JSFunction>::cast(constructor),
2490
                            handle(debug_context()->global_proxy()),
2491 2492
                            argc,
                            argv);
2493 2494 2495
}


2496
MaybeHandle<Object> Debug::MakeExecutionState() {
2497
  // Create the execution state object.
2498
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()) };
2499
  return MakeJSObject("MakeExecutionState", arraysize(argv), argv);
2500 2501 2502
}


2503
MaybeHandle<Object> Debug::MakeBreakEvent(Handle<Object> break_points_hit) {
2504
  // Create the new break event object.
2505 2506
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()),
                            break_points_hit };
2507
  return MakeJSObject("MakeBreakEvent", arraysize(argv), argv);
2508 2509 2510
}


2511
MaybeHandle<Object> Debug::MakeExceptionEvent(Handle<Object> exception,
2512 2513
                                              bool uncaught,
                                              Handle<Object> promise) {
2514
  // Create the new exception event object.
2515
  Handle<Object> argv[] = { isolate_->factory()->NewNumberFromInt(break_id()),
2516
                            exception,
2517 2518
                            isolate_->factory()->ToBoolean(uncaught),
                            promise };
2519
  return MakeJSObject("MakeExceptionEvent", arraysize(argv), argv);
2520 2521 2522
}


2523
MaybeHandle<Object> Debug::MakeCompileEvent(Handle<Script> script,
2524
                                            v8::DebugEvent type) {
2525
  // Create the compile event object.
2526
  Handle<Object> script_wrapper = Script::GetWrapper(script);
2527
  Handle<Object> argv[] = { script_wrapper,
2528
                            isolate_->factory()->NewNumberFromInt(type) };
2529
  return MakeJSObject("MakeCompileEvent", arraysize(argv), argv);
2530 2531 2532
}


2533 2534 2535
MaybeHandle<Object> Debug::MakePromiseEvent(Handle<JSObject> event_data) {
  // Create the promise event object.
  Handle<Object> argv[] = { event_data };
2536
  return MakeJSObject("MakePromiseEvent", arraysize(argv), argv);
2537 2538 2539
}


2540 2541 2542
MaybeHandle<Object> Debug::MakeAsyncTaskEvent(Handle<JSObject> task_event) {
  // Create the async task event object.
  Handle<Object> argv[] = { task_event };
2543
  return MakeJSObject("MakeAsyncTaskEvent", arraysize(argv), argv);
2544 2545 2546
}


2547
void Debug::OnThrow(Handle<Object> exception, bool uncaught) {
2548
  if (in_debug_scope() || ignore_events()) return;
2549 2550
  // Temporarily clear any scheduled_exception to allow evaluating
  // JavaScript from the debug event handler.
2551
  HandleScope scope(isolate_);
2552 2553 2554 2555 2556
  Handle<Object> scheduled_exception;
  if (isolate_->has_scheduled_exception()) {
    scheduled_exception = handle(isolate_->scheduled_exception(), isolate_);
    isolate_->clear_scheduled_exception();
  }
2557
  OnException(exception, uncaught, isolate_->GetPromiseOnStackOnThrow());
2558 2559 2560
  if (!scheduled_exception.is_null()) {
    isolate_->thread_local_top()->scheduled_exception_ = *scheduled_exception;
  }
2561 2562
}

2563

2564 2565
void Debug::OnPromiseReject(Handle<JSObject> promise, Handle<Object> value) {
  if (in_debug_scope() || ignore_events()) return;
2566
  HandleScope scope(isolate_);
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
  // Check whether the promise has been marked as having triggered a message.
  Handle<Symbol> key = isolate_->factory()->promise_debug_marker_symbol();
  if (JSObject::GetDataProperty(promise, key)->IsUndefined()) {
    OnException(value, false, promise);
  }
}


MaybeHandle<Object> Debug::PromiseHasUserDefinedRejectHandler(
    Handle<JSObject> promise) {
  Handle<JSFunction> fun = Handle<JSFunction>::cast(
      JSObject::GetDataProperty(isolate_->js_builtins_object(),
                                isolate_->factory()->NewStringFromStaticChars(
                                    "PromiseHasUserDefinedRejectHandler")));
  return Execution::Call(isolate_, fun, promise, 0, NULL);
2582
}
2583

2584 2585 2586

void Debug::OnException(Handle<Object> exception, bool uncaught,
                        Handle<Object> promise) {
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
  if (!uncaught && promise->IsJSObject()) {
    Handle<JSObject> jspromise = Handle<JSObject>::cast(promise);
    // Mark the promise as already having triggered a message.
    Handle<Symbol> key = isolate_->factory()->promise_debug_marker_symbol();
    JSObject::SetProperty(jspromise, key, key, STRICT).Assert();
    // Check whether the promise reject is considered an uncaught exception.
    Handle<Object> has_reject_handler;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(
        isolate_, has_reject_handler,
        PromiseHasUserDefinedRejectHandler(jspromise), /* void */);
    uncaught = has_reject_handler->IsFalse();
2598
  }
2599 2600 2601
  // Bail out if exception breaks are not active
  if (uncaught) {
    // Uncaught exceptions are reported by either flags.
2602
    if (!(break_on_uncaught_exception_ || break_on_exception_)) return;
2603 2604
  } else {
    // Caught exceptions are reported is activated.
2605
    if (!break_on_exception_) return;
2606 2607
  }

2608 2609
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2610 2611

  // Clear all current stepping setup.
2612
  ClearStepping();
2613

2614 2615 2616
  // Create the event data object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
2617 2618 2619 2620
  if (!MakeExceptionEvent(
          exception, uncaught, promise).ToHandle(&event_data)) {
    return;
  }
2621

2622
  // Process debug event.
2623
  ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2624 2625 2626 2627
  // Return to continue execution from where the exception was thrown.
}


2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
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);
}


2646
void Debug::OnDebugBreak(Handle<Object> break_points_hit,
2647
                            bool auto_continue) {
2648 2649
  // The caller provided for DebugScope.
  AssertDebugContext();
2650
  // Bail out if there is no listener for this event
2651
  if (ignore_events()) return;
2652

2653
  HandleScope scope(isolate_);
2654 2655 2656
  // Create the event data object.
  Handle<Object> event_data;
  // Bail out and don't call debugger if exception.
2657
  if (!MakeBreakEvent(break_points_hit).ToHandle(&event_data)) return;
2658

2659 2660 2661 2662
  // Process debug event.
  ProcessDebugEvent(v8::Break,
                    Handle<JSObject>::cast(event_data),
                    auto_continue);
2663 2664 2665
}


2666
void Debug::OnBeforeCompile(Handle<Script> script) {
2667
  if (in_debug_scope() || ignore_events()) return;
2668

2669
  HandleScope scope(isolate_);
2670 2671
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2672 2673

  // Create the event data object.
2674
  Handle<Object> event_data;
2675
  // Bail out and don't call debugger if exception.
2676 2677
  if (!MakeCompileEvent(script, v8::BeforeCompile).ToHandle(&event_data))
    return;
2678

2679 2680 2681 2682
  // Process debug event.
  ProcessDebugEvent(v8::BeforeCompile,
                    Handle<JSObject>::cast(event_data),
                    true);
2683 2684 2685 2686
}


// Handle debugger actions when a new script is compiled.
2687
void Debug::OnAfterCompile(Handle<Script> script) {
2688
  // Add the newly compiled script to the script cache.
2689
  if (script_cache_ != NULL) script_cache_->Add(script);
2690 2691

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

2694
  HandleScope scope(isolate_);
2695 2696
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
2697 2698 2699 2700

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

2701
  // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
2702 2703
  Handle<String> update_script_break_points_string =
      isolate_->factory()->InternalizeOneByteString(
2704
          STATIC_CHAR_VECTOR("UpdateScriptBreakPoints"));
2705
  Handle<GlobalObject> debug_global(debug_context()->global_object());
2706
  Handle<Object> update_script_break_points =
2707 2708
      Object::GetProperty(
          debug_global, update_script_break_points_string).ToHandleChecked();
2709 2710 2711
  if (!update_script_break_points->IsJSFunction()) {
    return;
  }
2712
  DCHECK(update_script_break_points->IsJSFunction());
2713 2714 2715

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

  // Call UpdateScriptBreakPoints expect no exceptions.
2719
  Handle<Object> argv[] = { wrapper };
2720 2721
  if (Execution::TryCall(Handle<JSFunction>::cast(update_script_break_points),
                         isolate_->js_builtins_object(),
2722
                         arraysize(argv),
2723
                         argv).is_null()) {
2724 2725 2726 2727
    return;
  }

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

2732
  // Process debug event.
2733
  ProcessDebugEvent(v8::AfterCompile, Handle<JSObject>::cast(event_data), true);
2734 2735 2736
}


2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
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);
}


2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
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);
}


2775 2776 2777
void Debug::ProcessDebugEvent(v8::DebugEvent event,
                              Handle<JSObject> event_data,
                              bool auto_continue) {
2778
  HandleScope scope(isolate_);
2779

2780
  // Create the execution state.
2781 2782
  Handle<Object> exec_state;
  // Bail out and don't call debugger if exception.
2783 2784
  if (!MakeExecutionState().ToHandle(&exec_state)) return;

2785 2786
  // First notify the message handler if any.
  if (message_handler_ != NULL) {
2787 2788 2789 2790
    NotifyMessageHandler(event,
                         Handle<JSObject>::cast(exec_state),
                         event_data,
                         auto_continue);
2791
  }
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
  // 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();
2809 2810 2811 2812 2813
    }
  }
}


2814 2815 2816 2817
void Debug::CallEventCallback(v8::DebugEvent event,
                              Handle<Object> exec_state,
                              Handle<Object> event_data,
                              v8::Debug::ClientData* client_data) {
2818
  DisableBreak no_break(this, true);
2819
  if (event_listener_->IsForeign()) {
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
    // 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);
2830
    DCHECK(!isolate_->has_scheduled_exception());
2831
  } else {
2832
    // Invoke the JavaScript debug event listener.
2833
    DCHECK(event_listener_->IsJSFunction());
2834 2835 2836 2837
    Handle<Object> argv[] = { Handle<Object>(Smi::FromInt(event), isolate_),
                              exec_state,
                              event_data,
                              event_listener_data_ };
2838
    Handle<JSReceiver> global(isolate_->global_proxy());
2839
    Execution::TryCall(Handle<JSFunction>::cast(event_listener_),
2840
                       global, arraysize(argv), argv);
2841 2842 2843 2844
  }
}


2845
Handle<Context> Debug::GetDebugContext() {
2846
  DebugScope debug_scope(this);
2847
  // The global handle may be destroyed soon after.  Return it reboxed.
2848
  return handle(*debug_context(), isolate_);
2849 2850 2851
}


2852 2853 2854 2855
void Debug::NotifyMessageHandler(v8::DebugEvent event,
                                 Handle<JSObject> exec_state,
                                 Handle<JSObject> event_data,
                                 bool auto_continue) {
2856 2857 2858
  // Prevent other interrupts from triggering, for example API callbacks,
  // while dispatching message handler callbacks.
  PostponeInterruptsScope no_interrupts(isolate_);
2859
  DCHECK(is_active_);
2860
  HandleScope scope(isolate_);
2861
  // Process the individual events.
2862
  bool sendEventMessage = false;
2863 2864
  switch (event) {
    case v8::Break:
2865
    case v8::BreakForCommand:
2866
      sendEventMessage = !auto_continue;
2867 2868
      break;
    case v8::Exception:
2869
      sendEventMessage = true;
2870 2871 2872 2873
      break;
    case v8::BeforeCompile:
      break;
    case v8::AfterCompile:
2874
      sendEventMessage = true;
2875 2876 2877 2878 2879 2880 2881
      break;
    case v8::NewFunction:
      break;
    default:
      UNREACHABLE();
  }

2882 2883 2884
  // 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.
2885
  DCHECK(in_debug_scope());
2886
  isolate_->stack_guard()->ClearDebugCommand();
2887 2888 2889 2890

  // Notify the debugger that a debug event has occurred unless auto continue is
  // active in which case no event is send.
  if (sendEventMessage) {
2891 2892 2893 2894 2895 2896
    MessageImpl message = MessageImpl::NewEvent(
        event,
        auto_continue,
        Handle<JSObject>::cast(exec_state),
        Handle<JSObject>::cast(event_data));
    InvokeMessageHandler(message);
2897
  }
2898 2899 2900 2901 2902

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

2905 2906 2907
  // DebugCommandProcessor goes here.
  bool running = auto_continue;

2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
  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();

2919
  // Process requests from the debugger.
2920
  do {
2921
    // Wait for new command in the queue.
2922
    command_received_.Wait();
2923 2924

    // Get the command from the queue.
2925
    CommandMessage command = command_queue_.Get();
2926 2927
    isolate_->logger()->DebugTag(
        "Got request from command queue, in interactive loop.");
2928
    if (!is_active()) {
2929 2930
      // Delete command text and user data.
      command.Dispose();
2931 2932 2933
      return;
    }

2934 2935 2936 2937 2938 2939 2940 2941
    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;
2942 2943 2944 2945
    MaybeHandle<Object> maybe_exception;
    MaybeHandle<Object> maybe_result =
        Execution::TryCall(process_debug_request, cmd_processor, 1,
                           request_args, &maybe_exception);
2946 2947 2948 2949

    if (maybe_result.ToHandle(&answer_value)) {
      if (answer_value->IsUndefined()) {
        answer = isolate_->factory()->empty_string();
2950
      } else {
2951
        answer = Handle<String>::cast(answer_value);
2952
      }
2953 2954 2955

      // Log the JSON request/response.
      if (FLAG_trace_debug_json) {
2956 2957
        PrintF("%s\n", request_text->ToCString().get());
        PrintF("%s\n", answer->ToCString().get());
2958 2959
      }

2960 2961 2962
      Handle<Object> is_running_args[] = { answer };
      maybe_result = Execution::Call(
          isolate_, is_running, cmd_processor, 1, is_running_args);
2963 2964 2965
      Handle<Object> result;
      if (!maybe_result.ToHandle(&result)) break;
      running = result->IsTrue();
2966
    } else {
2967 2968 2969 2970 2971
      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);
2972 2973 2974
    }

    // Return the result.
2975
    MessageImpl message = MessageImpl::NewResponse(
2976
        event, running, exec_state, event_data, answer, command.client_data());
2977 2978
    InvokeMessageHandler(message);
    command.Dispose();
2979

2980
    // Return from debug event processing if either the VM is put into the
2981
    // running state (through a continue command) or auto continue is active
2982
    // and there are no more commands queued.
2983
  } while (!running || has_commands());
2984
  command_queue_.Clear();
2985 2986 2987
}


2988 2989
void Debug::SetEventListener(Handle<Object> callback,
                             Handle<Object> data) {
2990
  GlobalHandles* global_handles = isolate_->global_handles();
2991

2992 2993 2994 2995 2996
  // Remove existing entry.
  GlobalHandles::Destroy(event_listener_.location());
  event_listener_ = Handle<Object>();
  GlobalHandles::Destroy(event_listener_data_.location());
  event_listener_data_ = Handle<Object>();
2997

2998
  // Set new entry.
2999
  if (!callback->IsUndefined() && !callback->IsNull()) {
3000 3001 3002
    event_listener_ = global_handles->Create(*callback);
    if (data.is_null()) data = isolate_->factory()->undefined_value();
    event_listener_data_ = global_handles->Create(*data);
3003 3004
  }

3005
  UpdateState();
3006 3007 3008
}


3009
void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
3010
  message_handler_ = handler;
3011
  UpdateState();
3012
  if (handler == NULL && in_debug_scope()) {
3013 3014
    // Send an empty command to the debugger if in a break to make JavaScript
    // run again if the debugger is closed.
3015
    EnqueueCommandMessage(Vector<const uint16_t>::empty());
3016
  }
3017
}
3018

3019

3020 3021

void Debug::UpdateState() {
3022
  is_active_ = message_handler_ != NULL || !event_listener_.is_null();
3023
  if (is_active_ || in_debug_scope()) {
3024 3025
    // Note that the debug context could have already been loaded to
    // bootstrap test cases.
3026
    isolate_->compilation_cache()->Disable();
3027
    is_active_ = Load();
3028
  } else if (is_loaded()) {
3029
    isolate_->compilation_cache()->Enable();
3030
    Unload();
3031
  }
3032 3033 3034 3035
}


// Calls the registered debug message handler. This callback is part of the
3036
// public API.
3037
void Debug::InvokeMessageHandler(MessageImpl message) {
3038
  if (message_handler_ != NULL) message_handler_(message);
3039 3040 3041
}


3042 3043 3044
// 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
3045
// by the API client thread.
3046 3047
void Debug::EnqueueCommandMessage(Vector<const uint16_t> command,
                                  v8::Debug::ClientData* client_data) {
3048
  // Need to cast away const.
3049
  CommandMessage message = CommandMessage::New(
3050
      Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
3051 3052
                       command.length()),
      client_data);
3053
  isolate_->logger()->DebugTag("Put command on command_queue.");
3054
  command_queue_.Put(message);
3055
  command_received_.Signal();
3056 3057

  // Set the debug command break flag to have the command processed.
3058
  if (!in_debug_scope()) isolate_->stack_guard()->RequestDebugCommand();
3059 3060 3061
}


3062
void Debug::EnqueueDebugCommand(v8::Debug::ClientData* client_data) {
3063 3064 3065 3066
  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.
3067
  if (!in_debug_scope()) isolate_->stack_guard()->RequestDebugCommand();
3068 3069 3070
}


3071
MaybeHandle<Object> Debug::Call(Handle<JSFunction> fun, Handle<Object> data) {
3072 3073
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return isolate_->factory()->undefined_value();
3074 3075

  // Create the execution state.
3076
  Handle<Object> exec_state;
3077 3078 3079
  if (!MakeExecutionState().ToHandle(&exec_state)) {
    return isolate_->factory()->undefined_value();
  }
3080

3081
  Handle<Object> argv[] = { exec_state, data };
3082
  return Execution::Call(
3083
      isolate_,
3084
      fun,
3085
      Handle<Object>(debug_context()->global_proxy(), isolate_),
3086
      arraysize(argv),
3087
      argv);
3088 3089 3090
}


3091
void Debug::HandleDebugBreak() {
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
  // 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_);
3103
    DCHECK(!it.done());
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130
    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_);
3131 3132
  DebugScope debug_scope(this);
  if (debug_scope.failed()) return;
3133 3134 3135 3136 3137 3138 3139

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


3140 3141 3142 3143 3144 3145
DebugScope::DebugScope(Debug* debug)
    : debug_(debug),
      prev_(debug->debugger_entry()),
      save_(debug_->isolate_),
      no_termination_exceptons_(debug_->isolate_,
                                StackGuard::TERMINATE_EXECUTION) {
3146
  // Link recursive debugger entry.
3147 3148
  base::NoBarrier_Store(&debug_->thread_local_.current_debug_scope_,
                        reinterpret_cast<base::AtomicWord>(this));
3149 3150

  // Store the previous break id and frame id.
3151 3152
  break_id_ = debug_->break_id();
  break_frame_id_ = debug_->break_frame_id();
3153 3154 3155

  // Create the new break info. If there is no JavaScript frames there is no
  // break frame id.
3156
  JavaScriptFrameIterator it(isolate());
3157
  bool has_js_frames = !it.done();
3158 3159 3160
  debug_->thread_local_.break_frame_id_ = has_js_frames ? it.frame()->id()
                                                        : StackFrame::NO_ID;
  debug_->SetNextBreakId();
3161

3162
  debug_->UpdateState();
3163
  // Make sure that debugger is loaded and enter the debugger context.
3164
  // The previous context is kept in save_.
3165 3166
  failed_ = !debug_->is_loaded();
  if (!failed_) isolate()->set_context(*debug->debug_context());
3167 3168 3169 3170
}



3171 3172
DebugScope::~DebugScope() {
  if (!failed_ && prev_ == NULL) {
3173 3174 3175 3176
    // 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.
3177
    if (!isolate()->has_pending_exception()) debug_->ClearMirrorCache();
3178 3179 3180

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

3184
  // Leaving this debugger entry.
3185 3186
  base::NoBarrier_Store(&debug_->thread_local_.current_debug_scope_,
                        reinterpret_cast<base::AtomicWord>(prev_));
3187 3188 3189 3190

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

3192
  debug_->UpdateState();
3193 3194 3195
}


3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
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_);
}


3259 3260 3261 3262 3263
v8::Isolate* MessageImpl::GetIsolate() const {
  return reinterpret_cast<v8::Isolate*>(exec_state_->GetIsolate());
}


3264 3265 3266 3267 3268 3269
v8::Handle<v8::Object> MessageImpl::GetEventData() const {
  return v8::Utils::ToLocal(event_data_);
}


v8::Handle<v8::String> MessageImpl::GetJSON() const {
3270 3271
  Isolate* isolate = event_data_->GetIsolate();
  v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate));
3272 3273 3274

  if (IsEvent()) {
    // Call toJSONProtocol on the debug event object.
3275 3276
    Handle<Object> fun = Object::GetProperty(
        isolate, event_data_, "toJSONProtocol").ToHandleChecked();
3277 3278 3279
    if (!fun->IsJSFunction()) {
      return v8::Handle<v8::String>();
    }
3280 3281 3282 3283 3284

    MaybeHandle<Object> maybe_json =
        Execution::TryCall(Handle<JSFunction>::cast(fun), event_data_, 0, NULL);
    Handle<Object> json;
    if (!maybe_json.ToHandle(&json) || !json->IsString()) {
3285 3286
      return v8::Handle<v8::String>();
    }
3287
    return scope.Escape(v8::Utils::ToLocal(Handle<String>::cast(json)));
3288 3289 3290 3291 3292 3293 3294
  } else {
    return v8::Utils::ToLocal(response_json_);
  }
}


v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
3295
  Isolate* isolate = event_data_->GetIsolate();
3296
  v8::Handle<v8::Context> context = GetDebugEventContext(isolate);
3297
  // Isolate::context() may be NULL when "script collected" event occurs.
3298
  DCHECK(!context.IsEmpty());
3299
  return context;
3300 3301 3302 3303 3304 3305 3306 3307
}


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


3308 3309 3310
EventDetailsImpl::EventDetailsImpl(DebugEvent event,
                                   Handle<JSObject> exec_state,
                                   Handle<JSObject> event_data,
3311 3312
                                   Handle<Object> callback_data,
                                   v8::Debug::ClientData* client_data)
3313 3314 3315
    : event_(event),
      exec_state_(exec_state),
      event_data_(event_data),
3316 3317
      callback_data_(callback_data),
      client_data_(client_data) {}
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335


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 {
3336
  return GetDebugEventContext(exec_state_->GetIsolate());
3337 3338 3339 3340 3341 3342 3343 3344
}


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


3345 3346 3347 3348 3349
v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
  return client_data_;
}


3350 3351
CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
                                   client_data_(NULL) {
3352 3353 3354
}


3355 3356
CommandMessage::CommandMessage(const Vector<uint16_t>& text,
                               v8::Debug::ClientData* data)
3357
    : text_(text),
3358
      client_data_(data) {
3359 3360 3361
}


3362
void CommandMessage::Dispose() {
3363 3364 3365 3366 3367 3368
  text_.Dispose();
  delete client_data_;
  client_data_ = NULL;
}


3369 3370 3371
CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
                                   v8::Debug::ClientData* data) {
  return CommandMessage(command.Clone(), data);
3372 3373 3374
}


3375 3376 3377
CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
                                                     size_(size) {
  messages_ = NewArray<CommandMessage>(size);
3378 3379 3380
}


3381
CommandMessageQueue::~CommandMessageQueue() {
3382
  while (!IsEmpty()) Get().Dispose();
3383 3384 3385 3386
  DeleteArray(messages_);
}


3387
CommandMessage CommandMessageQueue::Get() {
3388
  DCHECK(!IsEmpty());
3389 3390 3391 3392 3393 3394
  int result = start_;
  start_ = (start_ + 1) % size_;
  return messages_[result];
}


3395
void CommandMessageQueue::Put(const CommandMessage& message) {
3396 3397 3398 3399 3400 3401 3402 3403
  if ((end_ + 1) % size_ == start_) {
    Expand();
  }
  messages_[end_] = message;
  end_ = (end_ + 1) % size_;
}


3404 3405
void CommandMessageQueue::Expand() {
  CommandMessageQueue new_queue(size_ * 2);
3406 3407
  while (!IsEmpty()) {
    new_queue.Put(Get());
3408
  }
3409
  CommandMessage* array_to_free = messages_;
3410 3411
  *this = new_queue;
  new_queue.messages_ = array_to_free;
3412 3413
  // Make the new_queue empty so that it doesn't call Dispose on any messages.
  new_queue.start_ = new_queue.end_;
3414 3415 3416 3417
  // Automatic destructor called on new_queue, freeing array_to_free.
}


3418
LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size)
3419
    : logger_(logger), queue_(size) {}
3420 3421


3422
bool LockingCommandMessageQueue::IsEmpty() const {
3423
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3424
  return queue_.IsEmpty();
3425 3426
}

3427

3428
CommandMessage LockingCommandMessageQueue::Get() {
3429
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3430
  CommandMessage result = queue_.Get();
3431
  logger_->DebugEvent("Get", result.text());
3432 3433 3434 3435
  return result;
}


3436
void LockingCommandMessageQueue::Put(const CommandMessage& message) {
3437
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3438
  queue_.Put(message);
3439
  logger_->DebugEvent("Put", message.text());
3440 3441 3442
}


3443
void LockingCommandMessageQueue::Clear() {
3444
  base::LockGuard<base::Mutex> lock_guard(&mutex_);
3445 3446 3447
  queue_.Clear();
}

3448
} }  // namespace v8::internal