debug.cc 127 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "api.h"
#include "arguments.h"
#include "bootstrapper.h"
#include "code-stubs.h"
34
#include "codegen.h"
35
#include "compilation-cache.h"
36 37
#include "compiler.h"
#include "debug.h"
38
#include "deoptimizer.h"
39
#include "execution.h"
40
#include "full-codegen.h"
41
#include "global-handles.h"
42 43
#include "ic.h"
#include "ic-inl.h"
44
#include "isolate-inl.h"
45
#include "list.h"
46
#include "messages.h"
47 48
#include "natives.h"
#include "stub-cache.h"
49
#include "log.h"
50

51 52
#include "../include/v8-debug.h"

53 54
namespace v8 {
namespace internal {
55

56
#ifdef ENABLE_DEBUGGER_SUPPORT
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76


Debug::Debug(Isolate* isolate)
    : has_break_points_(false),
      script_cache_(NULL),
      debug_info_list_(NULL),
      disable_break_(false),
      break_on_exception_(false),
      break_on_uncaught_exception_(false),
      debug_break_return_(NULL),
      debug_break_slot_(NULL),
      isolate_(isolate) {
  memset(registers_, 0, sizeof(JSCallerSavedBuffer));
}


Debug::~Debug() {
}


77 78
static void PrintLn(v8::Local<v8::Value> value) {
  v8::Local<v8::String> s = value->ToString();
79
  ScopedVector<char> data(s->Utf8Length() + 1);
80
  if (data.start() == NULL) {
81 82 83
    V8::FatalProcessOutOfMemory("PrintLn");
    return;
  }
84
  s->WriteUtf8(data.start());
85
  PrintF("%s\n", data.start());
86 87 88
}


89 90 91
static Handle<Code> ComputeCallDebugPrepareStepIn(Isolate* isolate,
                                                  int argc,
                                                  Code::Kind kind) {
92
  return isolate->stub_cache()->ComputeCallDebugPrepareStepIn(argc, kind);
93 94 95
}


96 97 98 99 100
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>();
101 102
  Handle<Context> native_context(context->native_context());
  return v8::Utils::ToLocal(native_context);
103 104 105
}


106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
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() {
  ASSERT(reloc_iterator_ != NULL);
  ASSERT(reloc_iterator_original_ != NULL);
  delete reloc_iterator_;
  delete reloc_iterator_original_;
}


void BreakLocationIterator::Next() {
125
  DisallowHeapAllocation no_gc;
126 127 128 129 130 131 132 133 134 135
  ASSERT(!RinfoDone());

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

136 137
    // Whenever a statement position or (plain) position is passed update the
    // current value of these.
138 139
    if (RelocInfo::IsPosition(rmode())) {
      if (RelocInfo::IsStatementPosition(rmode())) {
140 141
        statement_position_ = static_cast<int>(
            rinfo()->data() - debug_info_->shared()->start_position());
142
      }
143 144
      // Always update the position as we don't want that to be before the
      // statement position.
145 146
      position_ = static_cast<int>(
          rinfo()->data() - debug_info_->shared()->start_position());
147 148 149 150
      ASSERT(position_ >= 0);
      ASSERT(statement_position_ >= 0);
    }

151 152 153 154 155 156 157 158
    if (IsDebugBreakSlot()) {
      // There is always a possible break point at a debug break slot.
      break_point_++;
      return;
    } else if (RelocInfo::IsCodeTarget(rmode())) {
      // Check for breakable code target. Look in the original code as setting
      // break points can cause the code targets in the running (debugged) code
      // to be of a different kind than in the original code.
159
      Address target = original_rinfo()->target_address();
160
      Code* code = Code::GetCodeFromTargetAddress(target);
161
      if ((code->is_inline_cache_stub() &&
162
           !code->is_binary_op_stub() &&
163 164
           !code->is_compare_ic_stub() &&
           !code->is_to_boolean_ic_stub()) ||
165
          RelocInfo::IsConstructCall(rmode())) {
166 167 168 169
        break_point_++;
        return;
      }
      if (code->kind() == Code::STUB) {
170 171 172 173
        if (IsDebuggerStatement()) {
          break_point_++;
          return;
        }
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        if (type_ == ALL_BREAK_LOCATIONS) {
          if (Debug::IsBreakStub(code)) {
            break_point_++;
            return;
          }
        } else {
          ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
          if (Debug::IsSourceBreakStub(code)) {
            break_point_++;
            return;
          }
        }
      }
    }

    // Check for break at return.
190
    if (RelocInfo::IsJSReturn(rmode())) {
191 192 193
      // Set the positions to the end of the function.
      if (debug_info_->shared()->HasSourceCode()) {
        position_ = debug_info_->shared()->end_position() -
194
                    debug_info_->shared()->start_position() - 1;
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
      } else {
        position_ = 0;
      }
      statement_position_ = position_;
      break_point_++;
      return;
    }
  }
}


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


214 215
// Find the break point at the supplied address, or the closest one before
// the address.
216 217 218 219 220 221
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.
222
    if (this->pc() <= pc && pc - this->pc() < distance) {
223
      closest_break_point = break_point();
224
      distance = static_cast<int>(pc - this->pc());
225 226 227 228 229 230 231 232 233 234 235 236 237
      // 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.
238 239
void BreakLocationIterator::FindBreakLocationFromPosition(int position,
    BreakPositionAlignment alignment) {
240 241 242 243
  // Run through all break points to locate the one closest to the source
  // position.
  int closest_break_point = 0;
  int distance = kMaxInt;
244

245
  while (!Done()) {
246 247 248 249 250 251 252 253 254 255 256 257
    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();
    }
258
    // Check if this break point is closer that what was previously found.
259
    if (position <= next_position && next_position - position < distance) {
260
      closest_break_point = break_point();
261
      distance = next_position - position;
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
      // 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_;
278 279 280 281 282 283
  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));
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

  // 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.
  if (!HasBreakPoint()) {
    SetDebugBreak();
  }
304
  ASSERT(IsDebugBreak() || IsDebuggerStatement());
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  // 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();
    ASSERT(!IsDebugBreak());
  }
}


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

329 330 331 332 333 334 335 336 337 338 339 340
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
    ASSERT(IsDebugBreak());
    return;
  }

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


void BreakLocationIterator::ClearOneShot() {
341 342 343 344 345
  // Debugger statement always calls debugger. No need to modify it.
  if (IsDebuggerStatement()) {
    return;
  }

346 347 348 349 350 351 352 353 354 355 356 357 358
  // If there is a real break point here no more to do.
  if (HasBreakPoint()) {
    ASSERT(IsDebugBreak());
    return;
  }

  // Patch code removing debug break.
  ClearDebugBreak();
  ASSERT(!IsDebugBreak());
}


void BreakLocationIterator::SetDebugBreak() {
359 360 361 362 363
  // Debugger statement always calls debugger. No need to modify it.
  if (IsDebuggerStatement()) {
    return;
  }

364
  // If there is already a break point here just return. This might happen if
365
  // the same code is flooded with break points twice. Flooding the same
366 367 368 369 370 371
  // function twice might happen when stepping in a function with an exception
  // handler as the handler and the function is the same.
  if (IsDebugBreak()) {
    return;
  }

372
  if (RelocInfo::IsJSReturn(rmode())) {
373 374
    // Patch the frame exit code with a break point.
    SetDebugBreakAtReturn();
375 376 377
  } else if (IsDebugBreakSlot()) {
    // Patch the code in the break slot.
    SetDebugBreakAtSlot();
378
  } else {
379 380
    // Patch the IC call.
    SetDebugBreakAtIC();
381 382 383 384 385 386
  }
  ASSERT(IsDebugBreak());
}


void BreakLocationIterator::ClearDebugBreak() {
387 388 389 390 391
  // Debugger statement always calls debugger. No need to modify it.
  if (IsDebuggerStatement()) {
    return;
  }

392
  if (RelocInfo::IsJSReturn(rmode())) {
393 394
    // Restore the frame exit code.
    ClearDebugBreakAtReturn();
395 396 397
  } else if (IsDebugBreakSlot()) {
    // Restore the code in the break slot.
    ClearDebugBreakAtSlot();
398
  } else {
399 400
    // Patch the IC call.
    ClearDebugBreakAtIC();
401 402 403 404 405
  }
  ASSERT(!IsDebugBreak());
}


406
bool BreakLocationIterator::IsStepInLocation(Isolate* isolate) {
407
  if (RelocInfo::IsConstructCall(original_rmode())) {
408 409 410
    return true;
  } else if (RelocInfo::IsCodeTarget(rmode())) {
    HandleScope scope(debug_info_->GetIsolate());
411
    Address target = original_rinfo()->target_address();
412
    Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
413 414 415
    if (target_code->kind() == Code::STUB) {
      return target_code->major_key() == CodeStub::CallFunction;
    }
416 417 418 419 420 421 422
    return target_code->is_call_stub() || target_code->is_keyed_call_stub();
  } else {
    return false;
  }
}


423 424
void BreakLocationIterator::PrepareStepIn(Isolate* isolate) {
  HandleScope scope(isolate);
425

426 427
  // Step in can only be prepared if currently positioned on an IC call,
  // construct call or CallFunction stub call.
428
  Address target = rinfo()->target_address();
429 430
  Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
  if (target_code->is_call_stub() || target_code->is_keyed_call_stub()) {
431 432 433 434 435
    // Step in through IC call is handled by the runtime system. Therefore make
    // sure that the any current IC is cleared and the runtime system is
    // called. If the executing code has a debug break at the location change
    // the call in the original code as it is the code there that will be
    // executed in place of the debug break call.
436
    Handle<Code> stub = ComputeCallDebugPrepareStepIn(
437
        isolate, target_code->arguments_count(), target_code->kind());
438 439 440 441 442 443
    if (IsDebugBreak()) {
      original_rinfo()->set_target_address(stub->entry());
    } else {
      rinfo()->set_target_address(stub->entry());
    }
  } else {
444 445 446
#ifdef DEBUG
    // All the following stuff is needed only for assertion checks so the code
    // is wrapped in ifdef.
447
    Handle<Code> maybe_call_function_stub = target_code;
448 449 450 451 452 453 454 455 456
    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 &&
         maybe_call_function_stub->major_key() == CodeStub::CallFunction);

457 458 459 460
    // 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.
461 462 463
    // Step in through CallFunction stub should also be prepared by caller of
    // this function (Debug::PrepareStep) which should flood target function
    // with breakpoints.
464 465 466
    ASSERT(RelocInfo::IsConstructCall(rmode()) ||
           target_code->is_inline_cache_stub() ||
           is_call_function_stub);
467
#endif
468 469 470 471 472 473
  }
}


// Check whether the break point is at a position which will exit the function.
bool BreakLocationIterator::IsExit() const {
474
  return (RelocInfo::IsJSReturn(rmode()));
475 476 477 478 479 480 481 482 483 484
}


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


// Check whether there is a debug break at the current position.
bool BreakLocationIterator::IsDebugBreak() {
485
  if (RelocInfo::IsJSReturn(rmode())) {
486
    return IsDebugBreakAtReturn();
487 488
  } else if (IsDebugBreakSlot()) {
    return IsDebugBreakAtSlot();
489 490 491 492 493 494
  } else {
    return Debug::IsDebugBreak(rinfo()->target_address());
  }
}


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

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


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


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


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


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


545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
bool BreakLocationIterator::RinfoDone() const {
  ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
  return reloc_iterator_->done();
}


void BreakLocationIterator::RinfoNext() {
  reloc_iterator_->next();
  reloc_iterator_original_->next();
#ifdef DEBUG
  ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
  if (!reloc_iterator_->done()) {
    ASSERT(rmode() == original_rmode());
  }
#endif
}


// Threading support.
void Debug::ThreadInit() {
565 566 567
  thread_local_.break_count_ = 0;
  thread_local_.break_id_ = 0;
  thread_local_.break_frame_id_ = StackFrame::NO_ID;
568
  thread_local_.last_step_action_ = StepNone;
569
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
570 571
  thread_local_.step_count_ = 0;
  thread_local_.last_fp_ = 0;
572
  thread_local_.queued_step_count_ = 0;
573
  thread_local_.step_into_fp_ = 0;
574
  thread_local_.step_out_fp_ = 0;
575
  thread_local_.after_break_target_ = 0;
576
  // TODO(isolates): frames_are_dropped_?
577
  thread_local_.debugger_entry_ = NULL;
578
  thread_local_.pending_interrupts_ = 0;
579
  thread_local_.restarter_frame_function_pointer_ = NULL;
580 581 582 583 584
}


char* Debug::ArchiveDebug(char* storage) {
  char* to = storage;
585
  OS::MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
586
  to += sizeof(ThreadLocal);
587
  OS::MemCopy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
588 589 590 591 592 593 594 595
  ThreadInit();
  ASSERT(to <= storage + ArchiveSpacePerThread());
  return storage + ArchiveSpacePerThread();
}


char* Debug::RestoreDebug(char* storage) {
  char* from = storage;
596 597
  OS::MemCopy(
      reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
598
  from += sizeof(ThreadLocal);
599
  OS::MemCopy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
600 601 602 603 604 605
  ASSERT(from <= storage + ArchiveSpacePerThread());
  return storage + ArchiveSpacePerThread();
}


int Debug::ArchiveSpacePerThread() {
606
  return sizeof(ThreadLocal) + sizeof(JSCallerSavedBuffer);
607 608 609
}


610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
// Frame structure (conforms InternalFrame structure):
//   -- code
//   -- SMI maker
//   -- function (slot is called "context")
//   -- frame base
Object** Debug::SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
                                       Handle<Code> code) {
  ASSERT(bottom_js_frame->is_java_script());

  Address fp = bottom_js_frame->fp();

  // Move function pointer into "context" slot.
  Memory::Object_at(fp + StandardFrameConstants::kContextOffset) =
      Memory::Object_at(fp + JavaScriptFrameConstants::kFunctionOffset);

  Memory::Object_at(fp + InternalFrameConstants::kCodeOffset) = *code;
  Memory::Object_at(fp + StandardFrameConstants::kMarkerOffset) =
      Smi::FromInt(StackFrame::INTERNAL);

  return reinterpret_cast<Object**>(&Memory::Object_at(
      fp + StandardFrameConstants::kContextOffset));
}

