debug.cc revision 3fb3ca8c7ca439d408449a395897395c0faae8d1
1// Copyright 2011 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "code-stubs.h"
34#include "codegen.h"
35#include "compilation-cache.h"
36#include "compiler.h"
37#include "debug.h"
38#include "deoptimizer.h"
39#include "execution.h"
40#include "global-handles.h"
41#include "ic.h"
42#include "ic-inl.h"
43#include "messages.h"
44#include "natives.h"
45#include "stub-cache.h"
46#include "log.h"
47
48#include "../include/v8-debug.h"
49
50namespace v8 {
51namespace internal {
52
53#ifdef ENABLE_DEBUGGER_SUPPORT
54
55
56Debug::Debug(Isolate* isolate)
57    : has_break_points_(false),
58      script_cache_(NULL),
59      debug_info_list_(NULL),
60      disable_break_(false),
61      break_on_exception_(false),
62      break_on_uncaught_exception_(false),
63      debug_break_return_(NULL),
64      debug_break_slot_(NULL),
65      isolate_(isolate) {
66  memset(registers_, 0, sizeof(JSCallerSavedBuffer));
67}
68
69
70Debug::~Debug() {
71}
72
73
74static void PrintLn(v8::Local<v8::Value> value) {
75  v8::Local<v8::String> s = value->ToString();
76  ScopedVector<char> data(s->Length() + 1);
77  if (data.start() == NULL) {
78    V8::FatalProcessOutOfMemory("PrintLn");
79    return;
80  }
81  s->WriteAscii(data.start());
82  PrintF("%s\n", data.start());
83}
84
85
86static Handle<Code> ComputeCallDebugBreak(int argc, Code::Kind kind) {
87  Isolate* isolate = Isolate::Current();
88  CALL_HEAP_FUNCTION(
89      isolate,
90      isolate->stub_cache()->ComputeCallDebugBreak(argc, kind),
91      Code);
92}
93
94
95static Handle<Code> ComputeCallDebugPrepareStepIn(int argc, Code::Kind kind) {
96  Isolate* isolate = Isolate::Current();
97  CALL_HEAP_FUNCTION(
98      isolate,
99      isolate->stub_cache()->ComputeCallDebugPrepareStepIn(argc, kind),
100      Code);
101}
102
103
104static v8::Handle<v8::Context> GetDebugEventContext(Isolate* isolate) {
105  Handle<Context> context = isolate->debug()->debugger_entry()->GetContext();
106  // Isolate::context() may have been NULL when "script collected" event
107  // occured.
108  if (context.is_null()) return v8::Local<v8::Context>();
109  Handle<Context> global_context(context->global_context());
110  return v8::Utils::ToLocal(global_context);
111}
112
113
114BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
115                                             BreakLocatorType type) {
116  debug_info_ = debug_info;
117  type_ = type;
118  reloc_iterator_ = NULL;
119  reloc_iterator_original_ = NULL;
120  Reset();  // Initialize the rest of the member variables.
121}
122
123
124BreakLocationIterator::~BreakLocationIterator() {
125  ASSERT(reloc_iterator_ != NULL);
126  ASSERT(reloc_iterator_original_ != NULL);
127  delete reloc_iterator_;
128  delete reloc_iterator_original_;
129}
130
131
132void BreakLocationIterator::Next() {
133  AssertNoAllocation nogc;
134  ASSERT(!RinfoDone());
135
136  // Iterate through reloc info for code and original code stopping at each
137  // breakable code target.
138  bool first = break_point_ == -1;
139  while (!RinfoDone()) {
140    if (!first) RinfoNext();
141    first = false;
142    if (RinfoDone()) return;
143
144    // Whenever a statement position or (plain) position is passed update the
145    // current value of these.
146    if (RelocInfo::IsPosition(rmode())) {
147      if (RelocInfo::IsStatementPosition(rmode())) {
148        statement_position_ = static_cast<int>(
149            rinfo()->data() - debug_info_->shared()->start_position());
150      }
151      // Always update the position as we don't want that to be before the
152      // statement position.
153      position_ = static_cast<int>(
154          rinfo()->data() - debug_info_->shared()->start_position());
155      ASSERT(position_ >= 0);
156      ASSERT(statement_position_ >= 0);
157    }
158
159    if (IsDebugBreakSlot()) {
160      // There is always a possible break point at a debug break slot.
161      break_point_++;
162      return;
163    } else if (RelocInfo::IsCodeTarget(rmode())) {
164      // Check for breakable code target. Look in the original code as setting
165      // break points can cause the code targets in the running (debugged) code
166      // to be of a different kind than in the original code.
167      Address target = original_rinfo()->target_address();
168      Code* code = Code::GetCodeFromTargetAddress(target);
169      if ((code->is_inline_cache_stub() &&
170           !code->is_binary_op_stub() &&
171           !code->is_unary_op_stub() &&
172           !code->is_compare_ic_stub()) ||
173          RelocInfo::IsConstructCall(rmode())) {
174        break_point_++;
175        return;
176      }
177      if (code->kind() == Code::STUB) {
178        if (IsDebuggerStatement()) {
179          break_point_++;
180          return;
181        }
182        if (type_ == ALL_BREAK_LOCATIONS) {
183          if (Debug::IsBreakStub(code)) {
184            break_point_++;
185            return;
186          }
187        } else {
188          ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
189          if (Debug::IsSourceBreakStub(code)) {
190            break_point_++;
191            return;
192          }
193        }
194      }
195    }
196
197    // Check for break at return.
198    if (RelocInfo::IsJSReturn(rmode())) {
199      // Set the positions to the end of the function.
200      if (debug_info_->shared()->HasSourceCode()) {
201        position_ = debug_info_->shared()->end_position() -
202                    debug_info_->shared()->start_position() - 1;
203      } else {
204        position_ = 0;
205      }
206      statement_position_ = position_;
207      break_point_++;
208      return;
209    }
210  }
211}
212
213
214void BreakLocationIterator::Next(int count) {
215  while (count > 0) {
216    Next();
217    count--;
218  }
219}
220
221
222// Find the break point closest to the supplied address.
223void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
224  // Run through all break points to locate the one closest to the address.
225  int closest_break_point = 0;
226  int distance = kMaxInt;
227  while (!Done()) {
228    // Check if this break point is closer that what was previously found.
229    if (this->pc() < pc && pc - this->pc() < distance) {
230      closest_break_point = break_point();
231      distance = static_cast<int>(pc - this->pc());
232      // Check whether we can't get any closer.
233      if (distance == 0) break;
234    }
235    Next();
236  }
237
238  // Move to the break point found.
239  Reset();
240  Next(closest_break_point);
241}
242
243
244// Find the break point closest to the supplied source position.
245void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
246  // Run through all break points to locate the one closest to the source
247  // position.
248  int closest_break_point = 0;
249  int distance = kMaxInt;
250  while (!Done()) {
251    // Check if this break point is closer that what was previously found.
252    if (position <= statement_position() &&
253        statement_position() - position < distance) {
254      closest_break_point = break_point();
255      distance = statement_position() - position;
256      // Check whether we can't get any closer.
257      if (distance == 0) break;
258    }
259    Next();
260  }
261
262  // Move to the break point found.
263  Reset();
264  Next(closest_break_point);
265}
266
267
268void BreakLocationIterator::Reset() {
269  // Create relocation iterators for the two code objects.
270  if (reloc_iterator_ != NULL) delete reloc_iterator_;
271  if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
272  reloc_iterator_ = new RelocIterator(debug_info_->code());
273  reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
274
275  // Position at the first break point.
276  break_point_ = -1;
277  position_ = 1;
278  statement_position_ = 1;
279  Next();
280}
281
282
283bool BreakLocationIterator::Done() const {
284  return RinfoDone();
285}
286
287
288void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
289  // If there is not already a real break point here patch code with debug
290  // break.
291  if (!HasBreakPoint()) {
292    SetDebugBreak();
293  }
294  ASSERT(IsDebugBreak() || IsDebuggerStatement());
295  // Set the break point information.
296  DebugInfo::SetBreakPoint(debug_info_, code_position(),
297                           position(), statement_position(),
298                           break_point_object);
299}
300
301
302void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
303  // Clear the break point information.
304  DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
305  // If there are no more break points here remove the debug break.
306  if (!HasBreakPoint()) {
307    ClearDebugBreak();
308    ASSERT(!IsDebugBreak());
309  }
310}
311
312
313void BreakLocationIterator::SetOneShot() {
314  // Debugger statement always calls debugger. No need to modify it.
315  if (IsDebuggerStatement()) {
316    return;
317  }
318
319  // If there is a real break point here no more to do.
320  if (HasBreakPoint()) {
321    ASSERT(IsDebugBreak());
322    return;
323  }
324
325  // Patch code with debug break.
326  SetDebugBreak();
327}
328
329
330void BreakLocationIterator::ClearOneShot() {
331  // Debugger statement always calls debugger. No need to modify it.
332  if (IsDebuggerStatement()) {
333    return;
334  }
335
336  // If there is a real break point here no more to do.
337  if (HasBreakPoint()) {
338    ASSERT(IsDebugBreak());
339    return;
340  }
341
342  // Patch code removing debug break.
343  ClearDebugBreak();
344  ASSERT(!IsDebugBreak());
345}
346
347
348void BreakLocationIterator::SetDebugBreak() {
349  // Debugger statement always calls debugger. No need to modify it.
350  if (IsDebuggerStatement()) {
351    return;
352  }
353
354  // If there is already a break point here just return. This might happen if
355  // the same code is flooded with break points twice. Flooding the same
356  // function twice might happen when stepping in a function with an exception
357  // handler as the handler and the function is the same.
358  if (IsDebugBreak()) {
359    return;
360  }
361
362  if (RelocInfo::IsJSReturn(rmode())) {
363    // Patch the frame exit code with a break point.
364    SetDebugBreakAtReturn();
365  } else if (IsDebugBreakSlot()) {
366    // Patch the code in the break slot.
367    SetDebugBreakAtSlot();
368  } else {
369    // Patch the IC call.
370    SetDebugBreakAtIC();
371  }
372  ASSERT(IsDebugBreak());
373}
374
375
376void BreakLocationIterator::ClearDebugBreak() {
377  // Debugger statement always calls debugger. No need to modify it.
378  if (IsDebuggerStatement()) {
379    return;
380  }
381
382  if (RelocInfo::IsJSReturn(rmode())) {
383    // Restore the frame exit code.
384    ClearDebugBreakAtReturn();
385  } else if (IsDebugBreakSlot()) {
386    // Restore the code in the break slot.
387    ClearDebugBreakAtSlot();
388  } else {
389    // Patch the IC call.
390    ClearDebugBreakAtIC();
391  }
392  ASSERT(!IsDebugBreak());
393}
394
395
396void BreakLocationIterator::PrepareStepIn() {
397  HandleScope scope;
398
399  // Step in can only be prepared if currently positioned on an IC call,
400  // construct call or CallFunction stub call.
401  Address target = rinfo()->target_address();
402  Handle<Code> code(Code::GetCodeFromTargetAddress(target));
403  if (code->is_call_stub() || code->is_keyed_call_stub()) {
404    // Step in through IC call is handled by the runtime system. Therefore make
405    // sure that the any current IC is cleared and the runtime system is
406    // called. If the executing code has a debug break at the location change
407    // the call in the original code as it is the code there that will be
408    // executed in place of the debug break call.
409    Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count(),
410                                                      code->kind());
411    if (IsDebugBreak()) {
412      original_rinfo()->set_target_address(stub->entry());
413    } else {
414      rinfo()->set_target_address(stub->entry());
415    }
416  } else {
417#ifdef DEBUG
418    // All the following stuff is needed only for assertion checks so the code
419    // is wrapped in ifdef.
420    Handle<Code> maybe_call_function_stub = code;
421    if (IsDebugBreak()) {
422      Address original_target = original_rinfo()->target_address();
423      maybe_call_function_stub =
424          Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
425    }
426    bool is_call_function_stub =
427        (maybe_call_function_stub->kind() == Code::STUB &&
428         maybe_call_function_stub->major_key() == CodeStub::CallFunction);
429
430    // Step in through construct call requires no changes to the running code.
431    // Step in through getters/setters should already be prepared as well
432    // because caller of this function (Debug::PrepareStep) is expected to
433    // flood the top frame's function with one shot breakpoints.
434    // Step in through CallFunction stub should also be prepared by caller of
435    // this function (Debug::PrepareStep) which should flood target function
436    // with breakpoints.
437    ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
438           || is_call_function_stub);
439#endif
440  }
441}
442
443
444// Check whether the break point is at a position which will exit the function.
445bool BreakLocationIterator::IsExit() const {
446  return (RelocInfo::IsJSReturn(rmode()));
447}
448
449
450bool BreakLocationIterator::HasBreakPoint() {
451  return debug_info_->HasBreakPoint(code_position());
452}
453
454
455// Check whether there is a debug break at the current position.
456bool BreakLocationIterator::IsDebugBreak() {
457  if (RelocInfo::IsJSReturn(rmode())) {
458    return IsDebugBreakAtReturn();
459  } else if (IsDebugBreakSlot()) {
460    return IsDebugBreakAtSlot();
461  } else {
462    return Debug::IsDebugBreak(rinfo()->target_address());
463  }
464}
465
466
467void BreakLocationIterator::SetDebugBreakAtIC() {
468  // Patch the original code with the current address as the current address
469  // might have changed by the inline caching since the code was copied.
470  original_rinfo()->set_target_address(rinfo()->target_address());
471
472  RelocInfo::Mode mode = rmode();
473  if (RelocInfo::IsCodeTarget(mode)) {
474    Address target = rinfo()->target_address();
475    Handle<Code> code(Code::GetCodeFromTargetAddress(target));
476
477    // Patch the code to invoke the builtin debug break function matching the
478    // calling convention used by the call site.
479    Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
480    rinfo()->set_target_address(dbgbrk_code->entry());
481  }
482}
483
484
485void BreakLocationIterator::ClearDebugBreakAtIC() {
486  // Patch the code to the original invoke.
487  rinfo()->set_target_address(original_rinfo()->target_address());
488}
489
490
491bool BreakLocationIterator::IsDebuggerStatement() {
492  return RelocInfo::DEBUG_BREAK == rmode();
493}
494
495
496bool BreakLocationIterator::IsDebugBreakSlot() {
497  return RelocInfo::DEBUG_BREAK_SLOT == rmode();
498}
499
500
501Object* BreakLocationIterator::BreakPointObjects() {
502  return debug_info_->GetBreakPointObjects(code_position());
503}
504
505
506// Clear out all the debug break code. This is ONLY supposed to be used when
507// shutting down the debugger as it will leave the break point information in
508// DebugInfo even though the code is patched back to the non break point state.
509void BreakLocationIterator::ClearAllDebugBreak() {
510  while (!Done()) {
511    ClearDebugBreak();
512    Next();
513  }
514}
515
516
517bool BreakLocationIterator::RinfoDone() const {
518  ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
519  return reloc_iterator_->done();
520}
521
522
523void BreakLocationIterator::RinfoNext() {
524  reloc_iterator_->next();
525  reloc_iterator_original_->next();
526#ifdef DEBUG
527  ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
528  if (!reloc_iterator_->done()) {
529    ASSERT(rmode() == original_rmode());
530  }
531#endif
532}
533
534
535// Threading support.
536void Debug::ThreadInit() {
537  thread_local_.break_count_ = 0;
538  thread_local_.break_id_ = 0;
539  thread_local_.break_frame_id_ = StackFrame::NO_ID;
540  thread_local_.last_step_action_ = StepNone;
541  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
542  thread_local_.step_count_ = 0;
543  thread_local_.last_fp_ = 0;
544  thread_local_.step_into_fp_ = 0;
545  thread_local_.step_out_fp_ = 0;
546  thread_local_.after_break_target_ = 0;
547  // TODO(isolates): frames_are_dropped_?
548  thread_local_.debugger_entry_ = NULL;
549  thread_local_.pending_interrupts_ = 0;
550  thread_local_.restarter_frame_function_pointer_ = NULL;
551}
552
553
554char* Debug::ArchiveDebug(char* storage) {
555  char* to = storage;
556  memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
557  to += sizeof(ThreadLocal);
558  memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
559  ThreadInit();
560  ASSERT(to <= storage + ArchiveSpacePerThread());
561  return storage + ArchiveSpacePerThread();
562}
563
564
565char* Debug::RestoreDebug(char* storage) {
566  char* from = storage;
567  memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
568  from += sizeof(ThreadLocal);
569  memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
570  ASSERT(from <= storage + ArchiveSpacePerThread());
571  return storage + ArchiveSpacePerThread();
572}
573
574
575int Debug::ArchiveSpacePerThread() {
576  return sizeof(ThreadLocal) + sizeof(JSCallerSavedBuffer);
577}
578
579
580// Frame structure (conforms InternalFrame structure):
581//   -- code
582//   -- SMI maker
583//   -- function (slot is called "context")
584//   -- frame base
585Object** Debug::SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
586                                       Handle<Code> code) {
587  ASSERT(bottom_js_frame->is_java_script());
588
589  Address fp = bottom_js_frame->fp();
590
591  // Move function pointer into "context" slot.
592  Memory::Object_at(fp + StandardFrameConstants::kContextOffset) =
593      Memory::Object_at(fp + JavaScriptFrameConstants::kFunctionOffset);
594
595  Memory::Object_at(fp + InternalFrameConstants::kCodeOffset) = *code;
596  Memory::Object_at(fp + StandardFrameConstants::kMarkerOffset) =
597      Smi::FromInt(StackFrame::INTERNAL);
598
599  return reinterpret_cast<Object**>(&Memory::Object_at(
600      fp + StandardFrameConstants::kContextOffset));
601}
602
603const int Debug::kFrameDropperFrameSize = 4;
604
605
606void ScriptCache::Add(Handle<Script> script) {
607  GlobalHandles* global_handles = Isolate::Current()->global_handles();
608  // Create an entry in the hash map for the script.
609  int id = Smi::cast(script->id())->value();
610  HashMap::Entry* entry =
611      HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
612  if (entry->value != NULL) {
613    ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
614    return;
615  }
616
617  // Globalize the script object, make it weak and use the location of the
618  // global handle as the value in the hash map.
619  Handle<Script> script_ =
620      Handle<Script>::cast(
621          (global_handles->Create(*script)));
622  global_handles->MakeWeak(
623      reinterpret_cast<Object**>(script_.location()),
624      this,
625      ScriptCache::HandleWeakScript);
626  entry->value = script_.location();
627}
628
629
630Handle<FixedArray> ScriptCache::GetScripts() {
631  Handle<FixedArray> instances = FACTORY->NewFixedArray(occupancy());
632  int count = 0;
633  for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
634    ASSERT(entry->value != NULL);
635    if (entry->value != NULL) {
636      instances->set(count, *reinterpret_cast<Script**>(entry->value));
637      count++;
638    }
639  }
640  return instances;
641}
642
643
644void ScriptCache::ProcessCollectedScripts() {
645  Debugger* debugger = Isolate::Current()->debugger();
646  for (int i = 0; i < collected_scripts_.length(); i++) {
647    debugger->OnScriptCollected(collected_scripts_[i]);
648  }
649  collected_scripts_.Clear();
650}
651
652
653void ScriptCache::Clear() {
654  GlobalHandles* global_handles = Isolate::Current()->global_handles();
655  // Iterate the script cache to get rid of all the weak handles.
656  for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
657    ASSERT(entry != NULL);
658    Object** location = reinterpret_cast<Object**>(entry->value);
659    ASSERT((*location)->IsScript());
660    global_handles->ClearWeakness(location);
661    global_handles->Destroy(location);
662  }
663  // Clear the content of the hash map.
664  HashMap::Clear();
665}
666
667
668void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
669  ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
670  // Find the location of the global handle.
671  Script** location =
672      reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
673  ASSERT((*location)->IsScript());
674
675  // Remove the entry from the cache.
676  int id = Smi::cast((*location)->id())->value();
677  script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
678  script_cache->collected_scripts_.Add(id);
679
680  // Clear the weak handle.
681  obj.Dispose();
682  obj.Clear();
683}
684
685
686void Debug::Setup(bool create_heap_objects) {
687  ThreadInit();
688  if (create_heap_objects) {
689    // Get code to handle debug break on return.
690    debug_break_return_ =
691        isolate_->builtins()->builtin(Builtins::kReturn_DebugBreak);
692    ASSERT(debug_break_return_->IsCode());
693    // Get code to handle debug break in debug break slots.
694    debug_break_slot_ =
695        isolate_->builtins()->builtin(Builtins::kSlot_DebugBreak);
696    ASSERT(debug_break_slot_->IsCode());
697  }
698}
699
700
701void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
702  Debug* debug = Isolate::Current()->debug();
703  DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
704  // We need to clear all breakpoints associated with the function to restore
705  // original code and avoid patching the code twice later because
706  // the function will live in the heap until next gc, and can be found by
707  // Runtime::FindSharedFunctionInfoInScript.
708  BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
709  it.ClearAllDebugBreak();
710  debug->RemoveDebugInfo(node->debug_info());
711#ifdef DEBUG
712  node = debug->debug_info_list_;
713  while (node != NULL) {
714    ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
715    node = node->next();
716  }
717#endif
718}
719
720
721DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
722  GlobalHandles* global_handles = Isolate::Current()->global_handles();
723  // Globalize the request debug info object and make it weak.
724  debug_info_ = Handle<DebugInfo>::cast(
725      (global_handles->Create(debug_info)));
726  global_handles->MakeWeak(
727      reinterpret_cast<Object**>(debug_info_.location()),
728      this,
729      Debug::HandleWeakDebugInfo);
730}
731
732
733DebugInfoListNode::~DebugInfoListNode() {
734  Isolate::Current()->global_handles()->Destroy(
735      reinterpret_cast<Object**>(debug_info_.location()));
736}
737
738
739bool Debug::CompileDebuggerScript(int index) {
740  Isolate* isolate = Isolate::Current();
741  Factory* factory = isolate->factory();
742  HandleScope scope(isolate);
743
744  // Bail out if the index is invalid.
745  if (index == -1) {
746    return false;
747  }
748
749  // Find source and name for the requested script.
750  Handle<String> source_code =
751      isolate->bootstrapper()->NativesSourceLookup(index);
752  Vector<const char> name = Natives::GetScriptName(index);
753  Handle<String> script_name = factory->NewStringFromAscii(name);
754
755  // Compile the script.
756  Handle<SharedFunctionInfo> function_info;
757  function_info = Compiler::Compile(source_code,
758                                    script_name,
759                                    0, 0, NULL, NULL,
760                                    Handle<String>::null(),
761                                    NATIVES_CODE);
762
763  // Silently ignore stack overflows during compilation.
764  if (function_info.is_null()) {
765    ASSERT(isolate->has_pending_exception());
766    isolate->clear_pending_exception();
767    return false;
768  }
769
770  // Execute the shared function in the debugger context.
771  Handle<Context> context = isolate->global_context();
772  bool caught_exception = false;
773  Handle<JSFunction> function =
774      factory->NewFunctionFromSharedFunctionInfo(function_info, context);
775
776  Execution::TryCall(function, Handle<Object>(context->global()),
777                     0, NULL, &caught_exception);
778
779  // Check for caught exceptions.
780  if (caught_exception) {
781    Handle<Object> message = MessageHandler::MakeMessageObject(
782        "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
783        Handle<String>(), Handle<JSArray>());
784    MessageHandler::ReportMessage(Isolate::Current(), NULL, message);
785    return false;
786  }
787
788  // Mark this script as native and return successfully.
789  Handle<Script> script(Script::cast(function->shared()->script()));
790  script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
791  return true;
792}
793
794
795bool Debug::Load() {
796  // Return if debugger is already loaded.
797  if (IsLoaded()) return true;
798
799  Debugger* debugger = isolate_->debugger();
800
801  // Bail out if we're already in the process of compiling the native
802  // JavaScript source code for the debugger.
803  if (debugger->compiling_natives() ||
804      debugger->is_loading_debugger())
805    return false;
806  debugger->set_loading_debugger(true);
807
808  // Disable breakpoints and interrupts while compiling and running the
809  // debugger scripts including the context creation code.
810  DisableBreak disable(true);
811  PostponeInterruptsScope postpone(isolate_);
812
813  // Create the debugger context.
814  HandleScope scope(isolate_);
815  Handle<Context> context =
816      isolate_->bootstrapper()->CreateEnvironment(
817          isolate_,
818          Handle<Object>::null(),
819          v8::Handle<ObjectTemplate>(),
820          NULL);
821
822  // Use the debugger context.
823  SaveContext save(isolate_);
824  isolate_->set_context(*context);
825
826  // Expose the builtins object in the debugger context.
827  Handle<String> key = isolate_->factory()->LookupAsciiSymbol("builtins");
828  Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
829  RETURN_IF_EMPTY_HANDLE_VALUE(
830      isolate_,
831      SetProperty(global, key, Handle<Object>(global->builtins()),
832                  NONE, kNonStrictMode),
833      false);
834
835  // Compile the JavaScript for the debugger in the debugger context.
836  debugger->set_compiling_natives(true);
837  bool caught_exception =
838      !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
839      !CompileDebuggerScript(Natives::GetIndex("debug"));
840
841  if (FLAG_enable_liveedit) {
842    caught_exception = caught_exception ||
843        !CompileDebuggerScript(Natives::GetIndex("liveedit"));
844  }
845
846  debugger->set_compiling_natives(false);
847
848  // Make sure we mark the debugger as not loading before we might
849  // return.
850  debugger->set_loading_debugger(false);
851
852  // Check for caught exceptions.
853  if (caught_exception) return false;
854
855  // Debugger loaded.
856  debug_context_ = context;
857
858  return true;
859}
860
861
862void Debug::Unload() {
863  // Return debugger is not loaded.
864  if (!IsLoaded()) {
865    return;
866  }
867
868  // Clear the script cache.
869  DestroyScriptCache();
870
871  // Clear debugger context global handle.
872  Isolate::Current()->global_handles()->Destroy(
873      reinterpret_cast<Object**>(debug_context_.location()));
874  debug_context_ = Handle<Context>();
875}
876
877
878// Set the flag indicating that preemption happened during debugging.
879void Debug::PreemptionWhileInDebugger() {
880  ASSERT(InDebugger());
881  Debug::set_interrupts_pending(PREEMPT);
882}
883
884
885void Debug::Iterate(ObjectVisitor* v) {
886  v->VisitPointer(BitCast<Object**>(&(debug_break_return_)));
887  v->VisitPointer(BitCast<Object**>(&(debug_break_slot_)));
888}
889
890
891Object* Debug::Break(Arguments args) {
892  Heap* heap = isolate_->heap();
893  HandleScope scope(isolate_);
894  ASSERT(args.length() == 0);
895
896  thread_local_.frame_drop_mode_ = FRAMES_UNTOUCHED;
897
898  // Get the top-most JavaScript frame.
899  JavaScriptFrameIterator it(isolate_);
900  JavaScriptFrame* frame = it.frame();
901
902  // Just continue if breaks are disabled or debugger cannot be loaded.
903  if (disable_break() || !Load()) {
904    SetAfterBreakTarget(frame);
905    return heap->undefined_value();
906  }
907
908  // Enter the debugger.
909  EnterDebugger debugger;
910  if (debugger.FailedToEnter()) {
911    return heap->undefined_value();
912  }
913
914  // Postpone interrupt during breakpoint processing.
915  PostponeInterruptsScope postpone(isolate_);
916
917  // Get the debug info (create it if it does not exist).
918  Handle<SharedFunctionInfo> shared =
919      Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
920  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
921
922  // Find the break point where execution has stopped.
923  BreakLocationIterator break_location_iterator(debug_info,
924                                                ALL_BREAK_LOCATIONS);
925  break_location_iterator.FindBreakLocationFromAddress(frame->pc());
926
927  // Check whether step next reached a new statement.
928  if (!StepNextContinue(&break_location_iterator, frame)) {
929    // Decrease steps left if performing multiple steps.
930    if (thread_local_.step_count_ > 0) {
931      thread_local_.step_count_--;
932    }
933  }
934
935  // If there is one or more real break points check whether any of these are
936  // triggered.
937  Handle<Object> break_points_hit(heap->undefined_value());
938  if (break_location_iterator.HasBreakPoint()) {
939    Handle<Object> break_point_objects =
940        Handle<Object>(break_location_iterator.BreakPointObjects());
941    break_points_hit = CheckBreakPoints(break_point_objects);
942  }
943
944  // If step out is active skip everything until the frame where we need to step
945  // out to is reached, unless real breakpoint is hit.
946  if (StepOutActive() && frame->fp() != step_out_fp() &&
947      break_points_hit->IsUndefined() ) {
948      // Step count should always be 0 for StepOut.
949      ASSERT(thread_local_.step_count_ == 0);
950  } else if (!break_points_hit->IsUndefined() ||
951             (thread_local_.last_step_action_ != StepNone &&
952              thread_local_.step_count_ == 0)) {
953    // Notify debugger if a real break point is triggered or if performing
954    // single stepping with no more steps to perform. Otherwise do another step.
955
956    // Clear all current stepping setup.
957    ClearStepping();
958
959    // Notify the debug event listeners.
960    isolate_->debugger()->OnDebugBreak(break_points_hit, false);
961  } else if (thread_local_.last_step_action_ != StepNone) {
962    // Hold on to last step action as it is cleared by the call to
963    // ClearStepping.
964    StepAction step_action = thread_local_.last_step_action_;
965    int step_count = thread_local_.step_count_;
966
967    // Clear all current stepping setup.
968    ClearStepping();
969
970    // Set up for the remaining steps.
971    PrepareStep(step_action, step_count);
972  }
973
974  if (thread_local_.frame_drop_mode_ == FRAMES_UNTOUCHED) {
975    SetAfterBreakTarget(frame);
976  } else if (thread_local_.frame_drop_mode_ ==
977      FRAME_DROPPED_IN_IC_CALL) {
978    // We must have been calling IC stub. Do not go there anymore.
979    Code* plain_return = isolate_->builtins()->builtin(
980        Builtins::kPlainReturn_LiveEdit);
981    thread_local_.after_break_target_ = plain_return->entry();
982  } else if (thread_local_.frame_drop_mode_ ==
983      FRAME_DROPPED_IN_DEBUG_SLOT_CALL) {
984    // Debug break slot stub does not return normally, instead it manually
985    // cleans the stack and jumps. We should patch the jump address.
986    Code* plain_return = isolate_->builtins()->builtin(
987        Builtins::kFrameDropper_LiveEdit);
988    thread_local_.after_break_target_ = plain_return->entry();
989  } else if (thread_local_.frame_drop_mode_ ==
990      FRAME_DROPPED_IN_DIRECT_CALL) {
991    // Nothing to do, after_break_target is not used here.
992  } else if (thread_local_.frame_drop_mode_ ==
993      FRAME_DROPPED_IN_RETURN_CALL) {
994    Code* plain_return = isolate_->builtins()->builtin(
995        Builtins::kFrameDropper_LiveEdit);
996    thread_local_.after_break_target_ = plain_return->entry();
997  } else {
998    UNREACHABLE();
999  }
1000
1001  return heap->undefined_value();
1002}
1003
1004
1005RUNTIME_FUNCTION(Object*, Debug_Break) {
1006  return isolate->debug()->Break(args);
1007}
1008
1009
1010// Check the break point objects for whether one or more are actually
1011// triggered. This function returns a JSArray with the break point objects
1012// which is triggered.
1013Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
1014  Factory* factory = isolate_->factory();
1015
1016  // Count the number of break points hit. If there are multiple break points
1017  // they are in a FixedArray.
1018  Handle<FixedArray> break_points_hit;
1019  int break_points_hit_count = 0;
1020  ASSERT(!break_point_objects->IsUndefined());
1021  if (break_point_objects->IsFixedArray()) {
1022    Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
1023    break_points_hit = factory->NewFixedArray(array->length());
1024    for (int i = 0; i < array->length(); i++) {
1025      Handle<Object> o(array->get(i));
1026      if (CheckBreakPoint(o)) {
1027        break_points_hit->set(break_points_hit_count++, *o);
1028      }
1029    }
1030  } else {
1031    break_points_hit = factory->NewFixedArray(1);
1032    if (CheckBreakPoint(break_point_objects)) {
1033      break_points_hit->set(break_points_hit_count++, *break_point_objects);
1034    }
1035  }
1036
1037  // Return undefined if no break points were triggered.
1038  if (break_points_hit_count == 0) {
1039    return factory->undefined_value();
1040  }
1041  // Return break points hit as a JSArray.
1042  Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit);
1043  result->set_length(Smi::FromInt(break_points_hit_count));
1044  return result;
1045}
1046
1047
1048// Check whether a single break point object is triggered.
1049bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
1050  Factory* factory = isolate_->factory();
1051  HandleScope scope(isolate_);
1052
1053  // Ignore check if break point object is not a JSObject.
1054  if (!break_point_object->IsJSObject()) return true;
1055
1056  // Get the function IsBreakPointTriggered (defined in debug-debugger.js).
1057  Handle<String> is_break_point_triggered_symbol =
1058      factory->LookupAsciiSymbol("IsBreakPointTriggered");
1059  Handle<JSFunction> check_break_point =
1060    Handle<JSFunction>(JSFunction::cast(
1061        debug_context()->global()->GetPropertyNoExceptionThrown(
1062            *is_break_point_triggered_symbol)));
1063
1064  // Get the break id as an object.
1065  Handle<Object> break_id = factory->NewNumberFromInt(Debug::break_id());
1066
1067  // Call HandleBreakPointx.
1068  bool caught_exception = false;
1069  const int argc = 2;
1070  Object** argv[argc] = {
1071    break_id.location(),
1072    reinterpret_cast<Object**>(break_point_object.location())
1073  };
1074  Handle<Object> result = Execution::TryCall(check_break_point,
1075      isolate_->js_builtins_object(), argc, argv, &caught_exception);
1076
1077  // If exception or non boolean result handle as not triggered
1078  if (caught_exception || !result->IsBoolean()) {
1079    return false;
1080  }
1081
1082  // Return whether the break point is triggered.
1083  ASSERT(!result.is_null());
1084  return (*result)->IsTrue();
1085}
1086
1087
1088// Check whether the function has debug information.
1089bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
1090  return !shared->debug_info()->IsUndefined();
1091}
1092
1093
1094// Return the debug info for this function. EnsureDebugInfo must be called
1095// prior to ensure the debug info has been generated for shared.
1096Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
1097  ASSERT(HasDebugInfo(shared));
1098  return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
1099}
1100
1101
1102void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
1103                          Handle<Object> break_point_object,
1104                          int* source_position) {
1105  HandleScope scope(isolate_);
1106
1107  if (!EnsureDebugInfo(shared)) {
1108    // Return if retrieving debug info failed.
1109    return;
1110  }
1111
1112  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1113  // Source positions starts with zero.
1114  ASSERT(source_position >= 0);
1115
1116  // Find the break point and change it.
1117  BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1118  it.FindBreakLocationFromPosition(*source_position);
1119  it.SetBreakPoint(break_point_object);
1120
1121  *source_position = it.position();
1122
1123  // At least one active break point now.
1124  ASSERT(debug_info->GetBreakPointCount() > 0);
1125}
1126
1127
1128void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
1129  HandleScope scope(isolate_);
1130
1131  DebugInfoListNode* node = debug_info_list_;
1132  while (node != NULL) {
1133    Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1134                                                   break_point_object);
1135    if (!result->IsUndefined()) {
1136      // Get information in the break point.
1137      BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1138      Handle<DebugInfo> debug_info = node->debug_info();
1139      Handle<SharedFunctionInfo> shared(debug_info->shared());
1140      int source_position =  break_point_info->statement_position()->value();
1141
1142      // Source positions starts with zero.
1143      ASSERT(source_position >= 0);
1144
1145      // Find the break point and clear it.
1146      BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1147      it.FindBreakLocationFromPosition(source_position);
1148      it.ClearBreakPoint(break_point_object);
1149
1150      // If there are no more break points left remove the debug info for this
1151      // function.
1152      if (debug_info->GetBreakPointCount() == 0) {
1153        RemoveDebugInfo(debug_info);
1154      }
1155
1156      return;
1157    }
1158    node = node->next();
1159  }
1160}
1161
1162
1163void Debug::ClearAllBreakPoints() {
1164  DebugInfoListNode* node = debug_info_list_;
1165  while (node != NULL) {
1166    // Remove all debug break code.
1167    BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1168    it.ClearAllDebugBreak();
1169    node = node->next();
1170  }
1171
1172  // Remove all debug info.
1173  while (debug_info_list_ != NULL) {
1174    RemoveDebugInfo(debug_info_list_->debug_info());
1175  }
1176}
1177
1178
1179void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
1180  // Make sure the function has setup the debug info.
1181  if (!EnsureDebugInfo(shared)) {
1182    // Return if we failed to retrieve the debug info.
1183    return;
1184  }
1185
1186  // Flood the function with break points.
1187  BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
1188  while (!it.Done()) {
1189    it.SetOneShot();
1190    it.Next();
1191  }
1192}
1193
1194
1195void Debug::FloodHandlerWithOneShot() {
1196  // Iterate through the JavaScript stack looking for handlers.
1197  StackFrame::Id id = break_frame_id();
1198  if (id == StackFrame::NO_ID) {
1199    // If there is no JavaScript stack don't do anything.
1200    return;
1201  }
1202  for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) {
1203    JavaScriptFrame* frame = it.frame();
1204    if (frame->HasHandler()) {
1205      Handle<SharedFunctionInfo> shared =
1206          Handle<SharedFunctionInfo>(
1207              JSFunction::cast(frame->function())->shared());
1208      // Flood the function with the catch block with break points
1209      FloodWithOneShot(shared);
1210      return;
1211    }
1212  }
1213}
1214
1215
1216void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1217  if (type == BreakUncaughtException) {
1218    break_on_uncaught_exception_ = enable;
1219  } else {
1220    break_on_exception_ = enable;
1221  }
1222}
1223
1224
1225bool Debug::IsBreakOnException(ExceptionBreakType type) {
1226  if (type == BreakUncaughtException) {
1227    return break_on_uncaught_exception_;
1228  } else {
1229    return break_on_exception_;
1230  }
1231}
1232
1233
1234void Debug::PrepareStep(StepAction step_action, int step_count) {
1235  HandleScope scope(isolate_);
1236  ASSERT(Debug::InDebugger());
1237
1238  // Remember this step action and count.
1239  thread_local_.last_step_action_ = step_action;
1240  if (step_action == StepOut) {
1241    // For step out target frame will be found on the stack so there is no need
1242    // to set step counter for it. It's expected to always be 0 for StepOut.
1243    thread_local_.step_count_ = 0;
1244  } else {
1245    thread_local_.step_count_ = step_count;
1246  }
1247
1248  // Get the frame where the execution has stopped and skip the debug frame if
1249  // any. The debug frame will only be present if execution was stopped due to
1250  // hitting a break point. In other situations (e.g. unhandled exception) the
1251  // debug frame is not present.
1252  StackFrame::Id id = break_frame_id();
1253  if (id == StackFrame::NO_ID) {
1254    // If there is no JavaScript stack don't do anything.
1255    return;
1256  }
1257  JavaScriptFrameIterator frames_it(isolate_, id);
1258  JavaScriptFrame* frame = frames_it.frame();
1259
1260  // First of all ensure there is one-shot break points in the top handler
1261  // if any.
1262  FloodHandlerWithOneShot();
1263
1264  // If the function on the top frame is unresolved perform step out. This will
1265  // be the case when calling unknown functions and having the debugger stopped
1266  // in an unhandled exception.
1267  if (!frame->function()->IsJSFunction()) {
1268    // Step out: Find the calling JavaScript frame and flood it with
1269    // breakpoints.
1270    frames_it.Advance();
1271    // Fill the function to return to with one-shot break points.
1272    JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1273    FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1274    return;
1275  }
1276
1277  // Get the debug info (create it if it does not exist).
1278  Handle<SharedFunctionInfo> shared =
1279      Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1280  if (!EnsureDebugInfo(shared)) {
1281    // Return if ensuring debug info failed.
1282    return;
1283  }
1284  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1285
1286  // Find the break location where execution has stopped.
1287  BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1288  it.FindBreakLocationFromAddress(frame->pc());
1289
1290  // Compute whether or not the target is a call target.
1291  bool is_load_or_store = false;
1292  bool is_inline_cache_stub = false;
1293  bool is_at_restarted_function = false;
1294  Handle<Code> call_function_stub;
1295
1296  if (thread_local_.restarter_frame_function_pointer_ == NULL) {
1297    if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
1298      bool is_call_target = false;
1299      Address target = it.rinfo()->target_address();
1300      Code* code = Code::GetCodeFromTargetAddress(target);
1301      if (code->is_call_stub() || code->is_keyed_call_stub()) {
1302        is_call_target = true;
1303      }
1304      if (code->is_inline_cache_stub()) {
1305        is_inline_cache_stub = true;
1306        is_load_or_store = !is_call_target;
1307      }
1308
1309      // Check if target code is CallFunction stub.
1310      Code* maybe_call_function_stub = code;
1311      // If there is a breakpoint at this line look at the original code to
1312      // check if it is a CallFunction stub.
1313      if (it.IsDebugBreak()) {
1314        Address original_target = it.original_rinfo()->target_address();
1315        maybe_call_function_stub =
1316            Code::GetCodeFromTargetAddress(original_target);
1317      }
1318      if (maybe_call_function_stub->kind() == Code::STUB &&
1319          maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1320        // Save reference to the code as we may need it to find out arguments
1321        // count for 'step in' later.
1322        call_function_stub = Handle<Code>(maybe_call_function_stub);
1323      }
1324    }
1325  } else {
1326    is_at_restarted_function = true;
1327  }
1328
1329  // If this is the last break code target step out is the only possibility.
1330  if (it.IsExit() || step_action == StepOut) {
1331    if (step_action == StepOut) {
1332      // Skip step_count frames starting with the current one.
1333      while (step_count-- > 0 && !frames_it.done()) {
1334        frames_it.Advance();
1335      }
1336    } else {
1337      ASSERT(it.IsExit());
1338      frames_it.Advance();
1339    }
1340    // Skip builtin functions on the stack.
1341    while (!frames_it.done() &&
1342           JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1343      frames_it.Advance();
1344    }
1345    // Step out: If there is a JavaScript caller frame, we need to
1346    // flood it with breakpoints.
1347    if (!frames_it.done()) {
1348      // Fill the function to return to with one-shot break points.
1349      JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1350      FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1351      // Set target frame pointer.
1352      ActivateStepOut(frames_it.frame());
1353    }
1354  } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1355               !call_function_stub.is_null() || is_at_restarted_function)
1356             || step_action == StepNext || step_action == StepMin) {
1357    // Step next or step min.
1358
1359    // Fill the current function with one-shot break points.
1360    FloodWithOneShot(shared);
1361
1362    // Remember source position and frame to handle step next.
1363    thread_local_.last_statement_position_ =
1364        debug_info->code()->SourceStatementPosition(frame->pc());
1365    thread_local_.last_fp_ = frame->fp();
1366  } else {
1367    // If there's restarter frame on top of the stack, just get the pointer
1368    // to function which is going to be restarted.
1369    if (is_at_restarted_function) {
1370      Handle<JSFunction> restarted_function(
1371          JSFunction::cast(*thread_local_.restarter_frame_function_pointer_));
1372      Handle<SharedFunctionInfo> restarted_shared(
1373          restarted_function->shared());
1374      FloodWithOneShot(restarted_shared);
1375    } else if (!call_function_stub.is_null()) {
1376      // If it's CallFunction stub ensure target function is compiled and flood
1377      // it with one shot breakpoints.
1378
1379      // Find out number of arguments from the stub minor key.
1380      // Reverse lookup required as the minor key cannot be retrieved
1381      // from the code object.
1382      Handle<Object> obj(
1383          isolate_->heap()->code_stubs()->SlowReverseLookup(
1384              *call_function_stub));
1385      ASSERT(!obj.is_null());
1386      ASSERT(!(*obj)->IsUndefined());
1387      ASSERT(obj->IsSmi());
1388      // Get the STUB key and extract major and minor key.
1389      uint32_t key = Smi::cast(*obj)->value();
1390      // Argc in the stub is the number of arguments passed - not the
1391      // expected arguments of the called function.
1392      int call_function_arg_count =
1393          CallFunctionStub::ExtractArgcFromMinorKey(
1394              CodeStub::MinorKeyFromKey(key));
1395      ASSERT(call_function_stub->major_key() ==
1396             CodeStub::MajorKeyFromKey(key));
1397
1398      // Find target function on the expression stack.
1399      // Expression stack looks like this (top to bottom):
1400      // argN
1401      // ...
1402      // arg0
1403      // Receiver
1404      // Function to call
1405      int expressions_count = frame->ComputeExpressionsCount();
1406      ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1407      Object* fun = frame->GetExpression(
1408          expressions_count - 2 - call_function_arg_count);
1409      if (fun->IsJSFunction()) {
1410        Handle<JSFunction> js_function(JSFunction::cast(fun));
1411        // Don't step into builtins.
1412        if (!js_function->IsBuiltin()) {
1413          // It will also compile target function if it's not compiled yet.
1414          FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1415        }
1416      }
1417    }
1418
1419    // Fill the current function with one-shot break points even for step in on
1420    // a call target as the function called might be a native function for
1421    // which step in will not stop. It also prepares for stepping in
1422    // getters/setters.
1423    FloodWithOneShot(shared);
1424
1425    if (is_load_or_store) {
1426      // Remember source position and frame to handle step in getter/setter. If
1427      // there is a custom getter/setter it will be handled in
1428      // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1429      // propagated on the next Debug::Break.
1430      thread_local_.last_statement_position_ =
1431          debug_info->code()->SourceStatementPosition(frame->pc());
1432      thread_local_.last_fp_ = frame->fp();
1433    }
1434
1435    // Step in or Step in min
1436    it.PrepareStepIn();
1437    ActivateStepIn(frame);
1438  }
1439}
1440
1441
1442// Check whether the current debug break should be reported to the debugger. It
1443// is used to have step next and step in only report break back to the debugger
1444// if on a different frame or in a different statement. In some situations
1445// there will be several break points in the same statement when the code is
1446// flooded with one-shot break points. This function helps to perform several
1447// steps before reporting break back to the debugger.
1448bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1449                             JavaScriptFrame* frame) {
1450  // If the step last action was step next or step in make sure that a new
1451  // statement is hit.
1452  if (thread_local_.last_step_action_ == StepNext ||
1453      thread_local_.last_step_action_ == StepIn) {
1454    // Never continue if returning from function.
1455    if (break_location_iterator->IsExit()) return false;
1456
1457    // Continue if we are still on the same frame and in the same statement.
1458    int current_statement_position =
1459        break_location_iterator->code()->SourceStatementPosition(frame->pc());
1460    return thread_local_.last_fp_ == frame->fp() &&
1461        thread_local_.last_statement_position_ == current_statement_position;
1462  }
1463
1464  // No step next action - don't continue.
1465  return false;
1466}
1467
1468
1469// Check whether the code object at the specified address is a debug break code
1470// object.
1471bool Debug::IsDebugBreak(Address addr) {
1472  Code* code = Code::GetCodeFromTargetAddress(addr);
1473  return code->ic_state() == DEBUG_BREAK;
1474}
1475
1476
1477// Check whether a code stub with the specified major key is a possible break
1478// point location when looking for source break locations.
1479bool Debug::IsSourceBreakStub(Code* code) {
1480  CodeStub::Major major_key = CodeStub::GetMajorKey(code);
1481  return major_key == CodeStub::CallFunction;
1482}
1483
1484
1485// Check whether a code stub with the specified major key is a possible break
1486// location.
1487bool Debug::IsBreakStub(Code* code) {
1488  CodeStub::Major major_key = CodeStub::GetMajorKey(code);
1489  return major_key == CodeStub::CallFunction;
1490}
1491
1492
1493// Find the builtin to use for invoking the debug break
1494Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
1495  // Find the builtin debug break function matching the calling convention
1496  // used by the call site.
1497  if (code->is_inline_cache_stub()) {
1498    switch (code->kind()) {
1499      case Code::CALL_IC:
1500      case Code::KEYED_CALL_IC:
1501        return ComputeCallDebugBreak(code->arguments_count(), code->kind());
1502
1503      case Code::LOAD_IC:
1504        return Isolate::Current()->builtins()->LoadIC_DebugBreak();
1505
1506      case Code::STORE_IC:
1507        return Isolate::Current()->builtins()->StoreIC_DebugBreak();
1508
1509      case Code::KEYED_LOAD_IC:
1510        return Isolate::Current()->builtins()->KeyedLoadIC_DebugBreak();
1511
1512      case Code::KEYED_STORE_IC:
1513        return Isolate::Current()->builtins()->KeyedStoreIC_DebugBreak();
1514
1515      default:
1516        UNREACHABLE();
1517    }
1518  }
1519  if (RelocInfo::IsConstructCall(mode)) {
1520    Handle<Code> result =
1521        Isolate::Current()->builtins()->ConstructCall_DebugBreak();
1522    return result;
1523  }
1524  if (code->kind() == Code::STUB) {
1525    ASSERT(code->major_key() == CodeStub::CallFunction);
1526    Handle<Code> result =
1527        Isolate::Current()->builtins()->StubNoRegisters_DebugBreak();
1528    return result;
1529  }
1530
1531  UNREACHABLE();
1532  return Handle<Code>::null();
1533}
1534
1535
1536// Simple function for returning the source positions for active break points.
1537Handle<Object> Debug::GetSourceBreakLocations(
1538    Handle<SharedFunctionInfo> shared) {
1539  Isolate* isolate = Isolate::Current();
1540  Heap* heap = isolate->heap();
1541  if (!HasDebugInfo(shared)) return Handle<Object>(heap->undefined_value());
1542  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1543  if (debug_info->GetBreakPointCount() == 0) {
1544    return Handle<Object>(heap->undefined_value());
1545  }
1546  Handle<FixedArray> locations =
1547      isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
1548  int count = 0;
1549  for (int i = 0; i < debug_info->break_points()->length(); i++) {
1550    if (!debug_info->break_points()->get(i)->IsUndefined()) {
1551      BreakPointInfo* break_point_info =
1552          BreakPointInfo::cast(debug_info->break_points()->get(i));
1553      if (break_point_info->GetBreakPointCount() > 0) {
1554        locations->set(count++, break_point_info->statement_position());
1555      }
1556    }
1557  }
1558  return locations;
1559}
1560
1561
1562void Debug::NewBreak(StackFrame::Id break_frame_id) {
1563  thread_local_.break_frame_id_ = break_frame_id;
1564  thread_local_.break_id_ = ++thread_local_.break_count_;
1565}
1566
1567
1568void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1569  thread_local_.break_frame_id_ = break_frame_id;
1570  thread_local_.break_id_ = break_id;
1571}
1572
1573
1574// Handle stepping into a function.
1575void Debug::HandleStepIn(Handle<JSFunction> function,
1576                         Handle<Object> holder,
1577                         Address fp,
1578                         bool is_constructor) {
1579  // If the frame pointer is not supplied by the caller find it.
1580  if (fp == 0) {
1581    StackFrameIterator it;
1582    it.Advance();
1583    // For constructor functions skip another frame.
1584    if (is_constructor) {
1585      ASSERT(it.frame()->is_construct());
1586      it.Advance();
1587    }
1588    fp = it.frame()->fp();
1589  }
1590
1591  // Flood the function with one-shot break points if it is called from where
1592  // step into was requested.
1593  if (fp == step_in_fp()) {
1594    // Don't allow step into functions in the native context.
1595    if (!function->IsBuiltin()) {
1596      if (function->shared()->code() ==
1597          Isolate::Current()->builtins()->builtin(Builtins::kFunctionApply) ||
1598          function->shared()->code() ==
1599          Isolate::Current()->builtins()->builtin(Builtins::kFunctionCall)) {
1600        // Handle function.apply and function.call separately to flood the
1601        // function to be called and not the code for Builtins::FunctionApply or
1602        // Builtins::FunctionCall. The receiver of call/apply is the target
1603        // function.
1604        if (!holder.is_null() && holder->IsJSFunction() &&
1605            !JSFunction::cast(*holder)->IsBuiltin()) {
1606          Handle<SharedFunctionInfo> shared_info(
1607              JSFunction::cast(*holder)->shared());
1608          Debug::FloodWithOneShot(shared_info);
1609        }
1610      } else {
1611        Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1612      }
1613    }
1614  }
1615}
1616
1617
1618void Debug::ClearStepping() {
1619  // Clear the various stepping setup.
1620  ClearOneShot();
1621  ClearStepIn();
1622  ClearStepOut();
1623  ClearStepNext();
1624
1625  // Clear multiple step counter.
1626  thread_local_.step_count_ = 0;
1627}
1628
1629// Clears all the one-shot break points that are currently set. Normally this
1630// function is called each time a break point is hit as one shot break points
1631// are used to support stepping.
1632void Debug::ClearOneShot() {
1633  // The current implementation just runs through all the breakpoints. When the
1634  // last break point for a function is removed that function is automatically
1635  // removed from the list.
1636
1637  DebugInfoListNode* node = debug_info_list_;
1638  while (node != NULL) {
1639    BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1640    while (!it.Done()) {
1641      it.ClearOneShot();
1642      it.Next();
1643    }
1644    node = node->next();
1645  }
1646}
1647
1648
1649void Debug::ActivateStepIn(StackFrame* frame) {
1650  ASSERT(!StepOutActive());
1651  thread_local_.step_into_fp_ = frame->fp();
1652}
1653
1654
1655void Debug::ClearStepIn() {
1656  thread_local_.step_into_fp_ = 0;
1657}
1658
1659
1660void Debug::ActivateStepOut(StackFrame* frame) {
1661  ASSERT(!StepInActive());
1662  thread_local_.step_out_fp_ = frame->fp();
1663}
1664
1665
1666void Debug::ClearStepOut() {
1667  thread_local_.step_out_fp_ = 0;
1668}
1669
1670
1671void Debug::ClearStepNext() {
1672  thread_local_.last_step_action_ = StepNone;
1673  thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1674  thread_local_.last_fp_ = 0;
1675}
1676
1677
1678// Ensures the debug information is present for shared.
1679bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1680  // Return if we already have the debug info for shared.
1681  if (HasDebugInfo(shared)) return true;
1682
1683  // Ensure shared in compiled. Return false if this failed.
1684  if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
1685
1686  // If preparing for the first break point make sure to deoptimize all
1687  // functions as debugging does not work with optimized code.
1688  if (!has_break_points_) {
1689    Deoptimizer::DeoptimizeAll();
1690  }
1691
1692  // Create the debug info object.
1693  Handle<DebugInfo> debug_info = FACTORY->NewDebugInfo(shared);
1694
1695  // Add debug info to the list.
1696  DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1697  node->set_next(debug_info_list_);
1698  debug_info_list_ = node;
1699
1700  // Now there is at least one break point.
1701  has_break_points_ = true;
1702
1703  return true;
1704}
1705
1706
1707void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1708  ASSERT(debug_info_list_ != NULL);
1709  // Run through the debug info objects to find this one and remove it.
1710  DebugInfoListNode* prev = NULL;
1711  DebugInfoListNode* current = debug_info_list_;
1712  while (current != NULL) {
1713    if (*current->debug_info() == *debug_info) {
1714      // Unlink from list. If prev is NULL we are looking at the first element.
1715      if (prev == NULL) {
1716        debug_info_list_ = current->next();
1717      } else {
1718        prev->set_next(current->next());
1719      }
1720      current->debug_info()->shared()->set_debug_info(
1721              isolate_->heap()->undefined_value());
1722      delete current;
1723
1724      // If there are no more debug info objects there are not more break
1725      // points.
1726      has_break_points_ = debug_info_list_ != NULL;
1727
1728      return;
1729    }
1730    // Move to next in list.
1731    prev = current;
1732    current = current->next();
1733  }
1734  UNREACHABLE();
1735}
1736
1737
1738void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
1739  HandleScope scope(isolate_);
1740
1741  // Get the executing function in which the debug break occurred.
1742  Handle<SharedFunctionInfo> shared =
1743      Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1744  if (!EnsureDebugInfo(shared)) {
1745    // Return if we failed to retrieve the debug info.
1746    return;
1747  }
1748  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1749  Handle<Code> code(debug_info->code());
1750  Handle<Code> original_code(debug_info->original_code());
1751#ifdef DEBUG
1752  // Get the code which is actually executing.
1753  Handle<Code> frame_code(frame->LookupCode());
1754  ASSERT(frame_code.is_identical_to(code));
1755#endif
1756
1757  // Find the call address in the running code. This address holds the call to
1758  // either a DebugBreakXXX or to the debug break return entry code if the
1759  // break point is still active after processing the break point.
1760  Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
1761
1762  // Check if the location is at JS exit or debug break slot.
1763  bool at_js_return = false;
1764  bool break_at_js_return_active = false;
1765  bool at_debug_break_slot = false;
1766  RelocIterator it(debug_info->code());
1767  while (!it.done() && !at_js_return && !at_debug_break_slot) {
1768    if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
1769      at_js_return = (it.rinfo()->pc() ==
1770          addr - Assembler::kPatchReturnSequenceAddressOffset);
1771      break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
1772    }
1773    if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
1774      at_debug_break_slot = (it.rinfo()->pc() ==
1775          addr - Assembler::kPatchDebugBreakSlotAddressOffset);
1776    }
1777    it.next();
1778  }
1779
1780  // Handle the jump to continue execution after break point depending on the
1781  // break location.
1782  if (at_js_return) {
1783    // If the break point as return is still active jump to the corresponding
1784    // place in the original code. If not the break point was removed during
1785    // break point processing.
1786    if (break_at_js_return_active) {
1787      addr +=  original_code->instruction_start() - code->instruction_start();
1788    }
1789
1790    // Move back to where the call instruction sequence started.
1791    thread_local_.after_break_target_ =
1792        addr - Assembler::kPatchReturnSequenceAddressOffset;
1793  } else if (at_debug_break_slot) {
1794    // Address of where the debug break slot starts.
1795    addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;
1796
1797    // Continue just after the slot.
1798    thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
1799  } else if (IsDebugBreak(Assembler::target_address_at(addr))) {
1800    // We now know that there is still a debug break call at the target address,
1801    // so the break point is still there and the original code will hold the
1802    // address to jump to in order to complete the call which is replaced by a
1803    // call to DebugBreakXXX.
1804
1805    // Find the corresponding address in the original code.
1806    addr += original_code->instruction_start() - code->instruction_start();
1807
1808    // Install jump to the call address in the original code. This will be the
1809    // call which was overwritten by the call to DebugBreakXXX.
1810    thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1811  } else {
1812    // There is no longer a break point present. Don't try to look in the
1813    // original code as the running code will have the right address. This takes
1814    // care of the case where the last break point is removed from the function
1815    // and therefore no "original code" is available.
1816    thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1817  }
1818}
1819
1820
1821bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
1822  HandleScope scope(isolate_);
1823
1824  // If there are no break points this cannot be break at return, as
1825  // the debugger statement and stack guard bebug break cannot be at
1826  // return.
1827  if (!has_break_points_) {
1828    return false;
1829  }
1830
1831  // Get the executing function in which the debug break occurred.
1832  Handle<SharedFunctionInfo> shared =
1833      Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1834  if (!EnsureDebugInfo(shared)) {
1835    // Return if we failed to retrieve the debug info.
1836    return false;
1837  }
1838  Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1839  Handle<Code> code(debug_info->code());
1840#ifdef DEBUG
1841  // Get the code which is actually executing.
1842  Handle<Code> frame_code(frame->LookupCode());
1843  ASSERT(frame_code.is_identical_to(code));
1844#endif
1845
1846  // Find the call address in the running code.
1847  Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
1848
1849  // Check if the location is at JS return.
1850  RelocIterator it(debug_info->code());
1851  while (!it.done()) {
1852    if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
1853      return (it.rinfo()->pc() ==
1854          addr - Assembler::kPatchReturnSequenceAddressOffset);
1855    }
1856    it.next();
1857  }
1858  return false;
1859}
1860
1861
1862void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
1863                                  FrameDropMode mode,
1864                                  Object** restarter_frame_function_pointer) {
1865  thread_local_.frame_drop_mode_ = mode;
1866  thread_local_.break_frame_id_ = new_break_frame_id;
1867  thread_local_.restarter_frame_function_pointer_ =
1868      restarter_frame_function_pointer;
1869}
1870
1871
1872bool Debug::IsDebugGlobal(GlobalObject* global) {
1873  return IsLoaded() && global == debug_context()->global();
1874}
1875
1876
1877void Debug::ClearMirrorCache() {
1878  PostponeInterruptsScope postpone(isolate_);
1879  HandleScope scope(isolate_);
1880  ASSERT(isolate_->context() == *Debug::debug_context());
1881
1882  // Clear the mirror cache.
1883  Handle<String> function_name =
1884      isolate_->factory()->LookupSymbol(CStrVector("ClearMirrorCache"));
1885  Handle<Object> fun(Isolate::Current()->global()->GetPropertyNoExceptionThrown(
1886      *function_name));
1887  ASSERT(fun->IsJSFunction());
1888  bool caught_exception;
1889  Execution::TryCall(Handle<JSFunction>::cast(fun),
1890      Handle<JSObject>(Debug::debug_context()->global()),
1891      0, NULL, &caught_exception);
1892}
1893
1894
1895void Debug::CreateScriptCache() {
1896  Heap* heap = isolate_->heap();
1897  HandleScope scope(isolate_);
1898
1899  // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1900  // rid of all the cached script wrappers and the second gets rid of the
1901  // scripts which are no longer referenced.
1902  heap->CollectAllGarbage(false);
1903  heap->CollectAllGarbage(false);
1904
1905  ASSERT(script_cache_ == NULL);
1906  script_cache_ = new ScriptCache();
1907
1908  // Scan heap for Script objects.
1909  int count = 0;
1910  HeapIterator iterator;
1911  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
1912    if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
1913      script_cache_->Add(Handle<Script>(Script::cast(obj)));
1914      count++;
1915    }
1916  }
1917}
1918
1919
1920void Debug::DestroyScriptCache() {
1921  // Get rid of the script cache if it was created.
1922  if (script_cache_ != NULL) {
1923    delete script_cache_;
1924    script_cache_ = NULL;
1925  }
1926}
1927
1928
1929void Debug::AddScriptToScriptCache(Handle<Script> script) {
1930  if (script_cache_ != NULL) {
1931    script_cache_->Add(script);
1932  }
1933}
1934
1935
1936Handle<FixedArray> Debug::GetLoadedScripts() {
1937  // Create and fill the script cache when the loaded scripts is requested for
1938  // the first time.
1939  if (script_cache_ == NULL) {
1940    CreateScriptCache();
1941  }
1942
1943  // If the script cache is not active just return an empty array.
1944  ASSERT(script_cache_ != NULL);
1945  if (script_cache_ == NULL) {
1946    isolate_->factory()->NewFixedArray(0);
1947  }
1948
1949  // Perform GC to get unreferenced scripts evicted from the cache before
1950  // returning the content.
1951  isolate_->heap()->CollectAllGarbage(false);
1952
1953  // Get the scripts from the cache.
1954  return script_cache_->GetScripts();
1955}
1956
1957
1958void Debug::AfterGarbageCollection() {
1959  // Generate events for collected scripts.
1960  if (script_cache_ != NULL) {
1961    script_cache_->ProcessCollectedScripts();
1962  }
1963}
1964
1965
1966Debugger::Debugger(Isolate* isolate)
1967    : debugger_access_(OS::CreateMutex()),
1968      event_listener_(Handle<Object>()),
1969      event_listener_data_(Handle<Object>()),
1970      compiling_natives_(false),
1971      is_loading_debugger_(false),
1972      never_unload_debugger_(false),
1973      message_handler_(NULL),
1974      debugger_unload_pending_(false),
1975      host_dispatch_handler_(NULL),
1976      dispatch_handler_access_(OS::CreateMutex()),
1977      debug_message_dispatch_handler_(NULL),
1978      message_dispatch_helper_thread_(NULL),
1979      host_dispatch_micros_(100 * 1000),
1980      agent_(NULL),
1981      command_queue_(isolate->logger(), kQueueInitialSize),
1982      command_received_(OS::CreateSemaphore(0)),
1983      event_command_queue_(isolate->logger(), kQueueInitialSize),
1984      isolate_(isolate) {
1985}
1986
1987
1988Debugger::~Debugger() {
1989  delete debugger_access_;
1990  debugger_access_ = 0;
1991  delete dispatch_handler_access_;
1992  dispatch_handler_access_ = 0;
1993  delete command_received_;
1994  command_received_ = 0;
1995}
1996
1997
1998Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1999                                      int argc, Object*** argv,
2000                                      bool* caught_exception) {
2001  ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2002
2003  // Create the execution state object.
2004  Handle<String> constructor_str =
2005      isolate_->factory()->LookupSymbol(constructor_name);
2006  Handle<Object> constructor(
2007      isolate_->global()->GetPropertyNoExceptionThrown(*constructor_str));
2008  ASSERT(constructor->IsJSFunction());
2009  if (!constructor->IsJSFunction()) {
2010    *caught_exception = true;
2011    return isolate_->factory()->undefined_value();
2012  }
2013  Handle<Object> js_object = Execution::TryCall(
2014      Handle<JSFunction>::cast(constructor),
2015      Handle<JSObject>(isolate_->debug()->debug_context()->global()),
2016      argc, argv, caught_exception);
2017  return js_object;
2018}
2019
2020
2021Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
2022  // Create the execution state object.
2023  Handle<Object> break_id = isolate_->factory()->NewNumberFromInt(
2024      isolate_->debug()->break_id());
2025  const int argc = 1;
2026  Object** argv[argc] = { break_id.location() };
2027  return MakeJSObject(CStrVector("MakeExecutionState"),
2028                      argc, argv, caught_exception);
2029}
2030
2031
2032Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
2033                                        Handle<Object> break_points_hit,
2034                                        bool* caught_exception) {
2035  // Create the new break event object.
2036  const int argc = 2;
2037  Object** argv[argc] = { exec_state.location(),
2038                          break_points_hit.location() };
2039  return MakeJSObject(CStrVector("MakeBreakEvent"),
2040                      argc,
2041                      argv,
2042                      caught_exception);
2043}
2044
2045
2046Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
2047                                            Handle<Object> exception,
2048                                            bool uncaught,
2049                                            bool* caught_exception) {
2050  Factory* factory = isolate_->factory();
2051  // Create the new exception event object.
2052  const int argc = 3;
2053  Object** argv[argc] = { exec_state.location(),
2054                          exception.location(),
2055                          uncaught ? factory->true_value().location() :
2056                                     factory->false_value().location()};
2057  return MakeJSObject(CStrVector("MakeExceptionEvent"),
2058                      argc, argv, caught_exception);
2059}
2060
2061
2062Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
2063                                              bool* caught_exception) {
2064  // Create the new function event object.
2065  const int argc = 1;
2066  Object** argv[argc] = { function.location() };
2067  return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
2068                      argc, argv, caught_exception);
2069}
2070
2071
2072Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
2073                                          bool before,
2074                                          bool* caught_exception) {
2075  Factory* factory = isolate_->factory();
2076  // Create the compile event object.
2077  Handle<Object> exec_state = MakeExecutionState(caught_exception);
2078  Handle<Object> script_wrapper = GetScriptWrapper(script);
2079  const int argc = 3;
2080  Object** argv[argc] = { exec_state.location(),
2081                          script_wrapper.location(),
2082                          before ? factory->true_value().location() :
2083                                   factory->false_value().location() };
2084
2085  return MakeJSObject(CStrVector("MakeCompileEvent"),
2086                      argc,
2087                      argv,
2088                      caught_exception);
2089}
2090
2091
2092Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
2093                                                  bool* caught_exception) {
2094  // Create the script collected event object.
2095  Handle<Object> exec_state = MakeExecutionState(caught_exception);
2096  Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
2097  const int argc = 2;
2098  Object** argv[argc] = { exec_state.location(), id_object.location() };
2099
2100  return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
2101                      argc,
2102                      argv,
2103                      caught_exception);
2104}
2105
2106
2107void Debugger::OnException(Handle<Object> exception, bool uncaught) {
2108  HandleScope scope(isolate_);
2109  Debug* debug = isolate_->debug();
2110
2111  // Bail out based on state or if there is no listener for this event
2112  if (debug->InDebugger()) return;
2113  if (!Debugger::EventActive(v8::Exception)) return;
2114
2115  // Bail out if exception breaks are not active
2116  if (uncaught) {
2117    // Uncaught exceptions are reported by either flags.
2118    if (!(debug->break_on_uncaught_exception() ||
2119          debug->break_on_exception())) return;
2120  } else {
2121    // Caught exceptions are reported is activated.
2122    if (!debug->break_on_exception()) return;
2123  }
2124
2125  // Enter the debugger.
2126  EnterDebugger debugger;
2127  if (debugger.FailedToEnter()) return;
2128
2129  // Clear all current stepping setup.
2130  debug->ClearStepping();
2131  // Create the event data object.
2132  bool caught_exception = false;
2133  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2134  Handle<Object> event_data;
2135  if (!caught_exception) {
2136    event_data = MakeExceptionEvent(exec_state, exception, uncaught,
2137                                    &caught_exception);
2138  }
2139  // Bail out and don't call debugger if exception.
2140  if (caught_exception) {
2141    return;
2142  }
2143
2144  // Process debug event.
2145  ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2146  // Return to continue execution from where the exception was thrown.
2147}
2148
2149
2150void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
2151                            bool auto_continue) {
2152  HandleScope scope(isolate_);
2153
2154  // Debugger has already been entered by caller.
2155  ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2156
2157  // Bail out if there is no listener for this event
2158  if (!Debugger::EventActive(v8::Break)) return;
2159
2160  // Debugger must be entered in advance.
2161  ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2162
2163  // Create the event data object.
2164  bool caught_exception = false;
2165  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2166  Handle<Object> event_data;
2167  if (!caught_exception) {
2168    event_data = MakeBreakEvent(exec_state, break_points_hit,
2169                                &caught_exception);
2170  }
2171  // Bail out and don't call debugger if exception.
2172  if (caught_exception) {
2173    return;
2174  }
2175
2176  // Process debug event.
2177  ProcessDebugEvent(v8::Break,
2178                    Handle<JSObject>::cast(event_data),
2179                    auto_continue);
2180}
2181
2182
2183void Debugger::OnBeforeCompile(Handle<Script> script) {
2184  HandleScope scope(isolate_);
2185
2186  // Bail out based on state or if there is no listener for this event
2187  if (isolate_->debug()->InDebugger()) return;
2188  if (compiling_natives()) return;
2189  if (!EventActive(v8::BeforeCompile)) return;
2190
2191  // Enter the debugger.
2192  EnterDebugger debugger;
2193  if (debugger.FailedToEnter()) return;
2194
2195  // Create the event data object.
2196  bool caught_exception = false;
2197  Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
2198  // Bail out and don't call debugger if exception.
2199  if (caught_exception) {
2200    return;
2201  }
2202
2203  // Process debug event.
2204  ProcessDebugEvent(v8::BeforeCompile,
2205                    Handle<JSObject>::cast(event_data),
2206                    true);
2207}
2208
2209
2210// Handle debugger actions when a new script is compiled.
2211void Debugger::OnAfterCompile(Handle<Script> script,
2212                              AfterCompileFlags after_compile_flags) {
2213  HandleScope scope(isolate_);
2214  Debug* debug = isolate_->debug();
2215
2216  // Add the newly compiled script to the script cache.
2217  debug->AddScriptToScriptCache(script);
2218
2219  // No more to do if not debugging.
2220  if (!IsDebuggerActive()) return;
2221
2222  // No compile events while compiling natives.
2223  if (compiling_natives()) return;
2224
2225  // Store whether in debugger before entering debugger.
2226  bool in_debugger = debug->InDebugger();
2227
2228  // Enter the debugger.
2229  EnterDebugger debugger;
2230  if (debugger.FailedToEnter()) return;
2231
2232  // If debugging there might be script break points registered for this
2233  // script. Make sure that these break points are set.
2234
2235  // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
2236  Handle<String> update_script_break_points_symbol =
2237      isolate_->factory()->LookupAsciiSymbol("UpdateScriptBreakPoints");
2238  Handle<Object> update_script_break_points =
2239      Handle<Object>(debug->debug_context()->global()->
2240          GetPropertyNoExceptionThrown(*update_script_break_points_symbol));
2241  if (!update_script_break_points->IsJSFunction()) {
2242    return;
2243  }
2244  ASSERT(update_script_break_points->IsJSFunction());
2245
2246  // Wrap the script object in a proper JS object before passing it
2247  // to JavaScript.
2248  Handle<JSValue> wrapper = GetScriptWrapper(script);
2249
2250  // Call UpdateScriptBreakPoints expect no exceptions.
2251  bool caught_exception = false;
2252  const int argc = 1;
2253  Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2254  Execution::TryCall(Handle<JSFunction>::cast(update_script_break_points),
2255      Isolate::Current()->js_builtins_object(), argc, argv,
2256      &caught_exception);
2257  if (caught_exception) {
2258    return;
2259  }
2260  // Bail out based on state or if there is no listener for this event
2261  if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
2262  if (!Debugger::EventActive(v8::AfterCompile)) return;
2263
2264  // Create the compile state object.
2265  Handle<Object> event_data = MakeCompileEvent(script,
2266                                               false,
2267                                               &caught_exception);
2268  // Bail out and don't call debugger if exception.
2269  if (caught_exception) {
2270    return;
2271  }
2272  // Process debug event.
2273  ProcessDebugEvent(v8::AfterCompile,
2274                    Handle<JSObject>::cast(event_data),
2275                    true);
2276}
2277
2278
2279void Debugger::OnScriptCollected(int id) {
2280  HandleScope scope(isolate_);
2281
2282  // No more to do if not debugging.
2283  if (!IsDebuggerActive()) return;
2284  if (!Debugger::EventActive(v8::ScriptCollected)) return;
2285
2286  // Enter the debugger.
2287  EnterDebugger debugger;
2288  if (debugger.FailedToEnter()) return;
2289
2290  // Create the script collected state object.
2291  bool caught_exception = false;
2292  Handle<Object> event_data = MakeScriptCollectedEvent(id,
2293                                                       &caught_exception);
2294  // Bail out and don't call debugger if exception.
2295  if (caught_exception) {
2296    return;
2297  }
2298
2299  // Process debug event.
2300  ProcessDebugEvent(v8::ScriptCollected,
2301                    Handle<JSObject>::cast(event_data),
2302                    true);
2303}
2304
2305
2306void Debugger::ProcessDebugEvent(v8::DebugEvent event,
2307                                 Handle<JSObject> event_data,
2308                                 bool auto_continue) {
2309  HandleScope scope(isolate_);
2310
2311  // Clear any pending debug break if this is a real break.
2312  if (!auto_continue) {
2313    isolate_->debug()->clear_interrupt_pending(DEBUGBREAK);
2314  }
2315
2316  // Create the execution state.
2317  bool caught_exception = false;
2318  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2319  if (caught_exception) {
2320    return;
2321  }
2322  // First notify the message handler if any.
2323  if (message_handler_ != NULL) {
2324    NotifyMessageHandler(event,
2325                         Handle<JSObject>::cast(exec_state),
2326                         event_data,
2327                         auto_continue);
2328  }
2329  // Notify registered debug event listener. This can be either a C or
2330  // a JavaScript function. Don't call event listener for v8::Break
2331  // here, if it's only a debug command -- they will be processed later.
2332  if ((event != v8::Break || !auto_continue) && !event_listener_.is_null()) {
2333    CallEventCallback(event, exec_state, event_data, NULL);
2334  }
2335  // Process pending debug commands.
2336  if (event == v8::Break) {
2337    while (!event_command_queue_.IsEmpty()) {
2338      CommandMessage command = event_command_queue_.Get();
2339      if (!event_listener_.is_null()) {
2340        CallEventCallback(v8::BreakForCommand,
2341                          exec_state,
2342                          event_data,
2343                          command.client_data());
2344      }
2345      command.Dispose();
2346    }
2347  }
2348}
2349
2350
2351void Debugger::CallEventCallback(v8::DebugEvent event,
2352                                 Handle<Object> exec_state,
2353                                 Handle<Object> event_data,
2354                                 v8::Debug::ClientData* client_data) {
2355  if (event_listener_->IsForeign()) {
2356    CallCEventCallback(event, exec_state, event_data, client_data);
2357  } else {
2358    CallJSEventCallback(event, exec_state, event_data);
2359  }
2360}
2361
2362
2363void Debugger::CallCEventCallback(v8::DebugEvent event,
2364                                  Handle<Object> exec_state,
2365                                  Handle<Object> event_data,
2366                                  v8::Debug::ClientData* client_data) {
2367  Handle<Foreign> callback_obj(Handle<Foreign>::cast(event_listener_));
2368  v8::Debug::EventCallback2 callback =
2369      FUNCTION_CAST<v8::Debug::EventCallback2>(callback_obj->address());
2370  EventDetailsImpl event_details(
2371      event,
2372      Handle<JSObject>::cast(exec_state),
2373      Handle<JSObject>::cast(event_data),
2374      event_listener_data_,
2375      client_data);
2376  callback(event_details);
2377}
2378
2379
2380void Debugger::CallJSEventCallback(v8::DebugEvent event,
2381                                   Handle<Object> exec_state,
2382                                   Handle<Object> event_data) {
2383  ASSERT(event_listener_->IsJSFunction());
2384  Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
2385
2386  // Invoke the JavaScript debug event listener.
2387  const int argc = 4;
2388  Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2389                          exec_state.location(),
2390                          Handle<Object>::cast(event_data).location(),
2391                          event_listener_data_.location() };
2392  bool caught_exception = false;
2393  Execution::TryCall(fun, isolate_->global(), argc, argv, &caught_exception);
2394  // Silently ignore exceptions from debug event listeners.
2395}
2396
2397
2398Handle<Context> Debugger::GetDebugContext() {
2399  never_unload_debugger_ = true;
2400  EnterDebugger debugger;
2401  return isolate_->debug()->debug_context();
2402}
2403
2404
2405void Debugger::UnloadDebugger() {
2406  Debug* debug = isolate_->debug();
2407
2408  // Make sure that there are no breakpoints left.
2409  debug->ClearAllBreakPoints();
2410
2411  // Unload the debugger if feasible.
2412  if (!never_unload_debugger_) {
2413    debug->Unload();
2414  }
2415
2416  // Clear the flag indicating that the debugger should be unloaded.
2417  debugger_unload_pending_ = false;
2418}
2419
2420
2421void Debugger::NotifyMessageHandler(v8::DebugEvent event,
2422                                    Handle<JSObject> exec_state,
2423                                    Handle<JSObject> event_data,
2424                                    bool auto_continue) {
2425  HandleScope scope(isolate_);
2426
2427  if (!isolate_->debug()->Load()) return;
2428
2429  // Process the individual events.
2430  bool sendEventMessage = false;
2431  switch (event) {
2432    case v8::Break:
2433    case v8::BreakForCommand:
2434      sendEventMessage = !auto_continue;
2435      break;
2436    case v8::Exception:
2437      sendEventMessage = true;
2438      break;
2439    case v8::BeforeCompile:
2440      break;
2441    case v8::AfterCompile:
2442      sendEventMessage = true;
2443      break;
2444    case v8::ScriptCollected:
2445      sendEventMessage = true;
2446      break;
2447    case v8::NewFunction:
2448      break;
2449    default:
2450      UNREACHABLE();
2451  }
2452
2453  // The debug command interrupt flag might have been set when the command was
2454  // added. It should be enough to clear the flag only once while we are in the
2455  // debugger.
2456  ASSERT(isolate_->debug()->InDebugger());
2457  isolate_->stack_guard()->Continue(DEBUGCOMMAND);
2458
2459  // Notify the debugger that a debug event has occurred unless auto continue is
2460  // active in which case no event is send.
2461  if (sendEventMessage) {
2462    MessageImpl message = MessageImpl::NewEvent(
2463        event,
2464        auto_continue,
2465        Handle<JSObject>::cast(exec_state),
2466        Handle<JSObject>::cast(event_data));
2467    InvokeMessageHandler(message);
2468  }
2469
2470  // If auto continue don't make the event cause a break, but process messages
2471  // in the queue if any. For script collected events don't even process
2472  // messages in the queue as the execution state might not be what is expected
2473  // by the client.
2474  if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
2475    return;
2476  }
2477
2478  v8::TryCatch try_catch;
2479
2480  // DebugCommandProcessor goes here.
2481  v8::Local<v8::Object> cmd_processor;
2482  {
2483    v8::Local<v8::Object> api_exec_state =
2484        v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2485    v8::Local<v8::String> fun_name =
2486        v8::String::New("debugCommandProcessor");
2487    v8::Local<v8::Function> fun =
2488        v8::Function::Cast(*api_exec_state->Get(fun_name));
2489
2490    v8::Handle<v8::Boolean> running =
2491        auto_continue ? v8::True() : v8::False();
2492    static const int kArgc = 1;
2493    v8::Handle<Value> argv[kArgc] = { running };
2494    cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2495    if (try_catch.HasCaught()) {
2496      PrintLn(try_catch.Exception());
2497      return;
2498    }
2499  }
2500
2501  bool running = auto_continue;
2502
2503  // Process requests from the debugger.
2504  while (true) {
2505    // Wait for new command in the queue.
2506    if (Debugger::host_dispatch_handler_) {
2507      // In case there is a host dispatch - do periodic dispatches.
2508      if (!command_received_->Wait(host_dispatch_micros_)) {
2509        // Timout expired, do the dispatch.
2510        Debugger::host_dispatch_handler_();
2511        continue;
2512      }
2513    } else {
2514      // In case there is no host dispatch - just wait.
2515      command_received_->Wait();
2516    }
2517
2518    // Get the command from the queue.
2519    CommandMessage command = command_queue_.Get();
2520    isolate_->logger()->DebugTag(
2521        "Got request from command queue, in interactive loop.");
2522    if (!Debugger::IsDebuggerActive()) {
2523      // Delete command text and user data.
2524      command.Dispose();
2525      return;
2526    }
2527
2528    // Invoke JavaScript to process the debug request.
2529    v8::Local<v8::String> fun_name;
2530    v8::Local<v8::Function> fun;
2531    v8::Local<v8::Value> request;
2532    v8::TryCatch try_catch;
2533    fun_name = v8::String::New("processDebugRequest");
2534    fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2535
2536    request = v8::String::New(command.text().start(),
2537                              command.text().length());
2538    static const int kArgc = 1;
2539    v8::Handle<Value> argv[kArgc] = { request };
2540    v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2541
2542    // Get the response.
2543    v8::Local<v8::String> response;
2544    if (!try_catch.HasCaught()) {
2545      // Get response string.
2546      if (!response_val->IsUndefined()) {
2547        response = v8::String::Cast(*response_val);
2548      } else {
2549        response = v8::String::New("");
2550      }
2551
2552      // Log the JSON request/response.
2553      if (FLAG_trace_debug_json) {
2554        PrintLn(request);
2555        PrintLn(response);
2556      }
2557
2558      // Get the running state.
2559      fun_name = v8::String::New("isRunning");
2560      fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2561      static const int kArgc = 1;
2562      v8::Handle<Value> argv[kArgc] = { response };
2563      v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2564      if (!try_catch.HasCaught()) {
2565        running = running_val->ToBoolean()->Value();
2566      }
2567    } else {
2568      // In case of failure the result text is the exception text.
2569      response = try_catch.Exception()->ToString();
2570    }
2571
2572    // Return the result.
2573    MessageImpl message = MessageImpl::NewResponse(
2574        event,
2575        running,
2576        Handle<JSObject>::cast(exec_state),
2577        Handle<JSObject>::cast(event_data),
2578        Handle<String>(Utils::OpenHandle(*response)),
2579        command.client_data());
2580    InvokeMessageHandler(message);
2581    command.Dispose();
2582
2583    // Return from debug event processing if either the VM is put into the
2584    // runnning state (through a continue command) or auto continue is active
2585    // and there are no more commands queued.
2586    if (running && !HasCommands()) {
2587      return;
2588    }
2589  }
2590}
2591
2592
2593void Debugger::SetEventListener(Handle<Object> callback,
2594                                Handle<Object> data) {
2595  HandleScope scope(isolate_);
2596  GlobalHandles* global_handles = isolate_->global_handles();
2597
2598  // Clear the global handles for the event listener and the event listener data
2599  // object.
2600  if (!event_listener_.is_null()) {
2601    global_handles->Destroy(
2602        reinterpret_cast<Object**>(event_listener_.location()));
2603    event_listener_ = Handle<Object>();
2604  }
2605  if (!event_listener_data_.is_null()) {
2606    global_handles->Destroy(
2607        reinterpret_cast<Object**>(event_listener_data_.location()));
2608    event_listener_data_ = Handle<Object>();
2609  }
2610
2611  // If there is a new debug event listener register it together with its data
2612  // object.
2613  if (!callback->IsUndefined() && !callback->IsNull()) {
2614    event_listener_ = Handle<Object>::cast(
2615        global_handles->Create(*callback));
2616    if (data.is_null()) {
2617      data = isolate_->factory()->undefined_value();
2618    }
2619    event_listener_data_ = Handle<Object>::cast(
2620        global_handles->Create(*data));
2621  }
2622
2623  ListenersChanged();
2624}
2625
2626
2627void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
2628  ScopedLock with(debugger_access_);
2629
2630  message_handler_ = handler;
2631  ListenersChanged();
2632  if (handler == NULL) {
2633    // Send an empty command to the debugger if in a break to make JavaScript
2634    // run again if the debugger is closed.
2635    if (isolate_->debug()->InDebugger()) {
2636      ProcessCommand(Vector<const uint16_t>::empty());
2637    }
2638  }
2639}
2640
2641
2642void Debugger::ListenersChanged() {
2643  if (IsDebuggerActive()) {
2644    // Disable the compilation cache when the debugger is active.
2645    isolate_->compilation_cache()->Disable();
2646    debugger_unload_pending_ = false;
2647  } else {
2648    isolate_->compilation_cache()->Enable();
2649    // Unload the debugger if event listener and message handler cleared.
2650    // Schedule this for later, because we may be in non-V8 thread.
2651    debugger_unload_pending_ = true;
2652  }
2653}
2654
2655
2656void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2657                                      int period) {
2658  host_dispatch_handler_ = handler;
2659  host_dispatch_micros_ = period * 1000;
2660}
2661
2662
2663void Debugger::SetDebugMessageDispatchHandler(
2664    v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2665  ScopedLock with(dispatch_handler_access_);
2666  debug_message_dispatch_handler_ = handler;
2667
2668  if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2669    message_dispatch_helper_thread_ = new MessageDispatchHelperThread(isolate_);
2670    message_dispatch_helper_thread_->Start();
2671  }
2672}
2673
2674
2675// Calls the registered debug message handler. This callback is part of the
2676// public API.
2677void Debugger::InvokeMessageHandler(MessageImpl message) {
2678  ScopedLock with(debugger_access_);
2679
2680  if (message_handler_ != NULL) {
2681    message_handler_(message);
2682  }
2683}
2684
2685
2686// Puts a command coming from the public API on the queue.  Creates
2687// a copy of the command string managed by the debugger.  Up to this
2688// point, the command data was managed by the API client.  Called
2689// by the API client thread.
2690void Debugger::ProcessCommand(Vector<const uint16_t> command,
2691                              v8::Debug::ClientData* client_data) {
2692  // Need to cast away const.
2693  CommandMessage message = CommandMessage::New(
2694      Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
2695                       command.length()),
2696      client_data);
2697  isolate_->logger()->DebugTag("Put command on command_queue.");
2698  command_queue_.Put(message);
2699  command_received_->Signal();
2700
2701  // Set the debug command break flag to have the command processed.
2702  if (!isolate_->debug()->InDebugger()) {
2703    isolate_->stack_guard()->DebugCommand();
2704  }
2705
2706  MessageDispatchHelperThread* dispatch_thread;
2707  {
2708    ScopedLock with(dispatch_handler_access_);
2709    dispatch_thread = message_dispatch_helper_thread_;
2710  }
2711
2712  if (dispatch_thread == NULL) {
2713    CallMessageDispatchHandler();
2714  } else {
2715    dispatch_thread->Schedule();
2716  }
2717}
2718
2719
2720bool Debugger::HasCommands() {
2721  return !command_queue_.IsEmpty();
2722}
2723
2724
2725void Debugger::EnqueueDebugCommand(v8::Debug::ClientData* client_data) {
2726  CommandMessage message = CommandMessage::New(Vector<uint16_t>(), client_data);
2727  event_command_queue_.Put(message);
2728
2729  // Set the debug command break flag to have the command processed.
2730  if (!isolate_->debug()->InDebugger()) {
2731    isolate_->stack_guard()->DebugCommand();
2732  }
2733}
2734
2735
2736bool Debugger::IsDebuggerActive() {
2737  ScopedLock with(debugger_access_);
2738
2739  return message_handler_ != NULL || !event_listener_.is_null();
2740}
2741
2742
2743Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2744                              Handle<Object> data,
2745                              bool* pending_exception) {
2746  // When calling functions in the debugger prevent it from beeing unloaded.
2747  Debugger::never_unload_debugger_ = true;
2748
2749  // Enter the debugger.
2750  EnterDebugger debugger;
2751  if (debugger.FailedToEnter()) {
2752    return isolate_->factory()->undefined_value();
2753  }
2754
2755  // Create the execution state.
2756  bool caught_exception = false;
2757  Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2758  if (caught_exception) {
2759    return isolate_->factory()->undefined_value();
2760  }
2761
2762  static const int kArgc = 2;
2763  Object** argv[kArgc] = { exec_state.location(), data.location() };
2764  Handle<Object> result = Execution::Call(
2765      fun,
2766      Handle<Object>(isolate_->debug()->debug_context_->global_proxy()),
2767      kArgc,
2768      argv,
2769      pending_exception);
2770  return result;
2771}
2772
2773
2774static void StubMessageHandler2(const v8::Debug::Message& message) {
2775  // Simply ignore message.
2776}
2777
2778
2779bool Debugger::StartAgent(const char* name, int port,
2780                          bool wait_for_connection) {
2781  ASSERT(Isolate::Current() == isolate_);
2782  if (wait_for_connection) {
2783    // Suspend V8 if it is already running or set V8 to suspend whenever
2784    // it starts.
2785    // Provide stub message handler; V8 auto-continues each suspend
2786    // when there is no message handler; we doesn't need it.
2787    // Once become suspended, V8 will stay so indefinitely long, until remote
2788    // debugger connects and issues "continue" command.
2789    Debugger::message_handler_ = StubMessageHandler2;
2790    v8::Debug::DebugBreak();
2791  }
2792
2793  if (Socket::Setup()) {
2794    if (agent_ == NULL) {
2795      agent_ = new DebuggerAgent(name, port);
2796      agent_->Start();
2797    }
2798    return true;
2799  }
2800
2801  return false;
2802}
2803
2804
2805void Debugger::StopAgent() {
2806  ASSERT(Isolate::Current() == isolate_);
2807  if (agent_ != NULL) {
2808    agent_->Shutdown();
2809    agent_->Join();
2810    delete agent_;
2811    agent_ = NULL;
2812  }
2813}
2814
2815
2816void Debugger::WaitForAgent() {
2817  ASSERT(Isolate::Current() == isolate_);
2818  if (agent_ != NULL)
2819    agent_->WaitUntilListening();
2820}
2821
2822
2823void Debugger::CallMessageDispatchHandler() {
2824  v8::Debug::DebugMessageDispatchHandler handler;
2825  {
2826    ScopedLock with(dispatch_handler_access_);
2827    handler = Debugger::debug_message_dispatch_handler_;
2828  }
2829  if (handler != NULL) {
2830    handler();
2831  }
2832}
2833
2834
2835MessageImpl MessageImpl::NewEvent(DebugEvent event,
2836                                  bool running,
2837                                  Handle<JSObject> exec_state,
2838                                  Handle<JSObject> event_data) {
2839  MessageImpl message(true, event, running,
2840                      exec_state, event_data, Handle<String>(), NULL);
2841  return message;
2842}
2843
2844
2845MessageImpl MessageImpl::NewResponse(DebugEvent event,
2846                                     bool running,
2847                                     Handle<JSObject> exec_state,
2848                                     Handle<JSObject> event_data,
2849                                     Handle<String> response_json,
2850                                     v8::Debug::ClientData* client_data) {
2851  MessageImpl message(false, event, running,
2852                      exec_state, event_data, response_json, client_data);
2853  return message;
2854}
2855
2856
2857MessageImpl::MessageImpl(bool is_event,
2858                         DebugEvent event,
2859                         bool running,
2860                         Handle<JSObject> exec_state,
2861                         Handle<JSObject> event_data,
2862                         Handle<String> response_json,
2863                         v8::Debug::ClientData* client_data)
2864    : is_event_(is_event),
2865      event_(event),
2866      running_(running),
2867      exec_state_(exec_state),
2868      event_data_(event_data),
2869      response_json_(response_json),
2870      client_data_(client_data) {}
2871
2872
2873bool MessageImpl::IsEvent() const {
2874  return is_event_;
2875}
2876
2877
2878bool MessageImpl::IsResponse() const {
2879  return !is_event_;
2880}
2881
2882
2883DebugEvent MessageImpl::GetEvent() const {
2884  return event_;
2885}
2886
2887
2888bool MessageImpl::WillStartRunning() const {
2889  return running_;
2890}
2891
2892
2893v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2894  return v8::Utils::ToLocal(exec_state_);
2895}
2896
2897
2898v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2899  return v8::Utils::ToLocal(event_data_);
2900}
2901
2902
2903v8::Handle<v8::String> MessageImpl::GetJSON() const {
2904  v8::HandleScope scope;
2905
2906  if (IsEvent()) {
2907    // Call toJSONProtocol on the debug event object.
2908    Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2909    if (!fun->IsJSFunction()) {
2910      return v8::Handle<v8::String>();
2911    }
2912    bool caught_exception;
2913    Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2914                                             event_data_,
2915                                             0, NULL, &caught_exception);
2916    if (caught_exception || !json->IsString()) {
2917      return v8::Handle<v8::String>();
2918    }
2919    return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2920  } else {
2921    return v8::Utils::ToLocal(response_json_);
2922  }
2923}
2924
2925
2926v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
2927  Isolate* isolate = Isolate::Current();
2928  v8::Handle<v8::Context> context = GetDebugEventContext(isolate);
2929  // Isolate::context() may be NULL when "script collected" event occures.
2930  ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
2931  return context;
2932}
2933
2934
2935v8::Debug::ClientData* MessageImpl::GetClientData() const {
2936  return client_data_;
2937}
2938
2939
2940EventDetailsImpl::EventDetailsImpl(DebugEvent event,
2941                                   Handle<JSObject> exec_state,
2942                                   Handle<JSObject> event_data,
2943                                   Handle<Object> callback_data,
2944                                   v8::Debug::ClientData* client_data)
2945    : event_(event),
2946      exec_state_(exec_state),
2947      event_data_(event_data),
2948      callback_data_(callback_data),
2949      client_data_(client_data) {}
2950
2951
2952DebugEvent EventDetailsImpl::GetEvent() const {
2953  return event_;
2954}
2955
2956
2957v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
2958  return v8::Utils::ToLocal(exec_state_);
2959}
2960
2961
2962v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
2963  return v8::Utils::ToLocal(event_data_);
2964}
2965
2966
2967v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
2968  return GetDebugEventContext(Isolate::Current());
2969}
2970
2971
2972v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
2973  return v8::Utils::ToLocal(callback_data_);
2974}
2975
2976
2977v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
2978  return client_data_;
2979}
2980
2981
2982CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2983                                   client_data_(NULL) {
2984}
2985
2986
2987CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2988                               v8::Debug::ClientData* data)
2989    : text_(text),
2990      client_data_(data) {
2991}
2992
2993
2994CommandMessage::~CommandMessage() {
2995}
2996
2997
2998void CommandMessage::Dispose() {
2999  text_.Dispose();
3000  delete client_data_;
3001  client_data_ = NULL;
3002}
3003
3004
3005CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
3006                                   v8::Debug::ClientData* data) {
3007  return CommandMessage(command.Clone(), data);
3008}
3009
3010
3011CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
3012                                                     size_(size) {
3013  messages_ = NewArray<CommandMessage>(size);
3014}
3015
3016
3017CommandMessageQueue::~CommandMessageQueue() {
3018  while (!IsEmpty()) {
3019    CommandMessage m = Get();
3020    m.Dispose();
3021  }
3022  DeleteArray(messages_);
3023}
3024
3025
3026CommandMessage CommandMessageQueue::Get() {
3027  ASSERT(!IsEmpty());
3028  int result = start_;
3029  start_ = (start_ + 1) % size_;
3030  return messages_[result];
3031}
3032
3033
3034void CommandMessageQueue::Put(const CommandMessage& message) {
3035  if ((end_ + 1) % size_ == start_) {
3036    Expand();
3037  }
3038  messages_[end_] = message;
3039  end_ = (end_ + 1) % size_;
3040}
3041
3042
3043void CommandMessageQueue::Expand() {
3044  CommandMessageQueue new_queue(size_ * 2);
3045  while (!IsEmpty()) {
3046    new_queue.Put(Get());
3047  }
3048  CommandMessage* array_to_free = messages_;
3049  *this = new_queue;
3050  new_queue.messages_ = array_to_free;
3051  // Make the new_queue empty so that it doesn't call Dispose on any messages.
3052  new_queue.start_ = new_queue.end_;
3053  // Automatic destructor called on new_queue, freeing array_to_free.
3054}
3055
3056
3057LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size)
3058    : logger_(logger), queue_(size) {
3059  lock_ = OS::CreateMutex();
3060}
3061
3062
3063LockingCommandMessageQueue::~LockingCommandMessageQueue() {
3064  delete lock_;
3065}
3066
3067
3068bool LockingCommandMessageQueue::IsEmpty() const {
3069  ScopedLock sl(lock_);
3070  return queue_.IsEmpty();
3071}
3072
3073
3074CommandMessage LockingCommandMessageQueue::Get() {
3075  ScopedLock sl(lock_);
3076  CommandMessage result = queue_.Get();
3077  logger_->DebugEvent("Get", result.text());
3078  return result;
3079}
3080
3081
3082void LockingCommandMessageQueue::Put(const CommandMessage& message) {
3083  ScopedLock sl(lock_);
3084  queue_.Put(message);
3085  logger_->DebugEvent("Put", message.text());
3086}
3087
3088
3089void LockingCommandMessageQueue::Clear() {
3090  ScopedLock sl(lock_);
3091  queue_.Clear();
3092}
3093
3094
3095MessageDispatchHelperThread::MessageDispatchHelperThread(Isolate* isolate)
3096    : Thread("v8:MsgDispHelpr"),
3097      sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
3098      already_signalled_(false) {
3099}
3100
3101
3102MessageDispatchHelperThread::~MessageDispatchHelperThread() {
3103  delete mutex_;
3104  delete sem_;
3105}
3106
3107
3108void MessageDispatchHelperThread::Schedule() {
3109  {
3110    ScopedLock lock(mutex_);
3111    if (already_signalled_) {
3112      return;
3113    }
3114    already_signalled_ = true;
3115  }
3116  sem_->Signal();
3117}
3118
3119
3120void MessageDispatchHelperThread::Run() {
3121  while (true) {
3122    sem_->Wait();
3123    {
3124      ScopedLock lock(mutex_);
3125      already_signalled_ = false;
3126    }
3127    {
3128      Locker locker;
3129      Isolate::Current()->debugger()->CallMessageDispatchHandler();
3130    }
3131  }
3132}
3133
3134#endif  // ENABLE_DEBUGGER_SUPPORT
3135
3136} }  // namespace v8::internal
3137