debug.h 20.6 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_DEBUG_DEBUG_H_
#define V8_DEBUG_DEBUG_H_
7

8 9
#include <vector>

10
#include "src/allocation.h"
11
#include "src/base/atomicops.h"
lpy's avatar
lpy committed
12
#include "src/base/hashmap.h"
13
#include "src/base/platform/platform.h"
14
#include "src/debug/debug-interface.h"
15
#include "src/debug/interface-types.h"
16 17
#include "src/execution.h"
#include "src/flags.h"
18
#include "src/frames.h"
19
#include "src/globals.h"
20
#include "src/heap/factory.h"
21
#include "src/objects/debug-objects.h"
22
#include "src/runtime/runtime.h"
23
#include "src/source-position-table.h"
24 25 26
#include "src/string-stream.h"
#include "src/v8threads.h"

27 28
namespace v8 {
namespace internal {
29

30
// Forward declarations.
31
class DebugScope;
32
class JSGeneratorObject;
33

34
// Step actions. NOTE: These values are in macros.py as well.
35
enum StepAction : int8_t {
36
  StepNone = -1,  // Stepping not prepared.
37 38 39 40
  StepOut = 0,    // Step out of the current function.
  StepNext = 1,   // Step to the next statement in the current function.
  StepIn = 2,     // Step into new functions invoked or the next statement
                  // in the current function.
41
  LastStepAction = StepIn
42
};
43 44 45 46 47 48 49

// Type of exception break. NOTE: These values are in macros.py as well.
enum ExceptionBreakType {
  BreakException = 0,
  BreakUncaughtException = 1
};

50 51 52 53 54 55
enum DebugBreakType {
  NOT_DEBUG_BREAK,
  DEBUGGER_STATEMENT,
  DEBUG_BREAK_SLOT,
  DEBUG_BREAK_SLOT_AT_CALL,
  DEBUG_BREAK_SLOT_AT_RETURN,
56
  DEBUG_BREAK_SLOT_AT_SUSPEND,
57
  DEBUG_BREAK_AT_ENTRY,
58
};
59

60 61 62 63 64
enum IgnoreBreakMode {
  kIgnoreIfAllFramesBlackboxed,
  kIgnoreIfTopFrameBlackboxed
};

65
class BreakLocation {
66
 public:
67 68
  static BreakLocation FromFrame(Handle<DebugInfo> debug_info,
                                 JavaScriptFrame* frame);
69

70 71
  static void AllAtCurrentStatement(Handle<DebugInfo> debug_info,
                                    JavaScriptFrame* frame,
72
                                    std::vector<BreakLocation>* result_out);
73

74
  inline bool IsSuspend() const { return type_ == DEBUG_BREAK_SLOT_AT_SUSPEND; }
75
  inline bool IsReturn() const { return type_ == DEBUG_BREAK_SLOT_AT_RETURN; }
76 77 78
  inline bool IsReturnOrSuspend() const {
    return type_ >= DEBUG_BREAK_SLOT_AT_RETURN;
  }
79
  inline bool IsCall() const { return type_ == DEBUG_BREAK_SLOT_AT_CALL; }
80 81 82 83
  inline bool IsDebugBreakSlot() const { return type_ >= DEBUG_BREAK_SLOT; }
  inline bool IsDebuggerStatement() const {
    return type_ == DEBUGGER_STATEMENT;
  }
84 85 86 87
  inline bool IsDebugBreakAtEntry() const {
    bool result = type_ == DEBUG_BREAK_AT_ENTRY;
    return result;
  }
88

89
  bool HasBreakPoint(Isolate* isolate, Handle<DebugInfo> debug_info) const;
90

91
  inline int position() const { return position_; }
92

93 94
  debug::BreakLocationType type() const;

95
  JSGeneratorObject GetGeneratorObjectForSuspendedFrame(
96 97
      JavaScriptFrame* frame) const;

98 99
 private:
  BreakLocation(Handle<AbstractCode> abstract_code, DebugBreakType type,
100
                int code_offset, int position, int generator_obj_reg_index)
101 102 103
      : abstract_code_(abstract_code),
        code_offset_(code_offset),
        type_(type),
104 105
        position_(position),
        generator_obj_reg_index_(generator_obj_reg_index) {
106 107
    DCHECK_NE(NOT_DEBUG_BREAK, type_);
  }
108

109 110 111 112 113 114
  BreakLocation(int position, DebugBreakType type)
      : code_offset_(0),
        type_(type),
        position_(position),
        generator_obj_reg_index_(0) {}

115 116 117
  static int BreakIndexFromCodeOffset(Handle<DebugInfo> debug_info,
                                      Handle<AbstractCode> abstract_code,
                                      int offset);
118

119 120 121 122 123 124 125
  void SetDebugBreak();
  void ClearDebugBreak();

