blob: 8b3b29e6362e44a24683c622c99152291921bb71 [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);
239 static void PrepareStep(StepAction step_action, int step_count);
240 static void ClearStepping();
241 static bool StepNextContinue(BreakLocationIterator* break_location_iterator,
242 JavaScriptFrame* frame);
243 static Handle<DebugInfo> GetDebugInfo(Handle<SharedFunctionInfo> shared);
244 static bool HasDebugInfo(Handle<SharedFunctionInfo> shared);
245
246 // Returns whether the operation succeeded.
247 static bool EnsureDebugInfo(Handle<SharedFunctionInfo> shared);
248
249 // Returns true if the current stub call is patched to call the debugger.
250 static bool IsDebugBreak(Address addr);
251 // Returns true if the current return statement has been patched to be
252 // a debugger breakpoint.
253 static bool IsDebugBreakAtReturn(RelocInfo* rinfo);
254
255 // Check whether a code stub with the specified major key is a possible break
256 // point location.
257 static bool IsSourceBreakStub(Code* code);
258 static bool IsBreakStub(Code* code);
259
260 // Find the builtin to use for invoking the debug break
261 static Handle<Code> FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode);
262
263 static Handle<Object> GetSourceBreakLocations(
264 Handle<SharedFunctionInfo> shared);
265
266 // Getter for the debug_context.
267 inline static Handle<Context> debug_context() { return debug_context_; }
268
269 // Check whether a global object is the debug global object.
270 static bool IsDebugGlobal(GlobalObject* global);
271
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100272 // Check whether this frame is just about to return.
273 static bool IsBreakAtReturn(JavaScriptFrame* frame);
274
Steve Blocka7e24c12009-10-30 11:49:00 +0000275 // Fast check to see if any break points are active.
276 inline static bool has_break_points() { return has_break_points_; }
277
278 static void NewBreak(StackFrame::Id break_frame_id);
279 static void SetBreak(StackFrame::Id break_frame_id, int break_id);
280 static StackFrame::Id break_frame_id() {
281 return thread_local_.break_frame_id_;
282 }
283 static int break_id() { return thread_local_.break_id_; }
284
285 static bool StepInActive() { return thread_local_.step_into_fp_ != 0; }
286 static void HandleStepIn(Handle<JSFunction> function,
287 Handle<Object> holder,
288 Address fp,
289 bool is_constructor);
290 static Address step_in_fp() { return thread_local_.step_into_fp_; }
291 static Address* step_in_fp_addr() { return &thread_local_.step_into_fp_; }
292
293 static bool StepOutActive() { return thread_local_.step_out_fp_ != 0; }
294 static Address step_out_fp() { return thread_local_.step_out_fp_; }
295
296 static EnterDebugger* debugger_entry() {
297 return thread_local_.debugger_entry_;
298 }
299 static void set_debugger_entry(EnterDebugger* entry) {
300 thread_local_.debugger_entry_ = entry;
301 }
302
303 // Check whether any of the specified interrupts are pending.
304 static bool is_interrupt_pending(InterruptFlag what) {
305 return (thread_local_.pending_interrupts_ & what) != 0;
306 }
307
308 // Set specified interrupts as pending.
309 static void set_interrupts_pending(InterruptFlag what) {
310 thread_local_.pending_interrupts_ |= what;
311 }
312
313 // Clear specified interrupts from pending.
314 static void clear_interrupt_pending(InterruptFlag what) {
315 thread_local_.pending_interrupts_ &= ~static_cast<int>(what);
316 }
317
318 // Getter and setter for the disable break state.
319 static bool disable_break() { return disable_break_; }
320 static void set_disable_break(bool disable_break) {
321 disable_break_ = disable_break;
322 }
323
324 // Getters for the current exception break state.
325 static bool break_on_exception() { return break_on_exception_; }
326 static bool break_on_uncaught_exception() {
327 return break_on_uncaught_exception_;
328 }
329
330 enum AddressId {
331 k_after_break_target_address,
332 k_debug_break_return_address,
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100333 k_debug_break_slot_address,
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100334 k_restarter_frame_function_pointer
Steve Blocka7e24c12009-10-30 11:49:00 +0000335 };
336
337 // Support for setting the address to jump to when returning from break point.
338 static Address* after_break_target_address() {
339 return reinterpret_cast<Address*>(&thread_local_.after_break_target_);
340 }
Ben Murdochbb769b22010-08-11 14:56:33 +0100341 static Address* restarter_frame_function_pointer_address() {
342 Object*** address = &thread_local_.restarter_frame_function_pointer_;
343 return reinterpret_cast<Address*>(address);
344 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000345
346 // Support for saving/restoring registers when handling debug break calls.
347 static Object** register_address(int r) {
348 return &registers_[r];
349 }
350
351 // Access to the debug break on return code.
352 static Code* debug_break_return() { return debug_break_return_; }
353 static Code** debug_break_return_address() {
354 return &debug_break_return_;
355 }
356
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100357 // Access to the debug break in debug break slot code.
358 static Code* debug_break_slot() { return debug_break_slot_; }
359 static Code** debug_break_slot_address() {
360 return &debug_break_slot_;
361 }
362
Steve Blocka7e24c12009-10-30 11:49:00 +0000363 static const int kEstimatedNofDebugInfoEntries = 16;
364 static const int kEstimatedNofBreakPointsInFunction = 16;
365
366 static void HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data);
367
368 friend class Debugger;
369 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
370 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
371
372 // Threading support.
373 static char* ArchiveDebug(char* to);
374 static char* RestoreDebug(char* from);
375 static int ArchiveSpacePerThread();
376 static void FreeThreadResources() { }
377
378 // Mirror cache handling.
379 static void ClearMirrorCache();
380
381 // Script cache handling.
382 static void CreateScriptCache();
383 static void DestroyScriptCache();
384 static void AddScriptToScriptCache(Handle<Script> script);
385 static Handle<FixedArray> GetLoadedScripts();
386
387 // Garbage collection notifications.
388 static void AfterGarbageCollection();
389
Steve Blocka7e24c12009-10-30 11:49:00 +0000390 // Code generator routines.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100391 static void GenerateSlot(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000392 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
393 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
394 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
395 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
396 static void GenerateConstructCallDebugBreak(MacroAssembler* masm);
397 static void GenerateReturnDebugBreak(MacroAssembler* masm);
398 static void GenerateStubNoRegistersDebugBreak(MacroAssembler* masm);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100399 static void GenerateSlotDebugBreak(MacroAssembler* masm);
Steve Block6ded16b2010-05-10 14:33:55 +0100400 static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
Iain Merrick75681382010-08-19 15:07:18 +0100401
402 // FrameDropper is a code replacement for a JavaScript frame with possibly
403 // several frames above.
404 // There is no calling conventions here, because it never actually gets
405 // called, it only gets returned to.
Steve Block6ded16b2010-05-10 14:33:55 +0100406 static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000407
408 // Called from stub-cache.cc.
409 static void GenerateCallICDebugBreak(MacroAssembler* masm);
410
Steve Block8defd9f2010-07-08 12:39:36 +0100411 // Describes how exactly a frame has been dropped from stack.
412 enum FrameDropMode {
413 // No frame has been dropped.
414 FRAMES_UNTOUCHED,
415 // The top JS frame had been calling IC stub. IC stub mustn't be called now.
416 FRAME_DROPPED_IN_IC_CALL,
417 // The top JS frame had been calling debug break slot stub. Patch the
418 // address this stub jumps to in the end.
419 FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
420 // The top JS frame had been calling some C++ function. The return address
421 // gets patched automatically.
422 FRAME_DROPPED_IN_DIRECT_CALL
423 };
424
425 static void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
Ben Murdochbb769b22010-08-11 14:56:33 +0100426 FrameDropMode mode,
427 Object** restarter_frame_function_pointer);
Steve Block6ded16b2010-05-10 14:33:55 +0100428
Ben Murdochbb769b22010-08-11 14:56:33 +0100429 // Initializes an artificial stack frame. The data it contains is used for:
430 // a. successful work of frame dropper code which eventually gets control,
431 // b. being compatible with regular stack structure for various stack
432 // iterators.
433 // Returns address of stack allocated pointer to restarted function,
434 // the value that is called 'restarter_frame_function_pointer'. The value
435 // at this address (possibly updated by GC) may be used later when preparing
436 // 'step in' operation.
Ben Murdochbb769b22010-08-11 14:56:33 +0100437 static Object** SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
438 Handle<Code> code);
439
Steve Block6ded16b2010-05-10 14:33:55 +0100440 static const int kFrameDropperFrameSize;
441
Iain Merrick75681382010-08-19 15:07:18 +0100442 // Architecture-specific constant.
443 static const bool kFrameDropperSupported;
444
Steve Blocka7e24c12009-10-30 11:49:00 +0000445 private:
446 static bool CompileDebuggerScript(int index);
447 static void ClearOneShot();
448 static void ActivateStepIn(StackFrame* frame);
449 static void ClearStepIn();
450 static void ActivateStepOut(StackFrame* frame);
451 static void ClearStepOut();
452 static void ClearStepNext();
453 // Returns whether the compile succeeded.
Steve Blocka7e24c12009-10-30 11:49:00 +0000454 static void RemoveDebugInfo(Handle<DebugInfo> debug_info);
455 static void SetAfterBreakTarget(JavaScriptFrame* frame);
456 static Handle<Object> CheckBreakPoints(Handle<Object> break_point);
457 static bool CheckBreakPoint(Handle<Object> break_point_object);
458
459 // Global handle to debug context where all the debugger JavaScript code is
460 // loaded.
461 static Handle<Context> debug_context_;
462
463 // Boolean state indicating whether any break points are set.
464 static bool has_break_points_;
465
466 // Cache of all scripts in the heap.
467 static ScriptCache* script_cache_;
468
469 // List of active debug info objects.
470 static DebugInfoListNode* debug_info_list_;
471
472 static bool disable_break_;
473 static bool break_on_exception_;
474 static bool break_on_uncaught_exception_;
475
476 // Per-thread data.
477 class ThreadLocal {
478 public:
479 // Counter for generating next break id.
480 int break_count_;
481
482 // Current break id.
483 int break_id_;
484
485 // Frame id for the frame of the current break.
486 StackFrame::Id break_frame_id_;
487
488 // Step action for last step performed.
489 StepAction last_step_action_;
490
491 // Source statement position from last step next action.
492 int last_statement_position_;
493
494 // Number of steps left to perform before debug event.
495 int step_count_;
496
497 // Frame pointer from last step next action.
498 Address last_fp_;
499
500 // Frame pointer for frame from which step in was performed.
501 Address step_into_fp_;
502
503 // Frame pointer for the frame where debugger should be called when current
504 // step out action is completed.
505 Address step_out_fp_;
506
507 // Storage location for jump when exiting debug break calls.
508 Address after_break_target_;
509
Steve Block8defd9f2010-07-08 12:39:36 +0100510 // Stores the way how LiveEdit has patched the stack. It is used when
511 // debugger returns control back to user script.
512 FrameDropMode frame_drop_mode_;
Steve Block6ded16b2010-05-10 14:33:55 +0100513
Steve Blocka7e24c12009-10-30 11:49:00 +0000514 // Top debugger entry.
515 EnterDebugger* debugger_entry_;
516
517 // Pending interrupts scheduled while debugging.
518 int pending_interrupts_;
Ben Murdochbb769b22010-08-11 14:56:33 +0100519
520 // When restarter frame is on stack, stores the address
521 // of the pointer to function being restarted. Otherwise (most of the time)
522 // stores NULL. This pointer is used with 'step in' implementation.
523 Object** restarter_frame_function_pointer_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000524 };
525
526 // Storage location for registers when handling debug break calls
527 static JSCallerSavedBuffer registers_;
528 static ThreadLocal thread_local_;
529 static void ThreadInit();
530
531 // Code to call for handling debug break on return.
532 static Code* debug_break_return_;
533
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100534 // Code to call for handling debug break in debug break slots.
535 static Code* debug_break_slot_;
536
Steve Blocka7e24c12009-10-30 11:49:00 +0000537 DISALLOW_COPY_AND_ASSIGN(Debug);
538};
539
540
541// Message delivered to the message handler callback. This is either a debugger
542// event or the response to a command.
543class MessageImpl: public v8::Debug::Message {
544 public:
545 // Create a message object for a debug event.
546 static MessageImpl NewEvent(DebugEvent event,
547 bool running,
548 Handle<JSObject> exec_state,
549 Handle<JSObject> event_data);
550
551 // Create a message object for the response to a debug command.
552 static MessageImpl NewResponse(DebugEvent event,
553 bool running,
554 Handle<JSObject> exec_state,
555 Handle<JSObject> event_data,
556 Handle<String> response_json,
557 v8::Debug::ClientData* client_data);
558
559 // Implementation of interface v8::Debug::Message.
560 virtual bool IsEvent() const;
561 virtual bool IsResponse() const;
562 virtual DebugEvent GetEvent() const;
563 virtual bool WillStartRunning() const;
564 virtual v8::Handle<v8::Object> GetExecutionState() const;
565 virtual v8::Handle<v8::Object> GetEventData() const;
566 virtual v8::Handle<v8::String> GetJSON() const;
567 virtual v8::Handle<v8::Context> GetEventContext() const;
568 virtual v8::Debug::ClientData* GetClientData() const;
569
570 private:
571 MessageImpl(bool is_event,
572 DebugEvent event,
573 bool running,
574 Handle<JSObject> exec_state,
575 Handle<JSObject> event_data,
576 Handle<String> response_json,
577 v8::Debug::ClientData* client_data);
578
579 bool is_event_; // Does this message represent a debug event?
580 DebugEvent event_; // Debug event causing the break.
581 bool running_; // Will the VM start running after this event?
582 Handle<JSObject> exec_state_; // Current execution state.
583 Handle<JSObject> event_data_; // Data associated with the event.
584 Handle<String> response_json_; // Response JSON if message holds a response.
585 v8::Debug::ClientData* client_data_; // Client data passed with the request.
586};
587
588
Leon Clarkef7060e22010-06-03 12:02:55 +0100589// Details of the debug event delivered to the debug event listener.
590class EventDetailsImpl : public v8::Debug::EventDetails {
591 public:
592 EventDetailsImpl(DebugEvent event,
593 Handle<JSObject> exec_state,
594 Handle<JSObject> event_data,
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100595 Handle<Object> callback_data,
596 v8::Debug::ClientData* client_data);
Leon Clarkef7060e22010-06-03 12:02:55 +0100597 virtual DebugEvent GetEvent() const;
598 virtual v8::Handle<v8::Object> GetExecutionState() const;
599 virtual v8::Handle<v8::Object> GetEventData() const;
600 virtual v8::Handle<v8::Context> GetEventContext() const;
601 virtual v8::Handle<v8::Value> GetCallbackData() const;
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100602 virtual v8::Debug::ClientData* GetClientData() const;
Leon Clarkef7060e22010-06-03 12:02:55 +0100603 private:
604 DebugEvent event_; // Debug event causing the break.
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100605 Handle<JSObject> exec_state_; // Current execution state.
606 Handle<JSObject> event_data_; // Data associated with the event.
607 Handle<Object> callback_data_; // User data passed with the callback
608 // when it was registered.
609 v8::Debug::ClientData* client_data_; // Data passed to DebugBreakForCommand.
Leon Clarkef7060e22010-06-03 12:02:55 +0100610};
611
612
Steve Blocka7e24c12009-10-30 11:49:00 +0000613// Message send by user to v8 debugger or debugger output message.
614// In addition to command text it may contain a pointer to some user data
615// which are expected to be passed along with the command reponse to message
616// handler.
617class CommandMessage {
618 public:
619 static CommandMessage New(const Vector<uint16_t>& command,
620 v8::Debug::ClientData* data);
621 CommandMessage();
622 ~CommandMessage();
623
624 // Deletes user data and disposes of the text.
625 void Dispose();
626 Vector<uint16_t> text() const { return text_; }
627 v8::Debug::ClientData* client_data() const { return client_data_; }
628 private:
629 CommandMessage(const Vector<uint16_t>& text,
630 v8::Debug::ClientData* data);
631
632 Vector<uint16_t> text_;
633 v8::Debug::ClientData* client_data_;
634};
635
636// A Queue of CommandMessage objects. A thread-safe version is
637// LockingCommandMessageQueue, based on this class.
638class CommandMessageQueue BASE_EMBEDDED {
639 public:
640 explicit CommandMessageQueue(int size);
641 ~CommandMessageQueue();
642 bool IsEmpty() const { return start_ == end_; }
643 CommandMessage Get();
644 void Put(const CommandMessage& message);
645 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
646 private:
647 // Doubles the size of the message queue, and copies the messages.
648 void Expand();
649
650 CommandMessage* messages_;
651 int start_;
652 int end_;
653 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
654};
655
656
Leon Clarkee46be812010-01-19 14:06:41 +0000657class MessageDispatchHelperThread;
658
659
Steve Blocka7e24c12009-10-30 11:49:00 +0000660// LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
661// messages. The message data is not managed by LockingCommandMessageQueue.
662// Pointers to the data are passed in and out. Implemented by adding a
663// Mutex to CommandMessageQueue. Includes logging of all puts and gets.
664class LockingCommandMessageQueue BASE_EMBEDDED {
665 public:
666 explicit LockingCommandMessageQueue(int size);
667 ~LockingCommandMessageQueue();
668 bool IsEmpty() const;
669 CommandMessage Get();
670 void Put(const CommandMessage& message);
671 void Clear();
672 private:
673 CommandMessageQueue queue_;
674 Mutex* lock_;
675 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
676};
677
678
679class Debugger {
680 public:
681 static void DebugRequest(const uint16_t* json_request, int length);
682
683 static Handle<Object> MakeJSObject(Vector<const char> constructor_name,
684 int argc, Object*** argv,
685 bool* caught_exception);
686 static Handle<Object> MakeExecutionState(bool* caught_exception);
687 static Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
688 Handle<Object> break_points_hit,
689 bool* caught_exception);
690 static Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
691 Handle<Object> exception,
692 bool uncaught,
693 bool* caught_exception);
694 static Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
695 bool* caught_exception);
696 static Handle<Object> MakeCompileEvent(Handle<Script> script,
697 bool before,
698 bool* caught_exception);
699 static Handle<Object> MakeScriptCollectedEvent(int id,
700 bool* caught_exception);
701 static void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
702 static void OnException(Handle<Object> exception, bool uncaught);
703 static void OnBeforeCompile(Handle<Script> script);
Steve Block6ded16b2010-05-10 14:33:55 +0100704
705 enum AfterCompileFlags {
706 NO_AFTER_COMPILE_FLAGS,
707 SEND_WHEN_DEBUGGING
708 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000709 static void OnAfterCompile(Handle<Script> script,
Steve Block6ded16b2010-05-10 14:33:55 +0100710 AfterCompileFlags after_compile_flags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000711 static void OnNewFunction(Handle<JSFunction> fun);
712 static void OnScriptCollected(int id);
713 static void ProcessDebugEvent(v8::DebugEvent event,
714 Handle<JSObject> event_data,
715 bool auto_continue);
716 static void NotifyMessageHandler(v8::DebugEvent event,
717 Handle<JSObject> exec_state,
718 Handle<JSObject> event_data,
719 bool auto_continue);
720 static void SetEventListener(Handle<Object> callback, Handle<Object> data);
721 static void SetMessageHandler(v8::Debug::MessageHandler2 handler);
722 static void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
723 int period);
Steve Blockd0582a62009-12-15 09:54:21 +0000724 static void SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +0000725 v8::Debug::DebugMessageDispatchHandler handler,
726 bool provide_locker);
Steve Blocka7e24c12009-10-30 11:49:00 +0000727
728 // Invoke the message handler function.
729 static void InvokeMessageHandler(MessageImpl message);
730
731 // Add a debugger command to the command queue.
732 static void ProcessCommand(Vector<const uint16_t> command,
733 v8::Debug::ClientData* client_data = NULL);
734
735 // Check whether there are commands in the command queue.
736 static bool HasCommands();
737
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100738 // Enqueue a debugger command to the command queue for event listeners.
739 static void EnqueueDebugCommand(v8::Debug::ClientData* client_data = NULL);
740
Steve Blocka7e24c12009-10-30 11:49:00 +0000741 static Handle<Object> Call(Handle<JSFunction> fun,
742 Handle<Object> data,
743 bool* pending_exception);
744
745 // Start the debugger agent listening on the provided port.
Leon Clarkee46be812010-01-19 14:06:41 +0000746 static bool StartAgent(const char* name, int port,
747 bool wait_for_connection = false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000748
749 // Stop the debugger agent.
750 static void StopAgent();
751
752 // Blocks until the agent has started listening for connections
753 static void WaitForAgent();
754
Leon Clarkee46be812010-01-19 14:06:41 +0000755 static void CallMessageDispatchHandler();
756
Steve Block6ded16b2010-05-10 14:33:55 +0100757 static Handle<Context> GetDebugContext();
758
Steve Blocka7e24c12009-10-30 11:49:00 +0000759 // Unload the debugger if possible. Only called when no debugger is currently
760 // active.
761 static void UnloadDebugger();
Steve Block6ded16b2010-05-10 14:33:55 +0100762 friend void ForceUnloadDebugger(); // In test-debug.cc
Steve Blocka7e24c12009-10-30 11:49:00 +0000763
764 inline static bool EventActive(v8::DebugEvent event) {
765 ScopedLock with(debugger_access_);
766
767 // Check whether the message handler was been cleared.
768 if (debugger_unload_pending_) {
Leon Clarkee46be812010-01-19 14:06:41 +0000769 if (Debug::debugger_entry() == NULL) {
770 UnloadDebugger();
771 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000772 }
773
774 // Currently argument event is not used.
775 return !compiling_natives_ && Debugger::IsDebuggerActive();
776 }
777
778 static void set_compiling_natives(bool compiling_natives) {
779 Debugger::compiling_natives_ = compiling_natives;
780 }
781 static bool compiling_natives() { return Debugger::compiling_natives_; }
782 static void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
783 static bool is_loading_debugger() { return Debugger::is_loading_debugger_; }
784
Steve Blocka7e24c12009-10-30 11:49:00 +0000785 static bool IsDebuggerActive();
Leon Clarkef7060e22010-06-03 12:02:55 +0100786
787 private:
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100788 static void CallEventCallback(v8::DebugEvent event,
789 Handle<Object> exec_state,
790 Handle<Object> event_data,
791 v8::Debug::ClientData* client_data);
792 static void CallCEventCallback(v8::DebugEvent event,
793 Handle<Object> exec_state,
794 Handle<Object> event_data,
795 v8::Debug::ClientData* client_data);
796 static void CallJSEventCallback(v8::DebugEvent event,
797 Handle<Object> exec_state,
798 Handle<Object> event_data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000799 static void ListenersChanged();
800
801 static Mutex* debugger_access_; // Mutex guarding debugger variables.
802 static Handle<Object> event_listener_; // Global handle to listener.
803 static Handle<Object> event_listener_data_;
804 static bool compiling_natives_; // Are we compiling natives?
805 static bool is_loading_debugger_; // Are we loading the debugger?
806 static bool never_unload_debugger_; // Can we unload the debugger?
807 static v8::Debug::MessageHandler2 message_handler_;
808 static bool debugger_unload_pending_; // Was message handler cleared?
809 static v8::Debug::HostDispatchHandler host_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000810 static Mutex* dispatch_handler_access_; // Mutex guarding dispatch handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000811 static v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000812 static MessageDispatchHelperThread* message_dispatch_helper_thread_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000813 static int host_dispatch_micros_;
814
815 static DebuggerAgent* agent_;
816
817 static const int kQueueInitialSize = 4;
818 static LockingCommandMessageQueue command_queue_;
819 static Semaphore* command_received_; // Signaled for each command received.
820
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100821 static LockingCommandMessageQueue event_command_queue_;
822
Steve Blocka7e24c12009-10-30 11:49:00 +0000823 friend class EnterDebugger;
824};
825
826
827// This class is used for entering the debugger. Create an instance in the stack
828// to enter the debugger. This will set the current break state, make sure the
829// debugger is loaded and switch to the debugger context. If the debugger for
830// some reason could not be entered FailedToEnter will return true.
831class EnterDebugger BASE_EMBEDDED {
832 public:
833 EnterDebugger()
834 : prev_(Debug::debugger_entry()),
835 has_js_frames_(!it_.done()) {
836 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(PREEMPT));
837 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(DEBUGBREAK));
838
839 // Link recursive debugger entry.
840 Debug::set_debugger_entry(this);
841
842 // Store the previous break id and frame id.
843 break_id_ = Debug::break_id();
844 break_frame_id_ = Debug::break_frame_id();
845
846 // Create the new break info. If there is no JavaScript frames there is no
847 // break frame id.
848 if (has_js_frames_) {
849 Debug::NewBreak(it_.frame()->id());
850 } else {
851 Debug::NewBreak(StackFrame::NO_ID);
852 }
853
854 // Make sure that debugger is loaded and enter the debugger context.
855 load_failed_ = !Debug::Load();
856 if (!load_failed_) {
857 // NOTE the member variable save which saves the previous context before
858 // this change.
859 Top::set_context(*Debug::debug_context());
860 }
861 }
862
863 ~EnterDebugger() {
864 // Restore to the previous break state.
865 Debug::SetBreak(break_frame_id_, break_id_);
866
867 // Check for leaving the debugger.
868 if (prev_ == NULL) {
869 // Clear mirror cache when leaving the debugger. Skip this if there is a
870 // pending exception as clearing the mirror cache calls back into
871 // JavaScript. This can happen if the v8::Debug::Call is used in which
872 // case the exception should end up in the calling code.
873 if (!Top::has_pending_exception()) {
874 // Try to avoid any pending debug break breaking in the clear mirror
875 // cache JavaScript code.
876 if (StackGuard::IsDebugBreak()) {
877 Debug::set_interrupts_pending(DEBUGBREAK);
878 StackGuard::Continue(DEBUGBREAK);
879 }
880 Debug::ClearMirrorCache();
881 }
882
883 // Request preemption and debug break when leaving the last debugger entry
884 // if any of these where recorded while debugging.
885 if (Debug::is_interrupt_pending(PREEMPT)) {
886 // This re-scheduling of preemption is to avoid starvation in some
887 // debugging scenarios.
888 Debug::clear_interrupt_pending(PREEMPT);
889 StackGuard::Preempt();
890 }
891 if (Debug::is_interrupt_pending(DEBUGBREAK)) {
892 Debug::clear_interrupt_pending(DEBUGBREAK);
893 StackGuard::DebugBreak();
894 }
895
896 // If there are commands in the queue when leaving the debugger request
897 // that these commands are processed.
898 if (Debugger::HasCommands()) {
899 StackGuard::DebugCommand();
900 }
901
902 // If leaving the debugger with the debugger no longer active unload it.
903 if (!Debugger::IsDebuggerActive()) {
904 Debugger::UnloadDebugger();
905 }
906 }
907
908 // Leaving this debugger entry.
909 Debug::set_debugger_entry(prev_);
910 }
911
912 // Check whether the debugger could be entered.
913 inline bool FailedToEnter() { return load_failed_; }
914
915 // Check whether there are any JavaScript frames on the stack.
916 inline bool HasJavaScriptFrames() { return has_js_frames_; }
917
918 // Get the active context from before entering the debugger.
919 inline Handle<Context> GetContext() { return save_.context(); }
920
921 private:
922 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
923 JavaScriptFrameIterator it_;
924 const bool has_js_frames_; // Were there any JavaScript frames?
925 StackFrame::Id break_frame_id_; // Previous break frame id.
926 int break_id_; // Previous break id.
927 bool load_failed_; // Did the debugger fail to load?
928 SaveContext save_; // Saves previous context.
929};
930
931
932// Stack allocated class for disabling break.
933class DisableBreak BASE_EMBEDDED {
934 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000935 explicit DisableBreak(bool disable_break) {
936 prev_disable_break_ = Debug::disable_break();
937 Debug::set_disable_break(disable_break);
938 }
939 ~DisableBreak() {
940 Debug::set_disable_break(prev_disable_break_);
941 }
942
943 private:
944 // The previous state of the disable break used to restore the value when this
945 // object is destructed.
946 bool prev_disable_break_;
947};
948
949
950// Debug_Address encapsulates the Address pointers used in generating debug
951// code.
952class Debug_Address {
953 public:
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100954 explicit Debug_Address(Debug::AddressId id) : id_(id) { }
Steve Blocka7e24c12009-10-30 11:49:00 +0000955
956 static Debug_Address AfterBreakTarget() {
957 return Debug_Address(Debug::k_after_break_target_address);
958 }
959
960 static Debug_Address DebugBreakReturn() {
961 return Debug_Address(Debug::k_debug_break_return_address);
962 }
963
Ben Murdochbb769b22010-08-11 14:56:33 +0100964 static Debug_Address RestarterFrameFunctionPointer() {
965 return Debug_Address(Debug::k_restarter_frame_function_pointer);
966 }
967
Steve Blocka7e24c12009-10-30 11:49:00 +0000968 Address address() const {
969 switch (id_) {
970 case Debug::k_after_break_target_address:
971 return reinterpret_cast<Address>(Debug::after_break_target_address());
972 case Debug::k_debug_break_return_address:
973 return reinterpret_cast<Address>(Debug::debug_break_return_address());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100974 case Debug::k_debug_break_slot_address:
975 return reinterpret_cast<Address>(Debug::debug_break_slot_address());
Ben Murdochbb769b22010-08-11 14:56:33 +0100976 case Debug::k_restarter_frame_function_pointer:
977 return reinterpret_cast<Address>(
978 Debug::restarter_frame_function_pointer_address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 default:
980 UNREACHABLE();
981 return NULL;
982 }
983 }
984 private:
985 Debug::AddressId id_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000986};
987
Leon Clarkee46be812010-01-19 14:06:41 +0000988// The optional thread that Debug Agent may use to temporary call V8 to process
989// pending debug requests if debuggee is not running V8 at the moment.
990// Techincally it does not call V8 itself, rather it asks embedding program
991// to do this via v8::Debug::HostDispatchHandler
992class MessageDispatchHelperThread: public Thread {
993 public:
994 MessageDispatchHelperThread();
995 ~MessageDispatchHelperThread();
996
997 void Schedule();
998
999 private:
1000 void Run();
1001
1002 Semaphore* const sem_;
1003 Mutex* const mutex_;
1004 bool already_signalled_;
1005
1006 DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
1007};
1008
Steve Blocka7e24c12009-10-30 11:49:00 +00001009
1010} } // namespace v8::internal
1011
1012#endif // ENABLE_DEBUGGER_SUPPORT
1013
1014#endif // V8_DEBUG_H_