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/codegen/source-position-table.h"
11
#include "src/common/globals.h"
12
#include "src/debug/debug-interface.h"
13
#include "src/debug/interface-types.h"
14
#include "src/execution/interrupts-scope.h"
15
#include "src/execution/isolate.h"
16
#include "src/handles/handles.h"
17
#include "src/objects/debug-objects.h"
18

19 20
namespace v8 {
namespace internal {
21

22
// Forward declarations.
Marja Hölttä's avatar
Marja Hölttä committed
23
class AbstractCode;
24
class DebugScope;
25 26
class InterpretedFrame;
class JavaScriptFrame;
27
class JSGeneratorObject;
28
class StackFrame;
29

30
// Step actions. NOTE: These values are in macros.py as well.
31
enum StepAction : int8_t {
32
  StepNone = -1,  // Stepping not prepared.
33 34 35 36
  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.
37
  LastStepAction = StepIn
38
};
39 40 41 42 43 44 45

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

46 47 48 49 50 51
enum DebugBreakType {
  NOT_DEBUG_BREAK,
  DEBUGGER_STATEMENT,
  DEBUG_BREAK_SLOT,
  DEBUG_BREAK_SLOT_AT_CALL,
  DEBUG_BREAK_SLOT_AT_RETURN,
52
  DEBUG_BREAK_SLOT_AT_SUSPEND,
53
  DEBUG_BREAK_AT_ENTRY,
54
};
55

56 57 58 59 60
enum IgnoreBreakMode {
  kIgnoreIfAllFramesBlackboxed,
  kIgnoreIfTopFrameBlackboxed
};

61
class BreakLocation {
62
 public:
63 64
  static BreakLocation FromFrame(Handle<DebugInfo> debug_info,
                                 JavaScriptFrame* frame);
65

66 67
  static void AllAtCurrentStatement(Handle<DebugInfo> debug_info,
                                    JavaScriptFrame* frame,
68
                                    std::vector<BreakLocation>* result_out);
69

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

85
  bool HasBreakPoint(Isolate* isolate, Handle<DebugInfo> debug_info) const;
86

87
  inline int position() const { return position_; }
88

89 90
  debug::BreakLocationType type() const;

91
  JSGeneratorObject GetGeneratorObjectForSuspendedFrame(
92 93
      JavaScriptFrame* frame) const;

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

105 106 107 108 109 110
  BreakLocation(int position, DebugBreakType type)
      : code_offset_(0),
        type_(type),
        position_(position),
        generator_obj_reg_index_(0) {}

111 112 113
  static int BreakIndexFromCodeOffset(Handle<DebugInfo> debug_info,
                                      Handle<AbstractCode> abstract_code,
                                      int offset);
114

115 116 117 118 119 120 121
  void SetDebugBreak();
  void ClearDebugBreak();

  Handle<AbstractCode> abstract_code_;
  int code_offset_;
  DebugBreakType type_;
  int position_;
122
  int generator_obj_reg_index_;
123

124
  friend class BreakIterator;
125
};
126

127
class V8_EXPORT_PRIVATE BreakIterator {
128
 public:
129
  explicit BreakIterator(Handle<DebugInfo> debug_info);
130

131 132 133
  BreakLocation GetBreakLocation();
  bool Done() const { return source_position_iterator_.done(); }
  void Next();
134

135
  void SkipToPosition(int position);
136 137
  void SkipTo(int count) {
    while (count-- > 0) Next();
138
  }
139

140
  int code_offset() { return source_position_iterator_.code_offset(); }
141 142 143
  int break_index() const { return break_index_; }
  inline int position() const { return position_; }
  inline int statement_position() const { return statement_position_; }
144

145 146
  void ClearDebugBreak();
  void SetDebugBreak();
147

148
 private:
149
  int BreakIndexFromPosition(int position);
150

151
  Isolate* isolate();
152

153 154
  DebugBreakType GetDebugBreakType();

155 156 157 158 159
  Handle<DebugInfo> debug_info_;
  int break_index_;
  int position_;
  int statement_position_;
  SourcePositionTableIterator source_position_iterator_;
160
  DisallowHeapAllocation no_gc_;
161

162
  DISALLOW_COPY_AND_ASSIGN(BreakIterator);
163
};
164 165 166 167 168

// 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:
169
  DebugInfoListNode(Isolate* isolate, DebugInfo debug_info);
170
  ~DebugInfoListNode();
171 172 173

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

176 177
 private:
  // Global (weak) handle to the debug info object.
178
  Address* debug_info_;
179 180 181 182 183

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

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
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_;
};


206 207 208 209 210 211 212
// 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.
213
class V8_EXPORT_PRIVATE Debug {
214
 public:
215
  // Debug event triggers.
216
  void OnDebugBreak(Handle<FixedArray> break_points_hit);
217

218
  void OnThrow(Handle<Object> exception);
219
  void OnPromiseReject(Handle<Object> promise, Handle<Object> value);
220
  void OnCompileError(Handle<Script> script);
221
  void OnAfterCompile(Handle<Script> script);
222

223
  void HandleDebugBreak(IgnoreBreakMode ignore_break_mode);
224

225 226 227
  // 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);
228

229 230 231 232
  // Scripts handling.
  Handle<FixedArray> GetLoadedScripts();