  Handle<AbstractCode> abstract_code_;
  int code_offset_;
  DebugBreakType type_;
  int position_;
126
  int generator_obj_reg_index_;
127

128
  friend class BreakIterator;
129
};
130

131 132
class BreakIterator {
 public:
133
  explicit BreakIterator(Handle<DebugInfo> debug_info);
134

135 136 137
  BreakLocation GetBreakLocation();
  bool Done() const { return source_position_iterator_.done(); }
  void Next();
138

139
  void SkipToPosition(int position);
140 141
  void SkipTo(int count) {
    while (count-- > 0) Next();
142
  }
143

144
  int code_offset() { return source_position_iterator_.code_offset(); }
145 146 147
  int break_index() const { return break_index_; }
  inline int position() const { return position_; }
  inline int statement_position() const { return statement_position_; }
148

149 150
  void ClearDebugBreak();
  void SetDebugBreak();
151

152
 private:
153
  int BreakIndexFromPosition(int position);
154

155
  Isolate* isolate();
156

157 158
  DebugBreakType GetDebugBreakType();

159 160 161 162 163
  Handle<DebugInfo> debug_info_;
  int break_index_;
  int position_;
  int statement_position_;
  SourcePositionTableIterator source_position_iterator_;
164
  DisallowHeapAllocation no_gc_;
165

166
  DISALLOW_COPY_AND_ASSIGN(BreakIterator);
167
};
168 169 170 171 172

// Linked list holding debug info objects. The debug info objects are kept as
// weak handles to avoid a debug info object to keep a function alive.
class DebugInfoListNode {
 public:
173
  DebugInfoListNode(Isolate* isolate, DebugInfo debug_info);
174
  ~DebugInfoListNode();
175 176 177

  DebugInfoListNode* next() { return next_; }
  void set_next(DebugInfoListNode* next) { next_ = next; }
dcarney's avatar
dcarney committed
178 179
  Handle<DebugInfo> debug_info() { return Handle<DebugInfo>(debug_info_); }

180 181
 private:
  // Global (weak) handle to the debug info object.
182
  Address* debug_info_;
183 184 185 186 187

  // Next pointer for linked list.
  DebugInfoListNode* next_;
};

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
class DebugFeatureTracker {
 public:
  enum Feature {
    kActive = 1,
    kBreakPoint = 2,
    kStepping = 3,
    kHeapSnapshot = 4,
    kAllocationTracking = 5,
    kProfiler = 6,
    kLiveEdit = 7,
  };

  explicit DebugFeatureTracker(Isolate* isolate)
      : isolate_(isolate), bitfield_(0) {}
  void Track(Feature feature);

 private:
  Isolate* isolate_;
  uint32_t bitfield_;
};


210 211 212 213 214 215 216 217 218
// This class contains the debugger support. The main purpose is to handle
// setting break points in the code.
//
// This class controls the debug info for all functions which currently have
// active breakpoints in them. This debug info is held in the heap root object
// debug_info which is a FixedArray. Each entry in this list is of class
// DebugInfo.
class Debug {
 public:
219
  // Debug event triggers.
220
  void OnDebugBreak(Handle<FixedArray> break_points_hit);
221

222
  void OnThrow(Handle<Object> exception);
223
  void OnPromiseReject(Handle<Object> promise, Handle<Object> value);
224
  void OnCompileError(Handle<Script> script);
225
  void OnAfterCompile(Handle<Script> script);
226

227
  void HandleDebugBreak(IgnoreBreakMode ignore_break_mode);
228

229 230 231
  // The break target may not be the top-most frame, since we may be
  // breaking before entering a function that cannot contain break points.
  void Break(JavaScriptFrame* frame, Handle<JSFunction> break_target);
232

233 234 235 236
  // Scripts handling.
  Handle<FixedArray> GetLoadedScripts();

