1 // Copyright 2012 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
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.
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.
31 #include "allocation.h"
32 #include "arguments.h"
33 #include "assembler.h"
34 #include "debug-agent.h"
35 #include "execution.h"
38 #include "frames-inl.h"
41 #include "string-stream.h"
42 #include "v8threads.h"
44 #ifdef ENABLE_DEBUGGER_SUPPORT
45 #include "../include/v8-debug.h"
51 // Forward declarations.
55 // Step actions. NOTE: These values are in macros.py as well.
57 StepNone = -1, // Stepping not prepared.
58 StepOut = 0, // Step out of the current function.
59 StepNext = 1, // Step to the next statement in the current function.
60 StepIn = 2, // Step into new functions invoked or the next statement
61 // in the current function.
62 StepMin = 3, // Perform a minimum step in the current function.
63 StepInMin = 4 // Step into new functions invoked or perform a minimum step
64 // in the current function.
68 // Type of exception break. NOTE: These values are in macros.py as well.
69 enum ExceptionBreakType {
71 BreakUncaughtException = 1
75 // Type of exception break. NOTE: These values are in macros.py as well.
76 enum BreakLocatorType {
77 ALL_BREAK_LOCATIONS = 0,
78 SOURCE_BREAK_LOCATIONS = 1
82 // The different types of breakpoint position alignments.
83 // Must match Debug.BreakPositionAlignment in debug-debugger.js
84 enum BreakPositionAlignment {
85 STATEMENT_ALIGNED = 0,
86 BREAK_POSITION_ALIGNED = 1
90 // Class for iterating through the break points in a function and changing
92 class BreakLocationIterator {
94 explicit BreakLocationIterator(Handle<DebugInfo> debug_info,
95 BreakLocatorType type);
96 virtual ~BreakLocationIterator();
100 void FindBreakLocationFromAddress(Address pc);
101 void FindBreakLocationFromPosition(int position,
102 BreakPositionAlignment alignment);
105 void SetBreakPoint(Handle<Object> break_point_object);
106 void ClearBreakPoint(Handle<Object> break_point_object);
109 bool IsStepInLocation(Isolate* isolate);
110 void PrepareStepIn(Isolate* isolate);
112 bool HasBreakPoint();
114 Object* BreakPointObjects();
115 void ClearAllDebugBreak();
118 inline int code_position() {
119 return static_cast<int>(pc() - debug_info_->code()->entry());
121 inline int break_point() { return break_point_; }
122 inline int position() { return position_; }
123 inline int statement_position() { return statement_position_; }
124 inline Address pc() { return reloc_iterator_->rinfo()->pc(); }
125 inline Code* code() { return debug_info_->code(); }
126 inline RelocInfo* rinfo() { return reloc_iterator_->rinfo(); }
127 inline RelocInfo::Mode rmode() const {
128 return reloc_iterator_->rinfo()->rmode();
130 inline RelocInfo* original_rinfo() {
131 return reloc_iterator_original_->rinfo();
133 inline RelocInfo::Mode original_rmode() const {
134 return reloc_iterator_original_->rinfo()->rmode();
137 bool IsDebuggerStatement();
140 bool RinfoDone() const;
143 BreakLocatorType type_;
146 int statement_position_;
147 Handle<DebugInfo> debug_info_;
148 RelocIterator* reloc_iterator_;
149 RelocIterator* reloc_iterator_original_;
152 void SetDebugBreak();
153 void ClearDebugBreak();
155 void SetDebugBreakAtIC();
156 void ClearDebugBreakAtIC();
158 bool IsDebugBreakAtReturn();
159 void SetDebugBreakAtReturn();
160 void ClearDebugBreakAtReturn();
162 bool IsDebugBreakSlot();
163 bool IsDebugBreakAtSlot();
164 void SetDebugBreakAtSlot();
165 void ClearDebugBreakAtSlot();
167 DISALLOW_COPY_AND_ASSIGN(BreakLocationIterator);
171 // Cache of all script objects in the heap. When a script is added a weak handle
172 // to it is created and that weak handle is stored in the cache. The weak handle
173 // callback takes care of removing the script from the cache. The key used in
174 // the cache is the script id.
175 class ScriptCache : private HashMap {
177 explicit ScriptCache(Isolate* isolate)
178 : HashMap(ScriptMatch), isolate_(isolate), collected_scripts_(10) {}
179 virtual ~ScriptCache() { Clear(); }
181 // Add script to the cache.
182 void Add(Handle<Script> script);
184 // Return the scripts in the cache.
185 Handle<FixedArray> GetScripts();
187 // Generate debugger events for collected scripts.
188 void ProcessCollectedScripts();
191 // Calculate the hash value from the key (script id).
192 static uint32_t Hash(int key) {
193 return ComputeIntegerHash(key, v8::internal::kZeroHashSeed);
196 // Scripts match if their keys (script id) match.
197 static bool ScriptMatch(void* key1, void* key2) { return key1 == key2; }
199 // Clear the cache releasing all the weak handles.
202 // Weak handle callback for scripts in the cache.
203 static void HandleWeakScript(
204 const v8::WeakCallbackData<v8::Value, void>& data);
207 // List used during GC to temporarily store id's of collected scripts.
208 List<int> collected_scripts_;
212 // Linked list holding debug info objects. The debug info objects are kept as
213 // weak handles to avoid a debug info object to keep a function alive.
214 class DebugInfoListNode {
216 explicit DebugInfoListNode(DebugInfo* debug_info);
217 virtual ~DebugInfoListNode();
219 DebugInfoListNode* next() { return next_; }
220 void set_next(DebugInfoListNode* next) { next_ = next; }
221 Handle<DebugInfo> debug_info() { return debug_info_; }
224 // Global (weak) handle to the debug info object.
225 Handle<DebugInfo> debug_info_;
227 // Next pointer for linked list.
228 DebugInfoListNode* next_;
231 // This class contains the debugger support. The main purpose is to handle
232 // setting break points in the code.
234 // This class controls the debug info for all functions which currently have
235 // active breakpoints in them. This debug info is held in the heap root object
236 // debug_info which is a FixedArray. Each entry in this list is of class
240 void SetUp(bool create_heap_objects);
243 bool IsLoaded() { return !debug_context_.is_null(); }
244 bool InDebugger() { return thread_local_.debugger_entry_ != NULL; }
245 void PreemptionWhileInDebugger();
246 void Iterate(ObjectVisitor* v);
248 Object* Break(Arguments args);
249 void SetBreakPoint(Handle<JSFunction> function,
250 Handle<Object> break_point_object,
251 int* source_position);
252 bool SetBreakPointForScript(Handle<Script> script,
253 Handle<Object> break_point_object,
254 int* source_position,
255 BreakPositionAlignment alignment);
256 void ClearBreakPoint(Handle<Object> break_point_object);
257 void ClearAllBreakPoints();
258 void FloodWithOneShot(Handle<JSFunction> function);
259 void FloodBoundFunctionWithOneShot(Handle<JSFunction> function);
260 void FloodHandlerWithOneShot();
261 void ChangeBreakOnException(ExceptionBreakType type, bool enable);
262 bool IsBreakOnException(ExceptionBreakType type);
263 void PrepareStep(StepAction step_action,
265 StackFrame::Id frame_id);
266 void ClearStepping();
268 bool IsStepping() { return thread_local_.step_count_ > 0; }
269 bool StepNextContinue(BreakLocationIterator* break_location_iterator,
270 JavaScriptFrame* frame);
271 static Handle<DebugInfo> GetDebugInfo(Handle<SharedFunctionInfo> shared);
272 static bool HasDebugInfo(Handle<SharedFunctionInfo> shared);
274 void PrepareForBreakPoints();
276 // This function is used in FunctionNameUsing* tests.
277 Object* FindSharedFunctionInfoInScript(Handle<Script> script, int position);
279 // Returns whether the operation succeeded. Compilation can only be triggered
280 // if a valid closure is passed as the second argument, otherwise the shared
281 // function needs to be compiled already.
282 bool EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
283 Handle<JSFunction> function);
285 // Returns true if the current stub call is patched to call the debugger.
286 static bool IsDebugBreak(Address addr);
287 // Returns true if the current return statement has been patched to be
288 // a debugger breakpoint.
289 static bool IsDebugBreakAtReturn(RelocInfo* rinfo);
291 // Check whether a code stub with the specified major key is a possible break
293 static bool IsSourceBreakStub(Code* code);
294 static bool IsBreakStub(Code* code);
296 // Find the builtin to use for invoking the debug break
297 static Handle<Code> FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode);
299 static Handle<Object> GetSourceBreakLocations(
300 Handle<SharedFunctionInfo> shared,
301 BreakPositionAlignment position_aligment);
303 // Getter for the debug_context.
304 inline Handle<Context> debug_context() { return debug_context_; }
306 // Check whether a global object is the debug global object.
307 bool IsDebugGlobal(GlobalObject* global);
309 // Check whether this frame is just about to return.
310 bool IsBreakAtReturn(JavaScriptFrame* frame);
312 // Fast check to see if any break points are active.
313 inline bool has_break_points() { return has_break_points_; }
315 void NewBreak(StackFrame::Id break_frame_id);
316 void SetBreak(StackFrame::Id break_frame_id, int break_id);
317 StackFrame::Id break_frame_id() {
318 return thread_local_.break_frame_id_;
320 int break_id() { return thread_local_.break_id_; }
322 bool StepInActive() { return thread_local_.step_into_fp_ != 0; }
323 void HandleStepIn(Handle<JSFunction> function,
324 Handle<Object> holder,
326 bool is_constructor);
327 Address step_in_fp() { return thread_local_.step_into_fp_; }
328 Address* step_in_fp_addr() { return &thread_local_.step_into_fp_; }
330 bool StepOutActive() { return thread_local_.step_out_fp_ != 0; }
331 Address step_out_fp() { return thread_local_.step_out_fp_; }
333 EnterDebugger* debugger_entry() {
334 return thread_local_.debugger_entry_;
336 void set_debugger_entry(EnterDebugger* entry) {
337 thread_local_.debugger_entry_ = entry;
340 // Check whether any of the specified interrupts are pending.
341 bool is_interrupt_pending(InterruptFlag what) {
342 return (thread_local_.pending_interrupts_ & what) != 0;
345 // Set specified interrupts as pending.
346 void set_interrupts_pending(InterruptFlag what) {
347 thread_local_.pending_interrupts_ |= what;
350 // Clear specified interrupts from pending.
351 void clear_interrupt_pending(InterruptFlag what) {
352 thread_local_.pending_interrupts_ &= ~static_cast<int>(what);
355 // Getter and setter for the disable break state.
356 bool disable_break() { return disable_break_; }
357 void set_disable_break(bool disable_break) {
358 disable_break_ = disable_break;
361 // Getters for the current exception break state.
362 bool break_on_exception() { return break_on_exception_; }
363 bool break_on_uncaught_exception() {
364 return break_on_uncaught_exception_;
368 k_after_break_target_address,
369 k_debug_break_return_address,
370 k_debug_break_slot_address,
371 k_restarter_frame_function_pointer
374 // Support for setting the address to jump to when returning from break point.
375 Address* after_break_target_address() {
376 return reinterpret_cast<Address*>(&thread_local_.after_break_target_);
378 Address* restarter_frame_function_pointer_address() {
379 Object*** address = &thread_local_.restarter_frame_function_pointer_;
380 return reinterpret_cast<Address*>(address);
383 // Support for saving/restoring registers when handling debug break calls.
384 Object** register_address(int r) {
385 return ®isters_[r];
388 // Access to the debug break on return code.
389 Code* debug_break_return() { return debug_break_return_; }
390 Code** debug_break_return_address() {
391 return &debug_break_return_;
394 // Access to the debug break in debug break slot code.
395 Code* debug_break_slot() { return debug_break_slot_; }
396 Code** debug_break_slot_address() {
397 return &debug_break_slot_;
400 static const int kEstimatedNofDebugInfoEntries = 16;
401 static const int kEstimatedNofBreakPointsInFunction = 16;
403 // Passed to MakeWeak.
404 static void HandleWeakDebugInfo(
405 const v8::WeakCallbackData<v8::Value, void>& data);
407 friend class Debugger;
408 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
409 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
411 // Threading support.
412 char* ArchiveDebug(char* to);
413 char* RestoreDebug(char* from);
414 static int ArchiveSpacePerThread();
415 void FreeThreadResources() { }
417 // Mirror cache handling.
418 void ClearMirrorCache();
420 // Script cache handling.
421 void CreateScriptCache();
422 void DestroyScriptCache();
423 void AddScriptToScriptCache(Handle<Script> script);
424 Handle<FixedArray> GetLoadedScripts();
426 // Record function from which eval was called.
427 static void RecordEvalCaller(Handle<Script> script);
429 // Garbage collection notifications.
430 void AfterGarbageCollection();
432 // Code generator routines.
433 static void GenerateSlot(MacroAssembler* masm);
434 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
435 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
436 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
437 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
438 static void GenerateCompareNilICDebugBreak(MacroAssembler* masm);
439 static void GenerateReturnDebugBreak(MacroAssembler* masm);
440 static void GenerateCallFunctionStubDebugBreak(MacroAssembler* masm);
441 static void GenerateCallFunctionStubRecordDebugBreak(MacroAssembler* masm);
442 static void GenerateCallConstructStubDebugBreak(MacroAssembler* masm);
443 static void GenerateCallConstructStubRecordDebugBreak(MacroAssembler* masm);
444 static void GenerateSlotDebugBreak(MacroAssembler* masm);
445 static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
447 // FrameDropper is a code replacement for a JavaScript frame with possibly
448 // several frames above.
449 // There is no calling conventions here, because it never actually gets
450 // called, it only gets returned to.
451 static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
453 // Called from stub-cache.cc.
454 static void GenerateCallICDebugBreak(MacroAssembler* masm);
456 // Describes how exactly a frame has been dropped from stack.
458 // No frame has been dropped.
460 // The top JS frame had been calling IC stub. IC stub mustn't be called now.
461 FRAME_DROPPED_IN_IC_CALL,
462 // The top JS frame had been calling debug break slot stub. Patch the
463 // address this stub jumps to in the end.
464 FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
465 // The top JS frame had been calling some C++ function. The return address
466 // gets patched automatically.
467 FRAME_DROPPED_IN_DIRECT_CALL,
468 FRAME_DROPPED_IN_RETURN_CALL,
472 void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
474 Object** restarter_frame_function_pointer);
476 // Initializes an artificial stack frame. The data it contains is used for:
477 // a. successful work of frame dropper code which eventually gets control,
478 // b. being compatible with regular stack structure for various stack
480 // Returns address of stack allocated pointer to restarted function,
481 // the value that is called 'restarter_frame_function_pointer'. The value
482 // at this address (possibly updated by GC) may be used later when preparing
483 // 'step in' operation.
484 static Object** SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
487 static const int kFrameDropperFrameSize;
489 // Architecture-specific constant.
490 static const bool kFrameDropperSupported;
493 * Defines layout of a stack frame that supports padding. This is a regular
494 * internal frame that has a flexible stack structure. LiveEdit can shift
495 * its lower part up the stack, taking up the 'padding' space when additional
496 * stack memory is required.
497 * Such frame is expected immediately above the topmost JavaScript frame.
501 * LiveEdit routine frames
503 * C frames of debug handler
507 * An internal frame that has n padding words:
508 * - any number of words as needed by code -- upper part of frame
509 * - padding size: a Smi storing n -- current size of padding
510 * - padding: n words filled with kPaddingValue in form of Smi
511 * - 3 context/type words of a regular InternalFrame
514 * Topmost JavaScript frame
519 class FramePaddingLayout : public AllStatic {
521 // Architecture-specific constant.
522 static const bool kIsSupported;
524 // A size of frame base including fp. Padding words starts right above
526 static const int kFrameBaseSize = 4;
528 // A number of words that should be reserved on stack for the LiveEdit use.
529 // Normally equals 1. Stored on stack in form of Smi.
530 static const int kInitialSize;
531 // A value that padding words are filled with (in form of Smi). Going
532 // bottom-top, the first word not having this value is a counter word.
533 static const int kPaddingValue;
537 explicit Debug(Isolate* isolate);
540 static bool CompileDebuggerScript(Isolate* isolate, int index);
542 void ActivateStepIn(StackFrame* frame);
544 void ActivateStepOut(StackFrame* frame);
545 void ClearStepNext();
546 // Returns whether the compile succeeded.
547 void RemoveDebugInfo(Handle<DebugInfo> debug_info);
548 void SetAfterBreakTarget(JavaScriptFrame* frame);
549 Handle<Object> CheckBreakPoints(Handle<Object> break_point);
550 bool CheckBreakPoint(Handle<Object> break_point_object);
552 // Global handle to debug context where all the debugger JavaScript code is
554 Handle<Context> debug_context_;
556 // Boolean state indicating whether any break points are set.
557 bool has_break_points_;
559 // Cache of all scripts in the heap.
560 ScriptCache* script_cache_;
562 // List of active debug info objects.
563 DebugInfoListNode* debug_info_list_;
566 bool break_on_exception_;
567 bool break_on_uncaught_exception_;
572 // Counter for generating next break id.
578 // Frame id for the frame of the current break.
579 StackFrame::Id break_frame_id_;
581 // Step action for last step performed.
582 StepAction last_step_action_;
584 // Source statement position from last step next action.
585 int last_statement_position_;
587 // Number of steps left to perform before debug event.
590 // Frame pointer from last step next action.
593 // Number of queued steps left to perform before debug event.
594 int queued_step_count_;
596 // Frame pointer for frame from which step in was performed.
597 Address step_into_fp_;
599 // Frame pointer for the frame where debugger should be called when current
600 // step out action is completed.
601 Address step_out_fp_;
603 // Storage location for jump when exiting debug break calls.
604 Address after_break_target_;
606 // Stores the way how LiveEdit has patched the stack. It is used when
607 // debugger returns control back to user script.
608 FrameDropMode frame_drop_mode_;
610 // Top debugger entry.
611 EnterDebugger* debugger_entry_;
613 // Pending interrupts scheduled while debugging.
614 int pending_interrupts_;
616 // When restarter frame is on stack, stores the address
617 // of the pointer to function being restarted. Otherwise (most of the time)
618 // stores NULL. This pointer is used with 'step in' implementation.
619 Object** restarter_frame_function_pointer_;
622 // Storage location for registers when handling debug break calls
623 JSCallerSavedBuffer registers_;
624 ThreadLocal thread_local_;
627 // Code to call for handling debug break on return.
628 Code* debug_break_return_;
630 // Code to call for handling debug break in debug break slots.
631 Code* debug_break_slot_;
635 friend class Isolate;
637 DISALLOW_COPY_AND_ASSIGN(Debug);
641 DECLARE_RUNTIME_FUNCTION(Object*, Debug_Break);
644 // Message delivered to the message handler callback. This is either a debugger
645 // event or the response to a command.
646 class MessageImpl: public v8::Debug::Message {
648 // Create a message object for a debug event.
649 static MessageImpl NewEvent(DebugEvent event,
651 Handle<JSObject> exec_state,
652 Handle<JSObject> event_data);
654 // Create a message object for the response to a debug command.
655 static MessageImpl NewResponse(DebugEvent event,
657 Handle<JSObject> exec_state,
658 Handle<JSObject> event_data,
659 Handle<String> response_json,
660 v8::Debug::ClientData* client_data);
662 // Implementation of interface v8::Debug::Message.
663 virtual bool IsEvent() const;
664 virtual bool IsResponse() const;
665 virtual DebugEvent GetEvent() const;
666 virtual bool WillStartRunning() const;
667 virtual v8::Handle<v8::Object> GetExecutionState() const;
668 virtual v8::Handle<v8::Object> GetEventData() const;
669 virtual v8::Handle<v8::String> GetJSON() const;
670 virtual v8::Handle<v8::Context> GetEventContext() const;
671 virtual v8::Debug::ClientData* GetClientData() const;
672 virtual v8::Isolate* GetIsolate() const;
675 MessageImpl(bool is_event,
678 Handle<JSObject> exec_state,
679 Handle<JSObject> event_data,
680 Handle<String> response_json,
681 v8::Debug::ClientData* client_data);
683 bool is_event_; // Does this message represent a debug event?
684 DebugEvent event_; // Debug event causing the break.
685 bool running_; // Will the VM start running after this event?
686 Handle<JSObject> exec_state_; // Current execution state.
687 Handle<JSObject> event_data_; // Data associated with the event.
688 Handle<String> response_json_; // Response JSON if message holds a response.
689 v8::Debug::ClientData* client_data_; // Client data passed with the request.
693 // Details of the debug event delivered to the debug event listener.
694 class EventDetailsImpl : public v8::Debug::EventDetails {
696 EventDetailsImpl(DebugEvent event,
697 Handle<JSObject> exec_state,
698 Handle<JSObject> event_data,
699 Handle<Object> callback_data,
700 v8::Debug::ClientData* client_data);
701 virtual DebugEvent GetEvent() const;
702 virtual v8::Handle<v8::Object> GetExecutionState() const;
703 virtual v8::Handle<v8::Object> GetEventData() const;
704 virtual v8::Handle<v8::Context> GetEventContext() const;
705 virtual v8::Handle<v8::Value> GetCallbackData() const;
706 virtual v8::Debug::ClientData* GetClientData() const;
708 DebugEvent event_; // Debug event causing the break.
709 Handle<JSObject> exec_state_; // Current execution state.
710 Handle<JSObject> event_data_; // Data associated with the event.
711 Handle<Object> callback_data_; // User data passed with the callback
712 // when it was registered.
713 v8::Debug::ClientData* client_data_; // Data passed to DebugBreakForCommand.
717 // Message send by user to v8 debugger or debugger output message.
718 // In addition to command text it may contain a pointer to some user data
719 // which are expected to be passed along with the command reponse to message
721 class CommandMessage {
723 static CommandMessage New(const Vector<uint16_t>& command,
724 v8::Debug::ClientData* data);
728 // Deletes user data and disposes of the text.
730 Vector<uint16_t> text() const { return text_; }
731 v8::Debug::ClientData* client_data() const { return client_data_; }
733 CommandMessage(const Vector<uint16_t>& text,
734 v8::Debug::ClientData* data);
736 Vector<uint16_t> text_;
737 v8::Debug::ClientData* client_data_;
740 // A Queue of CommandMessage objects. A thread-safe version is
741 // LockingCommandMessageQueue, based on this class.
742 class CommandMessageQueue BASE_EMBEDDED {
744 explicit CommandMessageQueue(int size);
745 ~CommandMessageQueue();
746 bool IsEmpty() const { return start_ == end_; }
747 CommandMessage Get();
748 void Put(const CommandMessage& message);
749 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
751 // Doubles the size of the message queue, and copies the messages.
754 CommandMessage* messages_;
757 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
761 class MessageDispatchHelperThread;
764 // LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
765 // messages. The message data is not managed by LockingCommandMessageQueue.
766 // Pointers to the data are passed in and out. Implemented by adding a
767 // Mutex to CommandMessageQueue. Includes logging of all puts and gets.
768 class LockingCommandMessageQueue BASE_EMBEDDED {
770 LockingCommandMessageQueue(Logger* logger, int size);
771 bool IsEmpty() const;
772 CommandMessage Get();
773 void Put(const CommandMessage& message);
777 CommandMessageQueue queue_;
778 mutable Mutex mutex_;
779 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
787 void DebugRequest(const uint16_t* json_request, int length);
789 Handle<Object> MakeJSObject(Vector<const char> constructor_name,
791 Handle<Object> argv[],
792 bool* caught_exception);
793 Handle<Object> MakeExecutionState(bool* caught_exception);
794 Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
795 Handle<Object> break_points_hit,
796 bool* caught_exception);
797 Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
798 Handle<Object> exception,
800 bool* caught_exception);
801 Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
802 bool* caught_exception);
803 Handle<Object> MakeCompileEvent(Handle<Script> script,
805 bool* caught_exception);
806 Handle<Object> MakeScriptCollectedEvent(int id,
807 bool* caught_exception);
808 void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
809 void OnException(Handle<Object> exception, bool uncaught);
810 void OnBeforeCompile(Handle<Script> script);
812 enum AfterCompileFlags {
813 NO_AFTER_COMPILE_FLAGS,
816 void OnAfterCompile(Handle<Script> script,
817 AfterCompileFlags after_compile_flags);
818 void OnScriptCollected(int id);
819 void ProcessDebugEvent(v8::DebugEvent event,
820 Handle<JSObject> event_data,
822 void NotifyMessageHandler(v8::DebugEvent event,
823 Handle<JSObject> exec_state,
824 Handle<JSObject> event_data,
826 void SetEventListener(Handle<Object> callback, Handle<Object> data);
827 void SetMessageHandler(v8::Debug::MessageHandler2 handler);
828 void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
830 void SetDebugMessageDispatchHandler(
831 v8::Debug::DebugMessageDispatchHandler handler,
832 bool provide_locker);
834 // Invoke the message handler function.
835 void InvokeMessageHandler(MessageImpl message);
837 // Add a debugger command to the command queue.
838 void ProcessCommand(Vector<const uint16_t> command,
839 v8::Debug::ClientData* client_data = NULL);
841 // Check whether there are commands in the command queue.
844 // Enqueue a debugger command to the command queue for event listeners.
845 void EnqueueDebugCommand(v8::Debug::ClientData* client_data = NULL);
847 Handle<Object> Call(Handle<JSFunction> fun,
849 bool* pending_exception);
851 // Start the debugger agent listening on the provided port.
852 bool StartAgent(const char* name, int port,
853 bool wait_for_connection = false);
855 // Stop the debugger agent.
858 // Blocks until the agent has started listening for connections
861 void CallMessageDispatchHandler();
863 Handle<Context> GetDebugContext();
865 // Unload the debugger if possible. Only called when no debugger is currently
867 void UnloadDebugger();
868 friend void ForceUnloadDebugger(); // In test-debug.cc
870 inline bool EventActive(v8::DebugEvent event) {
871 LockGuard<RecursiveMutex> lock_guard(debugger_access_);
873 // Check whether the message handler was been cleared.
874 if (debugger_unload_pending_) {
875 if (isolate_->debug()->debugger_entry() == NULL) {
880 if (((event == v8::BeforeCompile) || (event == v8::AfterCompile)) &&
881 !FLAG_debug_compile_events) {
884 } else if ((event == v8::ScriptCollected) &&
885 !FLAG_debug_script_collected_events) {
889 // Currently argument event is not used.
890 return !compiling_natives_ && Debugger::IsDebuggerActive();
893 void set_compiling_natives(bool compiling_natives) {
894 compiling_natives_ = compiling_natives;
896 bool compiling_natives() const { return compiling_natives_; }
897 void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
898 bool is_loading_debugger() const { return is_loading_debugger_; }
899 void set_live_edit_enabled(bool v) { live_edit_enabled_ = v; }
900 bool live_edit_enabled() const {
901 return FLAG_enable_liveedit && live_edit_enabled_ ;
903 void set_force_debugger_active(bool force_debugger_active) {
904 force_debugger_active_ = force_debugger_active;
906 bool force_debugger_active() const { return force_debugger_active_; }
908 bool IsDebuggerActive();
911 explicit Debugger(Isolate* isolate);
913 void CallEventCallback(v8::DebugEvent event,
914 Handle<Object> exec_state,
915 Handle<Object> event_data,
916 v8::Debug::ClientData* client_data);
917 void CallCEventCallback(v8::DebugEvent event,
918 Handle<Object> exec_state,
919 Handle<Object> event_data,
920 v8::Debug::ClientData* client_data);
921 void CallJSEventCallback(v8::DebugEvent event,
922 Handle<Object> exec_state,
923 Handle<Object> event_data);
924 void ListenersChanged();
926 RecursiveMutex* debugger_access_; // Mutex guarding debugger variables.
927 Handle<Object> event_listener_; // Global handle to listener.
928 Handle<Object> event_listener_data_;
929 bool compiling_natives_; // Are we compiling natives?
930 bool is_loading_debugger_; // Are we loading the debugger?
931 bool live_edit_enabled_; // Enable LiveEdit.
932 bool never_unload_debugger_; // Can we unload the debugger?
933 bool force_debugger_active_; // Activate debugger without event listeners.
934 v8::Debug::MessageHandler2 message_handler_;
935 bool debugger_unload_pending_; // Was message handler cleared?
936 v8::Debug::HostDispatchHandler host_dispatch_handler_;
937 Mutex dispatch_handler_access_; // Mutex guarding dispatch handler.
938 v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
939 MessageDispatchHelperThread* message_dispatch_helper_thread_;
940 TimeDelta host_dispatch_period_;
942 DebuggerAgent* agent_;
944 static const int kQueueInitialSize = 4;
945 LockingCommandMessageQueue command_queue_;
946 Semaphore command_received_; // Signaled for each command received.
947 LockingCommandMessageQueue event_command_queue_;
951 friend class EnterDebugger;
952 friend class Isolate;
954 DISALLOW_COPY_AND_ASSIGN(Debugger);
958 // This class is used for entering the debugger. Create an instance in the stack
959 // to enter the debugger. This will set the current break state, make sure the
960 // debugger is loaded and switch to the debugger context. If the debugger for
961 // some reason could not be entered FailedToEnter will return true.
962 class EnterDebugger BASE_EMBEDDED {
964 explicit EnterDebugger(Isolate* isolate);
967 // Check whether the debugger could be entered.
968 inline bool FailedToEnter() { return load_failed_; }
970 // Check whether there are any JavaScript frames on the stack.
971 inline bool HasJavaScriptFrames() { return has_js_frames_; }
973 // Get the active context from before entering the debugger.
974 inline Handle<Context> GetContext() { return save_.context(); }
978 EnterDebugger* prev_; // Previous debugger entry if entered recursively.
979 JavaScriptFrameIterator it_;
980 const bool has_js_frames_; // Were there any JavaScript frames?
981 StackFrame::Id break_frame_id_; // Previous break frame id.
982 int break_id_; // Previous break id.
983 bool load_failed_; // Did the debugger fail to load?
984 SaveContext save_; // Saves previous context.
988 // Stack allocated class for disabling break.
989 class DisableBreak BASE_EMBEDDED {
991 explicit DisableBreak(Isolate* isolate, bool disable_break)
992 : isolate_(isolate) {
993 prev_disable_break_ = isolate_->debug()->disable_break();
994 isolate_->debug()->set_disable_break(disable_break);
997 isolate_->debug()->set_disable_break(prev_disable_break_);
1002 // The previous state of the disable break used to restore the value when this
1003 // object is destructed.
1004 bool prev_disable_break_;
1008 // Debug_Address encapsulates the Address pointers used in generating debug
1010 class Debug_Address {
1012 explicit Debug_Address(Debug::AddressId id) : id_(id) { }
1014 static Debug_Address AfterBreakTarget() {
1015 return Debug_Address(Debug::k_after_break_target_address);
1018 static Debug_Address DebugBreakReturn() {
1019 return Debug_Address(Debug::k_debug_break_return_address);
1022 static Debug_Address RestarterFrameFunctionPointer() {
1023 return Debug_Address(Debug::k_restarter_frame_function_pointer);
1026 Address address(Isolate* isolate) const {
1027 Debug* debug = isolate->debug();
1029 case Debug::k_after_break_target_address:
1030 return reinterpret_cast<Address>(debug->after_break_target_address());
1031 case Debug::k_debug_break_return_address:
1032 return reinterpret_cast<Address>(debug->debug_break_return_address());
1033 case Debug::k_debug_break_slot_address:
1034 return reinterpret_cast<Address>(debug->debug_break_slot_address());
1035 case Debug::k_restarter_frame_function_pointer:
1036 return reinterpret_cast<Address>(
1037 debug->restarter_frame_function_pointer_address());
1045 Debug::AddressId id_;
1048 // The optional thread that Debug Agent may use to temporary call V8 to process
1049 // pending debug requests if debuggee is not running V8 at the moment.
1050 // Techincally it does not call V8 itself, rather it asks embedding program
1051 // to do this via v8::Debug::HostDispatchHandler
1052 class MessageDispatchHelperThread: public Thread {
1054 explicit MessageDispatchHelperThread(Isolate* isolate);
1055 ~MessageDispatchHelperThread() {}
1065 bool already_signalled_;
1067 DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
1071 } } // namespace v8::internal
1073 #endif // ENABLE_DEBUGGER_SUPPORT
1075 #endif // V8_DEBUG_H_