const int Debug::kFrameDropperFrameSize = 4;


636
void ScriptCache::Add(Handle<Script> script) {
637
  GlobalHandles* global_handles = isolate_->global_handles();
638
  // Create an entry in the hash map for the script.
639
  int id = script->id()->value();
640 641 642 643 644
  HashMap::Entry* entry =
      HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
  if (entry->value != NULL) {
    ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
    return;
645
  }
646 647 648
  // 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_ =
649
      Handle<Script>::cast(
650
          (global_handles->Create(*script)));
651 652 653
  global_handles->MakeWeak(reinterpret_cast<Object**>(script_.location()),
                           this,
                           ScriptCache::HandleWeakScript);
654
  entry->value = script_.location();
655 656 657
}


658
Handle<FixedArray> ScriptCache::GetScripts() {
659
  Factory* factory = isolate_->factory();
660
  Handle<FixedArray> instances = factory->NewFixedArray(occupancy());
661 662 663 664 665 666 667 668 669
  int count = 0;
  for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
    ASSERT(entry->value != NULL);
    if (entry->value != NULL) {
      instances->set(count, *reinterpret_cast<Script**>(entry->value));
      count++;
    }
  }
  return instances;
670 671 672
}


673
void ScriptCache::ProcessCollectedScripts() {
674
  Debugger* debugger = isolate_->debugger();
675
  for (int i = 0; i < collected_scripts_.length(); i++) {
676
    debugger->OnScriptCollected(collected_scripts_[i]);
677 678 679 680 681 682
  }
  collected_scripts_.Clear();
}


void ScriptCache::Clear() {
683
  GlobalHandles* global_handles = isolate_->global_handles();
684 685 686 687 688
  // Iterate the script cache to get rid of all the weak handles.
  for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
    ASSERT(entry != NULL);
    Object** location = reinterpret_cast<Object**>(entry->value);
    ASSERT((*location)->IsScript());
689 690
    global_handles->ClearWeakness(location);
    global_handles->Destroy(location);
691 692 693 694 695 696
  }
  // Clear the content of the hash map.
  HashMap::Clear();
}


697
void ScriptCache::HandleWeakScript(v8::Isolate* isolate,
698
                                   v8::Persistent<v8::Value>* obj,
699
                                   void* data) {
700 701 702
  ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
  // Find the location of the global handle.
  Script** location =
703
      reinterpret_cast<Script**>(Utils::OpenPersistent(*obj).location());
704 705 706
  ASSERT((*location)->IsScript());

  // Remove the entry from the cache.
707
  int id = (*location)->id()->value();
708 709 710 711
  script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
  script_cache->collected_scripts_.Add(id);

  // Clear the weak handle.
712
  obj->Dispose();
713 714 715
}


716
void Debug::SetUp(bool create_heap_objects) {
717 718 719 720
  ThreadInit();
  if (create_heap_objects) {
    // Get code to handle debug break on return.
    debug_break_return_ =
721
        isolate_->builtins()->builtin(Builtins::kReturn_DebugBreak);
722
    ASSERT(debug_break_return_->IsCode());
723 724
    // Get code to handle debug break in debug break slots.
    debug_break_slot_ =
725
        isolate_->builtins()->builtin(Builtins::kSlot_DebugBreak);
726
    ASSERT(debug_break_slot_->IsCode());
727 728 729 730
  }
}


731
void Debug::HandleWeakDebugInfo(v8::Isolate* isolate,
732
                                v8::Persistent<v8::Value>* obj,
733 734
                                void* data) {
  Debug* debug = reinterpret_cast<Isolate*>(isolate)->debug();
735
  DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
736 737 738
  // We need to clear all breakpoints associated with the function to restore
  // original code and avoid patching the code twice later because
  // the function will live in the heap until next gc, and can be found by
739
  // Debug::FindSharedFunctionInfoInScript.
740 741
  BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
  it.ClearAllDebugBreak();
742
  debug->RemoveDebugInfo(node->debug_info());
743
#ifdef DEBUG
744
  node = debug->debug_info_list_;
745 746 747 748 749 750 751 752 753
  while (node != NULL) {
    ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
    node = node->next();
  }
#endif
}


DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
754
  GlobalHandles* global_handles = debug_info->GetIsolate()->global_handles();
755
  // Globalize the request debug info object and make it weak.
756
  debug_info_ = Handle<DebugInfo>::cast(
757
      (global_handles->Create(debug_info)));
758 759 760
  global_handles->MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
                           this,
                           Debug::HandleWeakDebugInfo);
761 762 763 764
}


DebugInfoListNode::~DebugInfoListNode() {
765
  debug_info_->GetIsolate()->global_handles()->Destroy(
766
      reinterpret_cast<Object**>(debug_info_.location()));
767 768 769
}


770
bool Debug::CompileDebuggerScript(Isolate* isolate, int index) {
771 772
  Factory* factory = isolate->factory();
  HandleScope scope(isolate);
773

774
  // Bail out if the index is invalid.
775 776 777
  if (index == -1) {
    return false;
  }
778 779

  // Find source and name for the requested script.
780
  Handle<String> source_code =
781
      isolate->bootstrapper()->NativesSourceLookup(index);
782
  Vector<const char> name = Natives::GetScriptName(index);
783
  Handle<String> script_name = factory->NewStringFromAscii(name);
784
  Handle<Context> context = isolate->native_context();
785 786

  // Compile the script.
787 788 789
  Handle<SharedFunctionInfo> function_info;
  function_info = Compiler::Compile(source_code,
                                    script_name,
790
                                    0, 0,
791
                                    false,
792 793
                                    context,
                                    NULL, NULL,
794 795
                                    Handle<String>::null(),
                                    NATIVES_CODE);
796 797

  // Silently ignore stack overflows during compilation.
798
  if (function_info.is_null()) {
799 800
    ASSERT(isolate->has_pending_exception());
    isolate->clear_pending_exception();
801 802 803
    return false;
  }

804
  // Execute the shared function in the debugger context.
805
  bool caught_exception;
806
  Handle<JSFunction> function =
807
      factory->NewFunctionFromSharedFunctionInfo(function_info, context);
808

809
  Handle<Object> exception =
810 811 812 813 814
      Execution::TryCall(function,
                         Handle<Object>(context->global_object(), isolate),
                         0,
                         NULL,
                         &caught_exception);
815 816

  // Check for caught exceptions.
817
  if (caught_exception) {
818 819 820
    ASSERT(!isolate->has_pending_exception());
    MessageLocation computed_location;
    isolate->ComputeLocation(&computed_location);
821
    Handle<Object> message = MessageHandler::MakeMessageObject(
822
        isolate, "error_loading_debugger", &computed_location,
823 824
        Vector<Handle<Object> >::empty(), Handle<String>(), Handle<JSArray>());
    ASSERT(!isolate->has_pending_exception());
825 826
    if (!exception.is_null()) {
      isolate->set_pending_exception(*exception);
827
      MessageHandler::ReportMessage(isolate, NULL, message);
828 829
      isolate->clear_pending_exception();
    }
830 831 832
    return false;
  }

833 834
  // Mark this script as native and return successfully.
  Handle<Script> script(Script::cast(function->shared()->script()));
835
  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
836 837 838 839 840 841
  return true;
}


bool Debug::Load() {
  // Return if debugger is already loaded.
842
  if (IsLoaded()) return true;
843

844
  Debugger* debugger = isolate_->debugger();
845

846 847
  // Bail out if we're already in the process of compiling the native
  // JavaScript source code for the debugger.
848 849
  if (debugger->compiling_natives() ||
      debugger->is_loading_debugger())
850
    return false;
851
  debugger->set_loading_debugger(true);
852 853 854

  // Disable breakpoints and interrupts while compiling and running the
  // debugger scripts including the context creation code.
855
  DisableBreak disable(isolate_, true);
856
  PostponeInterruptsScope postpone(isolate_);
857

858
  // Create the debugger context.
859
  HandleScope scope(isolate_);
860
  Handle<Context> context =
861
      isolate_->bootstrapper()->CreateEnvironment(
862 863 864
          Handle<Object>::null(),
          v8::Handle<ObjectTemplate>(),
          NULL);
865

866 867 868
  // Fail if no context could be created.
  if (context.is_null()) return false;

869
  // Use the debugger context.
870 871
  SaveContext save(isolate_);
  isolate_->set_context(*context);
872 873

  // Expose the builtins object in the debugger context.
874
  Handle<String> key = isolate_->factory()->InternalizeOneByteString(
875
      STATIC_ASCII_VECTOR("builtins"));
876
  Handle<GlobalObject> global = Handle<GlobalObject>(context->global_object());
877
  RETURN_IF_EMPTY_HANDLE_VALUE(
878
      isolate_,
879 880 881 882 883
      JSReceiver::SetProperty(global,
                              key,
                              Handle<Object>(global->builtins(), isolate_),
                              NONE,
                              kNonStrictMode),
884
      false);
885 886

  // Compile the JavaScript for the debugger in the debugger context.
887
  debugger->set_compiling_natives(true);
888
  bool caught_exception =
889 890
      !CompileDebuggerScript(isolate_, Natives::GetIndex("mirror")) ||
      !CompileDebuggerScript(isolate_, Natives::GetIndex("debug"));
891 892 893

  if (FLAG_enable_liveedit) {
    caught_exception = caught_exception ||
894
        !CompileDebuggerScript(isolate_, Natives::GetIndex("liveedit"));
895 896
  }

897
  debugger->set_compiling_natives(false);
898

899 900
  // Make sure we mark the debugger as not loading before we might
  // return.
901
  debugger->set_loading_debugger(false);
902

903 904
  // Check for caught exceptions.
  if (caught_exception) return false;
905

906 907 908
  // Debugger loaded, create debugger context global handle.
  debug_context_ = Handle<Context>::cast(
      isolate_->global_handles()->Create(*context));
909

910 911 912 913 914 915 916 917 918 919
  return true;
}


void Debug::Unload() {
  // Return debugger is not loaded.
  if (!IsLoaded()) {
    return;
  }

920 921 922
  // Clear the script cache.
  DestroyScriptCache();

923
  // Clear debugger context global handle.
924
  isolate_->global_handles()->Destroy(
925
      reinterpret_cast<Object**>(debug_context_.location()));
926 927 928 929
  debug_context_ = Handle<Context>();
}


930 931 932
// Set the flag indicating that preemption happened during debugging.
void Debug::PreemptionWhileInDebugger() {
  ASSERT(InDebugger());
933
  Debug::set_interrupts_pending(PREEMPT);
934 935 936
}


937
void Debug::Iterate(ObjectVisitor* v) {
938 939
  v->VisitPointer(BitCast<Object**>(&(debug_break_return_)));
  v->VisitPointer(BitCast<Object**>(&(debug_break_slot_)));
940 941 942
}


943 944 945
Object* Debug::Break(Arguments args) {
  Heap* heap = isolate_->heap();
  HandleScope scope(isolate_);
946
  ASSERT(args.length() == 0);
947

948
  thread_local_.frame_drop_mode_ = FRAMES_UNTOUCHED;
949

950
  // Get the top-most JavaScript frame.
951
  JavaScriptFrameIterator it(isolate_);
952 953 954
  JavaScriptFrame* frame = it.frame();

  // Just continue if breaks are disabled or debugger cannot be loaded.
955 956
  if (disable_break() || !Load()) {
    SetAfterBreakTarget(frame);
957
    return heap->undefined_value();
958 959
  }

960
  // Enter the debugger.
961
  EnterDebugger debugger(isolate_);
962
  if (debugger.FailedToEnter()) {
963
    return heap->undefined_value();
964
  }
965

966
  // Postpone interrupt during breakpoint processing.
967
  PostponeInterruptsScope postpone(isolate_);
968 969 970

  // Get the debug info (create it if it does not exist).
  Handle<SharedFunctionInfo> shared =
971
      Handle<SharedFunctionInfo>(frame->function()->shared());
972 973 974 975 976
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);

  // Find the break point where execution has stopped.
  BreakLocationIterator break_location_iterator(debug_info,
                                                ALL_BREAK_LOCATIONS);
977 978 979
  // 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);
980 981

  // Check whether step next reached a new statement.
982
  if (!StepNextContinue(&break_location_iterator, frame)) {
983
    // Decrease steps left if performing multiple steps.
984 985
    if (thread_local_.step_count_ > 0) {
      thread_local_.step_count_--;
986 987 988 989 990
    }
  }

  // If there is one or more real break points check whether any of these are
  // triggered.
991
  Handle<Object> break_points_hit(heap->undefined_value(), isolate_);
992 993
  if (break_location_iterator.HasBreakPoint()) {
    Handle<Object> break_point_objects =
994
        Handle<Object>(break_location_iterator.BreakPointObjects(), isolate_);
995
    break_points_hit = CheckBreakPoints(break_point_objects);
996 997
  }

998 999
  // If step out is active skip everything until the frame where we need to step
  // out to is reached, unless real breakpoint is hit.