  // Break point handling.
237
  bool SetBreakPoint(Handle<JSFunction> function,
238 239
                     Handle<BreakPoint> break_point, int* source_position);
  void ClearBreakPoint(Handle<BreakPoint> break_point);
240 241
  void ChangeBreakOnException(ExceptionBreakType type, bool enable);
  bool IsBreakOnException(ExceptionBreakType type);
242

243 244 245 246
  bool SetBreakPointForScript(Handle<Script> script, Handle<String> condition,
                              int* source_position, int* id);
  bool SetBreakpointForFunction(Handle<JSFunction> function,
                                Handle<String> condition, int* id);
247 248
  void RemoveBreakpoint(int id);

249 250
  // Find breakpoints from the debug info and the break location and check
  // whether they are hit. Return an empty handle if not, or a FixedArray with
251
  // hit BreakPoint objects.
252 253
  MaybeHandle<FixedArray> GetHitBreakPoints(Handle<DebugInfo> debug_info,
                                            int position);
254

255
  // Stepping handling.
256
  void PrepareStep(StepAction step_action);
257
  void PrepareStepIn(Handle<JSFunction> function);
258
  void PrepareStepInSuspendedGenerator();
259
  void PrepareStepOnThrow();
260
  void ClearStepping();
261

262 263 264
  void SetBreakOnNextFunctionCall();
  void ClearBreakOnNextFunctionCall();

265
  void DeoptimizeFunction(Handle<SharedFunctionInfo> shared);
266
  void PrepareFunctionForDebugExecution(Handle<SharedFunctionInfo> shared);
267
  void InstallDebugBreakTrampoline();
268
  bool GetPossibleBreakpoints(Handle<Script> script, int start_position,
269
                              int end_position, bool restrict_to_function,
270
                              std::vector<BreakLocation>* locations);
271

272 273
  bool IsBlackboxed(Handle<SharedFunctionInfo> shared);

274 275
  bool CanBreakAtEntry(Handle<SharedFunctionInfo> shared);

276
  void SetDebugDelegate(debug::DebugDelegate* delegate);
277

278
  // Returns whether the operation succeeded.
279 280 281
  bool EnsureBreakInfo(Handle<SharedFunctionInfo> shared);
  void CreateBreakInfo(Handle<SharedFunctionInfo> shared);
  Handle<DebugInfo> GetOrCreateDebugInfo(Handle<SharedFunctionInfo> shared);
282

283 284 285 286
  void InstallCoverageInfo(Handle<SharedFunctionInfo> shared,
                           Handle<CoverageInfo> coverage_info);
  void RemoveAllCoverageInfos();

287
  // This function is used in FunctionNameUsing* tests.
288 289
  Handle<Object> FindSharedFunctionInfoInScript(Handle<Script> script,
                                                int position);
290

291
  static Handle<Object> GetSourceBreakLocations(
292
      Isolate* isolate, Handle<SharedFunctionInfo> shared);
293

294
  // Check whether this frame is just about to return.
295
  bool IsBreakAtReturn(JavaScriptFrame* frame);
296

297
  // Support for LiveEdit
298
  void ScheduleFrameRestart(StackFrame* frame);
299

300
  bool AllFramesOnStackAreBlackboxed();
301

302 303 304 305 306
  // Set new script source, throw an exception if error occurred. When preview
  // is true: try to set source, throw exception if any without actual script
  // change. stack_changed is true if after editing script on pause stack is
  // changed and client should request stack trace again.
  bool SetScriptSource(Handle<Script> script, Handle<String> source,
307
                       bool preview, debug::LiveEditResult* result);
308

309 310
  int GetFunctionDebuggingId(Handle<JSFunction> function);

311
  // Threading support.
312 313
  char* ArchiveDebug(char* to);
  char* RestoreDebug(char* from);
314
  static int ArchiveSpacePerThread();
315
  void FreeThreadResources() { }
316
  void Iterate(RootVisitor* v);
317
  void InitThread(const ExecutionAccess& lock) { ThreadInit(); }
318

Yang Guo's avatar
Yang Guo committed
319
  bool CheckExecutionState() { return is_active(); }
320

321 322 323 324 325 326
  void StartSideEffectCheckMode();
  void StopSideEffectCheckMode();

