blob: 0d63085f151e50fe50395bed436fb07cca3ef834 [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"
Steve Blocka7e24c12009-10-30 11:49:00 +000032#include "debug-agent.h"
33#include "execution.h"
34#include "factory.h"
35#include "hashmap.h"
36#include "platform.h"
37#include "string-stream.h"
38#include "v8threads.h"
39
40#ifdef ENABLE_DEBUGGER_SUPPORT
41#include "../include/v8-debug.h"
42
43namespace v8 {
44namespace internal {
45
46
47// Forward declarations.
48class EnterDebugger;
49
50
51// Step actions. NOTE: These values are in macros.py as well.
52enum StepAction {
53 StepNone = -1, // Stepping not prepared.
54 StepOut = 0, // Step out of the current function.
55 StepNext = 1, // Step to the next statement in the current function.
56 StepIn = 2, // Step into new functions invoked or the next statement
57 // in the current function.
58 StepMin = 3, // Perform a minimum step in the current function.
59 StepInMin = 4 // Step into new functions invoked or perform a minimum step
60 // in the current function.
61};
62
63
64// Type of exception break. NOTE: These values are in macros.py as well.
65enum ExceptionBreakType {
66 BreakException = 0,
67 BreakUncaughtException = 1
68};
69
70
71// Type of exception break. NOTE: These values are in macros.py as well.
72enum BreakLocatorType {
73 ALL_BREAK_LOCATIONS = 0,
74 SOURCE_BREAK_LOCATIONS = 1
75};
76
77
78// Class for iterating through the break points in a function and changing
79// them.
80class BreakLocationIterator {
81 public:
82 explicit BreakLocationIterator(Handle<DebugInfo> debug_info,
83 BreakLocatorType type);
84 virtual ~BreakLocationIterator();
85
86 void Next();
87 void Next(int count);
88 void FindBreakLocationFromAddress(Address pc);
89 void FindBreakLocationFromPosition(int position);
90 void Reset();
91 bool Done() const;
92 void SetBreakPoint(Handle<Object> break_point_object);
93 void ClearBreakPoint(Handle<Object> break_point_object);
94 void SetOneShot();
95 void ClearOneShot();
96 void PrepareStepIn();
97 bool IsExit() const;
98 bool HasBreakPoint();
99 bool IsDebugBreak();
100 Object* BreakPointObjects();
101 void ClearAllDebugBreak();
102
103
Steve Blockd0582a62009-12-15 09:54:21 +0000104 inline int code_position() {
105 return static_cast<int>(pc() - debug_info_->code()->entry());
106 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000107 inline int break_point() { return break_point_; }
108 inline int position() { return position_; }
109 inline int statement_position() { return statement_position_; }
110 inline Address pc() { return reloc_iterator_->rinfo()->pc(); }
111 inline Code* code() { return debug_info_->code(); }
112 inline RelocInfo* rinfo() { return reloc_iterator_->rinfo(); }
113 inline RelocInfo::Mode rmode() const {
114 return reloc_iterator_->rinfo()->rmode();
115 }
116 inline RelocInfo* original_rinfo() {
117 return reloc_iterator_original_->rinfo();
118 }
119 inline RelocInfo::Mode original_rmode() const {
120 return reloc_iterator_original_->rinfo()->rmode();
121 }
122
123 bool IsDebuggerStatement();
124
125 protected:
126 bool RinfoDone() const;
127 void RinfoNext();
128
129 BreakLocatorType type_;
130 int break_point_;
131 int position_;
132 int statement_position_;
133 Handle<DebugInfo> debug_info_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000134 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
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100148 bool IsDebugBreakSlot();
149 bool IsDebugBreakAtSlot();
150 void SetDebugBreakAtSlot();
151 void ClearDebugBreakAtSlot();
152
Steve Blocka7e24c12009-10-30 11:49:00 +0000153 DISALLOW_COPY_AND_ASSIGN(BreakLocationIterator);
154};
155
156
157// Cache of all script objects in the heap. When a script is added a weak handle
158// to it is created and that weak handle is stored in the cache. The weak handle
159// callback takes care of removing the script from the cache. The key used in
160// the cache is the script id.
161class ScriptCache : private HashMap {
162 public:
163 ScriptCache() : HashMap(ScriptMatch), collected_scripts_(10) {}
164 virtual ~ScriptCache() { Clear(); }
165
166 // Add script to the cache.
167 void Add(Handle<Script> script);
168
169 // Return the scripts in the cache.
170 Handle<FixedArray> GetScripts();
171
172 // Generate debugger events for collected scripts.
173 void ProcessCollectedScripts();
174
175 private:
176 // Calculate the hash value from the key (script id).
177 static uint32_t Hash(int key) { return ComputeIntegerHash(key); }
178
179 // Scripts match if their keys (script id) match.
180 static bool ScriptMatch(void* key1, void* key2) { return key1 == key2; }
181
182 // Clear the cache releasing all the weak handles.
183 void Clear();
184
185 // Weak handle callback for scripts in the cache.
186 static void HandleWeakScript(v8::Persistent<v8::Value> obj, void* data);
187
188 // List used during GC to temporarily store id's of collected scripts.
189 List<int> collected_scripts_;
190};
191
192
193// Linked list holding debug info objects. The debug info objects are kept as
194// weak handles to avoid a debug info object to keep a function alive.
195class DebugInfoListNode {
196 public:
197 explicit DebugInfoListNode(DebugInfo* debug_info);
198 virtual ~DebugInfoListNode();
199
200 DebugInfoListNode* next() { return next_; }
201 void set_next(DebugInfoListNode* next) { next_ = next; }
202 Handle<DebugInfo> debug_info() { return debug_info_; }
203
204 private:
205 // Global (weak) handle to the debug info object.
206 Handle<DebugInfo> debug_info_;
207
208 // Next pointer for linked list.
209 DebugInfoListNode* next_;
210};
211
212
213// This class contains the debugger support. The main purpose is to handle
214// setting break points in the code.
215//
216// This class controls the debug info for all functions which currently have
217// active breakpoints in them. This debug info is held in the heap root object
218// debug_info which is a FixedArray. Each entry in this list is of class
219// DebugInfo.
220class Debug {
221 public:
222 static void Setup(bool create_heap_objects);
223 static bool Load();
224 static void Unload();
225 static bool IsLoaded() { return !debug_context_.is_null(); }
226 static bool InDebugger() { return thread_local_.debugger_entry_ != NULL; }
227 static void PreemptionWhileInDebugger();
228 static void Iterate(ObjectVisitor* v);
229
230 static Object* Break(Arguments args);
231 static void SetBreakPoint(Handle<SharedFunctionInfo> shared,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100232 Handle<Object> break_point_object,
233 int* source_position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000234 static void ClearBreakPoint(Handle<Object> break_point_object);
235 static void ClearAllBreakPoints();
236 static void FloodWithOneShot(Handle<SharedFunctionInfo> shared);
237 static void FloodHandlerWithOneShot();
238 static void ChangeBreakOnException(ExceptionBreakType type, bool enable);
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100239 static bool IsBreakOnException(ExceptionBreakType type);
Steve Blocka7e24c12009-10-30 11:49:00 +0000240 static void PrepareStep(StepAction step_action, int step_count);
241 static void ClearStepping();
242 static bool StepNextContinue(BreakLocationIterator* break_location_iterator,
243 JavaScriptFrame* frame);
244 static Handle<DebugInfo> GetDebugInfo(Handle<SharedFunctionInfo> shared);
245 static bool HasDebugInfo(Handle<SharedFunctionInfo> shared);
246
247 // Returns whether the operation succeeded.
248 static bool EnsureDebugInfo(Handle<SharedFunctionInfo> shared);
249
250 // Returns true if the current stub call is patched to call the debugger.
251 static bool IsDebugBreak(Address addr);
252 // Returns true if the current return statement has been patched to be
253 // a debugger breakpoint.
254 static bool IsDebugBreakAtReturn(RelocInfo* rinfo);
255
256 // Check whether a code stub with the specified major key is a possible break
257 // point location.
258 static bool IsSourceBreakStub(Code* code);
259 static bool IsBreakStub(Code* code);
260
261 // Find the builtin to use for invoking the debug break
262 static Handle<Code> FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode);
263
264 static Handle<Object> GetSourceBreakLocations(
265 Handle<SharedFunctionInfo> shared);
266
267 // Getter for the debug_context.
268 inline static Handle<Context> debug_context() { return debug_context_; }
269
270 // Check whether a global object is the debug global object.
271 static bool IsDebugGlobal(GlobalObject* global);
272
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100273 // Check whether this frame is just about to return.
274 static bool IsBreakAtReturn(JavaScriptFrame* frame);
275
Steve Blocka7e24c12009-10-30 11:49:00 +0000276 // Fast check to see if any break points are active.
277 inline static bool has_break_points() { return has_break_points_; }
278
279 static void NewBreak(StackFrame::Id break_frame_id);
280 static void SetBreak(StackFrame::Id break_frame_id, int break_id);
281 static StackFrame::Id break_frame_id() {
282 return thread_local_.break_frame_id_;
283 }
284 static int break_id() { return thread_local_.break_id_; }
285
286 static bool StepInActive() { return thread_local_.step_into_fp_ != 0; }
287 static void HandleStepIn(Handle<JSFunction> function,
288 Handle<Object> holder,
289 Address fp,
290 bool is_constructor);
291 static Address step_in_fp() { return thread_local_.step_into_fp_; }
292 static Address* step_in_fp_addr() { return &thread_local_.step_into_fp_; }
293
294 static bool StepOutActive() { return thread_local_.step_out_fp_ != 0; }
295 static Address step_out_fp() { return thread_local_.step_out_fp_; }
296
297 static EnterDebugger* debugger_entry() {
298 return thread_local_.debugger_entry_;
299 }
300 static void set_debugger_entry(EnterDebugger* entry) {
301 thread_local_.debugger_entry_ = entry;
302 }
303
304 // Check whether any of the specified interrupts are pending.
305 static bool is_interrupt_pending(InterruptFlag what) {
306 return (thread_local_.pending_interrupts_ & what) != 0;
307 }
308
309 // Set specified interrupts as pending.
310 static void set_interrupts_pending(InterruptFlag what) {
311 thread_local_.pending_interrupts_ |= what;
312 }
313
314 // Clear specified interrupts from pending.
315 static void clear_interrupt_pending(InterruptFlag what) {
316 thread_local_.pending_interrupts_ &= ~static_cast<int>(what);
317 }
318
319 // Getter and setter for the disable break state.
320 static bool disable_break() { return disable_break_; }
321 static void set_disable_break(bool disable_break) {
322 disable_break_ = disable_break;
323 }
324
325 // Getters for the current exception break state.
326 static bool break_on_exception() { return break_on_exception_; }
327 static bool break_on_uncaught_exception() {
328 return break_on_uncaught_exception_;
329 }
330
331 enum AddressId {
332 k_after_break_target_address,
333 k_debug_break_return_address,
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100334 k_debug_break_slot_address,
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100335 k_restarter_frame_function_pointer
Steve Blocka7e24c12009-10-30 11:49:00 +0000336 };
337
338 // Support for setting the address to jump to when returning from break point.
339 static Address* after_break_target_address() {
340 return reinterpret_cast<Address*>(&thread_local_.after_break_target_);
341 }
Ben Murdochbb769b22010-08-11 14:56:33 +0100342 static Address* restarter_frame_function_pointer_address() {
343 Object*** address = &thread_local_.restarter_frame_function_pointer_;
344 return reinterpret_cast<Address*>(address);
345 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000346
347 // Support for saving/restoring registers when handling debug break calls.
348 static Object** register_address(int r) {
349 return &registers_[r];
350 }
351
352 // Access to the debug break on return code.
353 static Code* debug_break_return() { return debug_break_return_; }
354 static Code** debug_break_return_address() {
355 return &debug_break_return_;
356 }
357
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100358 // Access to the debug break in debug break slot code.
359 static Code* debug_break_slot() { return debug_break_slot_; }
360 static Code** debug_break_slot_address() {
361 return &debug_break_slot_;
362 }
363
Steve Blocka7e24c12009-10-30 11:49:00 +0000364 static const int kEstimatedNofDebugInfoEntries = 16;
365 static const int kEstimatedNofBreakPointsInFunction = 16;
366
367 static void HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data);
368
369 friend class Debugger;
370 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
371 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
372
373 // Threading support.
374 static char* ArchiveDebug(char* to);
375 static char* RestoreDebug(char* from);
376 static int ArchiveSpacePerThread();
377 static void FreeThreadResources() { }
378
379 // Mirror cache handling.
380 static void ClearMirrorCache();
381
382 // Script cache handling.
383 static void CreateScriptCache();
384 static void DestroyScriptCache();
385 static void AddScriptToScriptCache(Handle<Script> script);
386 static Handle<FixedArray> GetLoadedScripts();
387
388 // Garbage collection notifications.
389 static void AfterGarbageCollection();
390
Steve Blocka7e24c12009-10-30 11:49:00 +0000391 // Code generator routines.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100392 static void GenerateSlot(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000393 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
394 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
395 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
396 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
397 static void GenerateConstructCallDebugBreak(MacroAssembler* masm);
398 static void GenerateReturnDebugBreak(MacroAssembler* masm);
399 static void GenerateStubNoRegistersDebugBreak(MacroAssembler* masm);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100400 static void GenerateSlotDebugBreak(MacroAssembler* masm);
Steve Block6ded16b2010-05-10 14:33:55 +0100401 static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
Iain Merrick75681382010-08-19 15:07:18 +0100402
403 // FrameDropper is a code replacement for a JavaScript frame with possibly
404 // several frames above.
405 // There is no calling conventions here, because it never actually gets
406 // called, it only gets returned to.
Steve Block6ded16b2010-05-10 14:33:55 +0100407 static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000408
409 // Called from stub-cache.cc.
410 static void GenerateCallICDebugBreak(MacroAssembler* masm);
411
Steve Block8defd9f2010-07-08 12:39:36 +0100412 // Describes how exactly a frame has been dropped from stack.
413 enum FrameDropMode {
414 // No frame has been dropped.
415 FRAMES_UNTOUCHED,
416 // The top JS frame had been calling IC stub. IC stub mustn't be called now.
417 FRAME_DROPPED_IN_IC_CALL,
418 // The top JS frame had been calling debug break slot stub. Patch the
419 // address this stub jumps to in the end.
420 FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
421 // The top JS frame had been calling some C++ function. The return address
422 // gets patched automatically.
423 FRAME_DROPPED_IN_DIRECT_CALL
424 };
425
426 static void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
Ben Murdochbb769b22010-08-11 14:56:33 +0100427 FrameDropMode mode,
428 Object** restarter_frame_function_pointer);
Steve Block6ded16b2010-05-10 14:33:55 +0100429
Ben Murdochbb769b22010-08-11 14:56:33 +0100430 // Initializes an artificial stack frame. The data it contains is used for:
431 // a. successful work of frame dropper code which eventually gets control,
432 // b. being compatible with regular stack structure for various stack
433 // iterators.
434 // Returns address of stack allocated pointer to restarted function,
435 // the value that is called 'restarter_frame_function_pointer'. The value
436 // at this address (possibly updated by GC) may be used later when preparing
437 // 'step in' operation.
Ben Murdochbb769b22010-08-11 14:56:33 +0100438 static Object** SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
439 Handle<Code> code);
440
Steve Block6ded16b2010-05-10 14:33:55 +0100441 static const int kFrameDropperFrameSize;
442
Iain Merrick75681382010-08-19 15:07:18 +0100443 // Architecture-specific constant.
444 static const bool kFrameDropperSupported;
445
Steve Blocka7e24c12009-10-30 11:49:00 +0000446 private:
447 static bool CompileDebuggerScript(int index);
448 static void ClearOneShot();
449 static void ActivateStepIn(StackFrame* frame);
450 static void ClearStepIn();
451 static void ActivateStepOut(StackFrame* frame);
452 static void ClearStepOut();
453 static void ClearStepNext();
454 // Returns whether the compile succeeded.
Steve Blocka7e24c12009-10-30 11:49:00 +0000455 static void RemoveDebugInfo(Handle<DebugInfo> debug_info);
456 static void SetAfterBreakTarget(JavaScriptFrame* frame);
457 static Handle<Object> CheckBreakPoints(Handle<Object> break_point);
458 static bool CheckBreakPoint(Handle<Object> break_point_object);
459
460 // Global handle to debug context where all the debugger JavaScript code is
461 // loaded.
462 static Handle<Context> debug_context_;
463
464 // Boolean state indicating whether any break points are set.
465 static bool has_break_points_;
466
467 // Cache of all scripts in the heap.
468 static ScriptCache* script_cache_;
469
470 // List of active debug info objects.
471 static DebugInfoListNode* debug_info_list_;
472
473 static bool disable_break_;
474 static bool break_on_exception_;
475 static bool break_on_uncaught_exception_;
476
477 // Per-thread data.
478 class ThreadLocal {
479 public:
480 // Counter for generating next break id.
481 int break_count_;
482
483 // Current break id.
484 int break_id_;
485
486 // Frame id for the frame of the current break.
487 StackFrame::Id break_frame_id_;
488
489 // Step action for last step performed.
490 StepAction last_step_action_;
491
492 // Source statement position from last step next action.
493 int last_statement_position_;
494
495 // Number of steps left to perform before debug event.
496 int step_count_;
497
498 // Frame pointer from last step next action.
499 Address last_fp_;
500
501 // Frame pointer for frame from which step in was performed.
502 Address step_into_fp_;
503
504 // Frame pointer for the frame where debugger should be called when current
505 // step out action is completed.
506 Address step_out_fp_;
507
508 // Storage location for jump when exiting debug break calls.
509 Address after_break_target_;
510
Steve Block8defd9f2010-07-08 12:39:36 +0100511 // Stores the way how LiveEdit has patched the stack. It is used when
512 // debugger returns control back to user script.
513 FrameDropMode frame_drop_mode_;
Steve Block6ded16b2010-05-10 14:33:55 +0100514
Steve Blocka7e24c12009-10-30 11:49:00 +0000515 // Top debugger entry.
516 EnterDebugger* debugger_entry_;
517
518 // Pending interrupts scheduled while debugging.
519 int pending_interrupts_;
Ben Murdochbb769b22010-08-11 14:56:33 +0100520
521 // When restarter frame is on stack, stores the address
522 // of the pointer to function being restarted. Otherwise (most of the time)
523 // stores NULL. This pointer is used with 'step in' implementation.
524 Object** restarter_frame_function_pointer_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000525 };
526
527 // Storage location for registers when handling debug break calls
528 static JSCallerSavedBuffer registers_;
529 static ThreadLocal thread_local_;
530 static void ThreadInit();
531
532 // Code to call for handling debug break on return.
533 static Code* debug_break_return_;
534
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100535 // Code to call for handling debug break in debug break slots.
536 static Code* debug_break_slot_;
537
Steve Blocka7e24c12009-10-30 11:49:00 +0000538 DISALLOW_COPY_AND_ASSIGN(Debug);
539};
540
541
542// Message delivered to the message handler callback. This is either a debugger
543// event or the response to a command.
544class MessageImpl: public v8::Debug::Message {
545 public:
546 // Create a message object for a debug event.
547 static MessageImpl NewEvent(DebugEvent event,
548 bool running,
549 Handle<JSObject> exec_state,
550 Handle<JSObject> event_data);
551
552 // Create a message object for the response to a debug command.
553 static MessageImpl NewResponse(DebugEvent event,
554 bool running,
555 Handle<JSObject> exec_state,
556 Handle<JSObject> event_data,
557 Handle<String> response_json,
558 v8::Debug::ClientData* client_data);
559
560 // Implementation of interface v8::Debug::Message.
561 virtual bool IsEvent() const;
562 virtual bool IsResponse() const;
563 virtual DebugEvent GetEvent() const;
564 virtual bool WillStartRunning() const;
565 virtual v8::Handle<v8::Object> GetExecutionState() const;
566 virtual v8::Handle<v8::Object> GetEventData() const;
567 virtual v8::Handle<v8::String> GetJSON() const;
568 virtual v8::Handle<v8::Context> GetEventContext() const;
569 virtual v8::Debug::ClientData* GetClientData() const;
570
571 private:
572 MessageImpl(bool is_event,
573 DebugEvent event,
574 bool running,
575 Handle<JSObject> exec_state,
576 Handle<JSObject> event_data,
577 Handle<String> response_json,
578 v8::Debug::ClientData* client_data);
579
580 bool is_event_; // Does this message represent a debug event?
581 DebugEvent event_; // Debug event causing the break.
582 bool running_; // Will the VM start running after this event?
583 Handle<JSObject> exec_state_; // Current execution state.
584 Handle<JSObject> event_data_; // Data associated with the event.
585 Handle<String> response_json_; // Response JSON if message holds a response.
586 v8::Debug::ClientData* client_data_; // Client data passed with the request.
587};
588
589
Leon Clarkef7060e22010-06-03 12:02:55 +0100590// Details of the debug event delivered to the debug event listener.
591class EventDetailsImpl : public v8::Debug::EventDetails {
592 public:
593 EventDetailsImpl(DebugEvent event,
594 Handle<JSObject> exec_state,
595 Handle<JSObject> event_data,
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100596 Handle<Object> callback_data,
597 v8::Debug::ClientData* client_data);
Leon Clarkef7060e22010-06-03 12:02:55 +0100598 virtual DebugEvent GetEvent() const;
599 virtual v8::Handle<v8::Object> GetExecutionState() const;
600 virtual v8::Handle<v8::Object> GetEventData() const;
601 virtual v8::Handle<v8::Context> GetEventContext() const;
602 virtual v8::Handle<v8::Value> GetCallbackData() const;
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100603 virtual v8::Debug::ClientData* GetClientData() const;
Leon Clarkef7060e22010-06-03 12:02:55 +0100604 private:
605 DebugEvent event_; // Debug event causing the break.
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100606 Handle<JSObject> exec_state_; // Current execution state.
607 Handle<JSObject> event_data_; // Data associated with the event.
608 Handle<Object> callback_data_; // User data passed with the callback
609 // when it was registered.
610 v8::Debug::ClientData* client_data_; // Data passed to DebugBreakForCommand.
Leon Clarkef7060e22010-06-03 12:02:55 +0100611};
612
613
Steve Blocka7e24c12009-10-30 11:49:00 +0000614// Message send by user to v8 debugger or debugger output message.
615// In addition to command text it may contain a pointer to some user data
616// which are expected to be passed along with the command reponse to message
617// handler.
618class CommandMessage {
619 public:
620 static CommandMessage New(const Vector<uint16_t>& command,
621 v8::Debug::ClientData* data);
622 CommandMessage();
623 ~CommandMessage();
624
625 // Deletes user data and disposes of the text.
626 void Dispose();
627 Vector<uint16_t> text() const { return text_; }
628 v8::Debug::ClientData* client_data() const { return client_data_; }
629 private:
630 CommandMessage(const Vector<uint16_t>& text,
631 v8::Debug::ClientData* data);
632
633 Vector<uint16_t> text_;
634 v8::Debug::ClientData* client_data_;
635};
636
637// A Queue of CommandMessage objects. A thread-safe version is
638// LockingCommandMessageQueue, based on this class.
639class CommandMessageQueue BASE_EMBEDDED {
640 public:
641 explicit CommandMessageQueue(int size);
642 ~CommandMessageQueue();
643 bool IsEmpty() const { return start_ == end_; }
644 CommandMessage Get();
645 void Put(const CommandMessage& message);
646 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
647 private:
648 // Doubles the size of the message queue, and copies the messages.
649 void Expand();
650
651 CommandMessage* messages_;
652 int start_;
653 int end_;
654 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
655};
656
657
Leon Clarkee46be812010-01-19 14:06:41 +0000658class MessageDispatchHelperThread;
659
660
Steve Blocka7e24c12009-10-30 11:49:00 +0000661// LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
662// messages. The message data is not managed by LockingCommandMessageQueue.
663// Pointers to the data are passed in and out. Implemented by adding a
664// Mutex to CommandMessageQueue. Includes logging of all puts and gets.
665class LockingCommandMessageQueue BASE_EMBEDDED {
666 public:
667 explicit LockingCommandMessageQueue(int size);
668 ~LockingCommandMessageQueue();
669 bool IsEmpty() const;
670 CommandMessage Get();
671 void Put(const CommandMessage& message);
672 void Clear();
673 private:
674 CommandMessageQueue queue_;
675 Mutex* lock_;
676 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
677};
678
679
680class Debugger {
681 public:
682 static void DebugRequest(const uint16_t* json_request, int length);
683
684 static Handle<Object> MakeJSObject(Vector<const char> constructor_name,
685 int argc, Object*** argv,
686 bool* caught_exception);
687 static Handle<Object> MakeExecutionState(bool* caught_exception);
688 static Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
689 Handle<Object> break_points_hit,
690 bool* caught_exception);
691 static Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
692 Handle<Object> exception,
693 bool uncaught,
694 bool* caught_exception);
695 static Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
696 bool* caught_exception);
697 static Handle<Object> MakeCompileEvent(Handle<Script> script,
698 bool before,
699 bool* caught_exception);
700 static Handle<Object> MakeScriptCollectedEvent(int id,
701 bool* caught_exception);
702 static void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
703 static void OnException(Handle<Object> exception, bool uncaught);
704 static void OnBeforeCompile(Handle<Script> script);
Steve Block6ded16b2010-05-10 14:33:55 +0100705
706 enum AfterCompileFlags {
707 NO_AFTER_COMPILE_FLAGS,
708 SEND_WHEN_DEBUGGING
709 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000710 static void OnAfterCompile(Handle<Script> script,
Steve Block6ded16b2010-05-10 14:33:55 +0100711 AfterCompileFlags after_compile_flags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000712 static void OnNewFunction(Handle<JSFunction> fun);
713 static void OnScriptCollected(int id);
714 static void ProcessDebugEvent(v8::DebugEvent event,
715 Handle<JSObject> event_data,
716 bool auto_continue);
717 static void NotifyMessageHandler(v8::DebugEvent event,
718 Handle<JSObject> exec_state,
719 Handle<JSObject> event_data,
720 bool auto_continue);
721 static void SetEventListener(Handle<Object> callback, Handle<Object> data);
722 static void SetMessageHandler(v8::Debug::MessageHandler2 handler);
723 static void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
724 int period);
Steve Blockd0582a62009-12-15 09:54:21 +0000725 static void SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +0000726 v8::Debug::DebugMessageDispatchHandler handler,
727 bool provide_locker);
Steve Blocka7e24c12009-10-30 11:49:00 +0000728
729 // Invoke the message handler function.
730 static void InvokeMessageHandler(MessageImpl message);
731
732 // Add a debugger command to the command queue.
733 static void ProcessCommand(Vector<const uint16_t> command,
734 v8::Debug::ClientData* client_data = NULL);
735
736 // Check whether there are commands in the command queue.
737 static bool HasCommands();
738
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100739 // Enqueue a debugger command to the command queue for event listeners.
740 static void EnqueueDebugCommand(v8::Debug::ClientData* client_data = NULL);
741
Steve Blocka7e24c12009-10-30 11:49:00 +0000742 static Handle<Object> Call(Handle<JSFunction> fun,
743 Handle<Object> data,
744 bool* pending_exception);
745
746 // Start the debugger agent listening on the provided port.
Leon Clarkee46be812010-01-19 14:06:41 +0000747 static bool StartAgent(const char* name, int port,
748 bool wait_for_connection = false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000749
750 // Stop the debugger agent.
751 static void StopAgent();
752
753 // Blocks until the agent has started listening for connections
754 static void WaitForAgent();
755
Leon Clarkee46be812010-01-19 14:06:41 +0000756 static void CallMessageDispatchHandler();
757
Steve Block6ded16b2010-05-10 14:33:55 +0100758 static Handle<Context> GetDebugContext();
759
Steve Blocka7e24c12009-10-30 11:49:00 +0000760 // Unload the debugger if possible. Only called when no debugger is currently
761 // active.
762 static void UnloadDebugger();
Steve Block6ded16b2010-05-10 14:33:55 +0100763 friend void ForceUnloadDebugger(); // In test-debug.cc
Steve Blocka7e24c12009-10-30 11:49:00 +0000764
765 inline static bool EventActive(v8::DebugEvent event) {
766 ScopedLock with(debugger_access_);
767
768 // Check whether the message handler was been cleared.
769 if (debugger_unload_pending_) {
Leon Clarkee46be812010-01-19 14:06:41 +0000770 if (Debug::debugger_entry() == NULL) {
771 UnloadDebugger();
772 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000773 }
774
775 // Currently argument event is not used.
776 return !compiling_natives_ && Debugger::IsDebuggerActive();
777 }
778
779 static void set_compiling_natives(bool compiling_natives) {
780 Debugger::compiling_natives_ = compiling_natives;
781 }
782 static bool compiling_natives() { return Debugger::compiling_natives_; }
783 static void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
784 static bool is_loading_debugger() { return Debugger::is_loading_debugger_; }
785
Steve Blocka7e24c12009-10-30 11:49:00 +0000786 static bool IsDebuggerActive();
Leon Clarkef7060e22010-06-03 12:02:55 +0100787
788 private:
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100789 static void CallEventCallback(v8::DebugEvent event,
790 Handle<Object> exec_state,
791 Handle<Object> event_data,
792 v8::Debug::ClientData* client_data);
793 static void CallCEventCallback(v8::DebugEvent event,
794 Handle<Object> exec_state,
795 Handle<Object> event_data,
796 v8::Debug::ClientData* client_data);
797 static void CallJSEventCallback(v8::DebugEvent event,
798 Handle<Object> exec_state,
799 Handle<Object> event_data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000800 static void ListenersChanged();
801
802 static Mutex* debugger_access_; // Mutex guarding debugger variables.
803 static Handle<Object> event_listener_; // Global handle to listener.
804 static Handle<Object> event_listener_data_;
805 static bool compiling_natives_; // Are we compiling natives?
806 static bool is_loading_debugger_; // Are we loading the debugger?
807 static bool never_unload_debugger_; // Can we unload the debugger?
808 static v8::Debug::MessageHandler2 message_handler_;
809 static bool debugger_unload_pending_; // Was message handler cleared?
810 static v8::Debug::HostDispatchHandler host_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000811 static Mutex* dispatch_handler_access_; // Mutex guarding dispatch handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000812 static v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000813 static MessageDispatchHelperThread* message_dispatch_helper_thread_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000814 static int host_dispatch_micros_;
815
816 static DebuggerAgent* agent_;
817
818 static const int kQueueInitialSize = 4;
819 static LockingCommandMessageQueue command_queue_;
820 static Semaphore* command_received_; // Signaled for each command received.
821
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100822 static LockingCommandMessageQueue event_command_queue_;
823
Steve Blocka7e24c12009-10-30 11:49:00 +0000824 friend class EnterDebugger;
825};
826
827
828// This class is used for entering the debugger. Create an instance in the stack
829// to enter the debugger. This will set the current break state, make sure the
830// debugger is loaded and switch to the debugger context. If the debugger for
831// some reason could not be entered FailedToEnter will return true.
832class EnterDebugger BASE_EMBEDDED {
833 public:
834 EnterDebugger()
835 : prev_(Debug::debugger_entry()),
836 has_js_frames_(!it_.done()) {
837 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(PREEMPT));
838 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(DEBUGBREAK));
839
840 // Link recursive debugger entry.
841 Debug::set_debugger_entry(this);
842
843 // Store the previous break id and frame id.
844 break_id_ = Debug::break_id();
845 break_frame_id_ = Debug::break_frame_id();
846
847 // Create the new break info. If there is no JavaScript frames there is no
848 // break frame id.
849 if (has_js_frames_) {
850 Debug::NewBreak(it_.frame()->id());
851 } else {
852 Debug::NewBreak(StackFrame::NO_ID);
853 }
854
855 // Make sure that debugger is loaded and enter the debugger context.
856 load_failed_ = !Debug::Load();
857 if (!load_failed_) {
858 // NOTE the member variable save which saves the previous context before
859 // this change.
860 Top::set_context(*Debug::debug_context());
861 }
862 }
863
864 ~EnterDebugger() {
865 // Restore to the previous break state.
866 Debug::SetBreak(break_frame_id_, break_id_);
867
868 // Check for leaving the debugger.
869 if (prev_ == NULL) {
870 // Clear mirror cache when leaving the debugger. Skip this if there is a
871 // pending exception as clearing the mirror cache calls back into
872 // JavaScript. This can happen if the v8::Debug::Call is used in which
873 // case the exception should end up in the calling code.
874 if (!Top::has_pending_exception()) {
875 // Try to avoid any pending debug break breaking in the clear mirror
876 // cache JavaScript code.
877 if (StackGuard::IsDebugBreak()) {
878 Debug::set_interrupts_pending(DEBUGBREAK);
879 StackGuard::Continue(DEBUGBREAK);
880 }
881 Debug::ClearMirrorCache();
882 }
883
884 // Request preemption and debug break when leaving the last debugger entry
885 // if any of these where recorded while debugging.
886 if (Debug::is_interrupt_pending(PREEMPT)) {
887 // This re-scheduling of preemption is to avoid starvation in some
888 // debugging scenarios.
889 Debug::clear_interrupt_pending(PREEMPT);
890 StackGuard::Preempt();
891 }
892 if (Debug::is_interrupt_pending(DEBUGBREAK)) {
893 Debug::clear_interrupt_pending(DEBUGBREAK);
894 StackGuard::DebugBreak();
895 }
896
897 // If there are commands in the queue when leaving the debugger request
898 // that these commands are processed.
899 if (Debugger::HasCommands()) {
900 StackGuard::DebugCommand();
901 }
902
903 // If leaving the debugger with the debugger no longer active unload it.
904 if (!Debugger::IsDebuggerActive()) {
905 Debugger::UnloadDebugger();
906 }
907 }
908
909 // Leaving this debugger entry.
910 Debug::set_debugger_entry(prev_);
911 }
912
913 // Check whether the debugger could be entered.
914 inline bool FailedToEnter() { return load_failed_; }
915
916 // Check whether there are any JavaScript frames on the stack.
917 inline bool HasJavaScriptFrames() { return has_js_frames_; }
918
919 // Get the active context from before entering the debugger.
920 inline Handle<Context> GetContext() { return save_.context(); }
921
922 private:
923 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
924 JavaScriptFrameIterator it_;
925 const bool has_js_frames_; // Were there any JavaScript frames?
926 StackFrame::Id break_frame_id_; // Previous break frame id.
927 int break_id_; // Previous break id.
928 bool load_failed_; // Did the debugger fail to load?
929 SaveContext save_; // Saves previous context.
930};
931
932
933// Stack allocated class for disabling break.
934class DisableBreak BASE_EMBEDDED {
935 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000936 explicit DisableBreak(bool disable_break) {
937 prev_disable_break_ = Debug::disable_break();
938 Debug::set_disable_break(disable_break);
939 }
940 ~DisableBreak() {
941 Debug::set_disable_break(prev_disable_break_);
942 }
943
944 private:
945 // The previous state of the disable break used to restore the value when this
946 // object is destructed.
947 bool prev_disable_break_;
948};
949
950
951// Debug_Address encapsulates the Address pointers used in generating debug
952// code.
953class Debug_Address {
954 public:
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100955 explicit Debug_Address(Debug::AddressId id) : id_(id) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000956
957 static Debug_Address AfterBreakTarget() {
958 return Debug_Address(Debug::k_after_break_target_address);
959 }
960
961 static Debug_Address DebugBreakReturn() {
962 return Debug_Address(Debug::k_debug_break_return_address);
963 }
964
Ben Murdochbb769b22010-08-11 14:56:33 +0100965 static Debug_Address RestarterFrameFunctionPointer() {
966 return Debug_Address(Debug::k_restarter_frame_function_pointer);
967 }
968
Steve Blocka7e24c12009-10-30 11:49:00 +0000969 Address address() const {
970 switch (id_) {
971 case Debug::k_after_break_target_address:
972 return reinterpret_cast<Address>(Debug::after_break_target_address());
973 case Debug::k_debug_break_return_address:
974 return reinterpret_cast<Address>(Debug::debug_break_return_address());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100975 case Debug::k_debug_break_slot_address:
976 return reinterpret_cast<Address>(Debug::debug_break_slot_address());
Ben Murdochbb769b22010-08-11 14:56:33 +0100977 case Debug::k_restarter_frame_function_pointer:
978 return reinterpret_cast<Address>(
979 Debug::restarter_frame_function_pointer_address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000980 default:
981 UNREACHABLE();
982 return NULL;
983 }
984 }
985 private:
986 Debug::AddressId id_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000987};
988
Leon Clarkee46be812010-01-19 14:06:41 +0000989// The optional thread that Debug Agent may use to temporary call V8 to process
990// pending debug requests if debuggee is not running V8 at the moment.
991// Techincally it does not call V8 itself, rather it asks embedding program
992// to do this via v8::Debug::HostDispatchHandler
993class MessageDispatchHelperThread: public Thread {
994 public:
995 MessageDispatchHelperThread();
996 ~MessageDispatchHelperThread();
997
998 void Schedule();
999
1000 private:
1001 void Run();
1002
1003 Semaphore* const sem_;
1004 Mutex* const mutex_;
1005 bool already_signalled_;
1006
1007 DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
1008};
1009
Steve Blocka7e24c12009-10-30 11:49:00 +00001010
1011} } // namespace v8::internal
1012
1013#endif // ENABLE_DEBUGGER_SUPPORT
1014
1015#endif // V8_DEBUG_H_