1000
  if (StepOutActive() && frame->fp() != step_out_fp() &&
1001 1002
      break_points_hit->IsUndefined() ) {
      // Step count should always be 0 for StepOut.
1003
      ASSERT(thread_local_.step_count_ == 0);
1004
  } else if (!break_points_hit->IsUndefined() ||
1005 1006
             (thread_local_.last_step_action_ != StepNone &&
              thread_local_.step_count_ == 0)) {
1007 1008 1009
    // Notify debugger if a real break point is triggered or if performing
    // single stepping with no more steps to perform. Otherwise do another step.

1010
    // Clear all current stepping setup.
1011
    ClearStepping();
1012

1013 1014 1015 1016 1017 1018 1019
    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;

1020
      PrepareStep(StepNext, step_count, StackFrame::NO_ID);
1021 1022 1023 1024
    } else {
      // Notify the debug event listeners.
      isolate_->debugger()->OnDebugBreak(break_points_hit, false);
    }
1025
  } else if (thread_local_.last_step_action_ != StepNone) {
1026 1027
    // Hold on to last step action as it is cleared by the call to
    // ClearStepping.
1028 1029
    StepAction step_action = thread_local_.last_step_action_;
    int step_count = thread_local_.step_count_;
1030

1031 1032 1033 1034 1035 1036
    // 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_);
1037
      while (!it.done() && it.frame()->fp() < thread_local_.last_fp_) {
1038 1039 1040 1041
        count++;
        it.Advance();
      }

1042 1043 1044 1045 1046
      // 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;
1047 1048
      }

1049 1050 1051
      // Set up for StepOut to reach target frame.
      step_action = StepOut;
      step_count = count;
1052 1053
    }

1054
    // Clear all current stepping setup.
1055
    ClearStepping();
1056 1057

    // Set up for the remaining steps.
1058
    PrepareStep(step_action, step_count, StackFrame::NO_ID);
1059 1060
  }

1061 1062 1063
  if (thread_local_.frame_drop_mode_ == FRAMES_UNTOUCHED) {
    SetAfterBreakTarget(frame);
  } else if (thread_local_.frame_drop_mode_ ==
1064
      FRAME_DROPPED_IN_IC_CALL) {
1065
    // We must have been calling IC stub. Do not go there anymore.
1066 1067 1068 1069
    Code* plain_return = isolate_->builtins()->builtin(
        Builtins::kPlainReturn_LiveEdit);
    thread_local_.after_break_target_ = plain_return->entry();
  } else if (thread_local_.frame_drop_mode_ ==
1070 1071 1072
      FRAME_DROPPED_IN_DEBUG_SLOT_CALL) {
    // Debug break slot stub does not return normally, instead it manually
    // cleans the stack and jumps. We should patch the jump address.
1073
    Code* plain_return = isolate_->builtins()->builtin(
1074
        Builtins::kFrameDropper_LiveEdit);
1075 1076
    thread_local_.after_break_target_ = plain_return->entry();
  } else if (thread_local_.frame_drop_mode_ ==
1077
      FRAME_DROPPED_IN_DIRECT_CALL) {
1078
    // Nothing to do, after_break_target is not used here.
1079 1080 1081 1082 1083
  } else if (thread_local_.frame_drop_mode_ ==
      FRAME_DROPPED_IN_RETURN_CALL) {
    Code* plain_return = isolate_->builtins()->builtin(
        Builtins::kFrameDropper_LiveEdit);
    thread_local_.after_break_target_ = plain_return->entry();
1084
  } else {
1085
    UNREACHABLE();
1086
  }
1087

1088
  return heap->undefined_value();
1089 1090 1091
}


1092 1093 1094 1095 1096
RUNTIME_FUNCTION(Object*, Debug_Break) {
  return isolate->debug()->Break(args);
}


1097 1098 1099 1100
// 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) {
1101 1102
  Factory* factory = isolate_->factory();

1103 1104 1105
  // Count the number of break points hit. If there are multiple break points
  // they are in a FixedArray.
  Handle<FixedArray> break_points_hit;
1106 1107 1108 1109
  int break_points_hit_count = 0;
  ASSERT(!break_point_objects->IsUndefined());
  if (break_point_objects->IsFixedArray()) {
    Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
1110
    break_points_hit = factory->NewFixedArray(array->length());
1111
    for (int i = 0; i < array->length(); i++) {
1112
      Handle<Object> o(array->get(i), isolate_);
1113
      if (CheckBreakPoint(o)) {
1114
        break_points_hit->set(break_points_hit_count++, *o);
1115 1116 1117
      }
    }
  } else {
1118
    break_points_hit = factory->NewFixedArray(1);
1119
    if (CheckBreakPoint(break_point_objects)) {
1120
      break_points_hit->set(break_points_hit_count++, *break_point_objects);
1121 1122 1123
    }
  }

1124
  // Return undefined if no break points were triggered.
1125
  if (break_points_hit_count == 0) {
1126
    return factory->undefined_value();
1127
  }
1128
  // Return break points hit as a JSArray.
1129
  Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit);
1130 1131
  result->set_length(Smi::FromInt(break_points_hit_count));
  return result;
1132 1133 1134 1135 1136
}


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

1140 1141 1142
  // Ignore check if break point object is not a JSObject.
  if (!break_point_object->IsJSObject()) return true;

1143
  // Get the function IsBreakPointTriggered (defined in debug-debugger.js).
1144 1145
  Handle<String> is_break_point_triggered_string =
      factory->InternalizeOneByteString(
1146
          STATIC_ASCII_VECTOR("IsBreakPointTriggered"));
1147 1148
  Handle<JSFunction> check_break_point =
    Handle<JSFunction>(JSFunction::cast(
1149
        debug_context()->global_object()->GetPropertyNoExceptionThrown(
1150
            *is_break_point_triggered_string)));
1151 1152

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

  // Call HandleBreakPointx.
1156
  bool caught_exception;
1157
  Handle<Object> argv[] = { break_id, break_point_object };
1158
  Handle<Object> result = Execution::TryCall(check_break_point,
1159 1160 1161 1162
                                             isolate_->js_builtins_object(),
                                             ARRAY_SIZE(argv),
                                             argv,
                                             &caught_exception);
1163 1164 1165 1166 1167 1168 1169

  // If exception or non boolean result handle as not triggered
  if (caught_exception || !result->IsBoolean()) {
    return false;
  }

  // Return whether the break point is triggered.
1170 1171
  ASSERT(!result.is_null());
  return (*result)->IsTrue();
1172 1173 1174 1175 1176 1177 1178 1179 1180
}


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


1181 1182
// Return the debug info for this function. EnsureDebugInfo must be called
// prior to ensure the debug info has been generated for shared.
1183
Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
1184
  ASSERT(HasDebugInfo(shared));
1185 1186 1187 1188
  return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
}


1189
void Debug::SetBreakPoint(Handle<JSFunction> function,
1190 1191
                          Handle<Object> break_point_object,
                          int* source_position) {
1192
  HandleScope scope(isolate_);
1193

1194 1195
  PrepareForBreakPoints();

1196 1197 1198
  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1199 1200
    // Return if retrieving debug info failed.
    return;
1201 1202
  }

1203
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1204
  // Source positions starts with zero.
1205
  ASSERT(*source_position >= 0);
1206 1207 1208

  // Find the break point and change it.
  BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1209
  it.FindBreakLocationFromPosition(*source_position, STATEMENT_ALIGNED);
1210 1211
  it.SetBreakPoint(break_point_object);

1212 1213
  *source_position = it.position();

1214 1215 1216 1217 1218
  // At least one active break point now.
  ASSERT(debug_info->GetBreakPointCount() > 0);
}


1219 1220
bool Debug::SetBreakPointForScript(Handle<Script> script,
                                   Handle<Object> break_point_object,
1221 1222
                                   int* source_position,
                                   BreakPositionAlignment alignment) {
1223 1224
  HandleScope scope(isolate_);

1225 1226 1227 1228
  PrepareForBreakPoints();

  // Obtain shared function info for the function.
  Object* result = FindSharedFunctionInfoInScript(script, *source_position);
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  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.
  ASSERT(position >= 0);

  // Find the break point and change it.
  BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1253
  it.FindBreakLocationFromPosition(position, alignment);
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
  it.SetBreakPoint(break_point_object);

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

  // At least one active break point now.
  ASSERT(debug_info->GetBreakPointCount() > 0);
  return true;
}


1264
void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
1265
  HandleScope scope(isolate_);
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
  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);
1278 1279
      it.FindBreakLocationFromAddress(debug_info->code()->entry() +
          break_point_info->code_position()->value());
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
      it.ClearBreakPoint(break_point_object);

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

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


1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
void Debug::ClearAllBreakPoints() {
  DebugInfoListNode* node = debug_info_list_;
  while (node != NULL) {
    // Remove all debug break code.
    BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
    it.ClearAllDebugBreak();
    node = node->next();
  }

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


1311
void Debug::FloodWithOneShot(Handle<JSFunction> function) {
1312
  PrepareForBreakPoints();
1313 1314 1315 1316

  // Make sure the function is compiled and has set up the debug info.
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1317 1318 1319
    // Return if we failed to retrieve the debug info.
    return;
  }
1320 1321

  // Flood the function with break points.
1322
  BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
1323 1324 1325 1326 1327 1328 1329
  while (!it.Done()) {
    it.SetOneShot();
    it.Next();
  }
}


1330 1331
void Debug::FloodBoundFunctionWithOneShot(Handle<JSFunction> function) {
  Handle<FixedArray> new_bindings(function->function_bindings());
1332 1333
  Handle<Object> bindee(new_bindings->get(JSFunction::kBoundFunctionIndex),
                        isolate_);
1334 1335 1336

  if (!bindee.is_null() && bindee->IsJSFunction() &&
      !JSFunction::cast(*bindee)->IsBuiltin()) {
1337 1338
    Handle<JSFunction> bindee_function(JSFunction::cast(*bindee));
    Debug::FloodWithOneShot(bindee_function);
1339 1340 1341 1342
  }
}


1343
void Debug::FloodHandlerWithOneShot() {
1344
  // Iterate through the JavaScript stack looking for handlers.
1345
  StackFrame::Id id = break_frame_id();
1346 1347 1348 1349
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack don't do anything.
    return;
  }
1350
  for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) {
1351 1352 1353
    JavaScriptFrame* frame = it.frame();
    if (frame->HasHandler()) {
      // Flood the function with the catch block with break points
1354
      FloodWithOneShot(Handle<JSFunction>(frame->function()));
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
      return;
    }
  }
}


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


1370 1371 1372 1373 1374 1375 1376 1377 1378
bool Debug::IsBreakOnException(ExceptionBreakType type) {
  if (type == BreakUncaughtException) {
    return break_on_uncaught_exception_;
  } else {
    return break_on_exception_;
  }
}


1379 1380 1381
void Debug::PrepareStep(StepAction step_action,
                        int step_count,
                        StackFrame::Id frame_id) {
1382
  HandleScope scope(isolate_);
1383 1384 1385

  PrepareForBreakPoints();

1386 1387 1388 1389
  ASSERT(Debug::InDebugger());

  // Remember this step action and count.
  thread_local_.last_step_action_ = step_action;
1390 1391 1392 1393 1394 1395 1396
  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;
  }
1397 1398 1399 1400 1401

  // 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.
1402
  StackFrame::Id id = break_frame_id();
1403 1404 1405 1406
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack don't do anything.
    return;
  }
1407 1408 1409
  if (frame_id != StackFrame::NO_ID) {
    id = frame_id;
  }
1410
  JavaScriptFrameIterator frames_it(isolate_, id);
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
  JavaScriptFrame* frame = frames_it.frame();

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

  // If the function on the top frame is unresolved perform step out. This will
  // be the case when calling unknown functions and having the debugger stopped
  // in an unhandled exception.
  if (!frame->function()->IsJSFunction()) {
    // Step out: Find the calling JavaScript frame and flood it with
    // breakpoints.
    frames_it.Advance();
    // Fill the function to return to with one-shot break points.
1425
    JSFunction* function = frames_it.frame()->function();
1426
    FloodWithOneShot(Handle<JSFunction>(function));
1427 1428 1429 1430
    return;
  }

  // Get the debug info (create it if it does not exist).
1431
  Handle<JSFunction> function(frame->function());
1432 1433
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
1434 1435 1436
    // Return if ensuring debug info failed.
    return;
  }
1437 1438 1439 1440
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);

  // Find the break location where execution has stopped.
  BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1441 1442 1443
  // 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);
1444 1445

  // Compute whether or not the target is a call target.
1446 1447
  bool is_load_or_store = false;
  bool is_inline_cache_stub = false;
1448
  bool is_at_restarted_function = false;
1449 1450
  Handle<Code> call_function_stub;

1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
  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);
      if (code->is_call_stub() || code->is_keyed_call_stub()) {
        is_call_target = true;
      }
      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);
      }
      if (maybe_call_function_stub->kind() == Code::STUB &&
          maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
        // 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);
      }
1479
    }
1480 1481
  } else {
    is_at_restarted_function = true;
1482 1483
  }

1484
  // If this is the last break code target step out is the only possibility.
1485
  if (it.IsExit() || step_action == StepOut) {
1486 1487
    if (step_action == StepOut) {
      // Skip step_count frames starting with the current one.
ager@chromium.org's avatar
ager@chromium.org committed
1488
      while (step_count-- > 0 && !frames_it.done()) {
1489 1490 1491 1492 1493 1494 1495
        frames_it.Advance();
      }
    } else {
      ASSERT(it.IsExit());
      frames_it.Advance();
    }
    // Skip builtin functions on the stack.
1496
    while (!frames_it.done() && frames_it.frame()->function()->IsBuiltin()) {
1497 1498
      frames_it.Advance();
    }
1499 1500 1501 1502
    // 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.
1503
      JSFunction* function = frames_it.frame()->function();
1504
      FloodWithOneShot(Handle<JSFunction>(function));
1505 1506
      // Set target frame pointer.
      ActivateStepOut(frames_it.frame());
1507
    }
