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