  void ApplySideEffectChecks(Handle<DebugInfo> debug_info);
  void ClearSideEffectChecks(Handle<DebugInfo> debug_info);

327 328
  bool PerformSideEffectCheck(Handle<JSFunction> function,
                              Handle<Object> receiver);
329 330 331 332 333

  enum AccessorKind { kNotAccessor, kGetter, kSetter };
  bool PerformSideEffectCheckForCallback(Handle<Object> callback_info,
                                         Handle<Object> receiver,
                                         AccessorKind accessor_kind);
334
  bool PerformSideEffectCheckAtBytecode(InterpretedFrame* frame);
335
  bool PerformSideEffectCheckForObject(Handle<Object> object);
336

337 338
  // Flags and states.
  inline bool is_active() const { return is_active_; }
339
  inline bool in_debug_scope() const {
340
    return !!base::Relaxed_Load(&thread_local_.current_debug_scope_);
341
  }
342 343 344 345
  inline bool needs_check_on_function_call() const {
    return hook_on_function_call_;
  }

346
  void set_break_points_active(bool v) { break_points_active_ = v; }
347
  bool break_points_active() const { return break_points_active_; }
348 349 350

  StackFrame::Id break_frame_id() { return thread_local_.break_frame_id_; }

351
  Handle<Object> return_value_handle();
352 353
  Object return_value() { return thread_local_.return_value_; }
  void set_return_value(Object value) { thread_local_.return_value_ = value; }
354

355
  // Support for embedding into generated code.
356 357 358 359
  Address is_active_address() {
    return reinterpret_cast<Address>(&is_active_);
  }

360 361 362 363
  Address hook_on_function_call_address() {
    return reinterpret_cast<Address>(&hook_on_function_call_);
  }

364 365 366 367
  Address suspended_generator_address() {
    return reinterpret_cast<Address>(&thread_local_.suspended_generator_);
  }

368 369 370
  Address restart_fp_address() {
    return reinterpret_cast<Address>(&thread_local_.restart_fp_);
  }
371 372 373
  bool will_restart() const {
    return thread_local_.restart_fp_ != kNullAddress;
  }
374

375
  StepAction last_step_action() { return thread_local_.last_step_action_; }
376 377 378
  bool break_on_next_function_call() const {
    return thread_local_.break_on_next_function_call_;
  }
379

380 381
  DebugFeatureTracker* feature_tracker() { return &feature_tracker_; }

382 383 384 385
  // For functions in which we cannot set a break point, use a canonical
  // source position for break points.
  static const int kBreakAtEntryPosition = 0;

386 387
  void RemoveBreakInfoAndMaybeFree(Handle<DebugInfo> debug_info);

388
 private:
389
  explicit Debug(Isolate* isolate);
390
  ~Debug();
391

392
  void UpdateDebugInfosForExecutionMode();
393
  void UpdateState();
394
  void UpdateHookOnFunctionCall();
395 396
  void Unload();

397 398 399
  // Return the number of virtual frames below debugger entry.
  int CurrentFrameCount();

400
  inline bool ignore_events() const {
401 402
    return is_suppressed_ || !is_active_ ||
           isolate_->debug_execution_mode() == DebugInfo::kSideEffects;
403
  }
404
  inline bool break_disabled() const { return break_disabled_; }
405

406
  void clear_suspended_generator() {
407
    thread_local_.suspended_generator_ = Smi::kZero;
408 409 410
  }