1508
  } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1509
               !call_function_stub.is_null() || is_at_restarted_function)
1510
             || step_action == StepNext || step_action == StepMin) {
1511 1512 1513
    // Step next or step min.

    // Fill the current function with one-shot break points.
1514
    FloodWithOneShot(function);
1515 1516 1517 1518

    // Remember source position and frame to handle step next.
    thread_local_.last_statement_position_ =
        debug_info->code()->SourceStatementPosition(frame->pc());
1519
    thread_local_.last_fp_ = frame->UnpaddedFP();
1520
  } else {
1521 1522 1523 1524 1525
    // 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_));
1526
      FloodWithOneShot(restarted_function);
1527 1528 1529 1530
    } else if (!call_function_stub.is_null()) {
      // If it's CallFunction stub ensure target function is compiled and flood
      // it with one shot breakpoints.

1531 1532 1533 1534
      // Find out number of arguments from the stub minor key.
      // Reverse lookup required as the minor key cannot be retrieved
      // from the code object.
      Handle<Object> obj(
1535
          isolate_->heap()->code_stubs()->SlowReverseLookup(
1536 1537
              *call_function_stub),
          isolate_);
1538 1539
      ASSERT(!obj.is_null());
      ASSERT(!(*obj)->IsUndefined());
1540 1541 1542 1543 1544
      ASSERT(obj->IsSmi());
      // Get the STUB key and extract major and minor key.
      uint32_t key = Smi::cast(*obj)->value();
      // Argc in the stub is the number of arguments passed - not the
      // expected arguments of the called function.
1545 1546 1547
      int call_function_arg_count =
          CallFunctionStub::ExtractArgcFromMinorKey(
              CodeStub::MinorKeyFromKey(key));
1548 1549 1550 1551
      ASSERT(call_function_stub->major_key() ==
             CodeStub::MajorKeyFromKey(key));

      // Find target function on the expression stack.
1552
      // Expression stack looks like this (top to bottom):
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
      // argN
      // ...
      // arg0
      // Receiver
      // Function to call
      int expressions_count = frame->ComputeExpressionsCount();
      ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
      Object* fun = frame->GetExpression(
          expressions_count - 2 - call_function_arg_count);
      if (fun->IsJSFunction()) {
        Handle<JSFunction> js_function(JSFunction::cast(fun));
1564 1565 1566 1567
        if (js_function->shared()->bound()) {
          Debug::FloodBoundFunctionWithOneShot(js_function);
        } else if (!js_function->IsBuiltin()) {
          // Don't step into builtins.
1568
          // It will also compile target function if it's not compiled yet.
1569
          FloodWithOneShot(js_function);
1570 1571 1572 1573
        }
      }
    }

1574 1575
    // 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
1576 1577
    // which step in will not stop. It also prepares for stepping in
    // getters/setters.
1578
    FloodWithOneShot(function);
1579

1580 1581 1582 1583 1584 1585 1586
    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
      // Object::Get/SetPropertyWithCallback, otherwise the step action will be
      // propagated on the next Debug::Break.
      thread_local_.last_statement_position_ =
          debug_info->code()->SourceStatementPosition(frame->pc());
1587
      thread_local_.last_fp_ = frame->UnpaddedFP();
1588 1589
    }

1590
    // Step in or Step in min
1591
    it.PrepareStepIn(isolate_);
1592 1593 1594 1595 1596 1597 1598 1599 1600
    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
1601
// flooded with one-shot break points. This function helps to perform several
1602 1603 1604
// steps before reporting break back to the debugger.
bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
                             JavaScriptFrame* frame) {
1605 1606 1607 1608 1609 1610 1611
  // StepNext and StepOut shouldn't bring us deeper in code, so last frame
  // shouldn't be a parent of current frame.
  if (thread_local_.last_step_action_ == StepNext ||
      thread_local_.last_step_action_ == StepOut) {
    if (frame->fp() < thread_local_.last_fp_) return true;
  }

1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
  // If the step last action was step next or step in make sure that a new
  // statement is hit.
  if (thread_local_.last_step_action_ == StepNext ||
      thread_local_.last_step_action_ == StepIn) {
    // Never continue if returning from function.
    if (break_location_iterator->IsExit()) return false;

    // Continue if we are still on the same frame and in the same statement.
    int current_statement_position =
        break_location_iterator->code()->SourceStatementPosition(frame->pc());
1622
    return thread_local_.last_fp_ == frame->UnpaddedFP() &&
1623
        thread_local_.last_statement_position_ == current_statement_position;
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
  }

  // 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) {
1634
  Code* code = Code::GetCodeFromTargetAddress(addr);
1635
  return code->is_debug_stub() && code->extra_ic_state() == DEBUG_BREAK;
1636 1637 1638 1639 1640 1641
}


// Check whether a code stub with the specified major key is a possible break
// point location when looking for source break locations.
bool Debug::IsSourceBreakStub(Code* code) {
1642
  CodeStub::Major major_key = CodeStub::GetMajorKey(code);
1643 1644 1645 1646 1647 1648 1649
  return major_key == CodeStub::CallFunction;
}


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


// Find the builtin to use for invoking the debug break
1656
Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
1657
  Isolate* isolate = code->GetIsolate();
1658

1659 1660
  // Find the builtin debug break function matching the calling convention
  // used by the call site.
1661
  if (code->is_inline_cache_stub()) {
1662 1663
    switch (code->kind()) {
      case Code::CALL_IC:
1664
      case Code::KEYED_CALL_IC:
1665 1666
        return isolate->stub_cache()->ComputeCallDebugBreak(
            code->arguments_count(), code->kind());
1667 1668

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

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

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

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

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

1683 1684
      default:
        UNREACHABLE();
1685 1686
    }
  }
1687
  if (RelocInfo::IsConstructCall(mode)) {
1688 1689 1690 1691 1692
    if (code->has_function_cache()) {
      return isolate->builtins()->CallConstructStub_Recording_DebugBreak();
    } else {
      return isolate->builtins()->CallConstructStub_DebugBreak();
    }
1693 1694
  }
  if (code->kind() == Code::STUB) {
1695
    ASSERT(code->major_key() == CodeStub::CallFunction);
1696 1697 1698 1699 1700
    if (code->has_function_cache()) {
      return isolate->builtins()->CallFunctionStub_Recording_DebugBreak();
    } else {
      return isolate->builtins()->CallFunctionStub_DebugBreak();
    }
1701
  }
1702 1703 1704 1705 1706 1707 1708 1709

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


// Simple function for returning the source positions for active break points.
Handle<Object> Debug::GetSourceBreakLocations(
1710 1711
    Handle<SharedFunctionInfo> shared,
    BreakPositionAlignment position_alignment) {
1712
  Isolate* isolate = shared->GetIsolate();
1713
  Heap* heap = isolate->heap();
1714 1715 1716
  if (!HasDebugInfo(shared)) {
    return Handle<Object>(heap->undefined_value(), isolate);
  }
1717 1718
  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
  if (debug_info->GetBreakPointCount() == 0) {
1719
    return Handle<Object>(heap->undefined_value(), isolate);
1720 1721
  }
  Handle<FixedArray> locations =
1722
      isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
1723 1724 1725 1726 1727 1728
  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) {
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
        Smi* position;
        switch (position_alignment) {
        case STATEMENT_ALIGNED:
          position = break_point_info->statement_position();
          break;
        case BREAK_POSITION_ALIGNED:
          position = break_point_info->source_position();
          break;
        default:
          UNREACHABLE();
          position = break_point_info->statement_position();
        }

        locations->set(count++, position);
1743 1744 1745 1746 1747 1748 1749
      }
    }
  }
  return locations;
}


1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
void Debug::NewBreak(StackFrame::Id break_frame_id) {
  thread_local_.break_frame_id_ = break_frame_id;
  thread_local_.break_id_ = ++thread_local_.break_count_;
}


void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
  thread_local_.break_frame_id_ = break_frame_id;
  thread_local_.break_id_ = break_id;
}


1762 1763
// Handle stepping into a function.
void Debug::HandleStepIn(Handle<JSFunction> function,
1764
                         Handle<Object> holder,
1765 1766
                         Address fp,
                         bool is_constructor) {
1767
  Isolate* isolate = function->GetIsolate();
1768 1769
  // If the frame pointer is not supplied by the caller find it.
  if (fp == 0) {
1770
    StackFrameIterator it(isolate);
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
    it.Advance();
    // For constructor functions skip another frame.
    if (is_constructor) {
      ASSERT(it.frame()->is_construct());
      it.Advance();
    }
    fp = it.frame()->fp();
  }

  // Flood the function with one-shot break points if it is called from where
  // step into was requested.
1782
  if (fp == step_in_fp()) {
1783 1784 1785 1786 1787
    if (function->shared()->bound()) {
      // Handle Function.prototype.bind
      Debug::FloodBoundFunctionWithOneShot(function);
    } else if (!function->IsBuiltin()) {
      // Don't allow step into functions in the native context.
1788
      if (function->shared()->code() ==
1789
          isolate->builtins()->builtin(Builtins::kFunctionApply) ||
1790
          function->shared()->code() ==
1791
          isolate->builtins()->builtin(Builtins::kFunctionCall)) {
1792 1793
        // Handle function.apply and function.call separately to flood the
        // function to be called and not the code for Builtins::FunctionApply or
1794 1795
        // Builtins::FunctionCall. The receiver of call/apply is the target
        // function.
1796
        if (!holder.is_null() && holder->IsJSFunction()) {
1797
          Handle<JSFunction> js_function = Handle<JSFunction>::cast(holder);
1798 1799 1800 1801 1802 1803
          if (!js_function->IsBuiltin()) {
            Debug::FloodWithOneShot(js_function);
          } else if (js_function->shared()->bound()) {
            // Handle Function.prototype.bind
            Debug::FloodBoundFunctionWithOneShot(js_function);
          }
1804 1805
        }
      } else {
1806
        Debug::FloodWithOneShot(function);
1807
      }
1808
    }
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
1809
  }
1810 1811 1812
}


1813 1814 1815 1816
void Debug::ClearStepping() {
  // Clear the various stepping setup.
  ClearOneShot();
  ClearStepIn();
1817
  ClearStepOut();
1818 1819 1820 1821 1822 1823
  ClearStepNext();

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

1824

1825 1826 1827 1828 1829
// 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
1830
  // last break point for a function is removed that function is automatically
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
  // 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) {
1846
  ASSERT(!StepOutActive());
1847
  thread_local_.step_into_fp_ = frame->UnpaddedFP();
1848 1849 1850 1851 1852 1853 1854 1855
}


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


1856 1857
void Debug::ActivateStepOut(StackFrame* frame) {
  ASSERT(!StepInActive());
1858
  thread_local_.step_out_fp_ = frame->UnpaddedFP();
1859 1860 1861 1862 1863 1864 1865 1866
}


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


1867 1868
void Debug::ClearStepNext() {
  thread_local_.last_step_action_ = StepNone;
1869
  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1870 1871 1872 1873
  thread_local_.last_fp_ = 0;
}


1874
// Helper function to compile full code for debugging. This code will
1875 1876 1877 1878 1879 1880 1881 1882 1883
// have debug break slots and deoptimization information. Deoptimization
// information is required in case that an optimized version of this
// function is still activated on the stack. It will also make sure that
// the full code is compiled with the same flags as the previous version,
// that is flags which can change the code generated. The current method
// of mapping from already compiled full code without debug break slots
// to full code with debug break slots depends on the generated code is
// otherwise exactly the same.
static bool CompileFullCodeForDebugging(Handle<JSFunction> function,
1884 1885 1886
                                        Handle<Code> current_code) {
  ASSERT(!current_code->has_debug_break_slots());

1887
  CompilationInfoWithZone info(function);
1888 1889 1890 1891 1892 1893 1894
  info.MarkCompilingForDebugging(current_code);
  ASSERT(!info.shared_info()->is_compiled());
  ASSERT(!info.isolate()->has_pending_exception());

  // Use compile lazy which will end up compiling the full code in the
  // configuration configured above.
  bool result = Compiler::CompileLazy(&info);
1895
  ASSERT(result != info.isolate()->has_pending_exception());
1896 1897 1898
  info.isolate()->clear_pending_exception();
#if DEBUG
  if (result) {
1899
    Handle<Code> new_code(function->shared()->code());
1900 1901 1902 1903 1904 1905 1906 1907 1908
    ASSERT(new_code->has_debug_break_slots());
    ASSERT(current_code->is_compiled_optimizable() ==
           new_code->is_compiled_optimizable());
  }
#endif
  return result;
}


1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
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()) {
1921
      List<JSFunction*> functions(FLAG_max_inlining_levels + 1);
1922 1923 1924 1925 1926 1927 1928
      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()) {
1929
      JSFunction* function = frame->function();
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
      ASSERT(frame->LookupCode()->kind() == Code::FUNCTION);
      active_functions->Add(Handle<JSFunction>(function));
      function->shared()->code()->set_gc_metadata(active_code_marker);
    }
  }
}


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;

1946
    JSFunction* function = frame->function();
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958

    ASSERT(frame->LookupCode()->kind() == Code::FUNCTION);

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

