blob: 24f0db4133d26986c0823d0f624c63fdf82ece5b [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// 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#ifndef V8_DEBUG_H_
29#define V8_DEBUG_H_
30
31#include "assembler.h"
32#include "code-stubs.h"
33#include "debug-agent.h"
34#include "execution.h"
35#include "factory.h"
36#include "hashmap.h"
37#include "platform.h"
38#include "string-stream.h"
39#include "v8threads.h"
40
41#ifdef ENABLE_DEBUGGER_SUPPORT
42#include "../include/v8-debug.h"
43
44namespace v8 {
45namespace internal {
46
47
48// Forward declarations.
49class EnterDebugger;
50
51
52// Step actions. NOTE: These values are in macros.py as well.
53enum StepAction {
54 StepNone = -1, // Stepping not prepared.
55 StepOut = 0, // Step out of the current function.
56 StepNext = 1, // Step to the next statement in the current function.
57 StepIn = 2, // Step into new functions invoked or the next statement
58 // in the current function.
59 StepMin = 3, // Perform a minimum step in the current function.
60 StepInMin = 4 // Step into new functions invoked or perform a minimum step
61 // in the current function.
62};
63
64
65// Type of exception break. NOTE: These values are in macros.py as well.
66enum ExceptionBreakType {
67 BreakException = 0,
68 BreakUncaughtException = 1
69};
70
71
72// Type of exception break. NOTE: These values are in macros.py as well.
73enum BreakLocatorType {
74 ALL_BREAK_LOCATIONS = 0,
75 SOURCE_BREAK_LOCATIONS = 1
76};
77
78
79// Class for iterating through the break points in a function and changing
80// them.
81class BreakLocationIterator {
82 public:
83 explicit BreakLocationIterator(Handle<DebugInfo> debug_info,
84 BreakLocatorType type);
85 virtual ~BreakLocationIterator();
86
87 void Next();
88 void Next(int count);
89 void FindBreakLocationFromAddress(Address pc);
90 void FindBreakLocationFromPosition(int position);
91 void Reset();
92 bool Done() const;
93 void SetBreakPoint(Handle<Object> break_point_object);
94 void ClearBreakPoint(Handle<Object> break_point_object);
95 void SetOneShot();
96 void ClearOneShot();
97 void PrepareStepIn();
98 bool IsExit() const;
99 bool HasBreakPoint();
100 bool IsDebugBreak();
101 Object* BreakPointObjects();
102 void ClearAllDebugBreak();
103
104
Steve Blockd0582a62009-12-15 09:54:21 +0000105 inline int code_position() {
106 return static_cast<int>(pc() - debug_info_->code()->entry());
107 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000108 inline int break_point() { return break_point_; }
109 inline int position() { return position_; }
110 inline int statement_position() { return statement_position_; }
111 inline Address pc() { return reloc_iterator_->rinfo()->pc(); }
112 inline Code* code() { return debug_info_->code(); }
113 inline RelocInfo* rinfo() { return reloc_iterator_->rinfo(); }
114 inline RelocInfo::Mode rmode() const {
115 return reloc_iterator_->rinfo()->rmode();
116 }
117 inline RelocInfo* original_rinfo() {
118 return reloc_iterator_original_->rinfo();
119 }
120 inline RelocInfo::Mode original_rmode() const {
121 return reloc_iterator_original_->rinfo()->rmode();
122 }
123
124 bool IsDebuggerStatement();
125
126 protected:
127 bool RinfoDone() const;
128 void RinfoNext();
129
130 BreakLocatorType type_;
131 int break_point_;
132 int position_;
133 int statement_position_;
134 Handle<DebugInfo> debug_info_;
135 Handle<Code> debug_break_stub_;
136 RelocIterator* reloc_iterator_;
137 RelocIterator* reloc_iterator_original_;
138
139 private:
140 void SetDebugBreak();
141 void ClearDebugBreak();
142
143 void SetDebugBreakAtIC();
144 void ClearDebugBreakAtIC();
145
146 bool IsDebugBreakAtReturn();
147 void SetDebugBreakAtReturn();
148 void ClearDebugBreakAtReturn();
149
150 DISALLOW_COPY_AND_ASSIGN(BreakLocationIterator);
151};
152
153
154// Cache of all script objects in the heap. When a script is added a weak handle
155// to it is created and that weak handle is stored in the cache. The weak handle
156// callback takes care of removing the script from the cache. The key used in
157// the cache is the script id.
158class ScriptCache : private HashMap {
159 public:
160 ScriptCache() : HashMap(ScriptMatch), collected_scripts_(10) {}
161 virtual ~ScriptCache() { Clear(); }
162
163 // Add script to the cache.
164 void Add(Handle<Script> script);
165
166 // Return the scripts in the cache.
167 Handle<FixedArray> GetScripts();
168
169 // Generate debugger events for collected scripts.
170 void ProcessCollectedScripts();
171
172 private:
173 // Calculate the hash value from the key (script id).
174 static uint32_t Hash(int key) { return ComputeIntegerHash(key); }
175
176 // Scripts match if their keys (script id) match.
177 static bool ScriptMatch(void* key1, void* key2) { return key1 == key2; }
178
179 // Clear the cache releasing all the weak handles.
180 void Clear();
181
182 // Weak handle callback for scripts in the cache.
183 static void HandleWeakScript(v8::Persistent<v8::Value> obj, void* data);
184
185 // List used during GC to temporarily store id's of collected scripts.
186 List<int> collected_scripts_;
187};
188
189
190// Linked list holding debug info objects. The debug info objects are kept as
191// weak handles to avoid a debug info object to keep a function alive.
192class DebugInfoListNode {
193 public:
194 explicit DebugInfoListNode(DebugInfo* debug_info);
195 virtual ~DebugInfoListNode();
196
197 DebugInfoListNode* next() { return next_; }
198 void set_next(DebugInfoListNode* next) { next_ = next; }
199 Handle<DebugInfo> debug_info() { return debug_info_; }
200
201 private:
202 // Global (weak) handle to the debug info object.
203 Handle<DebugInfo> debug_info_;
204
205 // Next pointer for linked list.
206 DebugInfoListNode* next_;
207};
208
209
210// This class contains the debugger support. The main purpose is to handle
211// setting break points in the code.
212//
213// This class controls the debug info for all functions which currently have
214// active breakpoints in them. This debug info is held in the heap root object
215// debug_info which is a FixedArray. Each entry in this list is of class
216// DebugInfo.
217class Debug {
218 public:
219 static void Setup(bool create_heap_objects);
220 static bool Load();
221 static void Unload();
222 static bool IsLoaded() { return !debug_context_.is_null(); }
223 static bool InDebugger() { return thread_local_.debugger_entry_ != NULL; }
224 static void PreemptionWhileInDebugger();
225 static void Iterate(ObjectVisitor* v);
226
227 static Object* Break(Arguments args);
228 static void SetBreakPoint(Handle<SharedFunctionInfo> shared,
229 int source_position,
230 Handle<Object> break_point_object);
231 static void ClearBreakPoint(Handle<Object> break_point_object);
232 static void ClearAllBreakPoints();
233 static void FloodWithOneShot(Handle<SharedFunctionInfo> shared);
234 static void FloodHandlerWithOneShot();
235 static void ChangeBreakOnException(ExceptionBreakType type, bool enable);
236 static void PrepareStep(StepAction step_action, int step_count);
237 static void ClearStepping();
238 static bool StepNextContinue(BreakLocationIterator* break_location_iterator,
239 JavaScriptFrame* frame);
240 static Handle<DebugInfo> GetDebugInfo(Handle<SharedFunctionInfo> shared);
241 static bool HasDebugInfo(Handle<SharedFunctionInfo> shared);
242
243 // Returns whether the operation succeeded.
244 static bool EnsureDebugInfo(Handle<SharedFunctionInfo> shared);
245
246 // Returns true if the current stub call is patched to call the debugger.
247 static bool IsDebugBreak(Address addr);
248 // Returns true if the current return statement has been patched to be
249 // a debugger breakpoint.
250 static bool IsDebugBreakAtReturn(RelocInfo* rinfo);
251
252 // Check whether a code stub with the specified major key is a possible break
253 // point location.
254 static bool IsSourceBreakStub(Code* code);
255 static bool IsBreakStub(Code* code);
256
257 // Find the builtin to use for invoking the debug break
258 static Handle<Code> FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode);
259
260 static Handle<Object> GetSourceBreakLocations(
261 Handle<SharedFunctionInfo> shared);
262
263 // Getter for the debug_context.
264 inline static Handle<Context> debug_context() { return debug_context_; }
265
266 // Check whether a global object is the debug global object.
267 static bool IsDebugGlobal(GlobalObject* global);
268
269 // Fast check to see if any break points are active.
270 inline static bool has_break_points() { return has_break_points_; }
271
272 static void NewBreak(StackFrame::Id break_frame_id);
273 static void SetBreak(StackFrame::Id break_frame_id, int break_id);
274 static StackFrame::Id break_frame_id() {
275 return thread_local_.break_frame_id_;
276 }
277 static int break_id() { return thread_local_.break_id_; }
278
279 static bool StepInActive() { return thread_local_.step_into_fp_ != 0; }
280 static void HandleStepIn(Handle<JSFunction> function,
281 Handle<Object> holder,
282 Address fp,
283 bool is_constructor);
284 static Address step_in_fp() { return thread_local_.step_into_fp_; }
285 static Address* step_in_fp_addr() { return &thread_local_.step_into_fp_; }
286
287 static bool StepOutActive() { return thread_local_.step_out_fp_ != 0; }
288 static Address step_out_fp() { return thread_local_.step_out_fp_; }
289
290 static EnterDebugger* debugger_entry() {
291 return thread_local_.debugger_entry_;
292 }
293 static void set_debugger_entry(EnterDebugger* entry) {
294 thread_local_.debugger_entry_ = entry;
295 }
296
297 // Check whether any of the specified interrupts are pending.
298 static bool is_interrupt_pending(InterruptFlag what) {
299 return (thread_local_.pending_interrupts_ & what) != 0;
300 }
301
302 // Set specified interrupts as pending.
303 static void set_interrupts_pending(InterruptFlag what) {
304 thread_local_.pending_interrupts_ |= what;
305 }
306
307 // Clear specified interrupts from pending.
308 static void clear_interrupt_pending(InterruptFlag what) {
309 thread_local_.pending_interrupts_ &= ~static_cast<int>(what);
310 }
311
312 // Getter and setter for the disable break state.
313 static bool disable_break() { return disable_break_; }
314 static void set_disable_break(bool disable_break) {
315 disable_break_ = disable_break;
316 }
317
318 // Getters for the current exception break state.
319 static bool break_on_exception() { return break_on_exception_; }
320 static bool break_on_uncaught_exception() {
321 return break_on_uncaught_exception_;
322 }
323
324 enum AddressId {
325 k_after_break_target_address,
326 k_debug_break_return_address,
327 k_register_address
328 };
329
330 // Support for setting the address to jump to when returning from break point.
331 static Address* after_break_target_address() {
332 return reinterpret_cast<Address*>(&thread_local_.after_break_target_);
333 }
334
335 // Support for saving/restoring registers when handling debug break calls.
336 static Object** register_address(int r) {
337 return &registers_[r];
338 }
339
340 // Access to the debug break on return code.
341 static Code* debug_break_return() { return debug_break_return_; }
342 static Code** debug_break_return_address() {
343 return &debug_break_return_;
344 }
345
346 static const int kEstimatedNofDebugInfoEntries = 16;
347 static const int kEstimatedNofBreakPointsInFunction = 16;
348
349 static void HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data);
350
351 friend class Debugger;
352 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
353 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
354
355 // Threading support.
356 static char* ArchiveDebug(char* to);
357 static char* RestoreDebug(char* from);
358 static int ArchiveSpacePerThread();
359 static void FreeThreadResources() { }
360
361 // Mirror cache handling.
362 static void ClearMirrorCache();
363
364 // Script cache handling.
365 static void CreateScriptCache();
366 static void DestroyScriptCache();
367 static void AddScriptToScriptCache(Handle<Script> script);
368 static Handle<FixedArray> GetLoadedScripts();
369
370 // Garbage collection notifications.
371 static void AfterGarbageCollection();
372
Steve Blocka7e24c12009-10-30 11:49:00 +0000373 // Code generator routines.
374 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
375 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
376 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
377 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
378 static void GenerateConstructCallDebugBreak(MacroAssembler* masm);
379 static void GenerateReturnDebugBreak(MacroAssembler* masm);
380 static void GenerateStubNoRegistersDebugBreak(MacroAssembler* masm);
381
382 // Called from stub-cache.cc.
383 static void GenerateCallICDebugBreak(MacroAssembler* masm);
384
385 private:
386 static bool CompileDebuggerScript(int index);
387 static void ClearOneShot();
388 static void ActivateStepIn(StackFrame* frame);
389 static void ClearStepIn();
390 static void ActivateStepOut(StackFrame* frame);
391 static void ClearStepOut();
392 static void ClearStepNext();
393 // Returns whether the compile succeeded.
394 static bool EnsureCompiled(Handle<SharedFunctionInfo> shared);
395 static void RemoveDebugInfo(Handle<DebugInfo> debug_info);
396 static void SetAfterBreakTarget(JavaScriptFrame* frame);
397 static Handle<Object> CheckBreakPoints(Handle<Object> break_point);
398 static bool CheckBreakPoint(Handle<Object> break_point_object);
399
400 // Global handle to debug context where all the debugger JavaScript code is
401 // loaded.
402 static Handle<Context> debug_context_;
403
404 // Boolean state indicating whether any break points are set.
405 static bool has_break_points_;
406
407 // Cache of all scripts in the heap.
408 static ScriptCache* script_cache_;
409
410 // List of active debug info objects.
411 static DebugInfoListNode* debug_info_list_;
412
413 static bool disable_break_;
414 static bool break_on_exception_;
415 static bool break_on_uncaught_exception_;
416
417 // Per-thread data.
418 class ThreadLocal {
419 public:
420 // Counter for generating next break id.
421 int break_count_;
422
423 // Current break id.
424 int break_id_;
425
426 // Frame id for the frame of the current break.
427 StackFrame::Id break_frame_id_;
428
429 // Step action for last step performed.
430 StepAction last_step_action_;
431
432 // Source statement position from last step next action.
433 int last_statement_position_;
434
435 // Number of steps left to perform before debug event.
436 int step_count_;
437
438 // Frame pointer from last step next action.
439 Address last_fp_;
440
441 // Frame pointer for frame from which step in was performed.
442 Address step_into_fp_;
443
444 // Frame pointer for the frame where debugger should be called when current
445 // step out action is completed.
446 Address step_out_fp_;
447
448 // Storage location for jump when exiting debug break calls.
449 Address after_break_target_;
450
451 // Top debugger entry.
452 EnterDebugger* debugger_entry_;
453
454 // Pending interrupts scheduled while debugging.
455 int pending_interrupts_;
456 };
457
458 // Storage location for registers when handling debug break calls
459 static JSCallerSavedBuffer registers_;
460 static ThreadLocal thread_local_;
461 static void ThreadInit();
462
463 // Code to call for handling debug break on return.
464 static Code* debug_break_return_;
465
466 DISALLOW_COPY_AND_ASSIGN(Debug);
467};
468
469
470// Message delivered to the message handler callback. This is either a debugger
471// event or the response to a command.
472class MessageImpl: public v8::Debug::Message {
473 public:
474 // Create a message object for a debug event.
475 static MessageImpl NewEvent(DebugEvent event,
476 bool running,
477 Handle<JSObject> exec_state,
478 Handle<JSObject> event_data);
479
480 // Create a message object for the response to a debug command.
481 static MessageImpl NewResponse(DebugEvent event,
482 bool running,
483 Handle<JSObject> exec_state,
484 Handle<JSObject> event_data,
485 Handle<String> response_json,
486 v8::Debug::ClientData* client_data);
487
488 // Implementation of interface v8::Debug::Message.
489 virtual bool IsEvent() const;
490 virtual bool IsResponse() const;
491 virtual DebugEvent GetEvent() const;
492 virtual bool WillStartRunning() const;
493 virtual v8::Handle<v8::Object> GetExecutionState() const;
494 virtual v8::Handle<v8::Object> GetEventData() const;
495 virtual v8::Handle<v8::String> GetJSON() const;
496 virtual v8::Handle<v8::Context> GetEventContext() const;
497 virtual v8::Debug::ClientData* GetClientData() const;
498
499 private:
500 MessageImpl(bool is_event,
501 DebugEvent event,
502 bool running,
503 Handle<JSObject> exec_state,
504 Handle<JSObject> event_data,
505 Handle<String> response_json,
506 v8::Debug::ClientData* client_data);
507
508 bool is_event_; // Does this message represent a debug event?
509 DebugEvent event_; // Debug event causing the break.
510 bool running_; // Will the VM start running after this event?
511 Handle<JSObject> exec_state_; // Current execution state.
512 Handle<JSObject> event_data_; // Data associated with the event.
513 Handle<String> response_json_; // Response JSON if message holds a response.
514 v8::Debug::ClientData* client_data_; // Client data passed with the request.
515};
516
517
518// Message send by user to v8 debugger or debugger output message.
519// In addition to command text it may contain a pointer to some user data
520// which are expected to be passed along with the command reponse to message
521// handler.
522class CommandMessage {
523 public:
524 static CommandMessage New(const Vector<uint16_t>& command,
525 v8::Debug::ClientData* data);
526 CommandMessage();
527 ~CommandMessage();
528
529 // Deletes user data and disposes of the text.
530 void Dispose();
531 Vector<uint16_t> text() const { return text_; }
532 v8::Debug::ClientData* client_data() const { return client_data_; }
533 private:
534 CommandMessage(const Vector<uint16_t>& text,
535 v8::Debug::ClientData* data);
536
537 Vector<uint16_t> text_;
538 v8::Debug::ClientData* client_data_;
539};
540
541// A Queue of CommandMessage objects. A thread-safe version is
542// LockingCommandMessageQueue, based on this class.
543class CommandMessageQueue BASE_EMBEDDED {
544 public:
545 explicit CommandMessageQueue(int size);
546 ~CommandMessageQueue();
547 bool IsEmpty() const { return start_ == end_; }
548 CommandMessage Get();
549 void Put(const CommandMessage& message);
550 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
551 private:
552 // Doubles the size of the message queue, and copies the messages.
553 void Expand();
554
555 CommandMessage* messages_;
556 int start_;
557 int end_;
558 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
559};
560
561
562// LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
563// messages. The message data is not managed by LockingCommandMessageQueue.
564// Pointers to the data are passed in and out. Implemented by adding a
565// Mutex to CommandMessageQueue. Includes logging of all puts and gets.
566class LockingCommandMessageQueue BASE_EMBEDDED {
567 public:
568 explicit LockingCommandMessageQueue(int size);
569 ~LockingCommandMessageQueue();
570 bool IsEmpty() const;
571 CommandMessage Get();
572 void Put(const CommandMessage& message);
573 void Clear();
574 private:
575 CommandMessageQueue queue_;
576 Mutex* lock_;
577 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
578};
579
580
581class Debugger {
582 public:
583 static void DebugRequest(const uint16_t* json_request, int length);
584
585 static Handle<Object> MakeJSObject(Vector<const char> constructor_name,
586 int argc, Object*** argv,
587 bool* caught_exception);
588 static Handle<Object> MakeExecutionState(bool* caught_exception);
589 static Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
590 Handle<Object> break_points_hit,
591 bool* caught_exception);
592 static Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
593 Handle<Object> exception,
594 bool uncaught,
595 bool* caught_exception);
596 static Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
597 bool* caught_exception);
598 static Handle<Object> MakeCompileEvent(Handle<Script> script,
599 bool before,
600 bool* caught_exception);
601 static Handle<Object> MakeScriptCollectedEvent(int id,
602 bool* caught_exception);
603 static void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
604 static void OnException(Handle<Object> exception, bool uncaught);
605 static void OnBeforeCompile(Handle<Script> script);
606 static void OnAfterCompile(Handle<Script> script,
607 Handle<JSFunction> fun);
608 static void OnNewFunction(Handle<JSFunction> fun);
609 static void OnScriptCollected(int id);
610 static void ProcessDebugEvent(v8::DebugEvent event,
611 Handle<JSObject> event_data,
612 bool auto_continue);
613 static void NotifyMessageHandler(v8::DebugEvent event,
614 Handle<JSObject> exec_state,
615 Handle<JSObject> event_data,
616 bool auto_continue);
617 static void SetEventListener(Handle<Object> callback, Handle<Object> data);
618 static void SetMessageHandler(v8::Debug::MessageHandler2 handler);
619 static void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
620 int period);
Steve Blockd0582a62009-12-15 09:54:21 +0000621 static void SetDebugMessageDispatchHandler(
622 v8::Debug::DebugMessageDispatchHandler handler);
Steve Blocka7e24c12009-10-30 11:49:00 +0000623
624 // Invoke the message handler function.
625 static void InvokeMessageHandler(MessageImpl message);
626
627 // Add a debugger command to the command queue.
628 static void ProcessCommand(Vector<const uint16_t> command,
629 v8::Debug::ClientData* client_data = NULL);
630
631 // Check whether there are commands in the command queue.
632 static bool HasCommands();
633
634 static Handle<Object> Call(Handle<JSFunction> fun,
635 Handle<Object> data,
636 bool* pending_exception);
637
638 // Start the debugger agent listening on the provided port.
639 static bool StartAgent(const char* name, int port);
640
641 // Stop the debugger agent.
642 static void StopAgent();
643
644 // Blocks until the agent has started listening for connections
645 static void WaitForAgent();
646
647 // Unload the debugger if possible. Only called when no debugger is currently
648 // active.
649 static void UnloadDebugger();
650
651 inline static bool EventActive(v8::DebugEvent event) {
652 ScopedLock with(debugger_access_);
653
654 // Check whether the message handler was been cleared.
655 if (debugger_unload_pending_) {
656 UnloadDebugger();
657 }
658
659 // Currently argument event is not used.
660 return !compiling_natives_ && Debugger::IsDebuggerActive();
661 }
662
663 static void set_compiling_natives(bool compiling_natives) {
664 Debugger::compiling_natives_ = compiling_natives;
665 }
666 static bool compiling_natives() { return Debugger::compiling_natives_; }
667 static void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
668 static bool is_loading_debugger() { return Debugger::is_loading_debugger_; }
669
670 private:
671 static bool IsDebuggerActive();
672 static void ListenersChanged();
673
674 static Mutex* debugger_access_; // Mutex guarding debugger variables.
675 static Handle<Object> event_listener_; // Global handle to listener.
676 static Handle<Object> event_listener_data_;
677 static bool compiling_natives_; // Are we compiling natives?
678 static bool is_loading_debugger_; // Are we loading the debugger?
679 static bool never_unload_debugger_; // Can we unload the debugger?
680 static v8::Debug::MessageHandler2 message_handler_;
681 static bool debugger_unload_pending_; // Was message handler cleared?
682 static v8::Debug::HostDispatchHandler host_dispatch_handler_;
Steve Blockd0582a62009-12-15 09:54:21 +0000683 static v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000684 static int host_dispatch_micros_;
685
686 static DebuggerAgent* agent_;
687
688 static const int kQueueInitialSize = 4;
689 static LockingCommandMessageQueue command_queue_;
690 static Semaphore* command_received_; // Signaled for each command received.
691
692 friend class EnterDebugger;
693};
694
695
696// This class is used for entering the debugger. Create an instance in the stack
697// to enter the debugger. This will set the current break state, make sure the
698// debugger is loaded and switch to the debugger context. If the debugger for
699// some reason could not be entered FailedToEnter will return true.
700class EnterDebugger BASE_EMBEDDED {
701 public:
702 EnterDebugger()
703 : prev_(Debug::debugger_entry()),
704 has_js_frames_(!it_.done()) {
705 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(PREEMPT));
706 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(DEBUGBREAK));
707
708 // Link recursive debugger entry.
709 Debug::set_debugger_entry(this);
710
711 // Store the previous break id and frame id.
712 break_id_ = Debug::break_id();
713 break_frame_id_ = Debug::break_frame_id();
714
715 // Create the new break info. If there is no JavaScript frames there is no
716 // break frame id.
717 if (has_js_frames_) {
718 Debug::NewBreak(it_.frame()->id());
719 } else {
720 Debug::NewBreak(StackFrame::NO_ID);
721 }
722
723 // Make sure that debugger is loaded and enter the debugger context.
724 load_failed_ = !Debug::Load();
725 if (!load_failed_) {
726 // NOTE the member variable save which saves the previous context before
727 // this change.
728 Top::set_context(*Debug::debug_context());
729 }
730 }
731
732 ~EnterDebugger() {
733 // Restore to the previous break state.
734 Debug::SetBreak(break_frame_id_, break_id_);
735
736 // Check for leaving the debugger.
737 if (prev_ == NULL) {
738 // Clear mirror cache when leaving the debugger. Skip this if there is a
739 // pending exception as clearing the mirror cache calls back into
740 // JavaScript. This can happen if the v8::Debug::Call is used in which
741 // case the exception should end up in the calling code.
742 if (!Top::has_pending_exception()) {
743 // Try to avoid any pending debug break breaking in the clear mirror
744 // cache JavaScript code.
745 if (StackGuard::IsDebugBreak()) {
746 Debug::set_interrupts_pending(DEBUGBREAK);
747 StackGuard::Continue(DEBUGBREAK);
748 }
749 Debug::ClearMirrorCache();
750 }
751
752 // Request preemption and debug break when leaving the last debugger entry
753 // if any of these where recorded while debugging.
754 if (Debug::is_interrupt_pending(PREEMPT)) {
755 // This re-scheduling of preemption is to avoid starvation in some
756 // debugging scenarios.
757 Debug::clear_interrupt_pending(PREEMPT);
758 StackGuard::Preempt();
759 }
760 if (Debug::is_interrupt_pending(DEBUGBREAK)) {
761 Debug::clear_interrupt_pending(DEBUGBREAK);
762 StackGuard::DebugBreak();
763 }
764
765 // If there are commands in the queue when leaving the debugger request
766 // that these commands are processed.
767 if (Debugger::HasCommands()) {
768 StackGuard::DebugCommand();
769 }
770
771 // If leaving the debugger with the debugger no longer active unload it.
772 if (!Debugger::IsDebuggerActive()) {
773 Debugger::UnloadDebugger();
774 }
775 }
776
777 // Leaving this debugger entry.
778 Debug::set_debugger_entry(prev_);
779 }
780
781 // Check whether the debugger could be entered.
782 inline bool FailedToEnter() { return load_failed_; }
783
784 // Check whether there are any JavaScript frames on the stack.
785 inline bool HasJavaScriptFrames() { return has_js_frames_; }
786
787 // Get the active context from before entering the debugger.
788 inline Handle<Context> GetContext() { return save_.context(); }
789
790 private:
791 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
792 JavaScriptFrameIterator it_;
793 const bool has_js_frames_; // Were there any JavaScript frames?
794 StackFrame::Id break_frame_id_; // Previous break frame id.
795 int break_id_; // Previous break id.
796 bool load_failed_; // Did the debugger fail to load?
797 SaveContext save_; // Saves previous context.
798};
799
800
801// Stack allocated class for disabling break.
802class DisableBreak BASE_EMBEDDED {
803 public:
804 // Enter the debugger by storing the previous top context and setting the
805 // current top context to the debugger context.
806 explicit DisableBreak(bool disable_break) {
807 prev_disable_break_ = Debug::disable_break();
808 Debug::set_disable_break(disable_break);
809 }
810 ~DisableBreak() {
811 Debug::set_disable_break(prev_disable_break_);
812 }
813
814 private:
815 // The previous state of the disable break used to restore the value when this
816 // object is destructed.
817 bool prev_disable_break_;
818};
819
820
821// Debug_Address encapsulates the Address pointers used in generating debug
822// code.
823class Debug_Address {
824 public:
825 Debug_Address(Debug::AddressId id, int reg = 0)
826 : id_(id), reg_(reg) {
827 ASSERT(reg == 0 || id == Debug::k_register_address);
828 }
829
830 static Debug_Address AfterBreakTarget() {
831 return Debug_Address(Debug::k_after_break_target_address);
832 }
833
834 static Debug_Address DebugBreakReturn() {
835 return Debug_Address(Debug::k_debug_break_return_address);
836 }
837
838 static Debug_Address Register(int reg) {
839 return Debug_Address(Debug::k_register_address, reg);
840 }
841
842 Address address() const {
843 switch (id_) {
844 case Debug::k_after_break_target_address:
845 return reinterpret_cast<Address>(Debug::after_break_target_address());
846 case Debug::k_debug_break_return_address:
847 return reinterpret_cast<Address>(Debug::debug_break_return_address());
848 case Debug::k_register_address:
849 return reinterpret_cast<Address>(Debug::register_address(reg_));
850 default:
851 UNREACHABLE();
852 return NULL;
853 }
854 }
855 private:
856 Debug::AddressId id_;
857 int reg_;
858};
859
860
861} } // namespace v8::internal
862
863#endif // ENABLE_DEBUGGER_SUPPORT
864
865#endif // V8_DEBUG_H_