blob: 5ea2e522465494a457e6abc6f4a413ef2b8fdbb1 [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
Leon Clarkee46be812010-01-19 14:06:41 +0000562class MessageDispatchHelperThread;
563
564
Steve Blocka7e24c12009-10-30 11:49:00 +0000565// LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
566// messages. The message data is not managed by LockingCommandMessageQueue.
567// Pointers to the data are passed in and out. Implemented by adding a
568// Mutex to CommandMessageQueue. Includes logging of all puts and gets.
569class LockingCommandMessageQueue BASE_EMBEDDED {
570 public:
571 explicit LockingCommandMessageQueue(int size);
572 ~LockingCommandMessageQueue();
573 bool IsEmpty() const;
574 CommandMessage Get();
575 void Put(const CommandMessage& message);
576 void Clear();
577 private:
578 CommandMessageQueue queue_;
579 Mutex* lock_;
580 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
581};
582
583
584class Debugger {
585 public:
586 static void DebugRequest(const uint16_t* json_request, int length);
587
588 static Handle<Object> MakeJSObject(Vector<const char> constructor_name,
589 int argc, Object*** argv,
590 bool* caught_exception);
591 static Handle<Object> MakeExecutionState(bool* caught_exception);
592 static Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
593 Handle<Object> break_points_hit,
594 bool* caught_exception);
595 static Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
596 Handle<Object> exception,
597 bool uncaught,
598 bool* caught_exception);
599 static Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
600 bool* caught_exception);
601 static Handle<Object> MakeCompileEvent(Handle<Script> script,
602 bool before,
603 bool* caught_exception);
604 static Handle<Object> MakeScriptCollectedEvent(int id,
605 bool* caught_exception);
606 static void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
607 static void OnException(Handle<Object> exception, bool uncaught);
608 static void OnBeforeCompile(Handle<Script> script);
609 static void OnAfterCompile(Handle<Script> script,
610 Handle<JSFunction> fun);
611 static void OnNewFunction(Handle<JSFunction> fun);
612 static void OnScriptCollected(int id);
613 static void ProcessDebugEvent(v8::DebugEvent event,
614 Handle<JSObject> event_data,
615 bool auto_continue);
616 static void NotifyMessageHandler(v8::DebugEvent event,
617 Handle<JSObject> exec_state,
618 Handle<JSObject> event_data,
619 bool auto_continue);
620 static void SetEventListener(Handle<Object> callback, Handle<Object> data);
621 static void SetMessageHandler(v8::Debug::MessageHandler2 handler);
622 static void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
623 int period);
Steve Blockd0582a62009-12-15 09:54:21 +0000624 static void SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +0000625 v8::Debug::DebugMessageDispatchHandler handler,
626 bool provide_locker);
Steve Blocka7e24c12009-10-30 11:49:00 +0000627
628 // Invoke the message handler function.
629 static void InvokeMessageHandler(MessageImpl message);
630
631 // Add a debugger command to the command queue.
632 static void ProcessCommand(Vector<const uint16_t> command,
633 v8::Debug::ClientData* client_data = NULL);
634
635 // Check whether there are commands in the command queue.
636 static bool HasCommands();
637
638 static Handle<Object> Call(Handle<JSFunction> fun,
639 Handle<Object> data,
640 bool* pending_exception);
641
642 // Start the debugger agent listening on the provided port.
Leon Clarkee46be812010-01-19 14:06:41 +0000643 static bool StartAgent(const char* name, int port,
644 bool wait_for_connection = false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000645
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
Leon Clarkee46be812010-01-19 14:06:41 +0000652 static void CallMessageDispatchHandler();
653
Steve Blocka7e24c12009-10-30 11:49:00 +0000654 // Unload the debugger if possible. Only called when no debugger is currently
655 // active.
656 static void UnloadDebugger();
657
658 inline static bool EventActive(v8::DebugEvent event) {
659 ScopedLock with(debugger_access_);
660
661 // Check whether the message handler was been cleared.
662 if (debugger_unload_pending_) {
Leon Clarkee46be812010-01-19 14:06:41 +0000663 if (Debug::debugger_entry() == NULL) {
664 UnloadDebugger();
665 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000666 }
667
668 // Currently argument event is not used.
669 return !compiling_natives_ && Debugger::IsDebuggerActive();
670 }
671
672 static void set_compiling_natives(bool compiling_natives) {
673 Debugger::compiling_natives_ = compiling_natives;
674 }
675 static bool compiling_natives() { return Debugger::compiling_natives_; }
676 static void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
677 static bool is_loading_debugger() { return Debugger::is_loading_debugger_; }
678
679 private:
680 static bool IsDebuggerActive();
681 static void ListenersChanged();
682
683 static Mutex* debugger_access_; // Mutex guarding debugger variables.
684 static Handle<Object> event_listener_; // Global handle to listener.
685 static Handle<Object> event_listener_data_;
686 static bool compiling_natives_; // Are we compiling natives?
687 static bool is_loading_debugger_; // Are we loading the debugger?
688 static bool never_unload_debugger_; // Can we unload the debugger?
689 static v8::Debug::MessageHandler2 message_handler_;
690 static bool debugger_unload_pending_; // Was message handler cleared?
691 static v8::Debug::HostDispatchHandler host_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000692 static Mutex* dispatch_handler_access_; // Mutex guarding dispatch handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000693 static v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000694 static MessageDispatchHelperThread* message_dispatch_helper_thread_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 static int host_dispatch_micros_;
696
697 static DebuggerAgent* agent_;
698
699 static const int kQueueInitialSize = 4;
700 static LockingCommandMessageQueue command_queue_;
701 static Semaphore* command_received_; // Signaled for each command received.
702
703 friend class EnterDebugger;
704};
705
706
707// This class is used for entering the debugger. Create an instance in the stack
708// to enter the debugger. This will set the current break state, make sure the
709// debugger is loaded and switch to the debugger context. If the debugger for
710// some reason could not be entered FailedToEnter will return true.
711class EnterDebugger BASE_EMBEDDED {
712 public:
713 EnterDebugger()
714 : prev_(Debug::debugger_entry()),
715 has_js_frames_(!it_.done()) {
716 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(PREEMPT));
717 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(DEBUGBREAK));
718
719 // Link recursive debugger entry.
720 Debug::set_debugger_entry(this);
721
722 // Store the previous break id and frame id.
723 break_id_ = Debug::break_id();
724 break_frame_id_ = Debug::break_frame_id();
725
726 // Create the new break info. If there is no JavaScript frames there is no
727 // break frame id.
728 if (has_js_frames_) {
729 Debug::NewBreak(it_.frame()->id());
730 } else {
731 Debug::NewBreak(StackFrame::NO_ID);
732 }
733
734 // Make sure that debugger is loaded and enter the debugger context.
735 load_failed_ = !Debug::Load();
736 if (!load_failed_) {
737 // NOTE the member variable save which saves the previous context before
738 // this change.
739 Top::set_context(*Debug::debug_context());
740 }
741 }
742
743 ~EnterDebugger() {
744 // Restore to the previous break state.
745 Debug::SetBreak(break_frame_id_, break_id_);
746
747 // Check for leaving the debugger.
748 if (prev_ == NULL) {
749 // Clear mirror cache when leaving the debugger. Skip this if there is a
750 // pending exception as clearing the mirror cache calls back into
751 // JavaScript. This can happen if the v8::Debug::Call is used in which
752 // case the exception should end up in the calling code.
753 if (!Top::has_pending_exception()) {
754 // Try to avoid any pending debug break breaking in the clear mirror
755 // cache JavaScript code.
756 if (StackGuard::IsDebugBreak()) {
757 Debug::set_interrupts_pending(DEBUGBREAK);
758 StackGuard::Continue(DEBUGBREAK);
759 }
760 Debug::ClearMirrorCache();
761 }
762
763 // Request preemption and debug break when leaving the last debugger entry
764 // if any of these where recorded while debugging.
765 if (Debug::is_interrupt_pending(PREEMPT)) {
766 // This re-scheduling of preemption is to avoid starvation in some
767 // debugging scenarios.
768 Debug::clear_interrupt_pending(PREEMPT);
769 StackGuard::Preempt();
770 }
771 if (Debug::is_interrupt_pending(DEBUGBREAK)) {
772 Debug::clear_interrupt_pending(DEBUGBREAK);
773 StackGuard::DebugBreak();
774 }
775
776 // If there are commands in the queue when leaving the debugger request
777 // that these commands are processed.
778 if (Debugger::HasCommands()) {
779 StackGuard::DebugCommand();
780 }
781
782 // If leaving the debugger with the debugger no longer active unload it.
783 if (!Debugger::IsDebuggerActive()) {
784 Debugger::UnloadDebugger();
785 }
786 }
787
788 // Leaving this debugger entry.
789 Debug::set_debugger_entry(prev_);
790 }
791
792 // Check whether the debugger could be entered.
793 inline bool FailedToEnter() { return load_failed_; }
794
795 // Check whether there are any JavaScript frames on the stack.
796 inline bool HasJavaScriptFrames() { return has_js_frames_; }
797
798 // Get the active context from before entering the debugger.
799 inline Handle<Context> GetContext() { return save_.context(); }
800
801 private:
802 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
803 JavaScriptFrameIterator it_;
804 const bool has_js_frames_; // Were there any JavaScript frames?
805 StackFrame::Id break_frame_id_; // Previous break frame id.
806 int break_id_; // Previous break id.
807 bool load_failed_; // Did the debugger fail to load?
808 SaveContext save_; // Saves previous context.
809};
810
811
812// Stack allocated class for disabling break.
813class DisableBreak BASE_EMBEDDED {
814 public:
815 // Enter the debugger by storing the previous top context and setting the
816 // current top context to the debugger context.
817 explicit DisableBreak(bool disable_break) {
818 prev_disable_break_ = Debug::disable_break();
819 Debug::set_disable_break(disable_break);
820 }
821 ~DisableBreak() {
822 Debug::set_disable_break(prev_disable_break_);
823 }
824
825 private:
826 // The previous state of the disable break used to restore the value when this
827 // object is destructed.
828 bool prev_disable_break_;
829};
830
831
832// Debug_Address encapsulates the Address pointers used in generating debug
833// code.
834class Debug_Address {
835 public:
836 Debug_Address(Debug::AddressId id, int reg = 0)
837 : id_(id), reg_(reg) {
838 ASSERT(reg == 0 || id == Debug::k_register_address);
839 }
840
841 static Debug_Address AfterBreakTarget() {
842 return Debug_Address(Debug::k_after_break_target_address);
843 }
844
845 static Debug_Address DebugBreakReturn() {
846 return Debug_Address(Debug::k_debug_break_return_address);
847 }
848
849 static Debug_Address Register(int reg) {
850 return Debug_Address(Debug::k_register_address, reg);
851 }
852
853 Address address() const {
854 switch (id_) {
855 case Debug::k_after_break_target_address:
856 return reinterpret_cast<Address>(Debug::after_break_target_address());
857 case Debug::k_debug_break_return_address:
858 return reinterpret_cast<Address>(Debug::debug_break_return_address());
859 case Debug::k_register_address:
860 return reinterpret_cast<Address>(Debug::register_address(reg_));
861 default:
862 UNREACHABLE();
863 return NULL;
864 }
865 }
866 private:
867 Debug::AddressId id_;
868 int reg_;
869};
870
Leon Clarkee46be812010-01-19 14:06:41 +0000871// The optional thread that Debug Agent may use to temporary call V8 to process
872// pending debug requests if debuggee is not running V8 at the moment.
873// Techincally it does not call V8 itself, rather it asks embedding program
874// to do this via v8::Debug::HostDispatchHandler
875class MessageDispatchHelperThread: public Thread {
876 public:
877 MessageDispatchHelperThread();
878 ~MessageDispatchHelperThread();
879
880 void Schedule();
881
882 private:
883 void Run();
884
885 Semaphore* const sem_;
886 Mutex* const mutex_;
887 bool already_signalled_;
888
889 DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
890};
891
Steve Blocka7e24c12009-10-30 11:49:00 +0000892
893} } // namespace v8::internal
894
895#endif // ENABLE_DEBUGGER_SUPPORT
896
897#endif // V8_DEBUG_H_