blob: fb9269272f1f2200b00cd9a20c5eba0d2e9f1a40 [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,
Steve Blocka7e24c12009-10-30 11:49:00 +0000335 k_register_address
336 };
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 }
342
343 // Support for saving/restoring registers when handling debug break calls.
344 static Object** register_address(int r) {
345 return &registers_[r];
346 }
347
348 // Access to the debug break on return code.
349 static Code* debug_break_return() { return debug_break_return_; }
350 static Code** debug_break_return_address() {
351 return &debug_break_return_;
352 }
353
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100354 // Access to the debug break in debug break slot code.
355 static Code* debug_break_slot() { return debug_break_slot_; }
356 static Code** debug_break_slot_address() {
357 return &debug_break_slot_;
358 }
359
Steve Blocka7e24c12009-10-30 11:49:00 +0000360 static const int kEstimatedNofDebugInfoEntries = 16;
361 static const int kEstimatedNofBreakPointsInFunction = 16;
362
363 static void HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data);
364
365 friend class Debugger;
366 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
367 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
368
369 // Threading support.
370 static char* ArchiveDebug(char* to);
371 static char* RestoreDebug(char* from);
372 static int ArchiveSpacePerThread();
373 static void FreeThreadResources() { }
374
375 // Mirror cache handling.
376 static void ClearMirrorCache();
377
378 // Script cache handling.
379 static void CreateScriptCache();
380 static void DestroyScriptCache();
381 static void AddScriptToScriptCache(Handle<Script> script);
382 static Handle<FixedArray> GetLoadedScripts();
383
384 // Garbage collection notifications.
385 static void AfterGarbageCollection();
386
Steve Blocka7e24c12009-10-30 11:49:00 +0000387 // Code generator routines.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100388 static void GenerateSlot(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000389 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
390 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
391 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
392 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
393 static void GenerateConstructCallDebugBreak(MacroAssembler* masm);
394 static void GenerateReturnDebugBreak(MacroAssembler* masm);
395 static void GenerateStubNoRegistersDebugBreak(MacroAssembler* masm);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100396 static void GenerateSlotDebugBreak(MacroAssembler* masm);
Steve Block6ded16b2010-05-10 14:33:55 +0100397 static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
398 static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
Steve Blocka7e24c12009-10-30 11:49:00 +0000399
400 // Called from stub-cache.cc.
401 static void GenerateCallICDebugBreak(MacroAssembler* masm);
402
Steve Block8defd9f2010-07-08 12:39:36 +0100403 // Describes how exactly a frame has been dropped from stack.
404 enum FrameDropMode {
405 // No frame has been dropped.
406 FRAMES_UNTOUCHED,
407 // The top JS frame had been calling IC stub. IC stub mustn't be called now.
408 FRAME_DROPPED_IN_IC_CALL,
409 // The top JS frame had been calling debug break slot stub. Patch the
410 // address this stub jumps to in the end.
411 FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
412 // The top JS frame had been calling some C++ function. The return address
413 // gets patched automatically.
414 FRAME_DROPPED_IN_DIRECT_CALL
415 };
416
417 static void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
418 FrameDropMode mode);
Steve Block6ded16b2010-05-10 14:33:55 +0100419
420 static void SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
421 Handle<Code> code);
422 static const int kFrameDropperFrameSize;
423
Steve Blocka7e24c12009-10-30 11:49:00 +0000424 private:
425 static bool CompileDebuggerScript(int index);
426 static void ClearOneShot();
427 static void ActivateStepIn(StackFrame* frame);
428 static void ClearStepIn();
429 static void ActivateStepOut(StackFrame* frame);
430 static void ClearStepOut();
431 static void ClearStepNext();
432 // Returns whether the compile succeeded.
Steve Blocka7e24c12009-10-30 11:49:00 +0000433 static void RemoveDebugInfo(Handle<DebugInfo> debug_info);
434 static void SetAfterBreakTarget(JavaScriptFrame* frame);
435 static Handle<Object> CheckBreakPoints(Handle<Object> break_point);
436 static bool CheckBreakPoint(Handle<Object> break_point_object);
437
438 // Global handle to debug context where all the debugger JavaScript code is
439 // loaded.
440 static Handle<Context> debug_context_;
441
442 // Boolean state indicating whether any break points are set.
443 static bool has_break_points_;
444
445 // Cache of all scripts in the heap.
446 static ScriptCache* script_cache_;
447
448 // List of active debug info objects.
449 static DebugInfoListNode* debug_info_list_;
450
451 static bool disable_break_;
452 static bool break_on_exception_;
453 static bool break_on_uncaught_exception_;
454
455 // Per-thread data.
456 class ThreadLocal {
457 public:
458 // Counter for generating next break id.
459 int break_count_;
460
461 // Current break id.
462 int break_id_;
463
464 // Frame id for the frame of the current break.
465 StackFrame::Id break_frame_id_;
466
467 // Step action for last step performed.
468 StepAction last_step_action_;
469
470 // Source statement position from last step next action.
471 int last_statement_position_;
472
473 // Number of steps left to perform before debug event.
474 int step_count_;
475
476 // Frame pointer from last step next action.
477 Address last_fp_;
478
479 // Frame pointer for frame from which step in was performed.
480 Address step_into_fp_;
481
482 // Frame pointer for the frame where debugger should be called when current
483 // step out action is completed.
484 Address step_out_fp_;
485
486 // Storage location for jump when exiting debug break calls.
487 Address after_break_target_;
488
Steve Block8defd9f2010-07-08 12:39:36 +0100489 // Stores the way how LiveEdit has patched the stack. It is used when
490 // debugger returns control back to user script.
491 FrameDropMode frame_drop_mode_;
Steve Block6ded16b2010-05-10 14:33:55 +0100492
Steve Blocka7e24c12009-10-30 11:49:00 +0000493 // Top debugger entry.
494 EnterDebugger* debugger_entry_;
495
496 // Pending interrupts scheduled while debugging.
497 int pending_interrupts_;
498 };
499
500 // Storage location for registers when handling debug break calls
501 static JSCallerSavedBuffer registers_;
502 static ThreadLocal thread_local_;
503 static void ThreadInit();
504
505 // Code to call for handling debug break on return.
506 static Code* debug_break_return_;
507
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100508 // Code to call for handling debug break in debug break slots.
509 static Code* debug_break_slot_;
510
Steve Blocka7e24c12009-10-30 11:49:00 +0000511 DISALLOW_COPY_AND_ASSIGN(Debug);
512};
513
514
515// Message delivered to the message handler callback. This is either a debugger
516// event or the response to a command.
517class MessageImpl: public v8::Debug::Message {
518 public:
519 // Create a message object for a debug event.
520 static MessageImpl NewEvent(DebugEvent event,
521 bool running,
522 Handle<JSObject> exec_state,
523 Handle<JSObject> event_data);
524
525 // Create a message object for the response to a debug command.
526 static MessageImpl NewResponse(DebugEvent event,
527 bool running,
528 Handle<JSObject> exec_state,
529 Handle<JSObject> event_data,
530 Handle<String> response_json,
531 v8::Debug::ClientData* client_data);
532
533 // Implementation of interface v8::Debug::Message.
534 virtual bool IsEvent() const;
535 virtual bool IsResponse() const;
536 virtual DebugEvent GetEvent() const;
537 virtual bool WillStartRunning() const;
538 virtual v8::Handle<v8::Object> GetExecutionState() const;
539 virtual v8::Handle<v8::Object> GetEventData() const;
540 virtual v8::Handle<v8::String> GetJSON() const;
541 virtual v8::Handle<v8::Context> GetEventContext() const;
542 virtual v8::Debug::ClientData* GetClientData() const;
543
544 private:
545 MessageImpl(bool is_event,
546 DebugEvent event,
547 bool running,
548 Handle<JSObject> exec_state,
549 Handle<JSObject> event_data,
550 Handle<String> response_json,
551 v8::Debug::ClientData* client_data);
552
553 bool is_event_; // Does this message represent a debug event?
554 DebugEvent event_; // Debug event causing the break.
555 bool running_; // Will the VM start running after this event?
556 Handle<JSObject> exec_state_; // Current execution state.
557 Handle<JSObject> event_data_; // Data associated with the event.
558 Handle<String> response_json_; // Response JSON if message holds a response.
559 v8::Debug::ClientData* client_data_; // Client data passed with the request.
560};
561
562
Leon Clarkef7060e22010-06-03 12:02:55 +0100563// Details of the debug event delivered to the debug event listener.
564class EventDetailsImpl : public v8::Debug::EventDetails {
565 public:
566 EventDetailsImpl(DebugEvent event,
567 Handle<JSObject> exec_state,
568 Handle<JSObject> event_data,
569 Handle<Object> callback_data);
570 virtual DebugEvent GetEvent() const;
571 virtual v8::Handle<v8::Object> GetExecutionState() const;
572 virtual v8::Handle<v8::Object> GetEventData() const;
573 virtual v8::Handle<v8::Context> GetEventContext() const;
574 virtual v8::Handle<v8::Value> GetCallbackData() const;
575 private:
576 DebugEvent event_; // Debug event causing the break.
577 Handle<JSObject> exec_state_; // Current execution state.
578 Handle<JSObject> event_data_; // Data associated with the event.
579 Handle<Object> callback_data_; // User data passed with the callback when
580 // it was registered.
581};
582
583
Steve Blocka7e24c12009-10-30 11:49:00 +0000584// Message send by user to v8 debugger or debugger output message.
585// In addition to command text it may contain a pointer to some user data
586// which are expected to be passed along with the command reponse to message
587// handler.
588class CommandMessage {
589 public:
590 static CommandMessage New(const Vector<uint16_t>& command,
591 v8::Debug::ClientData* data);
592 CommandMessage();
593 ~CommandMessage();
594
595 // Deletes user data and disposes of the text.
596 void Dispose();
597 Vector<uint16_t> text() const { return text_; }
598 v8::Debug::ClientData* client_data() const { return client_data_; }
599 private:
600 CommandMessage(const Vector<uint16_t>& text,
601 v8::Debug::ClientData* data);
602
603 Vector<uint16_t> text_;
604 v8::Debug::ClientData* client_data_;
605};
606
607// A Queue of CommandMessage objects. A thread-safe version is
608// LockingCommandMessageQueue, based on this class.
609class CommandMessageQueue BASE_EMBEDDED {
610 public:
611 explicit CommandMessageQueue(int size);
612 ~CommandMessageQueue();
613 bool IsEmpty() const { return start_ == end_; }
614 CommandMessage Get();
615 void Put(const CommandMessage& message);
616 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
617 private:
618 // Doubles the size of the message queue, and copies the messages.
619 void Expand();
620
621 CommandMessage* messages_;
622 int start_;
623 int end_;
624 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
625};
626
627
Leon Clarkee46be812010-01-19 14:06:41 +0000628class MessageDispatchHelperThread;
629
630
Steve Blocka7e24c12009-10-30 11:49:00 +0000631// LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
632// messages. The message data is not managed by LockingCommandMessageQueue.
633// Pointers to the data are passed in and out. Implemented by adding a
634// Mutex to CommandMessageQueue. Includes logging of all puts and gets.
635class LockingCommandMessageQueue BASE_EMBEDDED {
636 public:
637 explicit LockingCommandMessageQueue(int size);
638 ~LockingCommandMessageQueue();
639 bool IsEmpty() const;
640 CommandMessage Get();
641 void Put(const CommandMessage& message);
642 void Clear();
643 private:
644 CommandMessageQueue queue_;
645 Mutex* lock_;
646 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
647};
648
649
650class Debugger {
651 public:
652 static void DebugRequest(const uint16_t* json_request, int length);
653
654 static Handle<Object> MakeJSObject(Vector<const char> constructor_name,
655 int argc, Object*** argv,
656 bool* caught_exception);
657 static Handle<Object> MakeExecutionState(bool* caught_exception);
658 static Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
659 Handle<Object> break_points_hit,
660 bool* caught_exception);
661 static Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
662 Handle<Object> exception,
663 bool uncaught,
664 bool* caught_exception);
665 static Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
666 bool* caught_exception);
667 static Handle<Object> MakeCompileEvent(Handle<Script> script,
668 bool before,
669 bool* caught_exception);
670 static Handle<Object> MakeScriptCollectedEvent(int id,
671 bool* caught_exception);
672 static void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
673 static void OnException(Handle<Object> exception, bool uncaught);
674 static void OnBeforeCompile(Handle<Script> script);
Steve Block6ded16b2010-05-10 14:33:55 +0100675
676 enum AfterCompileFlags {
677 NO_AFTER_COMPILE_FLAGS,
678 SEND_WHEN_DEBUGGING
679 };
Steve Blocka7e24c12009-10-30 11:49:00 +0000680 static void OnAfterCompile(Handle<Script> script,
Steve Block6ded16b2010-05-10 14:33:55 +0100681 AfterCompileFlags after_compile_flags);
Steve Blocka7e24c12009-10-30 11:49:00 +0000682 static void OnNewFunction(Handle<JSFunction> fun);
683 static void OnScriptCollected(int id);
684 static void ProcessDebugEvent(v8::DebugEvent event,
685 Handle<JSObject> event_data,
686 bool auto_continue);
687 static void NotifyMessageHandler(v8::DebugEvent event,
688 Handle<JSObject> exec_state,
689 Handle<JSObject> event_data,
690 bool auto_continue);
691 static void SetEventListener(Handle<Object> callback, Handle<Object> data);
692 static void SetMessageHandler(v8::Debug::MessageHandler2 handler);
693 static void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
694 int period);
Steve Blockd0582a62009-12-15 09:54:21 +0000695 static void SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +0000696 v8::Debug::DebugMessageDispatchHandler handler,
697 bool provide_locker);
Steve Blocka7e24c12009-10-30 11:49:00 +0000698
699 // Invoke the message handler function.
700 static void InvokeMessageHandler(MessageImpl message);
701
702 // Add a debugger command to the command queue.
703 static void ProcessCommand(Vector<const uint16_t> command,
704 v8::Debug::ClientData* client_data = NULL);
705
706 // Check whether there are commands in the command queue.
707 static bool HasCommands();
708
709 static Handle<Object> Call(Handle<JSFunction> fun,
710 Handle<Object> data,
711 bool* pending_exception);
712
713 // Start the debugger agent listening on the provided port.
Leon Clarkee46be812010-01-19 14:06:41 +0000714 static bool StartAgent(const char* name, int port,
715 bool wait_for_connection = false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000716
717 // Stop the debugger agent.
718 static void StopAgent();
719
720 // Blocks until the agent has started listening for connections
721 static void WaitForAgent();
722
Leon Clarkee46be812010-01-19 14:06:41 +0000723 static void CallMessageDispatchHandler();
724
Steve Block6ded16b2010-05-10 14:33:55 +0100725 static Handle<Context> GetDebugContext();
726
Steve Blocka7e24c12009-10-30 11:49:00 +0000727 // Unload the debugger if possible. Only called when no debugger is currently
728 // active.
729 static void UnloadDebugger();
Steve Block6ded16b2010-05-10 14:33:55 +0100730 friend void ForceUnloadDebugger(); // In test-debug.cc
Steve Blocka7e24c12009-10-30 11:49:00 +0000731
732 inline static bool EventActive(v8::DebugEvent event) {
733 ScopedLock with(debugger_access_);
734
735 // Check whether the message handler was been cleared.
736 if (debugger_unload_pending_) {
Leon Clarkee46be812010-01-19 14:06:41 +0000737 if (Debug::debugger_entry() == NULL) {
738 UnloadDebugger();
739 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000740 }
741
742 // Currently argument event is not used.
743 return !compiling_natives_ && Debugger::IsDebuggerActive();
744 }
745
746 static void set_compiling_natives(bool compiling_natives) {
747 Debugger::compiling_natives_ = compiling_natives;
748 }
749 static bool compiling_natives() { return Debugger::compiling_natives_; }
750 static void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
751 static bool is_loading_debugger() { return Debugger::is_loading_debugger_; }
752
Steve Blocka7e24c12009-10-30 11:49:00 +0000753 static bool IsDebuggerActive();
Leon Clarkef7060e22010-06-03 12:02:55 +0100754
755 private:
Steve Blocka7e24c12009-10-30 11:49:00 +0000756 static void ListenersChanged();
757
758 static Mutex* debugger_access_; // Mutex guarding debugger variables.
759 static Handle<Object> event_listener_; // Global handle to listener.
760 static Handle<Object> event_listener_data_;
761 static bool compiling_natives_; // Are we compiling natives?
762 static bool is_loading_debugger_; // Are we loading the debugger?
763 static bool never_unload_debugger_; // Can we unload the debugger?
764 static v8::Debug::MessageHandler2 message_handler_;
765 static bool debugger_unload_pending_; // Was message handler cleared?
766 static v8::Debug::HostDispatchHandler host_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000767 static Mutex* dispatch_handler_access_; // Mutex guarding dispatch handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000768 static v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
Leon Clarkee46be812010-01-19 14:06:41 +0000769 static MessageDispatchHelperThread* message_dispatch_helper_thread_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000770 static int host_dispatch_micros_;
771
772 static DebuggerAgent* agent_;
773
774 static const int kQueueInitialSize = 4;
775 static LockingCommandMessageQueue command_queue_;
776 static Semaphore* command_received_; // Signaled for each command received.
777
778 friend class EnterDebugger;
779};
780
781
782// This class is used for entering the debugger. Create an instance in the stack
783// to enter the debugger. This will set the current break state, make sure the
784// debugger is loaded and switch to the debugger context. If the debugger for
785// some reason could not be entered FailedToEnter will return true.
786class EnterDebugger BASE_EMBEDDED {
787 public:
788 EnterDebugger()
789 : prev_(Debug::debugger_entry()),
790 has_js_frames_(!it_.done()) {
791 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(PREEMPT));
792 ASSERT(prev_ != NULL || !Debug::is_interrupt_pending(DEBUGBREAK));
793
794 // Link recursive debugger entry.
795 Debug::set_debugger_entry(this);
796
797 // Store the previous break id and frame id.
798 break_id_ = Debug::break_id();
799 break_frame_id_ = Debug::break_frame_id();
800
801 // Create the new break info. If there is no JavaScript frames there is no
802 // break frame id.
803 if (has_js_frames_) {
804 Debug::NewBreak(it_.frame()->id());
805 } else {
806 Debug::NewBreak(StackFrame::NO_ID);
807 }
808
809 // Make sure that debugger is loaded and enter the debugger context.
810 load_failed_ = !Debug::Load();
811 if (!load_failed_) {
812 // NOTE the member variable save which saves the previous context before
813 // this change.
814 Top::set_context(*Debug::debug_context());
815 }
816 }
817
818 ~EnterDebugger() {
819 // Restore to the previous break state.
820 Debug::SetBreak(break_frame_id_, break_id_);
821
822 // Check for leaving the debugger.
823 if (prev_ == NULL) {
824 // Clear mirror cache when leaving the debugger. Skip this if there is a
825 // pending exception as clearing the mirror cache calls back into
826 // JavaScript. This can happen if the v8::Debug::Call is used in which
827 // case the exception should end up in the calling code.
828 if (!Top::has_pending_exception()) {
829 // Try to avoid any pending debug break breaking in the clear mirror
830 // cache JavaScript code.
831 if (StackGuard::IsDebugBreak()) {
832 Debug::set_interrupts_pending(DEBUGBREAK);
833 StackGuard::Continue(DEBUGBREAK);
834 }
835 Debug::ClearMirrorCache();
836 }
837
838 // Request preemption and debug break when leaving the last debugger entry
839 // if any of these where recorded while debugging.
840 if (Debug::is_interrupt_pending(PREEMPT)) {
841 // This re-scheduling of preemption is to avoid starvation in some
842 // debugging scenarios.
843 Debug::clear_interrupt_pending(PREEMPT);
844 StackGuard::Preempt();
845 }
846 if (Debug::is_interrupt_pending(DEBUGBREAK)) {
847 Debug::clear_interrupt_pending(DEBUGBREAK);
848 StackGuard::DebugBreak();
849 }
850
851 // If there are commands in the queue when leaving the debugger request
852 // that these commands are processed.
853 if (Debugger::HasCommands()) {
854 StackGuard::DebugCommand();
855 }
856
857 // If leaving the debugger with the debugger no longer active unload it.
858 if (!Debugger::IsDebuggerActive()) {
859 Debugger::UnloadDebugger();
860 }
861 }
862
863 // Leaving this debugger entry.
864 Debug::set_debugger_entry(prev_);
865 }
866
867 // Check whether the debugger could be entered.
868 inline bool FailedToEnter() { return load_failed_; }
869
870 // Check whether there are any JavaScript frames on the stack.
871 inline bool HasJavaScriptFrames() { return has_js_frames_; }
872
873 // Get the active context from before entering the debugger.
874 inline Handle<Context> GetContext() { return save_.context(); }
875
876 private:
877 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
878 JavaScriptFrameIterator it_;
879 const bool has_js_frames_; // Were there any JavaScript frames?
880 StackFrame::Id break_frame_id_; // Previous break frame id.
881 int break_id_; // Previous break id.
882 bool load_failed_; // Did the debugger fail to load?
883 SaveContext save_; // Saves previous context.
884};
885
886
887// Stack allocated class for disabling break.
888class DisableBreak BASE_EMBEDDED {
889 public:
890 // Enter the debugger by storing the previous top context and setting the
891 // current top context to the debugger context.
892 explicit DisableBreak(bool disable_break) {
893 prev_disable_break_ = Debug::disable_break();
894 Debug::set_disable_break(disable_break);
895 }
896 ~DisableBreak() {
897 Debug::set_disable_break(prev_disable_break_);
898 }
899
900 private:
901 // The previous state of the disable break used to restore the value when this
902 // object is destructed.
903 bool prev_disable_break_;
904};
905
906
907// Debug_Address encapsulates the Address pointers used in generating debug
908// code.
909class Debug_Address {
910 public:
911 Debug_Address(Debug::AddressId id, int reg = 0)
912 : id_(id), reg_(reg) {
913 ASSERT(reg == 0 || id == Debug::k_register_address);
914 }
915
916 static Debug_Address AfterBreakTarget() {
917 return Debug_Address(Debug::k_after_break_target_address);
918 }
919
920 static Debug_Address DebugBreakReturn() {
921 return Debug_Address(Debug::k_debug_break_return_address);
922 }
923
924 static Debug_Address Register(int reg) {
925 return Debug_Address(Debug::k_register_address, reg);
926 }
927
928 Address address() const {
929 switch (id_) {
930 case Debug::k_after_break_target_address:
931 return reinterpret_cast<Address>(Debug::after_break_target_address());
932 case Debug::k_debug_break_return_address:
933 return reinterpret_cast<Address>(Debug::debug_break_return_address());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100934 case Debug::k_debug_break_slot_address:
935 return reinterpret_cast<Address>(Debug::debug_break_slot_address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000936 case Debug::k_register_address:
937 return reinterpret_cast<Address>(Debug::register_address(reg_));
938 default:
939 UNREACHABLE();
940 return NULL;
941 }
942 }
943 private:
944 Debug::AddressId id_;
945 int reg_;
946};
947
Leon Clarkee46be812010-01-19 14:06:41 +0000948// The optional thread that Debug Agent may use to temporary call V8 to process
949// pending debug requests if debuggee is not running V8 at the moment.
950// Techincally it does not call V8 itself, rather it asks embedding program
951// to do this via v8::Debug::HostDispatchHandler
952class MessageDispatchHelperThread: public Thread {
953 public:
954 MessageDispatchHelperThread();
955 ~MessageDispatchHelperThread();
956
957 void Schedule();
958
959 private:
960 void Run();
961
962 Semaphore* const sem_;
963 Mutex* const mutex_;
964 bool already_signalled_;
965
966 DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
967};
968
Steve Blocka7e24c12009-10-30 11:49:00 +0000969
970} } // namespace v8::internal
971
972#endif // ENABLE_DEBUGGER_SUPPORT
973
974#endif // V8_DEBUG_H_