blob: 98d1919423af4471ee9658507fb955f889c62958 [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_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000135 RelocIterator* reloc_iterator_;
136 RelocIterator* reloc_iterator_original_;
137
138 private:
139 void SetDebugBreak();
140 void ClearDebugBreak();
141
142 void SetDebugBreakAtIC();
143 void ClearDebugBreakAtIC();
144
145 bool IsDebugBreakAtReturn();
146 void SetDebugBreakAtReturn();
147 void ClearDebugBreakAtReturn();
148
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100149 bool IsDebugBreakSlot();
150 bool IsDebugBreakAtSlot();
151 void SetDebugBreakAtSlot();
152 void ClearDebugBreakAtSlot();
153
Steve Blocka7e24c12009-10-30 11:49:00 +0000154 DISALLOW_COPY_AND_ASSIGN(BreakLocationIterator);
155};
156
157
158// Cache of all script objects in the heap. When a script is added a weak handle
159// to it is created and that weak handle is stored in the cache. The weak handle
160// callback takes care of removing the script from the cache. The key used in
161// the cache is the script id.
162class ScriptCache : private HashMap {
163 public:
164 ScriptCache() : HashMap(ScriptMatch), collected_scripts_(10) {}
165 virtual ~ScriptCache() { Clear(); }
166
167 // Add script to the cache.
168 void Add(Handle<Script> script);
169
170 // Return the scripts in the cache.
171 Handle<FixedArray> GetScripts();
172
173 // Generate debugger events for collected scripts.
174 void ProcessCollectedScripts();
175
176 private:
177 // Calculate the hash value from the key (script id).
178 static uint32_t Hash(int key) { return ComputeIntegerHash(key); }
179
180 // Scripts match if their keys (script id) match.
181 static bool ScriptMatch(void* key1, void* key2) { return key1 == key2; }
182
183 // Clear the cache releasing all the weak handles.
184 void Clear();
185
186 // Weak handle callback for scripts in the cache.
187 static void HandleWeakScript(v8::Persistent<v8::Value> obj, void* data);
188
189 // List used during GC to temporarily store id's of collected scripts.
190 List<int> collected_scripts_;
191};
192
193
194// Linked list holding debug info objects. The debug info objects are kept as
195// weak handles to avoid a debug info object to keep a function alive.
196class DebugInfoListNode {
197 public:
198 explicit DebugInfoListNode(DebugInfo* debug_info);
199 virtual ~DebugInfoListNode();
200
201 DebugInfoListNode* next() { return next_; }
202 void set_next(DebugInfoListNode* next) { next_ = next; }
203 Handle<DebugInfo> debug_info() { return debug_info_; }
204
205 private:
206 // Global (weak) handle to the debug info object.
207 Handle<DebugInfo> debug_info_;
208
209 // Next pointer for linked list.
210 DebugInfoListNode* next_;
211};
212
213
214// This class contains the debugger support. The main purpose is to handle
215// setting break points in the code.
216//
217// This class controls the debug info for all functions which currently have
218// active breakpoints in them. This debug info is held in the heap root object
219// debug_info which is a FixedArray. Each entry in this list is of class
220// DebugInfo.
221class Debug {
222 public:
223 static void Setup(bool create_heap_objects);
224 static bool Load();
225 static void Unload();
226 static bool IsLoaded() { return !debug_context_.is_null(); }
227 static bool InDebugger() { return thread_local_.debugger_entry_ != NULL; }
228 static void PreemptionWhileInDebugger();
229 static void Iterate(ObjectVisitor* v);
230
231 static Object* Break(Arguments args);
232 static void SetBreakPoint(Handle<SharedFunctionInfo> shared,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100233 Handle<Object> break_point_object,
234 int* source_position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000235 static void ClearBreakPoint(Handle<Object> break_point_object);
236 static void ClearAllBreakPoints();
237 static void FloodWithOneShot(Handle<SharedFunctionInfo> shared);
238 static void FloodHandlerWithOneShot();
239 static void ChangeBreakOnException(ExceptionBreakType type, bool enable);
240 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,
Ben Murdochbb769b22010-08-11 14:56:33 +0100335 k_restarter_frame_function_pointer,
Steve Blocka7e24c12009-10-30 11:49:00 +0000336 k_register_address
337 };
338
339 // Support for setting the address to jump to when returning from break point.
340 static Address* after_break_target_address() {
341 return reinterpret_cast<Address*>(&thread_local_.after_break_target_);
342 }
Ben Murdochbb769b22010-08-11 14:56:33 +0100343 static Address* restarter_frame_function_pointer_address() {
344 Object*** address = &thread_local_.restarter_frame_function_pointer_;
345 return reinterpret_cast<Address*>(address);
346 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000347
348 // Support for saving/restoring registers when handling debug break calls.
349 static Object** register_address(int r) {
350 return &registers_[r];
351 }
352
353 // Access to the debug break on return code.
354 static Code* debug_break_return() { return debug_break_return_; }
355 static Code** debug_break_return_address() {
356 return &debug_break_return_;
357 }
358
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100359 // Access to the debug break in debug break slot code.
360 static Code* debug_break_slot() { return debug_break_slot_; }
361 static Code** debug_break_slot_address() {
362 return &debug_break_slot_;
363 }
364
Steve Blocka7e24c12009-10-30 11:49:00 +0000365 static const int kEstimatedNofDebugInfoEntries = 16;
366 static const int kEstimatedNofBreakPointsInFunction = 16;
367
368 static void HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data);
369
370 friend class Debugger;
371 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
372 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
373
374 // Threading support.
375 static char* ArchiveDebug(char* to);
376 static char* RestoreDebug(char* from);
377 static int ArchiveSpacePerThread();
378 static void FreeThreadResources() { }
379
380 // Mirror cache handling.
381 static void ClearMirrorCache();
382
383 // Script cache handling.
384 static void CreateScriptCache();
385 static void DestroyScriptCache();
386 static void AddScriptToScriptCache(Handle<Script> script);
387 static Handle<FixedArray> GetLoadedScripts();
388
389 // Garbage collection notifications.
390 static void AfterGarbageCollection();
391
Steve Blocka7e24c12009-10-30 11:49:00 +0000392 // Code generator routines.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100393 static void GenerateSlot(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000394 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
395 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
396 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
397 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
398 static void GenerateConstructCallDebugBreak(MacroAssembler* masm);
399 static void GenerateReturnDebugBreak(MacroAssembler* masm);
400 static void GenerateStubNoRegistersDebugBreak(MacroAssembler* masm);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100401 static void GenerateSlotDebugBreak(MacroAssembler* masm);
Steve Block6ded16b2010-05-10 14:33:55 +0100402 static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
Iain Merrick75681382010-08-19 15:07:18 +0100403
404 // FrameDropper is a code replacement for a JavaScript frame with possibly
405 // several frames above.
406 // There is no calling conventions here, because it never actually gets
407 // called, it only gets returned to.
Steve Block6ded16b2010-05-10 14:33:55 +0100408 static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000409
410 // Called from stub-cache.cc.
411 static void GenerateCallICDebugBreak(MacroAssembler* masm);
412
Steve Block8defd9f2010-07-08 12:39:36 +0100413 // Describes how exactly a frame has been dropped from stack.
414 enum FrameDropMode {
415 // No frame has been dropped.
416 FRAMES_UNTOUCHED,
417 // The top JS frame had been calling IC stub. IC stub mustn't be called now.
418 FRAME_DROPPED_IN_IC_CALL,
419 // The top JS frame had been calling debug break slot stub. Patch the
420 // address this stub jumps to in the end.
421 FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
422 // The top JS frame had been calling some C++ function. The return address
423 // gets patched automatically.
424 FRAME_DROPPED_IN_DIRECT_CALL
425 };
426
427 static void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
Ben Murdochbb769b22010-08-11 14:56:33 +0100428 FrameDropMode mode,
429 Object** restarter_frame_function_pointer);
Steve Block6ded16b2010-05-10 14:33:55 +0100430
Ben Murdochbb769b22010-08-11 14:56:33 +0100431 // Initializes an artificial stack frame. The data it contains is used for:
432 // a. successful work of frame dropper code which eventually gets control,
433 // b. being compatible with regular stack structure for various stack
434 // iterators.
435 // Returns address of stack allocated pointer to restarted function,
436 // the value that is called 'restarter_frame_function_pointer'. The value
437 // at this address (possibly updated by GC) may be used later when preparing
438 // 'step in' operation.
Ben Murdochbb769b22010-08-11 14:56:33 +0100439 static Object** SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
440 Handle<Code> code);
441
Steve Block6ded16b2010-05-10 14:33:55 +0100442 static const int kFrameDropperFrameSize;
443
Iain Merrick75681382010-08-19 15:07:18 +0100444 // Architecture-specific constant.
445 static const bool kFrameDropperSupported;
446
Steve Blocka7e24c12009-10-30 11:49:00 +0000447 private:
448 static bool CompileDebuggerScript(int index);
449 static void ClearOneShot();
450 static void ActivateStepIn(StackFrame* frame);
451 static void ClearStepIn();
452 static void ActivateStepOut(StackFrame* frame);
453 static void ClearStepOut();
454 static void ClearStepNext();
455 // Returns whether the compile succeeded.
Steve Blocka7e24c12009-10-30 11:49:00 +0000456 static void RemoveDebugInfo(Handle<DebugInfo> debug_info);
457 static void SetAfterBreakTarget(JavaScriptFrame* frame);
458 static Handle<Object> CheckBreakPoints(Handle<Object> break_point);
459 static bool CheckBreakPoint(Handle<Object> break_point_object);
460
461 // Global handle to debug context where all the debugger JavaScript code is
462 // loaded.
463 static Handle<Context> debug_context_;
464
465 // Boolean state indicating whether any break points are set.
466 static bool has_break_points_;
467
468 // Cache of all scripts in the heap.
469 static ScriptCache* script_cache_;
470
471 // List of active debug info objects.
472 static DebugInfoListNode* debug_info_list_;
473
474 static bool disable_break_;
475 static bool break_on_exception_;
476 static bool break_on_uncaught_exception_;
477
478 // Per-thread data.
479 class ThreadLocal {
480 public:
481 // Counter for generating next break id.
482 int break_count_;
483
484 // Current break id.
485 int break_id_;
486
487 // Frame id for the frame of the current break.
488 StackFrame::Id break_frame_id_;
489
490 // Step action for last step performed.
491 StepAction last_step_action_;
492
493 // Source statement position from last step next action.
494 int last_statement_position_;
495
496 // Number of steps left to perform before debug event.
497 int step_count_;
498
499 // Frame pointer from last step next action.
500 Address last_fp_;
501
502 // Frame pointer for frame from which step in was performed.
503 Address step_into_fp_;
504
505 // Frame pointer for the frame where debugger should be called when current
506 // step out action is completed.
507 Address step_out_fp_;
508
509 // Storage location for jump when exiting debug break calls.
510 Address after_break_target_;
511
Steve Block8defd9f2010-07-08 12:39:36 +0100512 // Stores the way how LiveEdit has patched the stack. It is used when
513 // debugger returns control back to user script.
514 FrameDropMode frame_drop_mode_;
Steve Block6ded16b2010-05-10 14:33:55 +0100515
Steve Blocka7e24c12009-10-30 11:49:00 +0000516 // Top debugger entry.
517 EnterDebugger* debugger_entry_;
518
519 // Pending interrupts scheduled while debugging.
520 int pending_interrupts_;
Ben Murdochbb769b22010-08-11 14:56:33 +0100521
522 // When restarter frame is on stack, stores the address
523 // of the pointer to function being restarted. Otherwise (most of the time)
524 // stores NULL. This pointer is used with 'step in' implementation.
525 Object** restarter_frame_function_pointer_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000526 };
527
528 // Storage location for registers when handling debug break calls
529 static JSCallerSavedBuffer registers_;
530 static ThreadLocal thread_local_;
531 static void ThreadInit();
532
533 // Code to call for handling debug break on return.
534 static Code* debug_break_return_;
535
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100536 // Code to call for handling debug break in debug break slots.
537 static Code* debug_break_slot_;
538
Steve Blocka7e24c12009-10-30 11:49:00 +0000539 DISALLOW_COPY_AND_ASSIGN(Debug);
540};
541
542
543// Message delivered to the message handler callback. This is either a debugger
544// event or the response to a command.
545class MessageImpl: public v8::Debug::Message {
546 public:
547 // Create a message object for a debug event.
548 static MessageImpl NewEvent(DebugEvent event,
549 bool running,
550 Handle<JSObject> exec_state,
551 Handle<JSObject> event_data);
552
553 // Create a message object for the response to a debug command.
554 static MessageImpl NewResponse(DebugEvent event,
555 bool running,
556 Handle<JSObject> exec_state,
557 Handle<JSObject> event_data,
558 Handle<String> response_json,
559 v8::Debug::ClientData* client_data);
560
561 // Implementation of interface v8::Debug::Message.
562 virtual bool IsEvent() const;
563 virtual bool IsResponse() const;
564 virtual DebugEvent GetEvent() const;
565 virtual bool WillStartRunning() const;
566 virtual v8::Handle<v8::Object> GetExecutionState() const;
567 virtual v8::Handle<v8::Object> GetEventData() const;
568 virtual v8::Handle<v8::String> GetJSON() const;
569 virtual v8::Handle<v8::Context> GetEventContext() const;
570 virtual v8::Debug::ClientData* GetClientData() const;
571
572 private:
573 MessageImpl(bool is_event,
574 DebugEvent event,
575 bool running,
576 Handle<JSObject> exec_state,
577 Handle<JSObject> event_data,
578 Handle<String> response_json,
579 v8::Debug::ClientData* client_data);
580
581 bool is_event_; // Does this message represent a debug event?
582 DebugEvent event_; // Debug event causing the break.
583 bool running_; // Will the VM start running after this event?
584 Handle<JSObject> exec_state_; // Current execution state.
585 Handle<JSObject> event_data_; // Data associated with the event.
586 Handle<String> response_json_; // Response JSON if message holds a response.
587 v8::Debug::ClientData* client_data_; // Client data passed with the request.
588};
589
590
Leon Clarkef7060e22010-06-03 12:02:55 +0100591// Details of the debug event delivered to the debug event listener.
592class EventDetailsImpl : public v8::Debug::EventDetails {
593 public:
594 EventDetailsImpl(DebugEvent event,
595 Handle<JSObject> exec_state,
596 Handle<JSObject> event_data,
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100597 Handle<Object> callback_data,
598 v8::Debug::ClientData* client_data);
Leon Clarkef7060e22010-06-03 12:02:55 +0100599 virtual DebugEvent GetEvent() const;
600 virtual v8::Handle<v8::Object> GetExecutionState() const;
601 virtual v8::Handle<v8::Object> GetEventData() const;
602 virtual v8::Handle<v8::Context> GetEventContext() const;
603 virtual v8::Handle<v8::Value> GetCallbackData() const;
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100604 virtual v8::Debug::ClientData* GetClientData() const;
Leon Clarkef7060e22010-06-03 12:02:55 +0100605 private:
606 DebugEvent event_; // Debug event causing the break.
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100607 Handle<JSObject> exec_state_; // Current execution state.
608 Handle<JSObject> event_data_; // Data associated with the event.
609 Handle<Object> callback_data_; // User data passed with the callback
610 // when it was registered.
611 v8::Debug::ClientData* client_data_; // Data passed to DebugBreakForCommand.
Leon Clarkef7060e22010-06-03 12:02:55 +0100612};
613
614
Steve Blocka7e24c12009-10-30 11:49:00 +0000615// Message send by user to v8 debugger or debugger output message.
616// In addition to command text it may contain a pointer to some user data
617// which are expected to be passed along with the command reponse to message
618// handler.
619class CommandMessage {
620 public:
621 static CommandMessage New(const Vector<uint16_t>& command,
622 v8::Debug::ClientData* data);
623 CommandMessage();
624 ~CommandMessage();
625
626 // Deletes user data and disposes of the text.
627 void Dispose();
628 Vector<uint16_t> text() const { return text_; }
629 v8::Debug::ClientData* client_data() const { return client_data_; }
630 private:
631 CommandMessage(const Vector<uint16_t>& text,
632 v8::Debug::ClientData* data);
633
634 Vector<uint16_t> text_;
635 v8::Debug::ClientData* client_data_;
636};
637
638// A Queue of CommandMessage objects. A thread-safe version is
639// LockingCommandMessageQueue, based on this class.
640class CommandMessageQueue BASE_EMBEDDED {
641 public:
642 explicit CommandMessageQueue(int size);
643 ~CommandMessageQueue();
644 bool IsEmpty() const { return start_ == end_; }
645 CommandMessage Get();
646 void Put(const CommandMessage& message);
647 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
648 private:
649 // Doubles the size of the message queue, and copies the messages.
650 void Expand();
651
652 CommandMessage* messages_;
653 int start_;
654 int end_;
655 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
656};
657
658
Leon Clarkee46be812010-01-19 14:06:41 +0000659class MessageDispatchHelperThread;
660
661
Steve Blocka7e24c12009-10-30 11:49:00 +0000662// LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
663// messages. The message data is not managed by LockingCommandMessageQueue.
664// Pointers to the data are passed in and out. Implemented by adding a
665// Mutex to CommandMessageQueue. Includes logging of all puts and gets.
666class LockingCommandMessageQueue BASE_EMBEDDED {
667 public:
668 explicit LockingCommandMessageQueue(int size);
669 ~LockingCommandMessageQueue();
670 bool IsEmpty() const;
671 CommandMessage Get();
672 void Put(const CommandMessage& message);
673 void Clear();
674 private:
675 CommandMessageQueue queue_;
676 Mutex* lock_;
677 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
678};
679
680
681class Debugger {
682 public:
683 static void DebugRequest(const uint16_t* json_request, int length);
684
685 static Handle<Object> MakeJSObject(Vector<const char> constructor_name,
686 int argc, Object*** argv,
687 bool* caught_exception);
688 static Handle<Object> MakeExecutionState(bool* caught_exception);
689 static Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
690 Handle<Object> break_points_hit,
691 bool* caught_exception);
692 static Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
693 Handle<Object> exception,
694 bool uncaught,
695 bool* caught_exception);
696 static Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
697 bool* caught_exception);
698 static Handle<Object> MakeCompileEvent(Handle<Script> script,
699 bool before,
700 bool* caught_exception);
701 static Handle<Object> MakeScriptCollectedEvent(int id,
702 bool* caught_exception);
703 static void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
704 static void OnException(Handle<Object> exception, bool uncaught);
705 static void OnBeforeCompile(Handle<Script> script);
Steve Block6ded16b2010-05-10 14:33:55 +0100706
707 enum AfterCompileFlags {
708 NO_AFTER_COMPILE_FLAGS,
709 SEND_WHEN_DEBUGGING
710 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000711 static void OnAfterCompile(Handle<Script> script,
Steve Block6ded16b2010-05-10 14:33:55 +0100712 AfterCompileFlags after_compile_flags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000713 static void OnNewFunction(Handle<JSFunction> fun);
714 static void OnScriptCollected(int id);
715 static void ProcessDebugEvent(v8::DebugEvent event,
716 Handle<JSObject> event_data,
717 bool auto_continue);
718 static void NotifyMessageHandler(v8::DebugEvent event,
719 Handle<JSObject> exec_state,
720 Handle<JSObject> event_data,
721 bool auto_continue);
722 static void SetEventListener(Handle<Object> callback, Handle<Object> data);
723 static void SetMessageHandler(v8::Debug::MessageHandler2 handler);
724 static void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
725 int period);
Steve Blockd0582a62009-12-15 09:54:21 +0000726 static void SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +0000727 v8::Debug::DebugMessageDispatchHandler handler,
728 bool provide_locker);
Steve Blocka7e24c12009-10-30 11:49:00 +0000729
730 // Invoke the message handler function.
731 static void InvokeMessageHandler(MessageImpl message);
732
733 // Add a debugger command to the command queue.
734 static void ProcessCommand(Vector<const uint16_t> command,
735 v8::Debug::ClientData* client_data = NULL);
736
737 // Check whether there are commands in the command queue.
738 static bool HasCommands();
739
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100740 // Enqueue a debugger command to the command queue for event listeners.
741 static void EnqueueDebugCommand(v8::Debug::ClientData* client_data = NULL);
742
Steve Blocka7e24c12009-10-30 11:49:00 +0000743 static Handle<Object> Call(Handle<JSFunction> fun,
744 Handle<Object> data,
745 bool* pending_exception);
746
747 // Start the debugger agent listening on the provided port.
Leon Clarkee46be812010-01-19 14:06:41 +0000748 static bool StartAgent(const char* name, int port,
749 bool wait_for_connection = false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000750
751 // Stop the debugger agent.
752 static void StopAgent();
753
754 // Blocks until the agent has started listening for connections
755 static void WaitForAgent();
756
Leon Clarkee46be812010-01-19 14:06:41 +0000757 static void CallMessageDispatchHandler();
758
Steve Block6ded16b2010-05-10 14:33:55 +0100759 static Handle<Context> GetDebugContext();
760
Steve Blocka7e24c12009-10-30 11:49:00 +0000761 // Unload the debugger if possible. Only called when no debugger is currently
762 // active.
763 static void UnloadDebugger();
Steve Block6ded16b2010-05-10 14:33:55 +0100764 friend void ForceUnloadDebugger(); // In test-debug.cc
Steve Blocka7e24c12009-10-30 11:49:00 +0000765
766 inline static bool EventActive(v8::DebugEvent event) {
767 ScopedLock with(debugger_access_);
768
769 // Check whether the message handler was been cleared.
770 if (debugger_unload_pending_) {
Leon Clarkee46be812010-01-19 14:06:41 +0000771 if (Debug::debugger_entry() == NULL) {
772 UnloadDebugger();
773 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000774 }
775
776 // Currently argument event is not used.
777 return !compiling_natives_ && Debugger::IsDebuggerActive();
778 }
779
780 static void set_compiling_natives(bool compiling_natives) {
781 Debugger::compiling_natives_ = compiling_natives;
782 }
783 static bool compiling_natives() { return Debugger::compiling_natives_; }
784 static void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
785 static bool is_loading_debugger() { return Debugger::is_loading_debugger_; }
786
Steve Blocka7e24c12009-10-30 11:49:00 +0000787 static bool IsDebuggerActive();
Leon Clarkef7060e22010-06-03 12:02:55 +0100788
789 private:
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100790 static void CallEventCallback(v8::DebugEvent event,
791 Handle<Object> exec_state,
792 Handle<Object> event_data,
793 v8::Debug::ClientData* client_data);
794 static void CallCEventCallback(v8::DebugEvent event,
795 Handle<Object> exec_state,
796 Handle<Object> event_data,
797 v8::Debug::ClientData* client_data);
798 static void CallJSEventCallback(v8::DebugEvent event,
799 Handle<Object> exec_state,
800 Handle<Object> event_data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000801 static void ListenersChanged();
802
803 static Mutex* debugger_access_; // Mutex guarding debugger variables.
804 static Handle<Object> event_listener_; // Global handle to listener.
805 static Handle<Object> event_listener_data_;
806 static bool compiling_natives_; // Are we compiling natives?
807 static bool is_loading_debugger_; // Are we loading the debugger?
808 static bool never_unload_debugger_; // Can we unload the debugger?
809 static v8::Debug::MessageHandler2 message_handler_;
810 static bool debugger_unload_pending_; // Was message handler cleared?
811 static v8::Debug::HostDispatchHandler host_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000812 static Mutex* dispatch_handler_access_; // Mutex guarding dispatch handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000813 static v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000814 static MessageDispatchHelperThread* message_dispatch_helper_thread_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000815 static int host_dispatch_micros_;
816
817 static DebuggerAgent* agent_;
818
819 static const int kQueueInitialSize = 4;
820 static LockingCommandMessageQueue command_queue_;
821 static Semaphore* command_received_; // Signaled for each command received.
822
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100823 static LockingCommandMessageQueue event_command_queue_;
824
Steve Blocka7e24c12009-10-30 11:49:00 +0000825 friend class EnterDebugger;
826};
827
828
829// This class is used for entering the debugger. Create an instance in the stack
830// to enter the debugger. This will set the current break state, make sure the
831// debugger is loaded and switch to the debugger context. If the debugger for
832// some reason could not be entered FailedToEnter will return true.
833class EnterDebugger BASE_EMBEDDED {
834 public:
835 EnterDebugger()
836 : prev_(Debug::debugger_entry()),
837 has_js_frames_(!it_.done()) {
838 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(PREEMPT));
839 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(DEBUGBREAK));
840
841 // Link recursive debugger entry.
842 Debug::set_debugger_entry(this);
843
844 // Store the previous break id and frame id.
845 break_id_ = Debug::break_id();
846 break_frame_id_ = Debug::break_frame_id();
847
848 // Create the new break info. If there is no JavaScript frames there is no
849 // break frame id.
850 if (has_js_frames_) {
851 Debug::NewBreak(it_.frame()->id());
852 } else {
853 Debug::NewBreak(StackFrame::NO_ID);
854 }
855
856 // Make sure that debugger is loaded and enter the debugger context.
857 load_failed_ = !Debug::Load();
858 if (!load_failed_) {
859 // NOTE the member variable save which saves the previous context before
860 // this change.
861 Top::set_context(*Debug::debug_context());
862 }
863 }
864
865 ~EnterDebugger() {
866 // Restore to the previous break state.
867 Debug::SetBreak(break_frame_id_, break_id_);
868
869 // Check for leaving the debugger.
870 if (prev_ == NULL) {
871 // Clear mirror cache when leaving the debugger. Skip this if there is a
872 // pending exception as clearing the mirror cache calls back into
873 // JavaScript. This can happen if the v8::Debug::Call is used in which
874 // case the exception should end up in the calling code.
875 if (!Top::has_pending_exception()) {
876 // Try to avoid any pending debug break breaking in the clear mirror
877 // cache JavaScript code.
878 if (StackGuard::IsDebugBreak()) {
879 Debug::set_interrupts_pending(DEBUGBREAK);
880 StackGuard::Continue(DEBUGBREAK);
881 }
882 Debug::ClearMirrorCache();
883 }
884
885 // Request preemption and debug break when leaving the last debugger entry
886 // if any of these where recorded while debugging.
887 if (Debug::is_interrupt_pending(PREEMPT)) {
888 // This re-scheduling of preemption is to avoid starvation in some
889 // debugging scenarios.
890 Debug::clear_interrupt_pending(PREEMPT);
891 StackGuard::Preempt();
892 }
893 if (Debug::is_interrupt_pending(DEBUGBREAK)) {
894 Debug::clear_interrupt_pending(DEBUGBREAK);
895 StackGuard::DebugBreak();
896 }
897
898 // If there are commands in the queue when leaving the debugger request
899 // that these commands are processed.
900 if (Debugger::HasCommands()) {
901 StackGuard::DebugCommand();
902 }
903
904 // If leaving the debugger with the debugger no longer active unload it.
905 if (!Debugger::IsDebuggerActive()) {
906 Debugger::UnloadDebugger();
907 }
908 }
909
910 // Leaving this debugger entry.
911 Debug::set_debugger_entry(prev_);
912 }
913
914 // Check whether the debugger could be entered.
915 inline bool FailedToEnter() { return load_failed_; }
916
917 // Check whether there are any JavaScript frames on the stack.
918 inline bool HasJavaScriptFrames() { return has_js_frames_; }
919
920 // Get the active context from before entering the debugger.
921 inline Handle<Context> GetContext() { return save_.context(); }
922
923 private:
924 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
925 JavaScriptFrameIterator it_;
926 const bool has_js_frames_; // Were there any JavaScript frames?
927 StackFrame::Id break_frame_id_; // Previous break frame id.
928 int break_id_; // Previous break id.
929 bool load_failed_; // Did the debugger fail to load?
930 SaveContext save_; // Saves previous context.
931};
932
933
934// Stack allocated class for disabling break.
935class DisableBreak BASE_EMBEDDED {
936 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000937 explicit DisableBreak(bool disable_break) {
938 prev_disable_break_ = Debug::disable_break();
939 Debug::set_disable_break(disable_break);
940 }
941 ~DisableBreak() {
942 Debug::set_disable_break(prev_disable_break_);
943 }
944
945 private:
946 // The previous state of the disable break used to restore the value when this
947 // object is destructed.
948 bool prev_disable_break_;
949};
950
951
952// Debug_Address encapsulates the Address pointers used in generating debug
953// code.
954class Debug_Address {
955 public:
956 Debug_Address(Debug::AddressId id, int reg = 0)
957 : id_(id), reg_(reg) {
958 ASSERT(reg == 0 || id == Debug::k_register_address);
959 }
960
961 static Debug_Address AfterBreakTarget() {
962 return Debug_Address(Debug::k_after_break_target_address);
963 }
964
965 static Debug_Address DebugBreakReturn() {
966 return Debug_Address(Debug::k_debug_break_return_address);
967 }
968
Ben Murdochbb769b22010-08-11 14:56:33 +0100969 static Debug_Address RestarterFrameFunctionPointer() {
970 return Debug_Address(Debug::k_restarter_frame_function_pointer);
971 }
972
Steve Blocka7e24c12009-10-30 11:49:00 +0000973 static Debug_Address Register(int reg) {
974 return Debug_Address(Debug::k_register_address, reg);
975 }
976
977 Address address() const {
978 switch (id_) {
979 case Debug::k_after_break_target_address:
980 return reinterpret_cast<Address>(Debug::after_break_target_address());
981 case Debug::k_debug_break_return_address:
982 return reinterpret_cast<Address>(Debug::debug_break_return_address());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100983 case Debug::k_debug_break_slot_address:
984 return reinterpret_cast<Address>(Debug::debug_break_slot_address());
Ben Murdochbb769b22010-08-11 14:56:33 +0100985 case Debug::k_restarter_frame_function_pointer:
986 return reinterpret_cast<Address>(
987 Debug::restarter_frame_function_pointer_address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000988 case Debug::k_register_address:
989 return reinterpret_cast<Address>(Debug::register_address(reg_));
990 default:
991 UNREACHABLE();
992 return NULL;
993 }
994 }
995 private:
996 Debug::AddressId id_;
997 int reg_;
998};
999
Leon Clarkee46be812010-01-19 14:06:41 +00001000// The optional thread that Debug Agent may use to temporary call V8 to process
1001// pending debug requests if debuggee is not running V8 at the moment.
1002// Techincally it does not call V8 itself, rather it asks embedding program
1003// to do this via v8::Debug::HostDispatchHandler
1004class MessageDispatchHelperThread: public Thread {
1005 public:
1006 MessageDispatchHelperThread();
1007 ~MessageDispatchHelperThread();
1008
1009 void Schedule();
1010
1011 private:
1012 void Run();
1013
1014 Semaphore* const sem_;
1015 Mutex* const mutex_;
1016 bool already_signalled_;
1017
1018 DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
1019};
1020
Steve Blocka7e24c12009-10-30 11:49:00 +00001021
1022} } // namespace v8::internal
1023
1024#endif // ENABLE_DEBUGGER_SUPPORT
1025
1026#endif // V8_DEBUG_H_