1959 1960 1961 1962 1963 1964 1965 1966
    // Iterate over the RelocInfo in the original code to compute the sum of the
    // constant pools sizes. (See Assembler::CheckConstPool())
    // Note that this is only useful for architectures using constant pools.
    int constpool_mask = RelocInfo::ModeMask(RelocInfo::CONST_POOL);
    int frame_const_pool_size = 0;
    for (RelocIterator it(*frame_code, constpool_mask); !it.done(); it.next()) {
      RelocInfo* info = it.rinfo();
      if (info->pc() >= frame->pc()) break;
1967
      frame_const_pool_size += static_cast<int>(info->data());
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    }
    intptr_t frame_offset =
      frame->pc() - frame_code->instruction_start() - frame_const_pool_size;

    // Iterate over the RelocInfo for new code to find the number of bytes
    // generated for debug slots and constant pools.
    int debug_break_slot_bytes = 0;
    int new_code_const_pool_size = 0;
    int mask = RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT) |
               RelocInfo::ModeMask(RelocInfo::CONST_POOL);
1978 1979 1980 1981
    for (RelocIterator it(*new_code, mask); !it.done(); it.next()) {
      // Check if the pc in the new code with debug break
      // slots is before this slot.
      RelocInfo* info = it.rinfo();
1982 1983 1984
      intptr_t new_offset = info->pc() - new_code->instruction_start() -
                            new_code_const_pool_size - debug_break_slot_bytes;
      if (new_offset >= frame_offset) {
1985 1986 1987
        break;
      }

1988 1989 1990 1991 1992
      if (RelocInfo::IsDebugBreakSlot(info->rmode())) {
        debug_break_slot_bytes += Assembler::kDebugBreakSlotLength;
      } else {
        ASSERT(RelocInfo::IsConstPool(info->rmode()));
        // The size of the constant pool is encoded in the data.
1993
        new_code_const_pool_size += static_cast<int>(info->data());
1994
      }
1995
    }
1996 1997 1998 1999 2000

    // Compute the equivalent pc in the new code.
    byte* new_pc = new_code->instruction_start() + frame_offset +
                   debug_break_slot_bytes + new_code_const_pool_size;

2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
    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()),
2017
             reinterpret_cast<intptr_t>(new_pc));
2018 2019 2020 2021
    }

    // Patch the return address to return into the code with
    // debug break slots.
2022
    frame->set_pc(new_pc);
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
  }
}


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


2055 2056 2057 2058
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_) {
2059
    if (FLAG_concurrent_recompilation) {
2060 2061 2062
      isolate_->optimizing_compiler_thread()->Flush();
    }

2063
    Deoptimizer::DeoptimizeAll(isolate_);
2064

2065 2066 2067
    Handle<Code> lazy_compile =
        Handle<Code>(isolate_->builtins()->builtin(Builtins::kLazyCompile));

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

2071 2072 2073 2074 2075 2076 2077
    // 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);

    {
      // We are going to iterate heap to find all functions without
      // debug break slots.
2078 2079 2080
      Heap* heap = isolate_->heap();
      heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
                              "preparing for breakpoints");
2081

2082 2083
      // Ensure no GC in this scope as we are going to use gc_metadata
      // field in the Code object to mark active functions.
2084
      DisallowHeapAllocation no_allocation;
2085

2086
      Object* active_code_marker = heap->the_hole_value();
2087

2088 2089 2090 2091 2092 2093 2094 2095
      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);
2096

2097 2098 2099
      // 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.
2100
      HeapIterator iterator(heap);
2101 2102 2103 2104
      HeapObject* obj = NULL;
      while (((obj = iterator.next()) != NULL)) {
        if (obj->IsJSFunction()) {
          JSFunction* function = JSFunction::cast(obj);
2105
          SharedFunctionInfo* shared = function->shared();
2106 2107 2108

          if (!shared->allows_lazy_compilation()) continue;
          if (!shared->script()->IsScript()) continue;
2109
          if (function->IsBuiltin()) continue;
2110 2111 2112 2113 2114
          if (shared->code()->gc_metadata() == active_code_marker) continue;

          Code::Kind kind = function->code()->kind();
          if (kind == Code::FUNCTION &&
              !function->code()->has_debug_break_slots()) {
2115 2116
            function->set_code(*lazy_compile);
            function->shared()->set_code(*lazy_compile);
2117
          } else if (kind == Code::BUILTIN &&
2118
              (function->IsInRecompileQueue() ||
2119
               function->IsMarkedForLazyRecompilation() ||
2120
               function->IsMarkedForConcurrentRecompilation())) {
2121 2122 2123 2124 2125 2126 2127 2128 2129
            // Abort in-flight compilation.
            Code* shared_code = function->shared()->code();
            if (shared_code->kind() == Code::FUNCTION &&
                shared_code->has_debug_break_slots()) {
              function->set_code(shared_code);
            } else {
              function->set_code(*lazy_compile);
              function->shared()->set_code(*lazy_compile);
            }
2130 2131
          }
        }
2132
      }
2133

2134 2135 2136 2137 2138 2139
      // 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));
      }
    }
2140 2141 2142 2143 2144

    // Now recompile all functions with activation frames and and
    // patch the return address to run in the new compiled code.
    for (int i = 0; i < active_functions.length(); i++) {
      Handle<JSFunction> function = active_functions[i];
2145
      Handle<SharedFunctionInfo> shared(function->shared());
2146 2147 2148 2149 2150 2151 2152

      if (function->code()->kind() == Code::FUNCTION &&
          function->code()->has_debug_break_slots()) {
        // Nothing to do. Function code already had debug break slots.
        continue;
      }

2153 2154 2155 2156 2157 2158 2159 2160 2161
      // If recompilation is not possible just skip it.
      if (shared->is_toplevel() ||
          !shared->allows_lazy_compilation() ||
          shared->code()->kind() == Code::BUILTIN) {
        continue;
      }

      // Make sure that the shared full code is compiled with debug
      // break slots.
2162
      if (!shared->code()->has_debug_break_slots()) {
2163 2164
        // Try to compile the full code with debug break slots. If it
        // fails just keep the current code.
2165
        Handle<Code> current_code(function->shared()->code());
2166 2167 2168 2169
        shared->set_code(*lazy_compile);
        bool prev_force_debugger_active =
            isolate_->debugger()->force_debugger_active();
        isolate_->debugger()->set_force_debugger_active(true);
2170
        ASSERT(current_code->kind() == Code::FUNCTION);
2171
        CompileFullCodeForDebugging(function, current_code);
2172 2173 2174 2175 2176 2177 2178 2179
        isolate_->debugger()->set_force_debugger_active(
            prev_force_debugger_active);
        if (!shared->is_compiled()) {
          shared->set_code(*current_code);
          continue;
        }
      }

2180 2181
      // Keep function code in sync with shared function info.
      function->set_code(shared->code());
2182
    }
2183 2184 2185 2186 2187 2188 2189

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

    ActiveFunctionsRedirector active_functions_redirector;
    isolate_->thread_manager()->IterateArchivedThreads(
          &active_functions_redirector);
2190 2191 2192 2193
  }
}


2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
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;
2212
  Heap* heap = isolate_->heap();
2213 2214
  while (!done) {
    { // Extra scope for iterator and no-allocation.
2215
      heap->EnsureHeapIsIterable();
2216
      DisallowHeapAllocation no_alloc_during_heap_iteration;
2217
      HeapIterator iterator(heap);
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
      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());
          ASSERT(shared->allows_lazy_compilation() || shared->is_compiled());
          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.

2277
    if (target.is_null()) return heap->undefined_value();
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301

    // 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.
      if (target_function.is_null()) {
        SharedFunctionInfo::CompileLazy(target, KEEP_EXCEPTION);
      } else {
        JSFunction::CompileLazy(target_function, KEEP_EXCEPTION);
      }
    }
  }  // End while loop.

  return *target;
}


2302
// Ensures the debug information is present for shared.
2303 2304
bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
                            Handle<JSFunction> function) {
2305 2306
  Isolate* isolate = shared->GetIsolate();

2307
  // Return if we already have the debug info for shared.
2308 2309 2310 2311
  if (HasDebugInfo(shared)) {
    ASSERT(shared->is_compiled());
    return true;
  }
2312

2313 2314 2315 2316 2317 2318
  // 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() &&
      !JSFunction::EnsureCompiled(function, CLEAR_EXCEPTION)) {
2319 2320
    return false;
  }
2321 2322

  // Create the debug info object.
2323
  Handle<DebugInfo> debug_info = isolate->factory()->NewDebugInfo(shared);
2324 2325 2326 2327 2328 2329

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

2330
  return true;
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
}


void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
  ASSERT(debug_info_list_ != NULL);
  // Run through the debug info objects to find this one and remove it.
  DebugInfoListNode* prev = NULL;
  DebugInfoListNode* current = debug_info_list_;
  while (current != NULL) {
    if (*current->debug_info() == *debug_info) {
      // Unlink from list. If prev is NULL we are looking at the first element.
      if (prev == NULL) {
        debug_info_list_ = current->next();
      } else {
        prev->set_next(current->next());
      }
2347 2348
      current->debug_info()->shared()->set_debug_info(
              isolate_->heap()->undefined_value());
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
      delete current;

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

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


void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
2366
  HandleScope scope(isolate_);
2367

2368 2369
  PrepareForBreakPoints();

2370
  // Get the executing function in which the debug break occurred.
2371 2372 2373
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
2374 2375 2376
    // Return if we failed to retrieve the debug info.
    return;
  }
2377 2378 2379 2380 2381
  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.
2382
  Handle<Code> frame_code(frame->LookupCode());
2383 2384 2385 2386 2387 2388
  ASSERT(frame_code.is_identical_to(code));
#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.
2389
  Address addr = frame->pc() - Assembler::kPatchDebugBreakSlotReturnOffset;
2390

2391
  // Check if the location is at JS exit or debug break slot.
2392 2393
  bool at_js_return = false;
  bool break_at_js_return_active = false;
2394
  bool at_debug_break_slot = false;
2395
  RelocIterator it(debug_info->code());
2396
  while (!it.done() && !at_js_return && !at_debug_break_slot) {
2397
    if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
2398 2399
      at_js_return = (it.rinfo()->pc() ==
          addr - Assembler::kPatchReturnSequenceAddressOffset);
2400
      break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
2401
    }
2402 2403 2404 2405
    if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
      at_debug_break_slot = (it.rinfo()->pc() ==
          addr - Assembler::kPatchDebugBreakSlotAddressOffset);
    }
2406 2407 2408 2409 2410
    it.next();
  }

  // Handle the jump to continue execution after break point depending on the
  // break location.
2411 2412 2413 2414 2415
  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) {
2416 2417 2418
      addr +=  original_code->instruction_start() - code->instruction_start();
    }

2419 2420 2421
    // Move back to where the call instruction sequence started.
    thread_local_.after_break_target_ =
        addr - Assembler::kPatchReturnSequenceAddressOffset;
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
  } else if (at_debug_break_slot) {
    // Address of where the debug break slot starts.
    addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;

    // Continue just after the slot.
    thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
  } else if (IsDebugBreak(Assembler::target_address_at(addr))) {
    // 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();
2436 2437 2438 2439

    // Install jump to the call address in the original code. This will be the
    // call which was overwritten by the call to DebugBreakXXX.
    thread_local_.after_break_target_ = Assembler::target_address_at(addr);
2440 2441 2442 2443 2444 2445
  } 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.
    thread_local_.after_break_target_ = Assembler::target_address_at(addr);
2446 2447 2448 2449
  }
}


2450
bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
2451
  HandleScope scope(isolate_);
2452

2453 2454 2455 2456 2457 2458 2459
  // If there are no break points this cannot be break at return, as
  // the debugger statement and stack guard bebug break cannot be at
  // return.
  if (!has_break_points_) {
    return false;
  }

2460 2461
  PrepareForBreakPoints();

2462
  // Get the executing function in which the debug break occurred.
2463 2464 2465
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<SharedFunctionInfo> shared(function->shared());
  if (!EnsureDebugInfo(shared, function)) {
2466 2467 2468 2469 2470 2471 2472
    // 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.
2473
  Handle<Code> frame_code(frame->LookupCode());
2474 2475 2476 2477
  ASSERT(frame_code.is_identical_to(code));
#endif

  // Find the call address in the running code.
2478
  Address addr = frame->pc() - Assembler::kPatchDebugBreakSlotReturnOffset;
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492

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


2493
void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
2494 2495
                                  FrameDropMode mode,
                                  Object** restarter_frame_function_pointer) {
2496 2497 2498
  if (mode != CURRENTLY_SET_MODE) {
    thread_local_.frame_drop_mode_ = mode;
  }
2499
  thread_local_.break_frame_id_ = new_break_frame_id;
2500 2501
  thread_local_.restarter_frame_function_pointer_ =
      restarter_frame_function_pointer;
2502 2503 2504
}


2505 2506 2507 2508 2509 2510 2511
const int Debug::FramePaddingLayout::kInitialSize = 1;


// Any even value bigger than kInitialSize as needed for stack scanning.
const int Debug::FramePaddingLayout::kPaddingValue = kInitialSize + 1;


2512
bool Debug::IsDebugGlobal(GlobalObject* global) {
2513
  return IsLoaded() && global == debug_context()->global_object();
2514 2515 2516
}


