[V8] Introduce a QML compilation mode
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / debug.h
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
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 "allocation.h"
32 #include "arguments.h"
33 #include "assembler.h"
34 #include "debug-agent.h"
35 #include "execution.h"
36 #include "factory.h"
37 #include "flags.h"
38 #include "frames-inl.h"
39 #include "hashmap.h"
40 #include "platform.h"
41 #include "string-stream.h"
42 #include "v8threads.h"
43
44 #ifdef ENABLE_DEBUGGER_SUPPORT
45 #include "../include/v8-debug.h"
46
47 namespace v8 {
48 namespace internal {
49
50
51 // Forward declarations.
52 class EnterDebugger;
53
54
55 // Step actions. NOTE: These values are in macros.py as well.
56 enum StepAction {
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.
65 };
66
67
68 // Type of exception break. NOTE: These values are in macros.py as well.
69 enum ExceptionBreakType {
70   BreakException = 0,
71   BreakUncaughtException = 1
72 };
73
74
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
79 };
80
81
82 // Class for iterating through the break points in a function and changing
83 // them.
84 class BreakLocationIterator {
85  public:
86   explicit BreakLocationIterator(Handle<DebugInfo> debug_info,
87                                  BreakLocatorType type);
88   virtual ~BreakLocationIterator();
89
90   void Next();
91   void Next(int count);
92   void FindBreakLocationFromAddress(Address pc);
93   void FindBreakLocationFromPosition(int position);
94   void Reset();
95   bool Done() const;
96   void SetBreakPoint(Handle<Object> break_point_object);
97   void ClearBreakPoint(Handle<Object> break_point_object);
98   void SetOneShot();
99   void ClearOneShot();
100   void PrepareStepIn();
101   bool IsExit() const;
102   bool HasBreakPoint();
103   bool IsDebugBreak();
104   Object* BreakPointObjects();
105   void ClearAllDebugBreak();
106
107
108   inline int code_position() {
109     return static_cast<int>(pc() - debug_info_->code()->entry());
110   }
111   inline int break_point() { return break_point_; }
112   inline int position() { return position_; }
113   inline int statement_position() { return statement_position_; }
114   inline Address pc() { return reloc_iterator_->rinfo()->pc(); }
115   inline Code* code() { return debug_info_->code(); }
116   inline RelocInfo* rinfo() { return reloc_iterator_->rinfo(); }
117   inline RelocInfo::Mode rmode() const {
118     return reloc_iterator_->rinfo()->rmode();
119   }
120   inline RelocInfo* original_rinfo() {
121     return reloc_iterator_original_->rinfo();
122   }
123   inline RelocInfo::Mode original_rmode() const {
124     return reloc_iterator_original_->rinfo()->rmode();
125   }
126
127   bool IsDebuggerStatement();
128
129  protected:
130   bool RinfoDone() const;
131   void RinfoNext();
132
133   BreakLocatorType type_;
134   int break_point_;
135   int position_;
136   int statement_position_;
137   Handle<DebugInfo> debug_info_;
138   RelocIterator* reloc_iterator_;
139   RelocIterator* reloc_iterator_original_;
140
141  private:
142   void SetDebugBreak();
143   void ClearDebugBreak();
144
145   void SetDebugBreakAtIC();
146   void ClearDebugBreakAtIC();
147
148   bool IsDebugBreakAtReturn();
149   void SetDebugBreakAtReturn();
150   void ClearDebugBreakAtReturn();
151
152   bool IsDebugBreakSlot();
153   bool IsDebugBreakAtSlot();
154   void SetDebugBreakAtSlot();
155   void ClearDebugBreakAtSlot();
156
157   DISALLOW_COPY_AND_ASSIGN(BreakLocationIterator);
158 };
159
160
161 // Cache of all script objects in the heap. When a script is added a weak handle
162 // to it is created and that weak handle is stored in the cache. The weak handle
163 // callback takes care of removing the script from the cache. The key used in
164 // the cache is the script id.
165 class ScriptCache : private HashMap {
166  public:
167   ScriptCache() : HashMap(ScriptMatch), collected_scripts_(10) {}
168   virtual ~ScriptCache() { Clear(); }
169
170   // Add script to the cache.
171   void Add(Handle<Script> script);
172
173   // Return the scripts in the cache.
174   Handle<FixedArray> GetScripts();
175
176   // Generate debugger events for collected scripts.
177   void ProcessCollectedScripts();
178
179  private:
180   // Calculate the hash value from the key (script id).
181   static uint32_t Hash(int key) {
182     return ComputeIntegerHash(key, v8::internal::kZeroHashSeed);
183   }
184
185   // Scripts match if their keys (script id) match.
186   static bool ScriptMatch(void* key1, void* key2) { return key1 == key2; }
187
188   // Clear the cache releasing all the weak handles.
189   void Clear();
190
191   // Weak handle callback for scripts in the cache.
192   static void HandleWeakScript(v8::Persistent<v8::Value> obj, void* data);
193
194   // List used during GC to temporarily store id's of collected scripts.
195   List<int> collected_scripts_;
196 };
197
198
199 // Linked list holding debug info objects. The debug info objects are kept as
200 // weak handles to avoid a debug info object to keep a function alive.
201 class DebugInfoListNode {
202  public:
203   explicit DebugInfoListNode(DebugInfo* debug_info);
204   virtual ~DebugInfoListNode();
205
206   DebugInfoListNode* next() { return next_; }
207   void set_next(DebugInfoListNode* next) { next_ = next; }
208   Handle<DebugInfo> debug_info() { return debug_info_; }
209
210  private:
211   // Global (weak) handle to the debug info object.
212   Handle<DebugInfo> debug_info_;
213
214   // Next pointer for linked list.
215   DebugInfoListNode* next_;
216 };
217
218 // This class contains the debugger support. The main purpose is to handle
219 // setting break points in the code.
220 //
221 // This class controls the debug info for all functions which currently have
222 // active breakpoints in them. This debug info is held in the heap root object
223 // debug_info which is a FixedArray. Each entry in this list is of class
224 // DebugInfo.
225 class Debug {
226  public:
227   void SetUp(bool create_heap_objects);
228   bool Load();
229   void Unload();
230   bool IsLoaded() { return !debug_context_.is_null(); }
231   bool InDebugger() { return thread_local_.debugger_entry_ != NULL; }
232   void PreemptionWhileInDebugger();
233   void Iterate(ObjectVisitor* v);
234
235   NO_INLINE(void PutValuesOnStackAndDie(int start,
236                                         Address c_entry_fp,
237                                         Address last_fp,
238                                         Address larger_fp,
239                                         int count,
240                                         int end));
241   Object* Break(Arguments args);
242   void SetBreakPoint(Handle<SharedFunctionInfo> shared,
243                      Handle<Object> break_point_object,
244                      int* source_position);
245   void ClearBreakPoint(Handle<Object> break_point_object);
246   void ClearAllBreakPoints();
247   void FloodWithOneShot(Handle<SharedFunctionInfo> shared);
248   void FloodBoundFunctionWithOneShot(Handle<JSFunction> function);
249   void FloodHandlerWithOneShot();
250   void ChangeBreakOnException(ExceptionBreakType type, bool enable);
251   bool IsBreakOnException(ExceptionBreakType type);
252   void PrepareStep(StepAction step_action, int step_count);
253   void ClearStepping();
254   void ClearStepOut();
255   bool IsStepping() { return thread_local_.step_count_ > 0; }
256   bool StepNextContinue(BreakLocationIterator* break_location_iterator,
257                         JavaScriptFrame* frame);
258   static Handle<DebugInfo> GetDebugInfo(Handle<SharedFunctionInfo> shared);
259   static bool HasDebugInfo(Handle<SharedFunctionInfo> shared);
260
261   void PrepareForBreakPoints();
262
263   // Returns whether the operation succeeded.
264   bool EnsureDebugInfo(Handle<SharedFunctionInfo> shared);
265
266   // Returns true if the current stub call is patched to call the debugger.
267   static bool IsDebugBreak(Address addr);
268   // Returns true if the current return statement has been patched to be
269   // a debugger breakpoint.
270   static bool IsDebugBreakAtReturn(RelocInfo* rinfo);
271
272   // Check whether a code stub with the specified major key is a possible break
273   // point location.
274   static bool IsSourceBreakStub(Code* code);
275   static bool IsBreakStub(Code* code);
276
277   // Find the builtin to use for invoking the debug break
278   static Handle<Code> FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode);
279
280   static Handle<Object> GetSourceBreakLocations(
281       Handle<SharedFunctionInfo> shared);
282
283   // Getter for the debug_context.
284   inline Handle<Context> debug_context() { return debug_context_; }
285
286   // Check whether a global object is the debug global object.
287   bool IsDebugGlobal(GlobalObject* global);
288
289   // Check whether this frame is just about to return.
290   bool IsBreakAtReturn(JavaScriptFrame* frame);
291
292   // Fast check to see if any break points are active.
293   inline bool has_break_points() { return has_break_points_; }
294
295   void NewBreak(StackFrame::Id break_frame_id);
296   void SetBreak(StackFrame::Id break_frame_id, int break_id);
297   StackFrame::Id break_frame_id() {
298     return thread_local_.break_frame_id_;
299   }
300   int break_id() { return thread_local_.break_id_; }
301
302   bool StepInActive() { return thread_local_.step_into_fp_ != 0; }
303   void HandleStepIn(Handle<JSFunction> function,
304                     Handle<Object> holder,
305                     Address fp,
306                     bool is_constructor);
307   Address step_in_fp() { return thread_local_.step_into_fp_; }
308   Address* step_in_fp_addr() { return &thread_local_.step_into_fp_; }
309
310   bool StepOutActive() { return thread_local_.step_out_fp_ != 0; }
311   Address step_out_fp() { return thread_local_.step_out_fp_; }
312
313   EnterDebugger* debugger_entry() {
314     return thread_local_.debugger_entry_;
315   }
316   void set_debugger_entry(EnterDebugger* entry) {
317     thread_local_.debugger_entry_ = entry;
318   }
319
320   // Check whether any of the specified interrupts are pending.
321   bool is_interrupt_pending(InterruptFlag what) {
322     return (thread_local_.pending_interrupts_ & what) != 0;
323   }
324
325   // Set specified interrupts as pending.
326   void set_interrupts_pending(InterruptFlag what) {
327     thread_local_.pending_interrupts_ |= what;
328   }
329
330   // Clear specified interrupts from pending.
331   void clear_interrupt_pending(InterruptFlag what) {
332     thread_local_.pending_interrupts_ &= ~static_cast<int>(what);
333   }
334
335   // Getter and setter for the disable break state.
336   bool disable_break() { return disable_break_; }
337   void set_disable_break(bool disable_break) {
338     disable_break_ = disable_break;
339   }
340
341   // Getters for the current exception break state.
342   bool break_on_exception() { return break_on_exception_; }
343   bool break_on_uncaught_exception() {
344     return break_on_uncaught_exception_;
345   }
346
347   enum AddressId {
348     k_after_break_target_address,
349     k_debug_break_return_address,
350     k_debug_break_slot_address,
351     k_restarter_frame_function_pointer
352   };
353
354   // Support for setting the address to jump to when returning from break point.
355   Address* after_break_target_address() {
356     return reinterpret_cast<Address*>(&thread_local_.after_break_target_);
357   }
358   Address* restarter_frame_function_pointer_address() {
359     Object*** address = &thread_local_.restarter_frame_function_pointer_;
360     return reinterpret_cast<Address*>(address);
361   }
362
363   // Support for saving/restoring registers when handling debug break calls.
364   Object** register_address(int r) {
365     return &registers_[r];
366   }
367
368   // Access to the debug break on return code.
369   Code* debug_break_return() { return debug_break_return_; }
370   Code** debug_break_return_address() {
371     return &debug_break_return_;
372   }
373
374   // Access to the debug break in debug break slot code.
375   Code* debug_break_slot() { return debug_break_slot_; }
376   Code** debug_break_slot_address() {
377     return &debug_break_slot_;
378   }
379
380   static const int kEstimatedNofDebugInfoEntries = 16;
381   static const int kEstimatedNofBreakPointsInFunction = 16;
382
383   // Passed to MakeWeak.
384   static void HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data);
385
386   friend class Debugger;
387   friend Handle<FixedArray> GetDebuggedFunctions();  // In test-debug.cc
388   friend void CheckDebuggerUnloaded(bool check_functions);  // In test-debug.cc
389
390   // Threading support.
391   char* ArchiveDebug(char* to);
392   char* RestoreDebug(char* from);
393   static int ArchiveSpacePerThread();
394   void FreeThreadResources() { }
395
396   // Mirror cache handling.
397   void ClearMirrorCache();
398
399   // Script cache handling.
400   void CreateScriptCache();
401   void DestroyScriptCache();
402   void AddScriptToScriptCache(Handle<Script> script);
403   Handle<FixedArray> GetLoadedScripts();
404
405   // Garbage collection notifications.
406   void AfterGarbageCollection();
407
408   // Code generator routines.
409   static void GenerateSlot(MacroAssembler* masm);
410   static void GenerateLoadICDebugBreak(MacroAssembler* masm);
411   static void GenerateStoreICDebugBreak(MacroAssembler* masm);
412   static void GenerateKeyedLoadICDebugBreak(MacroAssembler* masm);
413   static void GenerateKeyedStoreICDebugBreak(MacroAssembler* masm);
414   static void GenerateReturnDebugBreak(MacroAssembler* masm);
415   static void GenerateCallFunctionStubDebugBreak(MacroAssembler* masm);
416   static void GenerateCallFunctionStubRecordDebugBreak(MacroAssembler* masm);
417   static void GenerateCallConstructStubDebugBreak(MacroAssembler* masm);
418   static void GenerateCallConstructStubRecordDebugBreak(MacroAssembler* masm);
419   static void GenerateSlotDebugBreak(MacroAssembler* masm);
420   static void GeneratePlainReturnLiveEdit(MacroAssembler* masm);
421
422   // FrameDropper is a code replacement for a JavaScript frame with possibly
423   // several frames above.
424   // There is no calling conventions here, because it never actually gets
425   // called, it only gets returned to.
426   static void GenerateFrameDropperLiveEdit(MacroAssembler* masm);
427
428   // Called from stub-cache.cc.
429   static void GenerateCallICDebugBreak(MacroAssembler* masm);
430
431   // Describes how exactly a frame has been dropped from stack.
432   enum FrameDropMode {
433     // No frame has been dropped.
434     FRAMES_UNTOUCHED,
435     // The top JS frame had been calling IC stub. IC stub mustn't be called now.
436     FRAME_DROPPED_IN_IC_CALL,
437     // The top JS frame had been calling debug break slot stub. Patch the
438     // address this stub jumps to in the end.
439     FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
440     // The top JS frame had been calling some C++ function. The return address
441     // gets patched automatically.
442     FRAME_DROPPED_IN_DIRECT_CALL,
443     FRAME_DROPPED_IN_RETURN_CALL
444   };
445
446   void FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
447                                     FrameDropMode mode,
448                                     Object** restarter_frame_function_pointer);
449
450   // Initializes an artificial stack frame. The data it contains is used for:
451   //  a. successful work of frame dropper code which eventually gets control,
452   //  b. being compatible with regular stack structure for various stack
453   //     iterators.
454   // Returns address of stack allocated pointer to restarted function,
455   // the value that is called 'restarter_frame_function_pointer'. The value
456   // at this address (possibly updated by GC) may be used later when preparing
457   // 'step in' operation.
458   static Object** SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
459                                          Handle<Code> code);
460
461   static const int kFrameDropperFrameSize;
462
463   // Architecture-specific constant.
464   static const bool kFrameDropperSupported;
465
466   /**
467    * Defines layout of a stack frame that supports padding. This is a regular
468    * internal frame that has a flexible stack structure. LiveEdit can shift
469    * its lower part up the stack, taking up the 'padding' space when additional
470    * stack memory is required.
471    * Such frame is expected immediately above the topmost JavaScript frame.
472    *
473    * Stack Layout:
474    *   --- Top
475    *   LiveEdit routine frames
476    *   ---
477    *   C frames of debug handler
478    *   ---
479    *   ...
480    *   ---
481    *      An internal frame that has n padding words:
482    *      - any number of words as needed by code -- upper part of frame
483    *      - padding size: a Smi storing n -- current size of padding
484    *      - padding: n words filled with kPaddingValue in form of Smi
485    *      - 3 context/type words of a regular InternalFrame
486    *      - fp
487    *   ---
488    *      Topmost JavaScript frame
489    *   ---
490    *   ...
491    *   --- Bottom
492    */
493   class FramePaddingLayout : public AllStatic {
494    public:
495     // Architecture-specific constant.
496     static const bool kIsSupported;
497
498     // A size of frame base including fp. Padding words starts right above
499     // the base.
500     static const int kFrameBaseSize = 4;
501
502     // A number of words that should be reserved on stack for the LiveEdit use.
503     // Normally equals 1. Stored on stack in form of Smi.
504     static const int kInitialSize;
505     // A value that padding words are filled with (in form of Smi). Going
506     // bottom-top, the first word not having this value is a counter word.
507     static const int kPaddingValue;
508   };
509
510  private:
511   explicit Debug(Isolate* isolate);
512   ~Debug();
513
514   static bool CompileDebuggerScript(int index);
515   void ClearOneShot();
516   void ActivateStepIn(StackFrame* frame);
517   void ClearStepIn();
518   void ActivateStepOut(StackFrame* frame);
519   void ClearStepNext();
520   // Returns whether the compile succeeded.
521   void RemoveDebugInfo(Handle<DebugInfo> debug_info);
522   void SetAfterBreakTarget(JavaScriptFrame* frame);
523   Handle<Object> CheckBreakPoints(Handle<Object> break_point);
524   bool CheckBreakPoint(Handle<Object> break_point_object);
525
526   // Global handle to debug context where all the debugger JavaScript code is
527   // loaded.
528   Handle<Context> debug_context_;
529
530   // Boolean state indicating whether any break points are set.
531   bool has_break_points_;
532
533   // Cache of all scripts in the heap.
534   ScriptCache* script_cache_;
535
536   // List of active debug info objects.
537   DebugInfoListNode* debug_info_list_;
538
539   bool disable_break_;
540   bool break_on_exception_;
541   bool break_on_uncaught_exception_;
542
543   // Per-thread data.
544   class ThreadLocal {
545    public:
546     // Counter for generating next break id.
547     int break_count_;
548
549     // Current break id.
550     int break_id_;
551
552     // Frame id for the frame of the current break.
553     StackFrame::Id break_frame_id_;
554
555     // Step action for last step performed.
556     StepAction last_step_action_;
557
558     // Source statement position from last step next action.
559     int last_statement_position_;
560
561     // Number of steps left to perform before debug event.
562     int step_count_;
563
564     // Frame pointer from last step next action.
565     Address last_fp_;
566
567     // Number of queued steps left to perform before debug event.
568     int queued_step_count_;
569
570     // Frame pointer for frame from which step in was performed.
571     Address step_into_fp_;
572
573     // Frame pointer for the frame where debugger should be called when current
574     // step out action is completed.
575     Address step_out_fp_;
576
577     // Storage location for jump when exiting debug break calls.
578     Address after_break_target_;
579
580     // Stores the way how LiveEdit has patched the stack. It is used when
581     // debugger returns control back to user script.
582     FrameDropMode frame_drop_mode_;
583
584     // Top debugger entry.
585     EnterDebugger* debugger_entry_;
586
587     // Pending interrupts scheduled while debugging.
588     int pending_interrupts_;
589
590     // When restarter frame is on stack, stores the address
591     // of the pointer to function being restarted. Otherwise (most of the time)
592     // stores NULL. This pointer is used with 'step in' implementation.
593     Object** restarter_frame_function_pointer_;
594   };
595
596   // Storage location for registers when handling debug break calls
597   JSCallerSavedBuffer registers_;
598   ThreadLocal thread_local_;
599   void ThreadInit();
600
601   // Code to call for handling debug break on return.
602   Code* debug_break_return_;
603
604   // Code to call for handling debug break in debug break slots.
605   Code* debug_break_slot_;
606
607   Isolate* isolate_;
608
609   friend class Isolate;
610
611   DISALLOW_COPY_AND_ASSIGN(Debug);
612 };
613
614
615 DECLARE_RUNTIME_FUNCTION(Object*, Debug_Break);
616
617
618 // Message delivered to the message handler callback. This is either a debugger
619 // event or the response to a command.
620 class MessageImpl: public v8::Debug::Message {
621  public:
622   // Create a message object for a debug event.
623   static MessageImpl NewEvent(DebugEvent event,
624                               bool running,
625                               Handle<JSObject> exec_state,
626                               Handle<JSObject> event_data);
627
628   // Create a message object for the response to a debug command.
629   static MessageImpl NewResponse(DebugEvent event,
630                                  bool running,
631                                  Handle<JSObject> exec_state,
632                                  Handle<JSObject> event_data,
633                                  Handle<String> response_json,
634                                  v8::Debug::ClientData* client_data);
635
636   // Implementation of interface v8::Debug::Message.
637   virtual bool IsEvent() const;
638   virtual bool IsResponse() const;
639   virtual DebugEvent GetEvent() const;
640   virtual bool WillStartRunning() const;
641   virtual v8::Handle<v8::Object> GetExecutionState() const;
642   virtual v8::Handle<v8::Object> GetEventData() const;
643   virtual v8::Handle<v8::String> GetJSON() const;
644   virtual v8::Handle<v8::Context> GetEventContext() const;
645   virtual v8::Debug::ClientData* GetClientData() const;
646
647  private:
648   MessageImpl(bool is_event,
649               DebugEvent event,
650               bool running,
651               Handle<JSObject> exec_state,
652               Handle<JSObject> event_data,
653               Handle<String> response_json,
654               v8::Debug::ClientData* client_data);
655
656   bool is_event_;  // Does this message represent a debug event?
657   DebugEvent event_;  // Debug event causing the break.
658   bool running_;  // Will the VM start running after this event?
659   Handle<JSObject> exec_state_;  // Current execution state.
660   Handle<JSObject> event_data_;  // Data associated with the event.
661   Handle<String> response_json_;  // Response JSON if message holds a response.
662   v8::Debug::ClientData* client_data_;  // Client data passed with the request.
663 };
664
665
666 // Details of the debug event delivered to the debug event listener.
667 class EventDetailsImpl : public v8::Debug::EventDetails {
668  public:
669   EventDetailsImpl(DebugEvent event,
670                    Handle<JSObject> exec_state,
671                    Handle<JSObject> event_data,
672                    Handle<Object> callback_data,
673                    v8::Debug::ClientData* client_data);
674   virtual DebugEvent GetEvent() const;
675   virtual v8::Handle<v8::Object> GetExecutionState() const;
676   virtual v8::Handle<v8::Object> GetEventData() const;
677   virtual v8::Handle<v8::Context> GetEventContext() const;
678   virtual v8::Handle<v8::Value> GetCallbackData() const;
679   virtual v8::Debug::ClientData* GetClientData() const;
680  private:
681   DebugEvent event_;  // Debug event causing the break.
682   Handle<JSObject> exec_state_;         // Current execution state.
683   Handle<JSObject> event_data_;         // Data associated with the event.
684   Handle<Object> callback_data_;        // User data passed with the callback
685                                         // when it was registered.
686   v8::Debug::ClientData* client_data_;  // Data passed to DebugBreakForCommand.
687 };
688
689
690 // Message send by user to v8 debugger or debugger output message.
691 // In addition to command text it may contain a pointer to some user data
692 // which are expected to be passed along with the command reponse to message
693 // handler.
694 class CommandMessage {
695  public:
696   static CommandMessage New(const Vector<uint16_t>& command,
697                             v8::Debug::ClientData* data);
698   CommandMessage();
699   ~CommandMessage();
700
701   // Deletes user data and disposes of the text.
702   void Dispose();
703   Vector<uint16_t> text() const { return text_; }
704   v8::Debug::ClientData* client_data() const { return client_data_; }
705  private:
706   CommandMessage(const Vector<uint16_t>& text,
707                  v8::Debug::ClientData* data);
708
709   Vector<uint16_t> text_;
710   v8::Debug::ClientData* client_data_;
711 };
712
713 // A Queue of CommandMessage objects.  A thread-safe version is
714 // LockingCommandMessageQueue, based on this class.
715 class CommandMessageQueue BASE_EMBEDDED {
716  public:
717   explicit CommandMessageQueue(int size);
718   ~CommandMessageQueue();
719   bool IsEmpty() const { return start_ == end_; }
720   CommandMessage Get();
721   void Put(const CommandMessage& message);
722   void Clear() { start_ = end_ = 0; }  // Queue is empty after Clear().
723  private:
724   // Doubles the size of the message queue, and copies the messages.
725   void Expand();
726
727   CommandMessage* messages_;
728   int start_;
729   int end_;
730   int size_;  // The size of the queue buffer.  Queue can hold size-1 messages.
731 };
732
733
734 class MessageDispatchHelperThread;
735
736
737 // LockingCommandMessageQueue is a thread-safe circular buffer of CommandMessage
738 // messages.  The message data is not managed by LockingCommandMessageQueue.
739 // Pointers to the data are passed in and out. Implemented by adding a
740 // Mutex to CommandMessageQueue.  Includes logging of all puts and gets.
741 class LockingCommandMessageQueue BASE_EMBEDDED {
742  public:
743   LockingCommandMessageQueue(Logger* logger, int size);
744   ~LockingCommandMessageQueue();
745   bool IsEmpty() const;
746   CommandMessage Get();
747   void Put(const CommandMessage& message);
748   void Clear();
749  private:
750   Logger* logger_;
751   CommandMessageQueue queue_;
752   Mutex* lock_;
753   DISALLOW_COPY_AND_ASSIGN(LockingCommandMessageQueue);
754 };
755
756
757 class Debugger {
758  public:
759   ~Debugger();
760
761   void DebugRequest(const uint16_t* json_request, int length);
762
763   Handle<Object> MakeJSObject(Vector<const char> constructor_name,
764                               int argc,
765                               Handle<Object> argv[],
766                               bool* caught_exception);
767   Handle<Object> MakeExecutionState(bool* caught_exception);
768   Handle<Object> MakeBreakEvent(Handle<Object> exec_state,
769                                 Handle<Object> break_points_hit,
770                                 bool* caught_exception);
771   Handle<Object> MakeExceptionEvent(Handle<Object> exec_state,
772                                     Handle<Object> exception,
773                                     bool uncaught,
774                                     bool* caught_exception);
775   Handle<Object> MakeNewFunctionEvent(Handle<Object> func,
776                                       bool* caught_exception);
777   Handle<Object> MakeCompileEvent(Handle<Script> script,
778                                   bool before,
779                                   bool* caught_exception);
780   Handle<Object> MakeScriptCollectedEvent(int id,
781                                           bool* caught_exception);
782   void OnDebugBreak(Handle<Object> break_points_hit, bool auto_continue);
783   void OnException(Handle<Object> exception, bool uncaught);
784   void OnBeforeCompile(Handle<Script> script);
785
786   enum AfterCompileFlags {
787     NO_AFTER_COMPILE_FLAGS,
788     SEND_WHEN_DEBUGGING
789   };
790   void OnAfterCompile(Handle<Script> script,
791                       AfterCompileFlags after_compile_flags);
792   void OnNewFunction(Handle<JSFunction> fun);
793   void OnScriptCollected(int id);
794   void ProcessDebugEvent(v8::DebugEvent event,
795                          Handle<JSObject> event_data,
796                          bool auto_continue);
797   void NotifyMessageHandler(v8::DebugEvent event,
798                             Handle<JSObject> exec_state,
799                             Handle<JSObject> event_data,
800                             bool auto_continue);
801   void SetEventListener(Handle<Object> callback, Handle<Object> data);
802   void SetMessageHandler(v8::Debug::MessageHandler2 handler);
803   void SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
804                               int period);
805   void SetDebugMessageDispatchHandler(
806       v8::Debug::DebugMessageDispatchHandler handler,
807       bool provide_locker);
808
809   // Invoke the message handler function.
810   void InvokeMessageHandler(MessageImpl message);
811
812   // Add a debugger command to the command queue.
813   void ProcessCommand(Vector<const uint16_t> command,
814                       v8::Debug::ClientData* client_data = NULL);
815
816   // Check whether there are commands in the command queue.
817   bool HasCommands();
818
819   // Enqueue a debugger command to the command queue for event listeners.
820   void EnqueueDebugCommand(v8::Debug::ClientData* client_data = NULL);
821
822   Handle<Object> Call(Handle<JSFunction> fun,
823                       Handle<Object> data,
824                       bool* pending_exception);
825
826   // Start the debugger agent listening on the provided port.
827   bool StartAgent(const char* name, int port,
828                   bool wait_for_connection = false);
829
830   // Stop the debugger agent.
831   void StopAgent();
832
833   // Blocks until the agent has started listening for connections
834   void WaitForAgent();
835
836   void CallMessageDispatchHandler();
837
838   Handle<Context> GetDebugContext();
839
840   // Unload the debugger if possible. Only called when no debugger is currently
841   // active.
842   void UnloadDebugger();
843   friend void ForceUnloadDebugger();  // In test-debug.cc
844
845   inline bool EventActive(v8::DebugEvent event) {
846     ScopedLock with(debugger_access_);
847
848     // Check whether the message handler was been cleared.
849     if (debugger_unload_pending_) {
850       if (isolate_->debug()->debugger_entry() == NULL) {
851         UnloadDebugger();
852       }
853     }
854
855     if (((event == v8::BeforeCompile) || (event == v8::AfterCompile)) &&
856         !FLAG_debug_compile_events) {
857       return false;
858
859     } else if ((event == v8::ScriptCollected) &&
860                !FLAG_debug_script_collected_events) {
861       return false;
862     }
863
864     // Currently argument event is not used.
865     return !compiling_natives_ && Debugger::IsDebuggerActive();
866   }
867
868   void set_compiling_natives(bool compiling_natives) {
869     compiling_natives_ = compiling_natives;
870   }
871   bool compiling_natives() const { return compiling_natives_; }
872   void set_loading_debugger(bool v) { is_loading_debugger_ = v; }
873   bool is_loading_debugger() const { return is_loading_debugger_; }
874   void set_force_debugger_active(bool force_debugger_active) {
875     force_debugger_active_ = force_debugger_active;
876   }
877   bool force_debugger_active() const { return force_debugger_active_; }
878
879   bool IsDebuggerActive();
880
881  private:
882   explicit Debugger(Isolate* isolate);
883
884   void CallEventCallback(v8::DebugEvent event,
885                          Handle<Object> exec_state,
886                          Handle<Object> event_data,
887                          v8::Debug::ClientData* client_data);
888   void CallCEventCallback(v8::DebugEvent event,
889                           Handle<Object> exec_state,
890                           Handle<Object> event_data,
891                           v8::Debug::ClientData* client_data);
892   void CallJSEventCallback(v8::DebugEvent event,
893                            Handle<Object> exec_state,
894                            Handle<Object> event_data);
895   void ListenersChanged();
896
897   Mutex* debugger_access_;  // Mutex guarding debugger variables.
898   Handle<Object> event_listener_;  // Global handle to listener.
899   Handle<Object> event_listener_data_;
900   bool compiling_natives_;  // Are we compiling natives?
901   bool is_loading_debugger_;  // Are we loading the debugger?
902   bool never_unload_debugger_;  // Can we unload the debugger?
903   bool force_debugger_active_;  // Activate debugger without event listeners.
904   v8::Debug::MessageHandler2 message_handler_;
905   bool debugger_unload_pending_;  // Was message handler cleared?
906   v8::Debug::HostDispatchHandler host_dispatch_handler_;
907   Mutex* dispatch_handler_access_;  // Mutex guarding dispatch handler.
908   v8::Debug::DebugMessageDispatchHandler debug_message_dispatch_handler_;
909   MessageDispatchHelperThread* message_dispatch_helper_thread_;
910   int host_dispatch_micros_;
911
912   DebuggerAgent* agent_;
913
914   static const int kQueueInitialSize = 4;
915   LockingCommandMessageQueue command_queue_;
916   Semaphore* command_received_;  // Signaled for each command received.
917   LockingCommandMessageQueue event_command_queue_;
918
919   Isolate* isolate_;
920
921   friend class EnterDebugger;
922   friend class Isolate;
923
924   DISALLOW_COPY_AND_ASSIGN(Debugger);
925 };
926
927
928 // This class is used for entering the debugger. Create an instance in the stack
929 // to enter the debugger. This will set the current break state, make sure the
930 // debugger is loaded and switch to the debugger context. If the debugger for
931 // some reason could not be entered FailedToEnter will return true.
932 class EnterDebugger BASE_EMBEDDED {
933  public:
934   EnterDebugger();
935   ~EnterDebugger();
936
937   // Check whether the debugger could be entered.
938   inline bool FailedToEnter() { return load_failed_; }
939
940   // Check whether there are any JavaScript frames on the stack.
941   inline bool HasJavaScriptFrames() { return has_js_frames_; }
942
943   // Get the active context from before entering the debugger.
944   inline Handle<Context> GetContext() { return save_.context(); }
945
946  private:
947   Isolate* isolate_;
948   EnterDebugger* prev_;  // Previous debugger entry if entered recursively.
949   JavaScriptFrameIterator it_;
950   const bool has_js_frames_;  // Were there any JavaScript frames?
951   StackFrame::Id break_frame_id_;  // Previous break frame id.
952   int break_id_;  // Previous break id.
953   bool load_failed_;  // Did the debugger fail to load?
954   SaveContext save_;  // Saves previous context.
955 };
956
957
958 // Stack allocated class for disabling break.
959 class DisableBreak BASE_EMBEDDED {
960  public:
961   explicit DisableBreak(bool disable_break) : isolate_(Isolate::Current()) {
962     prev_disable_break_ = isolate_->debug()->disable_break();
963     isolate_->debug()->set_disable_break(disable_break);
964   }
965   ~DisableBreak() {
966     ASSERT(Isolate::Current() == isolate_);
967     isolate_->debug()->set_disable_break(prev_disable_break_);
968   }
969
970  private:
971   Isolate* isolate_;
972   // The previous state of the disable break used to restore the value when this
973   // object is destructed.
974   bool prev_disable_break_;
975 };
976
977
978 // Debug_Address encapsulates the Address pointers used in generating debug
979 // code.
980 class Debug_Address {
981  public:
982   explicit Debug_Address(Debug::AddressId id) : id_(id) { }
983
984   static Debug_Address AfterBreakTarget() {
985     return Debug_Address(Debug::k_after_break_target_address);
986   }
987
988   static Debug_Address DebugBreakReturn() {
989     return Debug_Address(Debug::k_debug_break_return_address);
990   }
991
992   static Debug_Address RestarterFrameFunctionPointer() {
993     return Debug_Address(Debug::k_restarter_frame_function_pointer);
994   }
995
996   Address address(Isolate* isolate) const {
997     Debug* debug = isolate->debug();
998     switch (id_) {
999       case Debug::k_after_break_target_address:
1000         return reinterpret_cast<Address>(debug->after_break_target_address());
1001       case Debug::k_debug_break_return_address:
1002         return reinterpret_cast<Address>(debug->debug_break_return_address());
1003       case Debug::k_debug_break_slot_address:
1004         return reinterpret_cast<Address>(debug->debug_break_slot_address());
1005       case Debug::k_restarter_frame_function_pointer:
1006         return reinterpret_cast<Address>(
1007             debug->restarter_frame_function_pointer_address());
1008       default:
1009         UNREACHABLE();
1010         return NULL;
1011     }
1012   }
1013
1014  private:
1015   Debug::AddressId id_;
1016 };
1017
1018 // The optional thread that Debug Agent may use to temporary call V8 to process
1019 // pending debug requests if debuggee is not running V8 at the moment.
1020 // Techincally it does not call V8 itself, rather it asks embedding program
1021 // to do this via v8::Debug::HostDispatchHandler
1022 class MessageDispatchHelperThread: public Thread {
1023  public:
1024   explicit MessageDispatchHelperThread(Isolate* isolate);
1025   ~MessageDispatchHelperThread();
1026
1027   void Schedule();
1028
1029  private:
1030   void Run();
1031
1032   Semaphore* const sem_;
1033   Mutex* const mutex_;
1034   bool already_signalled_;
1035
1036   DISALLOW_COPY_AND_ASSIGN(MessageDispatchHelperThread);
1037 };
1038
1039
1040 } }  // namespace v8::internal
1041
1042 #endif  // ENABLE_DEBUGGER_SUPPORT
1043
1044 #endif  // V8_DEBUG_H_