1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 #include "src/allocation.h"
9 #include "src/arguments.h"
10 #include "src/assembler.h"
11 #include "src/base/platform/platform.h"
12 #include "src/execution.h"
13 #include "src/factory.h"
14 #include "src/flags.h"
15 #include "src/frames-inl.h"
16 #include "src/hashmap.h"
17 #include "src/liveedit.h"
18 #include "src/string-stream.h"
19 #include "src/v8threads.h"
21 #include "include/v8-debug.h"
27 // Forward declarations.
31 // Step actions. NOTE: These values are in macros.py as well.
33 StepNone = -1, // Stepping not prepared.
34 StepOut = 0, // Step out of the current function.
35 StepNext = 1, // Step to the next statement in the current function.
36 StepIn = 2, // Step into new functions invoked or the next statement
37 // in the current function.
38 StepMin = 3, // Perform a minimum step in the current function.
39 StepInMin = 4 // Step into new functions invoked or perform a minimum step
40 // in the current function.
44 // Type of exception break. NOTE: These values are in macros.py as well.
45 enum ExceptionBreakType {
47 BreakUncaughtException = 1
51 // Type of exception break. NOTE: These values are in macros.py as well.
52 enum BreakLocatorType {
53 ALL_BREAK_LOCATIONS = 0,
54 SOURCE_BREAK_LOCATIONS = 1
58 // The different types of breakpoint position alignments.
59 // Must match Debug.BreakPositionAlignment in debug-debugger.js
60 enum BreakPositionAlignment {
61 STATEMENT_ALIGNED = 0,
62 BREAK_POSITION_ALIGNED = 1
66 // Class for iterating through the break points in a function and changing
68 class BreakLocationIterator {
70 explicit BreakLocationIterator(Handle<DebugInfo> debug_info,
71 BreakLocatorType type);
72 virtual ~BreakLocationIterator();
76 void FindBreakLocationFromAddress(Address pc);
77 void FindBreakLocationFromPosition(int position,
78 BreakPositionAlignment alignment);
81 void SetBreakPoint(Handle<Object> break_point_object);
82 void ClearBreakPoint(Handle<Object> break_point_object);
85 bool IsStepInLocation(Isolate* isolate);
86 void PrepareStepIn(Isolate* isolate);
90 Object* BreakPointObjects();
91 void ClearAllDebugBreak();
94 inline int code_position() {
95 return static_cast<int>(pc() - debug_info_->code()->entry());
97 inline int break_point() { return break_point_; }
98 inline int position() { return position_; }
99 inline int statement_position() { return statement_position_; }
100 inline Address pc() { return reloc_iterator_->rinfo()->pc(); }
101 inline Code* code() { return debug_info_->code(); }
102 inline RelocInfo* rinfo() { return reloc_iterator_->rinfo(); }
103 inline RelocInfo::Mode rmode() const {
104 return reloc_iterator_->rinfo()->rmode();
106 inline RelocInfo* original_rinfo() {
107 return reloc_iterator_original_->rinfo();
109 inline RelocInfo::Mode original_rmode() const {
110 return reloc_iterator_original_->rinfo()->rmode();
113 bool IsDebuggerStatement();
116 bool RinfoDone() const;
119 BreakLocatorType type_;
122 int statement_position_;
123 Handle<DebugInfo> debug_info_;
124 RelocIterator* reloc_iterator_;
125 RelocIterator* reloc_iterator_original_;
128 void SetDebugBreak();
129 void ClearDebugBreak();
131 void SetDebugBreakAtIC();
132 void ClearDebugBreakAtIC();
134 bool IsDebugBreakAtReturn();
135 void SetDebugBreakAtReturn();
136 void ClearDebugBreakAtReturn();
138 bool IsDebugBreakSlot();
139 bool IsDebugBreakAtSlot();
140 void SetDebugBreakAtSlot();
141 void ClearDebugBreakAtSlot();
143 DISALLOW_COPY_AND_ASSIGN(BreakLocationIterator);
147 // Cache of all script objects in the heap. When a script is added a weak handle
148 // to it is created and that weak handle is stored in the cache. The weak handle
149 // callback takes care of removing the script from the cache. The key used in
150 // the cache is the script id.
151 class ScriptCache : private HashMap {
153 explicit ScriptCache(Isolate* isolate);
154 virtual ~ScriptCache() { Clear(); }
156 // Add script to the cache.
157 void Add(Handle<Script> script);
159 // Return the scripts in the cache.
160 Handle<FixedArray> GetScripts();
163 // Calculate the hash value from the key (script id).
164 static uint32_t Hash(int key) {
165 return ComputeIntegerHash(key, v8::internal::kZeroHashSeed);
168 // Clear the cache releasing all the weak handles.
171 // Weak handle callback for scripts in the cache.
172 static void HandleWeakScript(
173 const v8::WeakCallbackData<v8::Value, void>& data);
179 // Linked list holding debug info objects. The debug info objects are kept as
180 // weak handles to avoid a debug info object to keep a function alive.
181 class DebugInfoListNode {
183 explicit DebugInfoListNode(DebugInfo* debug_info);
184 virtual ~DebugInfoListNode();
186 DebugInfoListNode* next() { return next_; }
187 void set_next(DebugInfoListNode* next) { next_ = next; }
188 Handle<DebugInfo> debug_info() { return debug_info_; }
191 // Global (weak) handle to the debug info object.
192 Handle<DebugInfo> debug_info_;
194 // Next pointer for linked list.
195 DebugInfoListNode* next_;
200 // Message delivered to the message handler callback. This is either a debugger
201 // event or the response to a command.
202 class MessageImpl: public v8::Debug::Message {
204 // Create a message object for a debug event.
205 static MessageImpl NewEvent(DebugEvent event,
207 Handle<JSObject> exec_state,
208 Handle<JSObject> event_data);
210 // Create a message object for the response to a debug command.
211 static MessageImpl NewResponse(DebugEvent event,
213 Handle<JSObject> exec_state,
214 Handle<JSObject> event_data,
215 Handle<String> response_json,
216 v8::Debug::ClientData* client_data);
218 // Implementation of interface v8::Debug::Message.
219 virtual bool IsEvent() const;
220 virtual bool IsResponse() const;
221 virtual DebugEvent GetEvent() const;
222 virtual bool WillStartRunning() const;
223 virtual v8::Handle<v8::Object> GetExecutionState() const;
224 virtual v8::Handle<v8::Object> GetEventData() const;
225 virtual v8::Handle<v8::String> GetJSON() const;
226 virtual v8::Handle<v8::Context> GetEventContext() const;
227 virtual v8::Debug::ClientData* GetClientData() const;
228 virtual v8::Isolate* GetIsolate() const;
231 MessageImpl(bool is_event,
234 Handle<JSObject> exec_state,
235 Handle<JSObject> event_data,
236 Handle<String> response_json,
237 v8::Debug::ClientData* client_data);
239 bool is_event_; // Does this message represent a debug event?
240 DebugEvent event_; // Debug event causing the break.
241 bool running_; // Will the VM start running after this event?
242 Handle<JSObject> exec_state_; // Current execution state.
243 Handle<JSObject> event_data_; // Data associated with the event.
244 Handle<String> response_json_; // Response JSON if message holds a response.
245 v8::Debug::ClientData* client_data_; // Client data passed with the request.
249 // Details of the debug event delivered to the debug event listener.
250 class EventDetailsImpl : public v8::Debug::EventDetails {
252 EventDetailsImpl(DebugEvent event,
253 Handle<JSObject> exec_state,
254 Handle<JSObject> event_data,
255 Handle<Object> callback_data,
256 v8::Debug::ClientData* client_data);
257 virtual DebugEvent GetEvent() const;
258 virtual v8::Handle<v8::Object> GetExecutionState() const;
259 virtual v8::Handle<v8::Object> GetEventData() const;
260 virtual v8::Handle<v8::Context> GetEventContext() const;
261 virtual v8::Handle<v8::Value> GetCallbackData() const;
262 virtual v8::Debug::ClientData* GetClientData() const;
264 DebugEvent event_; // Debug event causing the break.
265 Handle<JSObject> exec_state_; // Current execution state.
266 Handle<JSObject> event_data_; // Data associated with the event.
267 Handle<Object> callback_data_; // User data passed with the callback
268 // when it was registered.
269 v8::Debug::ClientData* client_data_; // Data passed to DebugBreakForCommand.
273 // Message send by user to v8 debugger or debugger output message.
274 // In addition to command text it may contain a pointer to some user data
275 // which are expected to be passed along with the command reponse to message
277 class CommandMessage {
279 static CommandMessage New(const Vector<uint16_t>& command,
280 v8::Debug::ClientData* data);
283 // Deletes user data and disposes of the text.
285 Vector<uint16_t> text() const { return text_; }
286 v8::Debug::ClientData* client_data() const { return client_data_; }
288 CommandMessage(const Vector<uint16_t>& text,
289 v8::Debug::ClientData* data);
291 Vector<uint16_t> text_;
292 v8::Debug::ClientData* client_data_;
296 // A Queue of CommandMessage objects. A thread-safe version is
297 // LockingCommandMessageQueue, based on this class.
298 class CommandMessageQueue BASE_EMBEDDED {
300 explicit CommandMessageQueue(int size);
301 ~CommandMessageQueue();
302 bool IsEmpty() const { return start_ == end_; }
303 CommandMessage Get();
304 void Put(const CommandMessage& message);
305 void Clear() { start_ = end_ = 0; } // Queue is empty after Clear().
307 // Doubles the size of the message queue, and copies the messages.
310 CommandMessage* messages_;
313 int size_; // The size of the queue buffer. Queue can hold size-1 messages.
317 // LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
318 // messages. The message data is not managed by LockingCommandMessageQueue.
319 // Pointers to the data are passed in and out. Implemented by adding a
320 // Mutex to CommandMessageQueue. Includes logging of all puts and gets.
321 class LockingCommandMessageQueue BASE_EMBEDDED {
323 LockingCommandMessageQueue(Logger* logger, int size);
324 bool IsEmpty() const;
325 CommandMessage Get();
326 void Put(const CommandMessage& message);
330 CommandMessageQueue queue_;
331 mutable base::Mutex mutex_;
332 DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
336 // This class contains the debugger support. The main purpose is to handle
337 // setting break points in the code.
339 // This class controls the debug info for all functions which currently have
340 // active breakpoints in them. This debug info is held in the heap root object
341 // debug_info which is a FixedArray. Each entry in this list is of class
345 // Debug event triggers.
346 void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
348 void OnThrow(Handle<Object> exception, bool uncaught);
349 void OnPromiseReject(Handle<JSObject> promise, Handle<Object> value);
350 void OnCompileError(Handle<Script> script);
351 void OnBeforeCompile(Handle<Script> script);
352 void OnAfterCompile(Handle<Script> script);
353 void OnPromiseEvent(Handle<JSObject> data);
354 void OnAsyncTaskEvent(Handle<JSObject> data);
357 void SetEventListener(Handle<Object> callback, Handle<Object> data);
358 void SetMessageHandler(v8::Debug::MessageHandler handler);
359 void EnqueueCommandMessage(Vector<const uint16_t> command,
360 v8::Debug::ClientData* client_data = NULL);
361 // Enqueue a debugger command to the command queue for event listeners.
362 void EnqueueDebugCommand(v8::Debug::ClientData* client_data = NULL);
363 MUST_USE_RESULT MaybeHandle<Object> Call(Handle<JSFunction> fun,
364 Handle<Object> data);
365 Handle<Context> GetDebugContext();
366 void HandleDebugBreak();
367 void ProcessDebugMessages(bool debug_command_only);
371 void Break(Arguments args, JavaScriptFrame*);
372 void SetAfterBreakTarget(JavaScriptFrame* frame);
375 Handle<FixedArray> GetLoadedScripts();
377 // Break point handling.
378 bool SetBreakPoint(Handle<JSFunction> function,
379 Handle<Object> break_point_object,
380 int* source_position);
381 bool SetBreakPointForScript(Handle<Script> script,
382 Handle<Object> break_point_object,
383 int* source_position,
384 BreakPositionAlignment alignment);
385 void ClearBreakPoint(Handle<Object> break_point_object);
386 void ClearAllBreakPoints();
387 void FloodWithOneShot(Handle<JSFunction> function);
388 void FloodBoundFunctionWithOneShot(Handle<JSFunction> function);
389 void FloodHandlerWithOneShot();
390 void ChangeBreakOnException(ExceptionBreakType type, bool enable);
391 bool IsBreakOnException(ExceptionBreakType type);
393 // Stepping handling.
394 void PrepareStep(StepAction step_action,
396 StackFrame::Id frame_id);
397 void ClearStepping();
399 bool IsStepping() { return thread_local_.step_count_ > 0; }
400 bool StepNextContinue(BreakLocationIterator* break_location_iterator,
401 JavaScriptFrame* frame);
402 bool StepInActive() { return thread_local_.step_into_fp_ != 0; }
403 void HandleStepIn(Handle<JSFunction> function,
404 Handle<Object> holder,
406 bool is_constructor);
407 bool StepOutActive() { return thread_local_.step_out_fp_ != 0; }
409 // Purge all code objects that have no debug break slots.
410 void PrepareForBreakPoints();
412 // Returns whether the operation succeeded. Compilation can only be triggered
413 // if a valid closure is passed as the second argument, otherwise the shared
414 // function needs to be compiled already.
415 bool EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
416 Handle<JSFunction> function);
417 static Handle<DebugInfo> GetDebugInfo(Handle<SharedFunctionInfo> shared);
418 static bool HasDebugInfo(Handle<SharedFunctionInfo> shared);
420 // This function is used in FunctionNameUsing* tests.
421 Object* FindSharedFunctionInfoInScript(Handle<Script> script, int position);
423 // Returns true if the current stub call is patched to call the debugger.
424 static bool IsDebugBreak(Address addr);
425 // Returns true if the current return statement has been patched to be
426 // a debugger breakpoint.
427 static bool IsDebugBreakAtReturn(RelocInfo* rinfo);
429 static Handle<Object> GetSourceBreakLocations(
430 Handle<SharedFunctionInfo> shared,
431 BreakPositionAlignment position_aligment);
433 // Check whether a global object is the debug global object.
434 bool IsDebugGlobal(GlobalObject* global);
436 // Check whether this frame is just about to return.
437 bool IsBreakAtReturn(JavaScriptFrame* frame);
439 // Support for LiveEdit
440 void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
441 LiveEdit::FrameDropMode mode,
442 Object** restarter_frame_function_pointer);
444 // Passed to MakeWeak.
445 static void HandleWeakDebugInfo(
446 const v8::WeakCallbackData<v8::Value, void>& data);
448 // Threading support.
449 char* ArchiveDebug(char* to);
450 char* RestoreDebug(char* from);
451 static int ArchiveSpacePerThread();
452 void FreeThreadResources() { }
454 // Record function from which eval was called.
455 static void RecordEvalCaller(Handle<Script> script);
458 DebugScope* debugger_entry() { return thread_local_.current_debug_scope_; }
459 inline Handle<Context> debug_context() { return debug_context_; }
460 void set_live_edit_enabled(bool v) { live_edit_enabled_ = v; }
461 bool live_edit_enabled() const {
462 return FLAG_enable_liveedit && live_edit_enabled_ ;
465 inline bool is_active() const { return is_active_; }
466 inline bool is_loaded() const { return !debug_context_.is_null(); }
467 inline bool has_break_points() const { return has_break_points_; }
468 inline bool in_debug_scope() const {
469 return thread_local_.current_debug_scope_ != NULL;
471 void set_disable_break(bool v) { break_disabled_ = v; }
473 StackFrame::Id break_frame_id() { return thread_local_.break_frame_id_; }
474 int break_id() { return thread_local_.break_id_; }
476 // Support for embedding into generated code.
477 Address is_active_address() {
478 return reinterpret_cast<Address>(&is_active_);
481 Address after_break_target_address() {
482 return reinterpret_cast<Address>(&after_break_target_);
485 Address restarter_frame_function_pointer_address() {
486 Object*** address = &thread_local_.restarter_frame_function_pointer_;
487 return reinterpret_cast<Address>(address);
490 Address step_in_fp_addr() {
491 return reinterpret_cast<Address>(&thread_local_.step_into_fp_);
495 explicit Debug(Isolate* isolate);
499 void SetNextBreakId() {
500 thread_local_.break_id_ = ++thread_local_.break_count_;
503 // Check whether there are commands in the command queue.
504 inline bool has_commands() const { return !command_queue_.IsEmpty(); }
505 inline bool ignore_events() const { return is_suppressed_ || !is_active_; }
507 void OnException(Handle<Object> exception, bool uncaught,
508 Handle<Object> promise);
510 // Constructors for debug event objects.
511 MUST_USE_RESULT MaybeHandle<Object> MakeJSObject(
512 const char* constructor_name,
514 Handle<Object> argv[]);
515 MUST_USE_RESULT MaybeHandle<Object> MakeExecutionState();
516 MUST_USE_RESULT MaybeHandle<Object> MakeBreakEvent(
517 Handle<Object> break_points_hit);
518 MUST_USE_RESULT MaybeHandle<Object> MakeExceptionEvent(
519 Handle<Object> exception,
521 Handle<Object> promise);
522 MUST_USE_RESULT MaybeHandle<Object> MakeCompileEvent(
523 Handle<Script> script, v8::DebugEvent type);
524 MUST_USE_RESULT MaybeHandle<Object> MakePromiseEvent(
525 Handle<JSObject> promise_event);
526 MUST_USE_RESULT MaybeHandle<Object> MakeAsyncTaskEvent(
527 Handle<JSObject> task_event);
529 // Mirror cache handling.
530 void ClearMirrorCache();
532 // Returns a promise if the pushed try-catch handler matches the current one.
533 bool PromiseHasRejectHandler(Handle<JSObject> promise);
535 void CallEventCallback(v8::DebugEvent event,
536 Handle<Object> exec_state,
537 Handle<Object> event_data,
538 v8::Debug::ClientData* client_data);
539 void ProcessDebugEvent(v8::DebugEvent event,
540 Handle<JSObject> event_data,
542 void NotifyMessageHandler(v8::DebugEvent event,
543 Handle<JSObject> exec_state,
544 Handle<JSObject> event_data,
546 void InvokeMessageHandler(MessageImpl message);
548 static bool CompileDebuggerScript(Isolate* isolate, int index);
550 void ActivateStepIn(StackFrame* frame);
552 void ActivateStepOut(StackFrame* frame);
553 void ClearStepNext();
554 // Returns whether the compile succeeded.
555 void RemoveDebugInfo(Handle<DebugInfo> debug_info);
556 Handle<Object> CheckBreakPoints(Handle<Object> break_point);
557 bool CheckBreakPoint(Handle<Object> break_point_object);
559 inline void AssertDebugContext() {
560 DCHECK(isolate_->context() == *debug_context());
561 DCHECK(in_debug_scope());
567 Handle<Context> debug_context_;
568 Handle<Object> event_listener_;
569 Handle<Object> event_listener_data_;
571 v8::Debug::MessageHandler message_handler_;
573 static const int kQueueInitialSize = 4;
574 base::Semaphore command_received_; // Signaled for each command received.
575 LockingCommandMessageQueue command_queue_;
576 LockingCommandMessageQueue event_command_queue_;
580 bool live_edit_enabled_;
581 bool has_break_points_;
582 bool break_disabled_;
583 bool break_on_exception_;
584 bool break_on_uncaught_exception_;
586 ScriptCache* script_cache_; // Cache of all scripts in the heap.
587 DebugInfoListNode* debug_info_list_; // List of active debug info objects.
589 // Storage location for jump when exiting debug break calls.
590 // Note that this address is not GC safe. It should be computed immediately
591 // before returning to the DebugBreakCallHelper.
592 Address after_break_target_;
597 // Top debugger entry.
598 DebugScope* current_debug_scope_;
600 // Counter for generating next break id.
606 // Frame id for the frame of the current break.
607 StackFrame::Id break_frame_id_;
609 // Step action for last step performed.
610 StepAction last_step_action_;
612 // Source statement position from last step next action.
613 int last_statement_position_;
615 // Number of steps left to perform before debug event.
618 // Frame pointer from last step next action.
621 // Number of queued steps left to perform before debug event.
622 int queued_step_count_;
624 // Frame pointer for frame from which step in was performed.
625 Address step_into_fp_;
627 // Frame pointer for the frame where debugger should be called when current
628 // step out action is completed.
629 Address step_out_fp_;
631 // Stores the way how LiveEdit has patched the stack. It is used when
632 // debugger returns control back to user script.
633 LiveEdit::FrameDropMode frame_drop_mode_;
635 // When restarter frame is on stack, stores the address
636 // of the pointer to function being restarted. Otherwise (most of the time)
637 // stores NULL. This pointer is used with 'step in' implementation.
638 Object** restarter_frame_function_pointer_;
641 // Storage location for registers when handling debug break calls
642 ThreadLocal thread_local_;
646 friend class Isolate;
647 friend class DebugScope;
648 friend class DisableBreak;
649 friend class LiveEdit;
650 friend class SuppressDebug;
652 friend Handle<FixedArray> GetDebuggedFunctions(); // In test-debug.cc
653 friend void CheckDebuggerUnloaded(bool check_functions); // In test-debug.cc
655 DISALLOW_COPY_AND_ASSIGN(Debug);
659 DECLARE_RUNTIME_FUNCTION(Debug_Break);
662 // This scope is used to load and enter the debug context and create a new
663 // break state. Leaving the scope will restore the previous state.
664 // On failure to load, FailedToEnter returns true.
665 class DebugScope BASE_EMBEDDED {
667 explicit DebugScope(Debug* debug);
670 // Check whether loading was successful.
671 inline bool failed() { return failed_; }
673 // Get the active context from before entering the debugger.
674 inline Handle<Context> GetContext() { return save_.context(); }
677 Isolate* isolate() { return debug_->isolate_; }
680 DebugScope* prev_; // Previous scope if entered recursively.
681 StackFrame::Id break_frame_id_; // Previous break frame id.
682 int break_id_; // Previous break id.
683 bool failed_; // Did the debug context fail to load?
684 SaveContext save_; // Saves previous context.
685 PostponeInterruptsScope no_termination_exceptons_;
689 // Stack allocated class for disabling break.
690 class DisableBreak BASE_EMBEDDED {
692 explicit DisableBreak(Debug* debug, bool disable_break)
693 : debug_(debug), old_state_(debug->break_disabled_) {
694 debug_->break_disabled_ = disable_break;
696 ~DisableBreak() { debug_->break_disabled_ = old_state_; }
701 DISALLOW_COPY_AND_ASSIGN(DisableBreak);
705 class SuppressDebug BASE_EMBEDDED {
707 explicit SuppressDebug(Debug* debug)
708 : debug_(debug), old_state_(debug->is_suppressed_) {
709 debug_->is_suppressed_ = true;
711 ~SuppressDebug() { debug_->is_suppressed_ = old_state_; }
716 DISALLOW_COPY_AND_ASSIGN(SuppressDebug);
720 // Code generator routines.
721 class DebugCodegen : public AllStatic {
723 static void GenerateSlot(MacroAssembler* masm);
724 static void GenerateCallICStubDebugBreak(MacroAssembler* masm);
725 static void GenerateLoadICDebugBreak(MacroAssembler* masm);
726 static void GenerateStoreICDebugBreak(MacroAssembler* masm);
727 static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
728 static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
729 static void GenerateCompareNilICDebugBreak(MacroAssembler* masm);
730 static void GenerateReturnDebugBreak(MacroAssembler* masm);
731 static void GenerateCallFunctionStubDebugBreak(MacroAssembler* masm);
732 static void GenerateCallConstructStubDebugBreak(MacroAssembler* masm);
733 static void GenerateCallConstructStubRecordDebugBreak(MacroAssembler* masm);
734 static void GenerateSlotDebugBreak(MacroAssembler* masm);
735 static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
737 // FrameDropper is a code replacement for a JavaScript frame with possibly
738 // several frames above.
739 // There is no calling conventions here, because it never actually gets
740 // called, it only gets returned to.
741 static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
745 } } // namespace v8::internal
747 #endif // V8_DEBUG_H_