2517
void Debug::ClearMirrorCache() {
2518
  PostponeInterruptsScope postpone(isolate_);
2519 2520
  HandleScope scope(isolate_);
  ASSERT(isolate_->context() == *Debug::debug_context());
2521 2522

  // Clear the mirror cache.
2523
  Handle<String> function_name = isolate_->factory()->InternalizeOneByteString(
2524
      STATIC_ASCII_VECTOR("ClearMirrorCache"));
2525
  Handle<Object> fun(
2526 2527
      isolate_->global_object()->GetPropertyNoExceptionThrown(*function_name),
      isolate_);
2528 2529
  ASSERT(fun->IsJSFunction());
  bool caught_exception;
2530
  Execution::TryCall(Handle<JSFunction>::cast(fun),
2531
      Handle<JSObject>(Debug::debug_context()->global_object()),
2532 2533 2534 2535
      0, NULL, &caught_exception);
}


2536
void Debug::CreateScriptCache() {
2537 2538
  Heap* heap = isolate_->heap();
  HandleScope scope(isolate_);
2539 2540 2541

  // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
  // rid of all the cached script wrappers and the second gets rid of the
2542 2543
  // scripts which are no longer referenced.  The second also sweeps precisely,
  // which saves us doing yet another GC to make the heap iterable.
2544 2545 2546
  heap->CollectAllGarbage(Heap::kNoGCFlags, "Debug::CreateScriptCache");
  heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
                          "Debug::CreateScriptCache");
2547 2548

  ASSERT(script_cache_ == NULL);
2549
  script_cache_ = new ScriptCache(isolate_);
2550 2551 2552

  // Scan heap for Script objects.
  int count = 0;
2553
  HeapIterator iterator(heap);
2554
  DisallowHeapAllocation no_allocation;
2555

2556
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
2557
    if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
      script_cache_->Add(Handle<Script>(Script::cast(obj)));
      count++;
    }
  }
}


void Debug::DestroyScriptCache() {
  // Get rid of the script cache if it was created.
  if (script_cache_ != NULL) {
    delete script_cache_;
    script_cache_ = NULL;
  }
}


void Debug::AddScriptToScriptCache(Handle<Script> script) {
  if (script_cache_ != NULL) {
    script_cache_->Add(script);
  }
}


Handle<FixedArray> Debug::GetLoadedScripts() {
  // Create and fill the script cache when the loaded scripts is requested for
  // the first time.
  if (script_cache_ == NULL) {
    CreateScriptCache();
  }

  // If the script cache is not active just return an empty array.
  ASSERT(script_cache_ != NULL);
  if (script_cache_ == NULL) {
2591
    isolate_->factory()->NewFixedArray(0);
2592 2593 2594 2595
  }

  // Perform GC to get unreferenced scripts evicted from the cache before
  // returning the content.
2596 2597
  isolate_->heap()->CollectAllGarbage(Heap::kNoGCFlags,
                                      "Debug::GetLoadedScripts");
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611

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


void Debug::AfterGarbageCollection() {
  // Generate events for collected scripts.
  if (script_cache_ != NULL) {
    script_cache_->ProcessCollectedScripts();
  }
}


2612
Debugger::Debugger(Isolate* isolate)
2613
    : debugger_access_(isolate->debugger_access()),
2614 2615 2616 2617
      event_listener_(Handle<Object>()),
      event_listener_data_(Handle<Object>()),
      compiling_natives_(false),
      is_loading_debugger_(false),
2618
      live_edit_enabled_(true),
2619
      never_unload_debugger_(false),
2620
      force_debugger_active_(false),
2621 2622 2623 2624 2625
      message_handler_(NULL),
      debugger_unload_pending_(false),
      host_dispatch_handler_(NULL),
      debug_message_dispatch_handler_(NULL),
      message_dispatch_helper_thread_(NULL),
2626
      host_dispatch_period_(TimeDelta::FromMilliseconds(100)),
2627
      agent_(NULL),
2628
      command_queue_(isolate->logger(), kQueueInitialSize),
2629
      command_received_(0),
2630 2631
      event_command_queue_(isolate->logger(), kQueueInitialSize),
      isolate_(isolate) {
2632 2633 2634
}


2635
Debugger::~Debugger() {}
2636 2637 2638


Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
2639 2640
                                      int argc,
                                      Handle<Object> argv[],
2641
                                      bool* caught_exception) {
2642
  ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2643 2644

  // Create the execution state object.
2645
  Handle<String> constructor_str =
2646
      isolate_->factory()->InternalizeUtf8String(constructor_name);
2647
  Handle<Object> constructor(
2648 2649
      isolate_->global_object()->GetPropertyNoExceptionThrown(*constructor_str),
      isolate_);
2650 2651 2652
  ASSERT(constructor->IsJSFunction());
  if (!constructor->IsJSFunction()) {
    *caught_exception = true;
2653
    return isolate_->factory()->undefined_value();
2654 2655 2656
  }
  Handle<Object> js_object = Execution::TryCall(
      Handle<JSFunction>::cast(constructor),
2657
      Handle<JSObject>(isolate_->debug()->debug_context()->global_object()),
2658 2659 2660
      argc,
      argv,
      caught_exception);
2661 2662 2663 2664 2665 2666
  return js_object;
}


Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
  // Create the execution state object.
2667
  Handle<Object> break_id = isolate_->factory()->NewNumberFromInt(
2668
      isolate_->debug()->break_id());
2669
  Handle<Object> argv[] = { break_id };
2670
  return MakeJSObject(CStrVector("MakeExecutionState"),
2671 2672 2673
                      ARRAY_SIZE(argv),
                      argv,
                      caught_exception);
2674 2675 2676 2677 2678 2679 2680
}


Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
                                        Handle<Object> break_points_hit,
                                        bool* caught_exception) {
  // Create the new break event object.
2681
  Handle<Object> argv[] = { exec_state, break_points_hit };
2682
  return MakeJSObject(CStrVector("MakeBreakEvent"),
2683
                      ARRAY_SIZE(argv),
2684 2685 2686 2687 2688 2689 2690 2691 2692
                      argv,
                      caught_exception);
}


Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
                                            Handle<Object> exception,
                                            bool uncaught,
                                            bool* caught_exception) {
2693
  Factory* factory = isolate_->factory();
2694
  // Create the new exception event object.
2695 2696
  Handle<Object> argv[] = { exec_state,
                            exception,
2697
                            factory->ToBoolean(uncaught) };
2698
  return MakeJSObject(CStrVector("MakeExceptionEvent"),
2699 2700 2701
                      ARRAY_SIZE(argv),
                      argv,
                      caught_exception);
2702 2703 2704 2705 2706 2707
}


Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
                                              bool* caught_exception) {
  // Create the new function event object.
2708
  Handle<Object> argv[] = { function };
2709
  return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
2710 2711 2712
                      ARRAY_SIZE(argv),
                      argv,
                      caught_exception);
2713 2714 2715 2716
}


Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
2717
                                          bool before,
2718
                                          bool* caught_exception) {
2719
  Factory* factory = isolate_->factory();
2720 2721
  // Create the compile event object.
  Handle<Object> exec_state = MakeExecutionState(caught_exception);
2722
  Handle<Object> script_wrapper = GetScriptWrapper(script);
2723 2724
  Handle<Object> argv[] = { exec_state,
                            script_wrapper,
2725
                            factory->ToBoolean(before) };
2726
  return MakeJSObject(CStrVector("MakeCompileEvent"),
2727
                      ARRAY_SIZE(argv),
2728 2729 2730 2731 2732
                      argv,
                      caught_exception);
}


2733 2734 2735 2736
Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
                                                  bool* caught_exception) {
  // Create the script collected event object.
  Handle<Object> exec_state = MakeExecutionState(caught_exception);
2737
  Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id), isolate_);
2738
  Handle<Object> argv[] = { exec_state, id_object };
2739 2740

  return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
2741
                      ARRAY_SIZE(argv),
2742 2743 2744 2745 2746
                      argv,
                      caught_exception);
}


2747
void Debugger::OnException(Handle<Object> exception, bool uncaught) {
2748 2749
  HandleScope scope(isolate_);
  Debug* debug = isolate_->debug();
2750 2751

  // Bail out based on state or if there is no listener for this event
2752
  if (debug->InDebugger()) return;
2753 2754 2755 2756 2757
  if (!Debugger::EventActive(v8::Exception)) return;

  // Bail out if exception breaks are not active
  if (uncaught) {
    // Uncaught exceptions are reported by either flags.
2758 2759
    if (!(debug->break_on_uncaught_exception() ||
          debug->break_on_exception())) return;
2760 2761
  } else {
    // Caught exceptions are reported is activated.
2762
    if (!debug->break_on_exception()) return;
2763 2764
  }

2765
  // Enter the debugger.
2766
  EnterDebugger debugger(isolate_);
2767
  if (debugger.FailedToEnter()) return;
2768 2769

  // Clear all current stepping setup.
2770
  debug->ClearStepping();
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
  // Create the event data object.
  bool caught_exception = false;
  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
  Handle<Object> event_data;
  if (!caught_exception) {
    event_data = MakeExceptionEvent(exec_state, exception, uncaught,
                                    &caught_exception);
  }
  // Bail out and don't call debugger if exception.
  if (caught_exception) {
    return;
  }

2784 2785
  // Process debug event.
  ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2786 2787 2788 2789
  // Return to continue execution from where the exception was thrown.
}


2790 2791
void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
                            bool auto_continue) {
2792
  HandleScope scope(isolate_);
2793

2794
  // Debugger has already been entered by caller.
2795
  ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2796

2797 2798 2799 2800
  // Bail out if there is no listener for this event
  if (!Debugger::EventActive(v8::Break)) return;

  // Debugger must be entered in advance.
2801
  ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815

  // Create the event data object.
  bool caught_exception = false;
  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
  Handle<Object> event_data;
  if (!caught_exception) {
    event_data = MakeBreakEvent(exec_state, break_points_hit,
                                &caught_exception);
  }
  // Bail out and don't call debugger if exception.
  if (caught_exception) {
    return;
  }

2816 2817 2818 2819
  // Process debug event.
  ProcessDebugEvent(v8::Break,
                    Handle<JSObject>::cast(event_data),
                    auto_continue);
2820 2821 2822 2823
}


void Debugger::OnBeforeCompile(Handle<Script> script) {
2824
  HandleScope scope(isolate_);
2825 2826

  // Bail out based on state or if there is no listener for this event
2827
  if (isolate_->debug()->InDebugger()) return;
2828 2829 2830
  if (compiling_natives()) return;
  if (!EventActive(v8::BeforeCompile)) return;

2831
  // Enter the debugger.
2832
  EnterDebugger debugger(isolate_);
2833
  if (debugger.FailedToEnter()) return;
2834 2835 2836

  // Create the event data object.
  bool caught_exception = false;
2837
  Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
2838 2839 2840 2841 2842
  // Bail out and don't call debugger if exception.
  if (caught_exception) {
    return;
  }

2843 2844 2845 2846
  // Process debug event.
  ProcessDebugEvent(v8::BeforeCompile,
                    Handle<JSObject>::cast(event_data),
                    true);
2847 2848 2849 2850
}


// Handle debugger actions when a new script is compiled.
2851 2852
void Debugger::OnAfterCompile(Handle<Script> script,
                              AfterCompileFlags after_compile_flags) {
2853 2854
  HandleScope scope(isolate_);
  Debug* debug = isolate_->debug();
2855

2856
  // Add the newly compiled script to the script cache.
2857
  debug->AddScriptToScriptCache(script);
2858 2859

  // No more to do if not debugging.
2860
  if (!IsDebuggerActive()) return;
2861

2862 2863 2864
  // No compile events while compiling natives.
  if (compiling_natives()) return;

2865
  // Store whether in debugger before entering debugger.
2866
  bool in_debugger = debug->InDebugger();
2867

2868
  // Enter the debugger.
2869
  EnterDebugger debugger(isolate_);
2870
  if (debugger.FailedToEnter()) return;
2871 2872 2873 2874

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

2875
  // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
2876 2877
  Handle<String> update_script_break_points_string =
      isolate_->factory()->InternalizeOneByteString(
2878
          STATIC_ASCII_VECTOR("UpdateScriptBreakPoints"));
2879
  Handle<Object> update_script_break_points =
2880 2881
      Handle<Object>(
          debug->debug_context()->global_object()->GetPropertyNoExceptionThrown(
2882
              *update_script_break_points_string),
2883
          isolate_);
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
  if (!update_script_break_points->IsJSFunction()) {
    return;
  }
  ASSERT(update_script_break_points->IsJSFunction());

  // Wrap the script object in a proper JS object before passing it
  // to JavaScript.
  Handle<JSValue> wrapper = GetScriptWrapper(script);

  // Call UpdateScriptBreakPoints expect no exceptions.
2894
  bool caught_exception;
2895
  Handle<Object> argv[] = { wrapper };
2896
  Execution::TryCall(Handle<JSFunction>::cast(update_script_break_points),
2897
                     isolate_->js_builtins_object(),
2898 2899 2900
                     ARRAY_SIZE(argv),
                     argv,
                     &caught_exception);
2901 2902 2903 2904
  if (caught_exception) {
    return;
  }
  // Bail out based on state or if there is no listener for this event
2905
  if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
2906 2907 2908 2909
  if (!Debugger::EventActive(v8::AfterCompile)) return;

  // Create the compile state object.
  Handle<Object> event_data = MakeCompileEvent(script,
2910
                                               false,
2911 2912 2913 2914 2915
                                               &caught_exception);
  // Bail out and don't call debugger if exception.
  if (caught_exception) {
    return;
  }
2916 2917 2918 2919
  // Process debug event.
  ProcessDebugEvent(v8::AfterCompile,
                    Handle<JSObject>::cast(event_data),
                    true);
2920 2921 2922
}