  bool has_suspended_generator() const {
411
    return thread_local_.suspended_generator_ != Smi::kZero;
412 413
  }

414
  bool IsExceptionBlackboxed(bool uncaught);
415

416 417
  void OnException(Handle<Object> exception, Handle<Object> promise,
                   v8::debug::ExceptionType exception_type);
418

419
  void ProcessCompileEvent(bool has_compile_error, Handle<Script> script);
420

421
  // Find the closest source position for a break point for a given position.
422
  int FindBreakablePosition(Handle<DebugInfo> debug_info, int source_position);
423 424 425 426 427 428 429
  // Instrument code to break at break points.
  void ApplyBreakPoints(Handle<DebugInfo> debug_info);
  // Clear code from instrumentation.
  void ClearBreakPoints(Handle<DebugInfo> debug_info);
  // Clear all code from instrumentation.
  void ClearAllBreakPoints();
  // Instrument a function with one-shots.
430 431
  void FloodWithOneShot(Handle<SharedFunctionInfo> function,
                        bool returns_only = false);
432
  // Clear all one-shot instrumentations, but restore break points.
433
  void ClearOneShot();
434

435 436
  bool IsFrameBlackboxed(JavaScriptFrame* frame);

437
  void ActivateStepOut(StackFrame* frame);
438 439 440
  MaybeHandle<FixedArray> CheckBreakPoints(Handle<DebugInfo> debug_info,
                                           BreakLocation* location,
                                           bool* has_break_points = nullptr);
441
  bool IsMutedAtCurrentLocation(JavaScriptFrame* frame);
442 443 444
  // Check whether a BreakPoint object is hit. Evaluate condition depending
  // on whether this is a regular break location or a break at function entry.
  bool CheckBreakPoint(Handle<BreakPoint> break_point, bool is_break_at_entry);
445

446
  inline void AssertDebugContext() {
447
    DCHECK(in_debug_scope());
448 449
  }

450
  void ThreadInit();
451

452 453
  void PrintBreakLocation();

454 455
  void ClearAllDebuggerHints();

456
  // Wraps logic for clearing and maybe freeing all debug infos.
457
  typedef std::function<void(Handle<DebugInfo>)> DebugInfoClearFunction;
458
  void ClearAllDebugInfos(const DebugInfoClearFunction& clear_function);
459

460 461 462 463
  void FindDebugInfo(Handle<DebugInfo> debug_info, DebugInfoListNode** prev,
                     DebugInfoListNode** curr);
  void FreeDebugInfoListNode(DebugInfoListNode* prev, DebugInfoListNode* node);

464
  debug::DebugDelegate* debug_delegate_ = nullptr;
465

466
  // Debugger is active, i.e. there is a debug event listener attached.
467
  bool is_active_;
468 469 470 471
  // Debugger needs to be notified on every new function call.
  // Used for stepping and read-only checks
  bool hook_on_function_call_;
  // Suppress debug events.
472
  bool is_suppressed_;
473 474
  // Running liveedit.
  bool running_live_edit_ = false;
475
  // Do not trigger debug break events.
476
  bool break_disabled_;
477
  // Do not break on break points.
478
  bool break_points_active_;
479
  // Trigger debug break events for all exceptions.
480
  bool break_on_exception_;
481
  // Trigger debug break events for uncaught exceptions.
482
  bool break_on_uncaught_exception_;
483 484
  // Termination exception because side effect check has failed.
  bool side_effect_check_failed_;
485

486 487
  // List of active debug info objects.
  DebugInfoListNode* debug_info_list_;
488

489 490 491 492
  // Used for side effect check to mark temporary objects.
  class TemporaryObjectsTracker;
  std::unique_ptr<TemporaryObjectsTracker> temporary_objects_;

493 494
  Handle<RegExpMatchInfo> regexp_match_info_;

495 496 497
  // Used to collect histogram data on debugger feature usage.
  DebugFeatureTracker feature_tracker_;

498
  // Per-thread data.
499 500
  class ThreadLocal {
   public:
501
    // Top debugger entry.
502
    base::AtomicWord current_debug_scope_;
503

504 505 506
    // Frame id for the frame of the current break.
    StackFrame::Id break_frame_id_;

507 508 509
    // Step action for last step performed.
    StepAction last_step_action_;

510 511
    // If set, next PrepareStepIn will ignore this function until stepped into
    // another function, at which point this will be cleared.
512
    Object ignore_step_into_function_;
513 514 515 516

