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