2923
void Debugger::OnScriptCollected(int id) {
2924
  HandleScope scope(isolate_);
2925 2926

  // No more to do if not debugging.
2927
  if (isolate_->debug()->InDebugger()) return;
2928 2929 2930 2931
  if (!IsDebuggerActive()) return;
  if (!Debugger::EventActive(v8::ScriptCollected)) return;

  // Enter the debugger.
2932
  EnterDebugger debugger(isolate_);
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
  if (debugger.FailedToEnter()) return;

  // Create the script collected state object.
  bool caught_exception = false;
  Handle<Object> event_data = MakeScriptCollectedEvent(id,
                                                       &caught_exception);
  // Bail out and don't call debugger if exception.
  if (caught_exception) {
    return;
  }

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


2951
void Debugger::ProcessDebugEvent(v8::DebugEvent event,
2952
                                 Handle<JSObject> event_data,
2953
                                 bool auto_continue) {
2954
  HandleScope scope(isolate_);
2955

2956 2957
  // Clear any pending debug break if this is a real break.
  if (!auto_continue) {
2958
    isolate_->debug()->clear_interrupt_pending(DEBUGBREAK);
2959 2960
  }

2961 2962 2963 2964 2965 2966
  // Create the execution state.
  bool caught_exception = false;
  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
  if (caught_exception) {
    return;
  }
2967 2968
  // First notify the message handler if any.
  if (message_handler_ != NULL) {
2969 2970 2971 2972
    NotifyMessageHandler(event,
                         Handle<JSObject>::cast(exec_state),
                         event_data,
                         auto_continue);
2973
  }
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
  // 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();
2991 2992 2993 2994 2995
    }
  }
}


2996 2997 2998 2999
void Debugger::CallEventCallback(v8::DebugEvent event,
                                 Handle<Object> exec_state,
                                 Handle<Object> event_data,
                                 v8::Debug::ClientData* client_data) {
3000
  if (event_listener_->IsForeign()) {
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
    CallCEventCallback(event, exec_state, event_data, client_data);
  } else {
    CallJSEventCallback(event, exec_state, event_data);
  }
}


void Debugger::CallCEventCallback(v8::DebugEvent event,
                                  Handle<Object> exec_state,
                                  Handle<Object> event_data,
                                  v8::Debug::ClientData* client_data) {
3012
  Handle<Foreign> callback_obj(Handle<Foreign>::cast(event_listener_));
3013
  v8::Debug::EventCallback2 callback =
3014 3015
      FUNCTION_CAST<v8::Debug::EventCallback2>(
          callback_obj->foreign_address());
3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
  EventDetailsImpl event_details(
      event,
      Handle<JSObject>::cast(exec_state),
      Handle<JSObject>::cast(event_data),
      event_listener_data_,
      client_data);
  callback(event_details);
}


void Debugger::CallJSEventCallback(v8::DebugEvent event,
                                   Handle<Object> exec_state,
                                   Handle<Object> event_data) {
  ASSERT(event_listener_->IsJSFunction());
  Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));

  // Invoke the JavaScript debug event listener.
3033
  Handle<Object> argv[] = { Handle<Object>(Smi::FromInt(event), isolate_),
3034 3035 3036
                            exec_state,
                            event_data,
                            event_listener_data_ };
3037
  bool caught_exception;
3038
  Execution::TryCall(fun,
3039
                     isolate_->global_object(),
3040 3041 3042
                     ARRAY_SIZE(argv),
                     argv,
                     &caught_exception);
3043 3044 3045 3046
  // Silently ignore exceptions from debug event listeners.
}


3047
Handle<Context> Debugger::GetDebugContext() {
3048
  never_unload_debugger_ = true;
3049
  EnterDebugger debugger(isolate_);
3050
  return isolate_->debug()->debug_context();
3051 3052 3053
}


3054
void Debugger::UnloadDebugger() {
3055
  Debug* debug = isolate_->debug();
3056

3057
  // Make sure that there are no breakpoints left.
3058
  debug->ClearAllBreakPoints();
3059 3060 3061

  // Unload the debugger if feasible.
  if (!never_unload_debugger_) {
3062
    debug->Unload();
3063 3064
  }

3065 3066
  // Clear the flag indicating that the debugger should be unloaded.
  debugger_unload_pending_ = false;
3067 3068 3069
}


3070
void Debugger::NotifyMessageHandler(v8::DebugEvent event,
3071 3072
                                    Handle<JSObject> exec_state,
                                    Handle<JSObject> event_data,
3073
                                    bool auto_continue) {
3074
  HandleScope scope(isolate_);
3075

3076
  if (!isolate_->debug()->Load()) return;
3077 3078

  // Process the individual events.
3079
  bool sendEventMessage = false;
3080 3081
  switch (event) {
    case v8::Break:
3082
    case v8::BreakForCommand:
3083
      sendEventMessage = !auto_continue;
3084 3085
      break;
    case v8::Exception:
3086
      sendEventMessage = true;
3087 3088 3089 3090
      break;
    case v8::BeforeCompile:
      break;
    case v8::AfterCompile:
3091
      sendEventMessage = true;
3092
      break;
3093 3094 3095
    case v8::ScriptCollected:
      sendEventMessage = true;
      break;
3096 3097 3098 3099 3100 3101
    case v8::NewFunction:
      break;
    default:
      UNREACHABLE();
  }

3102 3103 3104
  // 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.
3105 3106
  ASSERT(isolate_->debug()->InDebugger());
  isolate_->stack_guard()->Continue(DEBUGCOMMAND);
3107 3108 3109 3110

  // Notify the debugger that a debug event has occurred unless auto continue is
  // active in which case no event is send.
  if (sendEventMessage) {
3111 3112 3113 3114 3115 3116
    MessageImpl message = MessageImpl::NewEvent(
        event,
        auto_continue,
        Handle<JSObject>::cast(exec_state),
        Handle<JSObject>::cast(event_data));
    InvokeMessageHandler(message);
3117
  }
3118 3119 3120 3121 3122

  // 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.
3123
  if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
3124 3125
    return;
  }
3126 3127

  v8::TryCatch try_catch;
3128 3129 3130 3131 3132 3133 3134 3135 3136

  // DebugCommandProcessor goes here.
  v8::Local<v8::Object> cmd_processor;
  {
    v8::Local<v8::Object> api_exec_state =
        v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
    v8::Local<v8::String> fun_name =
        v8::String::New("debugCommandProcessor");
    v8::Local<v8::Function> fun =
3137
        v8::Local<v8::Function>::Cast(api_exec_state->Get(fun_name));
3138

3139
    v8::Handle<v8::Boolean> running = v8::Boolean::New(auto_continue);
3140 3141
    static const int kArgc = 1;
    v8::Handle<Value> argv[kArgc] = { running };
3142 3143
    cmd_processor = v8::Local<v8::Object>::Cast(
        fun->Call(api_exec_state, kArgc, argv));
3144 3145 3146 3147
    if (try_catch.HasCaught()) {
      PrintLn(try_catch.Exception());
      return;
    }
3148 3149
  }

3150 3151
  bool running = auto_continue;

3152
  // Process requests from the debugger.
3153
  while (true) {
3154
    // Wait for new command in the queue.
3155 3156
    if (Debugger::host_dispatch_handler_) {
      // In case there is a host dispatch - do periodic dispatches.
3157
      if (!command_received_.WaitFor(host_dispatch_period_)) {
3158 3159 3160 3161 3162 3163
        // Timout expired, do the dispatch.
        Debugger::host_dispatch_handler_();
        continue;
      }
    } else {
      // In case there is no host dispatch - just wait.
3164
      command_received_.Wait();
3165
    }
3166 3167

    // Get the command from the queue.
3168
    CommandMessage command = command_queue_.Get();
3169 3170
    isolate_->logger()->DebugTag(
        "Got request from command queue, in interactive loop.");
3171
    if (!Debugger::IsDebuggerActive()) {
3172 3173
      // Delete command text and user data.
      command.Dispose();
3174 3175 3176
      return;
    }

3177
    // Invoke JavaScript to process the debug request.
3178 3179
    v8::Local<v8::String> fun_name;
    v8::Local<v8::Function> fun;
3180
    v8::Local<v8::Value> request;
3181
    v8::TryCatch try_catch;
3182
    fun_name = v8::String::New("processDebugRequest");
3183
    fun = v8::Local<v8::Function>::Cast(cmd_processor->Get(fun_name));
3184

3185 3186
    request = v8::String::New(command.text().start(),
                              command.text().length());
3187 3188 3189
    static const int kArgc = 1;
    v8::Handle<Value> argv[kArgc] = { request };
    v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
3190

3191 3192
    // Get the response.
    v8::Local<v8::String> response;
3193
    if (!try_catch.HasCaught()) {
3194 3195
      // Get response string.
      if (!response_val->IsUndefined()) {
3196
        response = v8::Local<v8::String>::Cast(response_val);
3197 3198 3199
      } else {
        response = v8::String::New("");
      }
3200 3201 3202

      // Log the JSON request/response.
      if (FLAG_trace_debug_json) {
3203 3204
        PrintLn(request);
        PrintLn(response);
3205 3206 3207
      }

      // Get the running state.
3208
      fun_name = v8::String::New("isRunning");
3209
      fun = v8::Local<v8::Function>::Cast(cmd_processor->Get(fun_name));
3210 3211 3212 3213 3214
      static const int kArgc = 1;
      v8::Handle<Value> argv[kArgc] = { response };
      v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
      if (!try_catch.HasCaught()) {
        running = running_val->ToBoolean()->Value();
3215 3216 3217
      }
    } else {
      // In case of failure the result text is the exception text.
3218
      response = try_catch.Exception()->ToString();
3219 3220 3221
    }

    // Return the result.
3222 3223 3224 3225 3226 3227 3228 3229 3230
    MessageImpl message = MessageImpl::NewResponse(
        event,
        running,
        Handle<JSObject>::cast(exec_state),
        Handle<JSObject>::cast(event_data),
        Handle<String>(Utils::OpenHandle(*response)),
        command.client_data());
    InvokeMessageHandler(message);
    command.Dispose();
3231

3232
    // Return from debug event processing if either the VM is put into the
3233
    // running state (through a continue command) or auto continue is active
3234
    // and there are no more commands queued.
3235
    if (running && !HasCommands()) {
3236 3237 3238 3239 3240 3241
      return;
    }
  }
}


3242 3243
void Debugger::SetEventListener(Handle<Object> callback,
                                Handle<Object> data) {
3244 3245
  HandleScope scope(isolate_);
  GlobalHandles* global_handles = isolate_->global_handles();
3246 3247 3248 3249

  // Clear the global handles for the event listener and the event listener data
  // object.
  if (!event_listener_.is_null()) {
3250
    global_handles->Destroy(
3251 3252 3253 3254
        reinterpret_cast<Object**>(event_listener_.location()));
    event_listener_ = Handle<Object>();
  }
  if (!event_listener_data_.is_null()) {
3255
    global_handles->Destroy(
3256 3257 3258 3259 3260 3261 3262
        reinterpret_cast<Object**>(event_listener_data_.location()));
    event_listener_data_ = Handle<Object>();
  }

  // If there is a new debug event listener register it together with its data
  // object.
  if (!callback->IsUndefined() && !callback->IsNull()) {
3263
    event_listener_ = Handle<Object>::cast(
3264
        global_handles->Create(*callback));
3265
    if (data.is_null()) {
3266
      data = isolate_->factory()->undefined_value();
3267
    }
3268
    event_listener_data_ = Handle<Object>::cast(
3269
        global_handles->Create(*data));
3270 3271
  }

3272
  ListenersChanged();
3273 3274 3275
}


3276
void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
3277
  LockGuard<RecursiveMutex> with(debugger_access_);
3278

3279
  message_handler_ = handler;
3280
  ListenersChanged();
3281
  if (handler == NULL) {
3282 3283
    // Send an empty command to the debugger if in a break to make JavaScript
    // run again if the debugger is closed.
3284
    if (isolate_->debug()->InDebugger()) {
3285 3286
      ProcessCommand(Vector<const uint16_t>::empty());
    }
3287
  }
3288
}
3289

3290 3291

void Debugger::ListenersChanged() {
3292
  if (IsDebuggerActive()) {
3293
    // Disable the compilation cache when the debugger is active.
3294
    isolate_->compilation_cache()->Disable();
3295
    debugger_unload_pending_ = false;
3296
  } else {
3297
    isolate_->compilation_cache()->Enable();
3298
    // Unload the debugger if event listener and message handler cleared.
3299 3300
    // Schedule this for later, because we may be in non-V8 thread.
    debugger_unload_pending_ = true;
3301
  }
3302 3303 3304
}


3305
void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
3306
                                      TimeDelta period) {
3307
  host_dispatch_handler_ = handler;
3308
  host_dispatch_period_ = period;
3309 3310 3311
}


3312
void Debugger::SetDebugMessageDispatchHandler(
3313
    v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
3314
  LockGuard<Mutex> lock_guard(&dispatch_handler_access_);
3315
  debug_message_dispatch_handler_ = handler;
3316 3317

  if (provide_locker && message_dispatch_helper_thread_ == NULL) {
3318
    message_dispatch_helper_thread_ = new MessageDispatchHelperThread(isolate_);
3319 3320
    message_dispatch_helper_thread_->Start();
  }
3321 3322 3323
}


3324
// Calls the registered debug message handler. This callback is part of the
3325 3326
// public API.
void Debugger::InvokeMessageHandler(MessageImpl message) {
3327
  LockGuard<RecursiveMutex> with(debugger_access_);
3328

3329
  if (message_handler_ != NULL) {
3330
    message_handler_(message);
3331 3332 3333 3334
  }
}


3335 3336 3337
// 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
3338
// by the API client thread.
3339 3340 3341
void Debugger::ProcessCommand(Vector<const uint16_t> command,
                              v8::Debug::ClientData* client_data) {
  // Need to cast away const.
3342
  CommandMessage message = CommandMessage::New(
3343
      Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
3344 3345
                       command.length()),
      client_data);