  // Break point handling.
233
  bool SetBreakpoint(Handle<SharedFunctionInfo> shared,
234 235
                     Handle<BreakPoint> break_point, int* source_position);
  void ClearBreakPoint(Handle<BreakPoint> break_point);
236 237
  void ChangeBreakOnException(ExceptionBreakType type, bool enable);
  bool IsBreakOnException(ExceptionBreakType type);
238

239 240
  bool SetBreakPointForScript(Handle<Script> script, Handle<String> condition,
                              int* source_position, int* id);
241
  bool SetBreakpointForFunction(Handle<SharedFunctionInfo> shared,
242
                                Handle<String> condition, int* id);
243 244
  void RemoveBreakpoint(int id);

245 246
  // 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
247
  // hit BreakPoint objects.
248 249
  MaybeHandle<FixedArray> GetHitBreakPoints(Handle<DebugInfo> debug_info,
                                            int position);
250

251
  // Stepping handling.
252
  void PrepareStep(StepAction step_action);
253
  void PrepareStepIn(Handle<JSFunction> function);
254
  void PrepareStepInSuspendedGenerator();
255
  void PrepareStepOnThrow();
256
  void ClearStepping();
257

258 259 260
  void SetBreakOnNextFunctionCall();
  void ClearBreakOnNextFunctionCall();

261
  void DeoptimizeFunction(Handle<SharedFunctionInfo> shared);
262
  void PrepareFunctionForDebugExecution(Handle<SharedFunctionInfo> shared);
263
  void InstallDebugBreakTrampoline();
264
  bool GetPossibleBreakpoints(Handle<Script> script, int start_position,
265
                              int end_position, bool restrict_to_function,
266
                              std::vector<BreakLocation>* locations);
267

268 269
  MaybeHandle<JSArray> GetPrivateFields(Handle<JSReceiver> receiver);

270 271
  bool IsBlackboxed(Handle<SharedFunctionInfo> shared);

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

274
  void SetDebugDelegate(debug::DebugDelegate* delegate);
275

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

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

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

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

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

295
  // Support for LiveEdit
296
  void ScheduleFrameRestart(StackFrame* frame);
297

298
  bool AllFramesOnStackAreBlackboxed();
299

300 301 302 303 304
  // 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,
305
                       bool preview, debug::LiveEditResult* result);
306

307 308
  int GetFunctionDebuggingId(Handle<JSFunction> function);

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

Yang Guo's avatar
Yang Guo committed
317
  bool CheckExecutionState() { return is_active(); }
318

319 320 321 322 323 324
  void StartSideEffectCheckMode();
  void StopSideEffectCheckMode();

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

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

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

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

344
  void set_break_points_active(bool v) { break_points_active_ = v; }
345
  bool break_points_active() const { return break_points_active_; }
346

347
  StackFrameId break_frame_id() { return thread_local_.break_frame_id_; }
348

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

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

358 359 360 361
  Address hook_on_function_call_address() {
    return reinterpret_cast<Address>(&hook_on_function_call_);
  }

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

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

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

378 379
  DebugFeatureTracker* feature_tracker() { return &feature_tracker_; }

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

384 385
  void RemoveBreakInfoAndMaybeFree(Handle<DebugInfo> debug_info);

386
 private:
387
  explicit Debug(Isolate* isolate);
388
  ~Debug();
389

390
  void UpdateDebugInfosForExecutionMode();
391
  void UpdateState();
392
  void UpdateHookOnFunctionCall();
393 394
  void Unload();

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

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

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

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

412
  bool IsExceptionBlackboxed(bool uncaught);
413

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

417
  void ProcessCompileEvent(bool has_compile_error, Handle<Script> script);
418

419
  // Find the closest source position for a break point for a given position.
420
  int FindBreakablePosition(Handle<DebugInfo> debug_info, int source_position);
421 422 423 424 425 426 427
  // 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.
428 429
  void FloodWithOneShot(Handle<SharedFunctionInfo> function,
                        bool returns_only = false);
430
  // Clear all one-shot instrumentations, but restore break points.
431
  void ClearOneShot();
432

433 434
  bool IsFrameBlackboxed(JavaScriptFrame* frame);

435
  void ActivateStepOut(StackFrame* frame);
436 437 438
  MaybeHandle<FixedArray> CheckBreakPoints(Handle<DebugInfo> debug_info,
                                           BreakLocation* location,
                                           bool* has_break_points = nullptr);
439
  bool IsMutedAtCurrentLocation(JavaScriptFrame* frame);
440 441 442
  // 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);
443

444
  inline void AssertDebugContext() {
445
    DCHECK(in_debug_scope());
446 447
  }

448
  void ThreadInit();
449

450 451
  void PrintBreakLocation();

452 453
  void ClearAllDebuggerHints();

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

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

462
  debug::DebugDelegate* debug_delegate_ = nullptr;
463

464
  // Debugger is active, i.e. there is a debug event listener attached.
465
  bool is_active_;
466 467 468 469
  // 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.
470
  bool is_suppressed_;
471 472
  // Running liveedit.
  bool running_live_edit_ = false;
473
  // Do not trigger debug break events.
474
  bool break_disabled_;
475
  // Do not break on break points.
476
  bool break_points_active_;
477
  // Trigger debug break events for all exceptions.
478
  bool break_on_exception_;
479
  // Trigger debug break events for uncaught exceptions.
480
  bool break_on_uncaught_exception_;
481 482
  // Termination exception because side effect check has failed.
  bool side_effect_check_failed_;
483

484 485
  // List of active debug info objects.
  DebugInfoListNode* debug_info_list_;
486

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

491 492
  Handle<RegExpMatchInfo> regexp_match_info_;

493 494 495
  // Used to collect histogram data on debugger feature usage.
  DebugFeatureTracker feature_tracker_;

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

502
    // Frame id for the frame of the current break.
503
    StackFrameId break_frame_id_;
504

505 506 507
    // Step action for last step performed.
    StepAction last_step_action_;

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

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

515 516 517
    // Source statement position from last step next action.
    int last_statement_position_;

518
    // Frame pointer from last step next or step frame action.
519
    int last_frame_count_;
520

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

524
    // Value of the accumulator at the point of entering the debugger.
525
    Object return_value_;
526

527
    // The suspended generator object to track when stepping.
528
    Object suspended_generator_;
529

530 531 532
    // The new frame pointer to drop to when restarting a frame.
    Address restart_fp_;

533 534
    // Last used inspector breakpoint id.
    int last_breakpoint_id_;
535 536 537 538

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

  // Storage location for registers when handling debug break calls
542
  ThreadLocal thread_local_;
543

544 545 546
  Isolate* isolate_;

  friend class Isolate;
547
  friend class DebugScope;
548
  friend class DisableBreak;
549
  friend class LiveEdit;
550
  friend class SuppressDebug;
551

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

555
  DISALLOW_COPY_AND_ASSIGN(Debug);
556 557
};

558 559
// 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.
560
class DebugScope {
561
 public:
562 563
  explicit DebugScope(Debug* debug);
  ~DebugScope();
564 565

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

  Debug* debug_;
  DebugScope* prev_;               // Previous scope if entered recursively.
570
  StackFrameId break_frame_id_;    // Previous break frame id.
571
  PostponeInterruptsScope no_interrupts_;
572 573
};

574 575 576 577 578 579 580 581 582 583 584 585 586
// 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.
};
587

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

 private:
  Debug* debug_;
601
  bool previous_break_disabled_;
602 603 604
  DISALLOW_COPY_AND_ASSIGN(DisableBreak);
};

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

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

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

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

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

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

638

639 640
}  // namespace internal
}  // namespace v8
641

642
#endif  // V8_DEBUG_DEBUG_H_