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