    // If set then we need to repeat StepOut action at return.
    bool fast_forward_to_return_;

517 518 519
    // Source statement position from last step next action.
    int last_statement_position_;

520
    // Frame pointer from last step next or step frame action.
521
    int last_frame_count_;
522

523
    // Frame pointer of the target frame we want to arrive at.
524
    int target_frame_count_;
525

526
    // Value of the accumulator at the point of entering the debugger.
527
    Object return_value_;
528

529
    // The suspended generator object to track when stepping.
530
    Object suspended_generator_;
531

532 533 534
    // The new frame pointer to drop to when restarting a frame.
    Address restart_fp_;

535 536
    // Last used inspector breakpoint id.
    int last_breakpoint_id_;
537 538 539 540

    // This flag is true when SetBreakOnNextFunctionCall is called and it forces
    // debugger to break on next function call.
    bool break_on_next_function_call_;
541 542 543
  };

  // Storage location for registers when handling debug break calls
544
  ThreadLocal thread_local_;
545

546 547 548
  Isolate* isolate_;

  friend class Isolate;
549
  friend class DebugScope;
550
  friend class DisableBreak;
551
  friend class LiveEdit;
552
  friend class SuppressDebug;
553

554
  friend Handle<FixedArray> GetDebuggedFunctions();  // In test-debug.cc
555
  friend void CheckDebuggerUnloaded();               // In test-debug.cc
556

557
  DISALLOW_COPY_AND_ASSIGN(Debug);
558 559
};

560 561
// This scope is used to load and enter the debug context and create a new
// break state.  Leaving the scope will restore the previous state.
562
class DebugScope {
563
 public:
564 565
  explicit DebugScope(Debug* debug);
  ~DebugScope();
566 567

 private:
568 569 570 571
  Isolate* isolate() { return debug_->isolate_; }

  Debug* debug_;
  DebugScope* prev_;               // Previous scope if entered recursively.
572
  StackFrame::Id break_frame_id_;  // Previous break frame id.
573
  PostponeInterruptsScope no_interrupts_;
574 575
};

576 577 578 579 580 581 582 583 584 585 586 587 588
// This scope is used to handle return values in nested debug break points.
// When there are nested debug breaks, we use this to restore the return
// value to the previous state. This is not merged with DebugScope because
// return_value_ will not be cleared when we use DebugScope.
class ReturnValueScope {
 public:
  explicit ReturnValueScope(Debug* debug);
  ~ReturnValueScope();

 private:
  Debug* debug_;
  Handle<Object> return_value_;  // Previous result.
};
589

590
// Stack allocated class for disabling break.
591
class DisableBreak {
592
 public:
593
  explicit DisableBreak(Debug* debug, bool disable = true)
594
      : debug_(debug), previous_break_disabled_(debug->break_disabled_) {
595
    debug_->break_disabled_ = disable;
596 597 598
  }
  ~DisableBreak() {
    debug_->break_disabled_ = previous_break_disabled_;
599
  }
600 601 602

 private:
  Debug* debug_;
603
  bool previous_break_disabled_;
604 605 606
  DISALLOW_COPY_AND_ASSIGN(DisableBreak);
};

607
class SuppressDebug {
608 609 610 611
 public:
  explicit SuppressDebug(Debug* debug)
      : debug_(debug), old_state_(debug->is_suppressed_) {
    debug_->is_suppressed_ = true;
612
  }
613
  ~SuppressDebug() { debug_->is_suppressed_ = old_state_; }
614 615

 private:
616 617 618
  Debug* debug_;
  bool old_state_;
  DISALLOW_COPY_AND_ASSIGN(SuppressDebug);
619 620
};

621 622 623
// Code generator routines.
class DebugCodegen : public AllStatic {
 public:
624 625 626
  enum DebugBreakCallHelperMode {
    SAVE_RESULT_REGISTER,
    IGNORE_RESULT_REGISTER
627 628
  };

629 630
  // Builtin to drop frames to restart function.
  static void GenerateFrameDropperTrampoline(MacroAssembler* masm);
631

632 633 634
  // Builtin to atomically (wrt deopts) handle debugger statement and
  // drop frames to restart function if necessary.
  static void GenerateHandleDebuggerStatement(MacroAssembler* masm);
635 636 637

  // Builtin to trigger a debug break before entering the function.
  static void GenerateDebugBreakTrampoline(MacroAssembler* masm);
638 639
};

640

641 642
}  // namespace internal
}  // namespace v8
643

644
#endif  // V8_DEBUG_DEBUG_H_