3346
  isolate_->logger()->DebugTag("Put command on command_queue.");
3347
  command_queue_.Put(message);
3348
  command_received_.Signal();
3349 3350

  // Set the debug command break flag to have the command processed.
3351 3352
  if (!isolate_->debug()->InDebugger()) {
    isolate_->stack_guard()->DebugCommand();
3353
  }
3354

3355 3356
  MessageDispatchHelperThread* dispatch_thread;
  {
3357
    LockGuard<Mutex> lock_guard(&dispatch_handler_access_);
3358 3359 3360 3361 3362 3363 3364
    dispatch_thread = message_dispatch_helper_thread_;
  }

  if (dispatch_thread == NULL) {
    CallMessageDispatchHandler();
  } else {
    dispatch_thread->Schedule();
3365
  }
3366 3367 3368
}


3369 3370 3371 3372 3373
bool Debugger::HasCommands() {
  return !command_queue_.IsEmpty();
}


3374 3375 3376 3377 3378
void Debugger::EnqueueDebugCommand(v8::Debug::ClientData* client_data) {
  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.
3379 3380
  if (!isolate_->debug()->InDebugger()) {
    isolate_->stack_guard()->DebugCommand();
3381 3382 3383 3384
  }
}


3385
bool Debugger::IsDebuggerActive() {
3386
  LockGuard<RecursiveMutex> with(debugger_access_);
3387

3388 3389 3390
  return message_handler_ != NULL ||
      !event_listener_.is_null() ||
      force_debugger_active_;
3391 3392 3393 3394 3395 3396
}


Handle<Object> Debugger::Call(Handle<JSFunction> fun,
                              Handle<Object> data,
                              bool* pending_exception) {
3397 3398 3399
  // When calling functions in the debugger prevent it from beeing unloaded.
  Debugger::never_unload_debugger_ = true;

3400
  // Enter the debugger.
3401
  EnterDebugger debugger(isolate_);
3402
  if (debugger.FailedToEnter()) {
3403
    return isolate_->factory()->undefined_value();
3404 3405 3406 3407 3408 3409
  }

  // Create the execution state.
  bool caught_exception = false;
  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
  if (caught_exception) {
3410
    return isolate_->factory()->undefined_value();
3411 3412
  }

3413
  Handle<Object> argv[] = { exec_state, data };
3414
  Handle<Object> result = Execution::Call(
3415
      isolate_,
3416
      fun,
3417 3418
      Handle<Object>(isolate_->debug()->debug_context_->global_proxy(),
                     isolate_),
3419
      ARRAY_SIZE(argv),
3420 3421
      argv,
      pending_exception);
3422 3423 3424 3425
  return result;
}


3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
static void StubMessageHandler2(const v8::Debug::Message& message) {
  // Simply ignore message.
}


bool Debugger::StartAgent(const char* name, int port,
                          bool wait_for_connection) {
  if (wait_for_connection) {
    // Suspend V8 if it is already running or set V8 to suspend whenever
    // it starts.
    // Provide stub message handler; V8 auto-continues each suspend
    // when there is no message handler; we doesn't need it.
    // Once become suspended, V8 will stay so indefinitely long, until remote
    // debugger connects and issues "continue" command.
    Debugger::message_handler_ = StubMessageHandler2;
    v8::Debug::DebugBreak();
  }

3444 3445 3446
  if (agent_ == NULL) {
    agent_ = new DebuggerAgent(isolate_, name, port);
    agent_->Start();
3447
  }
3448
  return true;
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461
}


void Debugger::StopAgent() {
  if (agent_ != NULL) {
    agent_->Shutdown();
    agent_->Join();
    delete agent_;
    agent_ = NULL;
  }
}


3462 3463 3464 3465 3466
void Debugger::WaitForAgent() {
  if (agent_ != NULL)
    agent_->WaitUntilListening();
}

3467 3468 3469 3470

void Debugger::CallMessageDispatchHandler() {
  v8::Debug::DebugMessageDispatchHandler handler;
  {
3471
    LockGuard<Mutex> lock_guard(&dispatch_handler_access_);
3472 3473 3474 3475 3476 3477 3478 3479
    handler = Debugger::debug_message_dispatch_handler_;
  }
  if (handler != NULL) {
    handler();
  }
}


3480 3481
EnterDebugger::EnterDebugger(Isolate* isolate)
    : isolate_(isolate),
3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
      prev_(isolate_->debug()->debugger_entry()),
      it_(isolate_),
      has_js_frames_(!it_.done()),
      save_(isolate_) {
  Debug* debug = isolate_->debug();
  ASSERT(prev_ != NULL || !debug->is_interrupt_pending(PREEMPT));
  ASSERT(prev_ != NULL || !debug->is_interrupt_pending(DEBUGBREAK));

  // Link recursive debugger entry.
  debug->set_debugger_entry(this);

  // Store the previous break id and frame id.
  break_id_ = debug->break_id();
  break_frame_id_ = debug->break_frame_id();

  // Create the new break info. If there is no JavaScript frames there is no
  // break frame id.
  if (has_js_frames_) {
    debug->NewBreak(it_.frame()->id());
  } else {
    debug->NewBreak(StackFrame::NO_ID);
  }

  // Make sure that debugger is loaded and enter the debugger context.
  load_failed_ = !debug->Load();
  if (!load_failed_) {
    // NOTE the member variable save which saves the previous context before
    // this change.
    isolate_->set_context(*debug->debug_context());
  }
}


EnterDebugger::~EnterDebugger() {
  Debug* debug = isolate_->debug();

  // Restore to the previous break state.
  debug->SetBreak(break_frame_id_, break_id_);

  // Check for leaving the debugger.
3522
  if (!load_failed_ && prev_ == NULL) {
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
    // 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.
    if (!isolate_->has_pending_exception()) {
      // Try to avoid any pending debug break breaking in the clear mirror
      // cache JavaScript code.
      if (isolate_->stack_guard()->IsDebugBreak()) {
        debug->set_interrupts_pending(DEBUGBREAK);
        isolate_->stack_guard()->Continue(DEBUGBREAK);
      }
      debug->ClearMirrorCache();
    }

    // Request preemption and debug break when leaving the last debugger entry
    // if any of these where recorded while debugging.
    if (debug->is_interrupt_pending(PREEMPT)) {
      // This re-scheduling of preemption is to avoid starvation in some
      // debugging scenarios.
      debug->clear_interrupt_pending(PREEMPT);
      isolate_->stack_guard()->Preempt();
    }
    if (debug->is_interrupt_pending(DEBUGBREAK)) {
      debug->clear_interrupt_pending(DEBUGBREAK);
      isolate_->stack_guard()->DebugBreak();
    }

    // If there are commands in the queue when leaving the debugger request
    // that these commands are processed.
    if (isolate_->debugger()->HasCommands()) {
      isolate_->stack_guard()->DebugCommand();
    }

    // If leaving the debugger with the debugger no longer active unload it.
    if (!isolate_->debugger()->IsDebuggerActive()) {
      isolate_->debugger()->UnloadDebugger();
    }
  }

  // Leaving this debugger entry.
  debug->set_debugger_entry(prev_);
}


3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
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_);
}


3630 3631 3632 3633 3634
v8::Isolate* MessageImpl::GetIsolate() const {
  return reinterpret_cast<v8::Isolate*>(exec_state_->GetIsolate());
}


3635 3636 3637 3638 3639 3640
v8::Handle<v8::Object> MessageImpl::GetEventData() const {
  return v8::Utils::ToLocal(event_data_);
}


v8::Handle<v8::String> MessageImpl::GetJSON() const {
3641 3642
  v8::HandleScope scope(
      reinterpret_cast<v8::Isolate*>(event_data_->GetIsolate()));
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664

  if (IsEvent()) {
    // Call toJSONProtocol on the debug event object.
    Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
    if (!fun->IsJSFunction()) {
      return v8::Handle<v8::String>();
    }
    bool caught_exception;
    Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
                                             event_data_,
                                             0, NULL, &caught_exception);
    if (caught_exception || !json->IsString()) {
      return v8::Handle<v8::String>();
    }
    return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
  } else {
    return v8::Utils::ToLocal(response_json_);
  }
}


v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
3665
  Isolate* isolate = event_data_->GetIsolate();
3666 3667
  v8::Handle<v8::Context> context = GetDebugEventContext(isolate);
  // Isolate::context() may be NULL when "script collected" event occures.
3668
  ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
3669
  return context;
3670 3671 3672 3673 3674 3675 3676 3677
}


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


3678 3679 3680
EventDetailsImpl::EventDetailsImpl(DebugEvent event,
                                   Handle<JSObject> exec_state,
                                   Handle<JSObject> event_data,
3681 3682
                                   Handle<Object> callback_data,
                                   v8::Debug::ClientData* client_data)
3683 3684 3685
    : event_(event),
      exec_state_(exec_state),
      event_data_(event_data),
3686 3687
      callback_data_(callback_data),
      client_data_(client_data) {}
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705


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 {
3706
  return GetDebugEventContext(exec_state_->GetIsolate());
3707 3708 3709 3710 3711 3712 3713 3714
}


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


3715 3716 3717 3718 3719
v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
  return client_data_;
}


3720 3721
CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
                                   client_data_(NULL) {
3722 3723 3724
}


3725 3726
CommandMessage::CommandMessage(const Vector<uint16_t>& text,
                               v8::Debug::ClientData* data)
3727
    : text_(text),
3728
      client_data_(data) {
3729 3730 3731
}


3732
CommandMessage::~CommandMessage() {
3733 3734 3735
}


3736
void CommandMessage::Dispose() {
3737 3738 3739 3740 3741 3742
  text_.Dispose();
  delete client_data_;
  client_data_ = NULL;
}


3743 3744 3745
CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
                                   v8::Debug::ClientData* data) {
  return CommandMessage(command.Clone(), data);
3746 3747 3748
}


3749 3750 3751
CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
                                                     size_(size) {
  messages_ = NewArray<CommandMessage>(size);
3752 3753 3754
}


3755
CommandMessageQueue::~CommandMessageQueue() {
3756
  while (!IsEmpty()) {
3757
    CommandMessage m = Get();
3758 3759
    m.Dispose();
  }
3760 3761 3762 3763
  DeleteArray(messages_);
}


3764
CommandMessage CommandMessageQueue::Get() {
3765 3766 3767 3768 3769 3770 3771
  ASSERT(!IsEmpty());
  int result = start_;
  start_ = (start_ + 1) % size_;
  return messages_[result];
}


3772
void CommandMessageQueue::Put(const CommandMessage& message) {
3773 3774 3775 3776 3777 3778 3779 3780
  if ((end_ + 1) % size_ == start_) {
    Expand();
  }
  messages_[end_] = message;
  end_ = (end_ + 1) % size_;
}


3781 3782
void CommandMessageQueue::Expand() {
  CommandMessageQueue new_queue(size_ * 2);
3783 3784
  while (!IsEmpty()) {
    new_queue.Put(Get());
3785
  }
3786
  CommandMessage* array_to_free = messages_;
3787 3788
  *this = new_queue;
  new_queue.messages_ = array_to_free;
3789 3790
  // Make the new_queue empty so that it doesn't call Dispose on any messages.
  new_queue.start_ = new_queue.end_;
3791 3792 3793 3794
  // Automatic destructor called on new_queue, freeing array_to_free.
}


3795
LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size)
3796
    : logger_(logger), queue_(size) {}
3797 3798


3799
bool LockingCommandMessageQueue::IsEmpty() const {
3800
  LockGuard<Mutex> lock_guard(&mutex_);
3801
  return queue_.IsEmpty();
3802 3803
}

3804

3805
CommandMessage LockingCommandMessageQueue::Get() {
3806
  LockGuard<Mutex> lock_guard(&mutex_);
3807
  CommandMessage result = queue_.Get();
3808
  logger_->DebugEvent("Get", result.text());
3809 3810 3811 3812
  return result;
}


3813
void LockingCommandMessageQueue::Put(const CommandMessage& message) {
3814
  LockGuard<Mutex> lock_guard(&mutex_);
3815
  queue_.Put(message);
3816
  logger_->DebugEvent("Put", message.text());
3817 3818 3819
}


3820
void LockingCommandMessageQueue::Clear() {
3821
  LockGuard<Mutex> lock_guard(&mutex_);
3822 3823 3824
  queue_.Clear();
}

3825

3826
MessageDispatchHelperThread::MessageDispatchHelperThread(Isolate* isolate)
3827
    : Thread("v8:MsgDispHelpr"),
3828
      isolate_(isolate), sem_(0),
3829
      already_signalled_(false) {
3830
}
3831 3832 3833 3834


void MessageDispatchHelperThread::Schedule() {
  {
3835
    LockGuard<Mutex> lock_guard(&mutex_);
3836 3837 3838 3839 3840
    if (already_signalled_) {
      return;
    }
    already_signalled_ = true;
  }
3841
  sem_.Signal();
3842 3843 3844 3845 3846
}


void MessageDispatchHelperThread::Run() {
  while (true) {
3847
    sem_.Wait();
3848
    {
3849
      LockGuard<Mutex> lock_guard(&mutex_);
3850 3851 3852
      already_signalled_ = false;
    }
    {
3853 3854
      Locker locker(reinterpret_cast<v8::Isolate*>(isolate_));
      isolate_->debugger()->CallMessageDispatchHandler();
3855 3856 3857 3858
    }
  }
}

3859
#endif  // ENABLE_DEBUGGER_SUPPORT
3860

3861
} }  // namespace v8::internal