-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
debug.cc
3379 lines (3021 loc) Β· 126 KB
/
debug.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/debug/debug.h"
#include <memory>
#include <optional>
#include "src/api/api-inl.h"
#include "src/base/platform/mutex.h"
#include "src/builtins/builtins.h"
#include "src/codegen/compilation-cache.h"
#include "src/codegen/compiler.h"
#include "src/common/assert-scope.h"
#include "src/common/globals.h"
#include "src/common/message-template.h"
#include "src/debug/debug-evaluate.h"
#include "src/debug/liveedit.h"
#include "src/deoptimizer/deoptimizer.h"
#include "src/execution/execution.h"
#include "src/execution/frames-inl.h"
#include "src/execution/isolate-inl.h"
#include "src/execution/protectors-inl.h"
#include "src/execution/v8threads.h"
#include "src/handles/global-handles-inl.h"
#include "src/heap/heap-inl.h" // For NextDebuggingId.
#include "src/init/bootstrapper.h"
#include "src/interpreter/bytecode-array-iterator.h"
#include "src/logging/counters.h"
#include "src/logging/runtime-call-stats-scope.h"
#include "src/objects/api-callbacks-inl.h"
#include "src/objects/debug-objects-inl.h"
#include "src/objects/js-generator-inl.h"
#include "src/objects/js-promise-inl.h"
#include "src/objects/slots.h"
#include "src/snapshot/embedded/embedded-data.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-debug.h"
#include "src/wasm/wasm-objects-inl.h"
#endif // V8_ENABLE_WEBASSEMBLY
namespace v8 {
namespace internal {
class Debug::TemporaryObjectsTracker : public HeapObjectAllocationTracker {
public:
TemporaryObjectsTracker() = default;
~TemporaryObjectsTracker() override = default;
TemporaryObjectsTracker(const TemporaryObjectsTracker&) = delete;
TemporaryObjectsTracker& operator=(const TemporaryObjectsTracker&) = delete;
void AllocationEvent(Address addr, int size) override {
if (disabled) return;
AddRegion(addr, addr + size);
}
void MoveEvent(Address from, Address to, int size) override {
if (from == to) return;
base::MutexGuard guard(&mutex_);
if (RemoveFromRegions(from, from + size)) {
// We had the object tracked as temporary, so we will track the
// new location as temporary, too.
AddRegion(to, to + size);
} else {
// The object we moved is a non-temporary, so the new location is also
// non-temporary. Thus we remove everything we track there (because it
// must have become dead).
RemoveFromRegions(to, to + size);
}
}
bool HasObject(Handle<HeapObject> obj) {
if (IsJSObject(*obj) && Cast<JSObject>(obj)->GetEmbedderFieldCount()) {
// Embedder may store any pointers using embedder fields and implements
// non trivial logic, e.g. create wrappers lazily and store pointer to
// native object inside embedder field. We should consider all objects
// with embedder fields as non temporary.
return false;
}
Address addr = obj->address();
return HasRegionContainingObject(addr, addr + obj->Size());
}
bool disabled = false;
private:
bool HasRegionContainingObject(Address start, Address end) {
// Check if there is a region that contains (overlaps) this object's space.
auto it = FindOverlappingRegion(start, end, false);
// If there is, we expect the region to contain the entire object.
DCHECK_IMPLIES(it != regions_.end(),
it->second <= start && end <= it->first);
return it != regions_.end();
}
// This function returns any one of the overlapping regions (there might be
// multiple). If {include_adjacent} is true, it will also consider regions
// that have no overlap but are directly connected.
std::map<Address, Address>::iterator FindOverlappingRegion(
Address start, Address end, bool include_adjacent) {
// Region A = [start, end) overlaps with an existing region [existing_start,
// existing_end) iff (start <= existing_end) && (existing_start <= end).
// Since we index {regions_} by end address, we can find a candidate that
// satisfies the first condition using lower_bound.
if (include_adjacent) {
auto it = regions_.lower_bound(start);
if (it == regions_.end()) return regions_.end();
if (it->second <= end) return it;
} else {
auto it = regions_.upper_bound(start);
if (it == regions_.end()) return regions_.end();
if (it->second < end) return it;
}
return regions_.end();
}
void AddRegion(Address start, Address end) {
DCHECK_LT(start, end);
// Region [start, end) can be combined with an existing region if they
// overlap.
while (true) {
auto it = FindOverlappingRegion(start, end, true);
// If there is no such region, we don't need to merge anything.
if (it == regions_.end()) break;
// Otherwise, we found an overlapping region. We remove the old one and
// add the new region recursively (to handle cases where the new region
// overlaps multiple existing ones).
start = std::min(start, it->second);
end = std::max(end, it->first);
regions_.erase(it);
}
// Add the new (possibly combined) region.
regions_.emplace(end, start);
}
bool RemoveFromRegions(Address start, Address end) {
// Check if we have anything that overlaps with [start, end).
auto it = FindOverlappingRegion(start, end, false);
if (it == regions_.end()) return false;
// We need to update all overlapping regions.
for (; it != regions_.end();
it = FindOverlappingRegion(start, end, false)) {
Address existing_start = it->second;
Address existing_end = it->first;
// If we remove the region [start, end) from an existing region
// [existing_start, existing_end), there can be at most 2 regions left:
regions_.erase(it);
// The one before {start} is: [existing_start, start)
if (existing_start < start) AddRegion(existing_start, start);
// And the one after {end} is: [end, existing_end)
if (end < existing_end) AddRegion(end, existing_end);
}
return true;
}
// Tracking addresses is not enough, because a single allocation may combine
// multiple objects due to allocation folding. We track both start and end
// (exclusive) address of regions. We index by end address for faster lookup.
// Map: end address => start address
std::map<Address, Address> regions_;
base::Mutex mutex_;
};
Debug::Debug(Isolate* isolate)
: is_active_(false),
hook_on_function_call_(false),
is_suppressed_(false),
break_disabled_(false),
break_points_active_(true),
break_on_caught_exception_(false),
break_on_uncaught_exception_(false),
side_effect_check_failed_(false),
debug_infos_(isolate),
isolate_(isolate) {
ThreadInit();
}
Debug::~Debug() { DCHECK_NULL(debug_delegate_); }
BreakLocation BreakLocation::FromFrame(Handle<DebugInfo> debug_info,
JavaScriptFrame* frame) {
if (debug_info->CanBreakAtEntry()) {
return BreakLocation(Debug::kBreakAtEntryPosition, DEBUG_BREAK_AT_ENTRY);
}
auto summary = FrameSummary::GetTop(frame).AsJavaScript();
int offset = summary.code_offset();
DirectHandle<AbstractCode> abstract_code = summary.abstract_code();
BreakIterator it(debug_info);
it.SkipTo(BreakIndexFromCodeOffset(debug_info, abstract_code, offset));
return it.GetBreakLocation();
}
bool BreakLocation::IsPausedInJsFunctionEntry(JavaScriptFrame* frame) {
auto summary = FrameSummary::GetTop(frame);
return summary.code_offset() == kFunctionEntryBytecodeOffset;
}
MaybeHandle<FixedArray> Debug::CheckBreakPointsForLocations(
Handle<DebugInfo> debug_info, std::vector<BreakLocation>& break_locations,
bool* has_break_points) {
Handle<FixedArray> break_points_hit = isolate_->factory()->NewFixedArray(
debug_info->GetBreakPointCount(isolate_));
int break_points_hit_count = 0;
bool has_break_points_at_all = false;
for (size_t i = 0; i < break_locations.size(); i++) {
bool location_has_break_points;
MaybeHandle<FixedArray> check_result = CheckBreakPoints(
debug_info, &break_locations[i], &location_has_break_points);
has_break_points_at_all |= location_has_break_points;
if (!check_result.is_null()) {
DirectHandle<FixedArray> break_points_current_hit =
check_result.ToHandleChecked();
int num_objects = break_points_current_hit->length();
for (int j = 0; j < num_objects; ++j) {
break_points_hit->set(break_points_hit_count++,
break_points_current_hit->get(j));
}
}
}
*has_break_points = has_break_points_at_all;
if (break_points_hit_count == 0) return {};
break_points_hit->RightTrim(isolate_, break_points_hit_count);
return break_points_hit;
}
void BreakLocation::AllAtCurrentStatement(
Handle<DebugInfo> debug_info, JavaScriptFrame* frame,
std::vector<BreakLocation>* result_out) {
DCHECK(!debug_info->CanBreakAtEntry());
auto summary = FrameSummary::GetTop(frame).AsJavaScript();
int offset = summary.code_offset();
DirectHandle<AbstractCode> abstract_code = summary.abstract_code();
PtrComprCageBase cage_base = GetPtrComprCageBase(*debug_info);
if (IsCode(*abstract_code, cage_base)) offset = offset - 1;
int statement_position;
{
BreakIterator it(debug_info);
it.SkipTo(BreakIndexFromCodeOffset(debug_info, abstract_code, offset));
statement_position = it.statement_position();
}
for (BreakIterator it(debug_info); !it.Done(); it.Next()) {
if (it.statement_position() == statement_position) {
result_out->push_back(it.GetBreakLocation());
}
}
}
Tagged<JSGeneratorObject> BreakLocation::GetGeneratorObjectForSuspendedFrame(
JavaScriptFrame* frame) const {
DCHECK(IsSuspend());
DCHECK_GE(generator_obj_reg_index_, 0);
Tagged<Object> generator_obj =
UnoptimizedFrame::cast(frame)->ReadInterpreterRegister(
generator_obj_reg_index_);
return Cast<JSGeneratorObject>(generator_obj);
}
int BreakLocation::BreakIndexFromCodeOffset(
Handle<DebugInfo> debug_info, DirectHandle<AbstractCode> abstract_code,
int offset) {
// Run through all break points to locate the one closest to the address.
int closest_break = 0;
int distance = kMaxInt;
DCHECK(kFunctionEntryBytecodeOffset <= offset &&
offset < abstract_code->Size());
for (BreakIterator it(debug_info); !it.Done(); it.Next()) {
// Check if this break point is closer that what was previously found.
if (it.code_offset() <= offset && offset - it.code_offset() < distance) {
closest_break = it.break_index();
distance = offset - it.code_offset();
// Check whether we can't get any closer.
if (distance == 0) break;
}
}
return closest_break;
}
bool BreakLocation::HasBreakPoint(Isolate* isolate,
Handle<DebugInfo> debug_info) const {
// First check whether there is a break point with the same source position.
if (!debug_info->HasBreakInfo() ||
!debug_info->HasBreakPoint(isolate, position_)) {
return false;
}
if (debug_info->CanBreakAtEntry()) {
DCHECK_EQ(Debug::kBreakAtEntryPosition, position_);
return debug_info->BreakAtEntry();
} else {
// Then check whether a break point at that source position would have
// the same code offset. Otherwise it's just a break location that we can
// step to, but not actually a location where we can put a break point.
DCHECK(IsBytecodeArray(*abstract_code_, isolate));
BreakIterator it(debug_info);
it.SkipToPosition(position_);
return it.code_offset() == code_offset_;
}
}
debug::BreakLocationType BreakLocation::type() const {
switch (type_) {
case DEBUGGER_STATEMENT:
return debug::kDebuggerStatementBreakLocation;
case DEBUG_BREAK_SLOT_AT_CALL:
return debug::kCallBreakLocation;
case DEBUG_BREAK_SLOT_AT_RETURN:
return debug::kReturnBreakLocation;
// Externally, suspend breaks should look like normal breaks.
case DEBUG_BREAK_SLOT_AT_SUSPEND:
default:
return debug::kCommonBreakLocation;
}
}
BreakIterator::BreakIterator(Handle<DebugInfo> debug_info)
: debug_info_(debug_info),
break_index_(-1),
source_position_iterator_(
debug_info->DebugBytecodeArray(isolate())->SourcePositionTable()) {
position_ = debug_info->shared()->StartPosition();
statement_position_ = position_;
// There is at least one break location.
DCHECK(!Done());
Next();
}
int BreakIterator::BreakIndexFromPosition(int source_position) {
for (; !Done(); Next()) {
if (GetDebugBreakType() == DEBUG_BREAK_SLOT_AT_SUSPEND) continue;
if (source_position <= position()) {
int first_break = break_index();
for (; !Done(); Next()) {
if (GetDebugBreakType() == DEBUG_BREAK_SLOT_AT_SUSPEND) continue;
if (source_position == position()) return break_index();
}
return first_break;
}
}
return break_index();
}
void BreakIterator::Next() {
DisallowGarbageCollection no_gc;
DCHECK(!Done());
bool first = break_index_ == -1;
while (!Done()) {
if (!first) source_position_iterator_.Advance();
first = false;
if (Done()) return;
position_ = source_position_iterator_.source_position().ScriptOffset();
if (source_position_iterator_.is_statement()) {
statement_position_ = position_;
}
DCHECK_LE(0, position_);
DCHECK_LE(0, statement_position_);
DebugBreakType type = GetDebugBreakType();
if (type != NOT_DEBUG_BREAK) break;
}
break_index_++;
}
DebugBreakType BreakIterator::GetDebugBreakType() {
Tagged<BytecodeArray> bytecode_array =
debug_info_->OriginalBytecodeArray(isolate());
interpreter::Bytecode bytecode =
interpreter::Bytecodes::FromByte(bytecode_array->get(code_offset()));
// Make sure we read the actual bytecode, not a prefix scaling bytecode.
if (interpreter::Bytecodes::IsPrefixScalingBytecode(bytecode)) {
bytecode = interpreter::Bytecodes::FromByte(
bytecode_array->get(code_offset() + 1));
}
if (bytecode == interpreter::Bytecode::kDebugger) {
return DEBUGGER_STATEMENT;
} else if (bytecode == interpreter::Bytecode::kReturn) {
return DEBUG_BREAK_SLOT_AT_RETURN;
} else if (bytecode == interpreter::Bytecode::kSuspendGenerator) {
// SuspendGenerator should always only carry an expression position that
// is used in stack trace construction, but should never be a breakable
// position reported to the debugger front-end.
DCHECK(!source_position_iterator_.is_statement());
return DEBUG_BREAK_SLOT_AT_SUSPEND;
} else if (interpreter::Bytecodes::IsCallOrConstruct(bytecode)) {
return DEBUG_BREAK_SLOT_AT_CALL;
} else if (source_position_iterator_.is_statement()) {
return DEBUG_BREAK_SLOT;
} else {
return NOT_DEBUG_BREAK;
}
}
void BreakIterator::SkipToPosition(int position) {
BreakIterator it(debug_info_);
SkipTo(it.BreakIndexFromPosition(position));
}
void BreakIterator::SetDebugBreak() {
DCHECK(GetDebugBreakType() >= DEBUGGER_STATEMENT);
HandleScope scope(isolate());
Handle<BytecodeArray> bytecode_array(
debug_info_->DebugBytecodeArray(isolate()), isolate());
interpreter::BytecodeArrayIterator(bytecode_array, code_offset())
.ApplyDebugBreak();
}
void BreakIterator::ClearDebugBreak() {
DCHECK(GetDebugBreakType() >= DEBUGGER_STATEMENT);
Tagged<BytecodeArray> bytecode_array =
debug_info_->DebugBytecodeArray(isolate());
Tagged<BytecodeArray> original =
debug_info_->OriginalBytecodeArray(isolate());
bytecode_array->set(code_offset(), original->get(code_offset()));
}
BreakLocation BreakIterator::GetBreakLocation() {
Handle<AbstractCode> code(
Cast<AbstractCode>(debug_info_->DebugBytecodeArray(isolate())),
isolate());
DebugBreakType type = GetDebugBreakType();
int generator_object_reg_index = -1;
int generator_suspend_id = -1;
if (type == DEBUG_BREAK_SLOT_AT_SUSPEND) {
// For suspend break, we'll need the generator object to be able to step
// over the suspend as if it didn't return. We get the interpreter register
// index that holds the generator object by reading it directly off the
// bytecode array, and we'll read the actual generator object off the
// interpreter stack frame in GetGeneratorObjectForSuspendedFrame.
Tagged<BytecodeArray> bytecode_array =
debug_info_->OriginalBytecodeArray(isolate());
interpreter::BytecodeArrayIterator iterator(
handle(bytecode_array, isolate()), code_offset());
DCHECK_EQ(iterator.current_bytecode(),
interpreter::Bytecode::kSuspendGenerator);
interpreter::Register generator_obj_reg = iterator.GetRegisterOperand(0);
generator_object_reg_index = generator_obj_reg.index();
// Also memorize the suspend ID, to be able to decide whether
// we are paused on the implicit initial yield later.
generator_suspend_id = iterator.GetUnsignedImmediateOperand(3);
}
return BreakLocation(code, type, code_offset(), position_,
generator_object_reg_index, generator_suspend_id);
}
Isolate* BreakIterator::isolate() { return debug_info_->GetIsolate(); }
// Threading support.
void Debug::ThreadInit() {
thread_local_.break_frame_id_ = StackFrameId::NO_ID;
thread_local_.last_step_action_ = StepNone;
thread_local_.last_statement_position_ = kNoSourcePosition;
thread_local_.last_bytecode_offset_ = kFunctionEntryBytecodeOffset;
thread_local_.last_frame_count_ = -1;
thread_local_.fast_forward_to_return_ = false;
thread_local_.ignore_step_into_function_ = Smi::zero();
thread_local_.target_frame_count_ = -1;
thread_local_.return_value_ = Smi::zero();
thread_local_.last_breakpoint_id_ = 0;
clear_restart_frame();
clear_suspended_generator();
base::Relaxed_Store(&thread_local_.current_debug_scope_,
static_cast<base::AtomicWord>(0));
thread_local_.break_on_next_function_call_ = false;
thread_local_.scheduled_break_on_next_function_call_ = false;
UpdateHookOnFunctionCall();
thread_local_.muted_function_ = Smi::zero();
thread_local_.muted_position_ = -1;
}
char* Debug::ArchiveDebug(char* storage) {
MemCopy(storage, reinterpret_cast<char*>(&thread_local_),
ArchiveSpacePerThread());
return storage + ArchiveSpacePerThread();
}
char* Debug::RestoreDebug(char* storage) {
MemCopy(reinterpret_cast<char*>(&thread_local_), storage,
ArchiveSpacePerThread());
// Enter the isolate.
v8::Isolate::Scope isolate_scope(reinterpret_cast<v8::Isolate*>(isolate_));
// Enter the debugger.
DebugScope debug_scope(this);
// Clear any one-shot breakpoints that may have been set by the other
// thread, and reapply breakpoints for this thread.
ClearOneShot();
if (thread_local_.last_step_action_ != StepNone) {
int current_frame_count = CurrentFrameCount();
int target_frame_count = thread_local_.target_frame_count_;
DCHECK(current_frame_count >= target_frame_count);
DebuggableStackFrameIterator frames_it(isolate_);
while (current_frame_count > target_frame_count) {
current_frame_count -= frames_it.FrameFunctionCount();
frames_it.Advance();
}
DCHECK(current_frame_count == target_frame_count);
// Set frame to what it was at Step break
thread_local_.break_frame_id_ = frames_it.frame()->id();
// Reset the previous step action for this thread.
PrepareStep(thread_local_.last_step_action_);
}
return storage + ArchiveSpacePerThread();
}
int Debug::ArchiveSpacePerThread() { return sizeof(ThreadLocal); }
void Debug::Iterate(RootVisitor* v) { Iterate(v, &thread_local_); }
char* Debug::Iterate(RootVisitor* v, char* thread_storage) {
ThreadLocal* thread_local_data =
reinterpret_cast<ThreadLocal*>(thread_storage);
Iterate(v, thread_local_data);
return thread_storage + ArchiveSpacePerThread();
}
void Debug::Iterate(RootVisitor* v, ThreadLocal* thread_local_data) {
v->VisitRootPointer(Root::kDebug, nullptr,
FullObjectSlot(&thread_local_data->return_value_));
v->VisitRootPointer(Root::kDebug, nullptr,
FullObjectSlot(&thread_local_data->suspended_generator_));
v->VisitRootPointer(
Root::kDebug, nullptr,
FullObjectSlot(&thread_local_data->ignore_step_into_function_));
v->VisitRootPointer(Root::kDebug, nullptr,
FullObjectSlot(&thread_local_data->muted_function_));
}
void DebugInfoCollection::Insert(Tagged<SharedFunctionInfo> sfi,
Tagged<DebugInfo> debug_info) {
DisallowGarbageCollection no_gc;
base::SharedMutexGuard<base::kExclusive> mutex_guard(
isolate_->shared_function_info_access());
DCHECK_EQ(sfi, debug_info->shared());
DCHECK(!Contains(sfi));
HandleLocation location =
isolate_->global_handles()->Create(debug_info).location();
list_.push_back(location);
map_.emplace(sfi->unique_id(), location);
DCHECK(Contains(sfi));
DCHECK_EQ(list_.size(), map_.size());
}
bool DebugInfoCollection::Contains(Tagged<SharedFunctionInfo> sfi) const {
auto it = map_.find(sfi->unique_id());
if (it == map_.end()) return false;
DCHECK_EQ(Cast<DebugInfo>(Tagged<Object>(*it->second))->shared(), sfi);
return true;
}
std::optional<Tagged<DebugInfo>> DebugInfoCollection::Find(
Tagged<SharedFunctionInfo> sfi) const {
auto it = map_.find(sfi->unique_id());
if (it == map_.end()) return {};
Tagged<DebugInfo> di = Cast<DebugInfo>(Tagged<Object>(*it->second));
DCHECK_EQ(di->shared(), sfi);
return di;
}
void DebugInfoCollection::DeleteSlow(Tagged<SharedFunctionInfo> sfi) {
DebugInfoCollection::Iterator it(this);
for (; it.HasNext(); it.Advance()) {
Tagged<DebugInfo> debug_info = it.Next();
if (debug_info->shared() != sfi) continue;
it.DeleteNext();
return;
}
UNREACHABLE();
}
Tagged<DebugInfo> DebugInfoCollection::EntryAsDebugInfo(size_t index) const {
DCHECK_LT(index, list_.size());
return Cast<DebugInfo>(Tagged<Object>(*list_[index]));
}
void DebugInfoCollection::DeleteIndex(size_t index) {
base::SharedMutexGuard<base::kExclusive> mutex_guard(
isolate_->shared_function_info_access());
Tagged<DebugInfo> debug_info = EntryAsDebugInfo(index);
Tagged<SharedFunctionInfo> sfi = debug_info->shared();
DCHECK(Contains(sfi));
auto it = map_.find(sfi->unique_id());
HandleLocation location = it->second;
DCHECK_EQ(location, list_[index]);
map_.erase(it);
list_[index] = list_.back();
list_.pop_back();
GlobalHandles::Destroy(location);
DCHECK(!Contains(sfi));
DCHECK_EQ(list_.size(), map_.size());
}
void Debug::Unload() {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
ClearAllBreakPoints();
ClearStepping();
RemoveAllCoverageInfos();
ClearAllDebuggerHints();
debug_delegate_ = nullptr;
}
debug::DebugDelegate::ActionAfterInstrumentation
Debug::OnInstrumentationBreak() {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
if (!debug_delegate_) {
return debug::DebugDelegate::ActionAfterInstrumentation::
kPauseIfBreakpointsHit;
}
DCHECK(in_debug_scope());
HandleScope scope(isolate_);
DisableBreak no_recursive_break(this);
return debug_delegate_->BreakOnInstrumentation(
v8::Utils::ToLocal(isolate_->native_context()), kInstrumentationId);
}
void Debug::Break(JavaScriptFrame* frame,
DirectHandle<JSFunction> break_target) {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
// Just continue if breaks are disabled or debugger cannot be loaded.
if (break_disabled()) return;
// Enter the debugger.
DebugScope debug_scope(this);
DisableBreak no_recursive_break(this);
// Return if we fail to retrieve debug info.
Handle<SharedFunctionInfo> shared(break_target->shared(), isolate_);
if (!EnsureBreakInfo(shared)) return;
PrepareFunctionForDebugExecution(shared);
Handle<DebugInfo> debug_info(TryGetDebugInfo(*shared).value(), isolate_);
// Find the break location where execution has stopped.
BreakLocation location = BreakLocation::FromFrame(debug_info, frame);
const bool hitInstrumentationBreak =
IsBreakOnInstrumentation(debug_info, location);
bool shouldPauseAfterInstrumentation = false;
if (hitInstrumentationBreak) {
debug::DebugDelegate::ActionAfterInstrumentation action =
OnInstrumentationBreak();
switch (action) {
case debug::DebugDelegate::ActionAfterInstrumentation::kPause:
shouldPauseAfterInstrumentation = true;
break;
case debug::DebugDelegate::ActionAfterInstrumentation::
kPauseIfBreakpointsHit:
shouldPauseAfterInstrumentation = false;
break;
case debug::DebugDelegate::ActionAfterInstrumentation::kContinue:
return;
}
}
// Find actual break points, if any, and trigger debug break event.
ClearMutedLocation();
bool has_break_points;
bool scheduled_break =
scheduled_break_on_function_call() || shouldPauseAfterInstrumentation;
MaybeHandle<FixedArray> break_points_hit =
CheckBreakPoints(debug_info, &location, &has_break_points);
if (!break_points_hit.is_null() || break_on_next_function_call() ||
scheduled_break) {
StepAction lastStepAction = last_step_action();
debug::BreakReasons break_reasons;
if (scheduled_break) {
break_reasons.Add(debug::BreakReason::kScheduled);
}
// If it's a debugger statement, add the reason and then mute the location
// so we don't stop a second time.
bool is_debugger_statement = IsBreakOnDebuggerStatement(shared, location);
if (is_debugger_statement) {
break_reasons.Add(debug::BreakReason::kDebuggerStatement);
}
// Clear all current stepping setup.
ClearStepping();
// Notify the debug event listeners.
OnDebugBreak(!break_points_hit.is_null()
? break_points_hit.ToHandleChecked()
: isolate_->factory()->empty_fixed_array(),
lastStepAction, break_reasons);
if (is_debugger_statement) {
// Don't pause here a second time
SetMutedLocation(shared, location);
}
return;
}
// Debug break at function entry, do not worry about stepping.
if (location.IsDebugBreakAtEntry()) {
DCHECK(debug_info->BreakAtEntry());
return;
}
DCHECK_NOT_NULL(frame);
// No break point. Check for stepping.
StepAction step_action = last_step_action();
int current_frame_count = CurrentFrameCount();
int target_frame_count = thread_local_.target_frame_count_;
int last_frame_count = thread_local_.last_frame_count_;
// StepOut at not return position was requested and return break locations
// were flooded with one shots.
if (thread_local_.fast_forward_to_return_) {
// We might hit an instrumentation breakpoint before running into a
// return/suspend location.
DCHECK(location.IsReturnOrSuspend() || hitInstrumentationBreak);
// We have to ignore recursive calls to function.
if (current_frame_count > target_frame_count) return;
ClearStepping();
PrepareStep(StepOut);
return;
}
bool step_break = false;
switch (step_action) {
case StepNone:
if (has_break_points) {
SetMutedLocation(shared, location);
}
return;
case StepOut:
// StepOut should not break in a deeper frame than target frame.
if (current_frame_count > target_frame_count) return;
step_break = true;
break;
case StepOver:
// StepOver should not break in a deeper frame than target frame.
if (current_frame_count > target_frame_count) return;
[[fallthrough]];
case StepInto: {
// StepInto and StepOver should enter "generator stepping" mode, except
// for the implicit initial yield in generators, where it should simply
// step out of the generator function.
if (location.IsSuspend()) {
DCHECK(!has_suspended_generator());
ClearStepping();
if (!IsGeneratorFunction(shared->kind()) ||
location.generator_suspend_id() > 0) {
thread_local_.suspended_generator_ =
location.GetGeneratorObjectForSuspendedFrame(frame);
} else {
PrepareStep(StepOut);
}
return;
}
FrameSummary summary = FrameSummary::GetTop(frame);
const bool frame_or_statement_changed =
current_frame_count != last_frame_count ||
thread_local_.last_statement_position_ !=
summary.SourceStatementPosition();
// If we stayed on the same frame and reached the same bytecode offset
// since the last step, we are in a loop and should pause. Otherwise
// we keep "stepping" through the loop without ever acutally pausing.
const bool potential_single_statement_loop =
current_frame_count == last_frame_count &&
thread_local_.last_bytecode_offset_ == summary.code_offset();
step_break = step_break || location.IsReturn() ||
potential_single_statement_loop ||
frame_or_statement_changed;
break;
}
}
StepAction lastStepAction = last_step_action();
// Clear all current stepping setup.
ClearStepping();
if (step_break) {
// If it's a debugger statement, add the reason and then mute the location
// so we don't stop a second time.
debug::BreakReasons break_reasons;
bool is_debugger_statement = IsBreakOnDebuggerStatement(shared, location);
if (is_debugger_statement) {
break_reasons.Add(debug::BreakReason::kDebuggerStatement);
}
// Notify the debug event listeners.
OnDebugBreak(isolate_->factory()->empty_fixed_array(), lastStepAction,
break_reasons);
if (is_debugger_statement) {
// Don't pause here a second time
SetMutedLocation(shared, location);
}
} else {
// Re-prepare to continue.
PrepareStep(step_action);
}
}
bool Debug::IsBreakOnInstrumentation(Handle<DebugInfo> debug_info,
const BreakLocation& location) {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
bool has_break_points_to_check =
break_points_active_ && location.HasBreakPoint(isolate_, debug_info);
if (!has_break_points_to_check) return {};
DirectHandle<Object> break_points =
debug_info->GetBreakPoints(isolate_, location.position());
DCHECK(!IsUndefined(*break_points, isolate_));
if (!IsFixedArray(*break_points)) {
const auto break_point = Cast<BreakPoint>(break_points);
return break_point->id() == kInstrumentationId;
}
DirectHandle<FixedArray> array(Cast<FixedArray>(*break_points), isolate_);
for (int i = 0; i < array->length(); ++i) {
const auto break_point =
Cast<BreakPoint>(direct_handle(array->get(i), isolate_));
if (break_point->id() == kInstrumentationId) {
return true;
}
}
return false;
}
bool Debug::IsBreakOnDebuggerStatement(
DirectHandle<SharedFunctionInfo> function, const BreakLocation& location) {
if (!function->HasBytecodeArray()) {
return false;
}
Tagged<BytecodeArray> original_bytecode =
function->GetBytecodeArray(isolate_);
interpreter::Bytecode bytecode = interpreter::Bytecodes::FromByte(
original_bytecode->get(location.code_offset()));
return bytecode == interpreter::Bytecode::kDebugger;
}
// Find break point objects for this location, if any, and evaluate them.
// Return an array of break point objects that evaluated true, or an empty
// handle if none evaluated true.
// has_break_points will be true, if there is any (non-instrumentation)
// breakpoint.
MaybeHandle<FixedArray> Debug::CheckBreakPoints(Handle<DebugInfo> debug_info,
BreakLocation* location,
bool* has_break_points) {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
bool has_break_points_to_check =
break_points_active_ && location->HasBreakPoint(isolate_, debug_info);
if (!has_break_points_to_check) {
*has_break_points = false;
return {};
}
return Debug::GetHitBreakPoints(debug_info, location->position(),
has_break_points);
}
bool Debug::IsMutedAtAnyBreakLocation(
DirectHandle<SharedFunctionInfo> function,
const std::vector<BreakLocation>& locations) {
// A break location is considered muted if break locations on the current
// statement have at least one break point, and all of these break points
// evaluate to false. Aside from not triggering a debug break event at the
// break location, we also do not trigger one for debugger statements, nor
// an exception event on exception at this location.
// This should have been computed at last break, and we should just
// check that we are not at that location.
if (IsSmi(thread_local_.muted_function_) ||
*function != thread_local_.muted_function_) {
return false;
}
for (const BreakLocation& location : locations) {
if (location.position() == thread_local_.muted_position_) {
return true;
}
}
return false;
}
#if V8_ENABLE_WEBASSEMBLY
void Debug::SetMutedWasmLocation(DirectHandle<Script> script, int position) {
thread_local_.muted_function_ = *script;
thread_local_.muted_position_ = position;
}
bool Debug::IsMutedAtWasmLocation(Tagged<Script> script, int position) {
return script == thread_local_.muted_function_ &&
position == thread_local_.muted_position_;
}
#endif // V8_ENABLE_WEBASSEMBLY
namespace {
// Convenience helper for easier std::optional translation.
bool ToHandle(Isolate* isolate, std::optional<Tagged<DebugInfo>> debug_info,
Handle<DebugInfo>* out) {
if (!debug_info.has_value()) return false;
*out = handle(debug_info.value(), isolate);
return true;
}
} // namespace
// Check whether a single break point object is triggered.
bool Debug::CheckBreakPoint(DirectHandle<BreakPoint> break_point,
bool is_break_at_entry) {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
HandleScope scope(isolate_);
// Instrumentation breakpoints are handled separately.
if (break_point->id() == kInstrumentationId) {
return false;
}
if (!break_point->condition()->length()) return true;
Handle<String> condition(break_point->condition(), isolate_);
MaybeHandle<Object> maybe_result;
Handle<Object> result;
if (is_break_at_entry) {
maybe_result = DebugEvaluate::WithTopmostArguments(isolate_, condition);
} else {
// Since we call CheckBreakpoint only for deoptimized frame on top of stack,
// we can use 0 as index of inlined frame.
const int inlined_jsframe_index = 0;
const bool throw_on_side_effect = false;
maybe_result =
DebugEvaluate::Local(isolate_, break_frame_id(), inlined_jsframe_index,
condition, throw_on_side_effect);
}
Handle<Object> maybe_exception;
bool exception_thrown = true;
if (maybe_result.ToHandle(&result)) {
exception_thrown = false;
} else if (isolate_->has_exception()) {
maybe_exception = handle(isolate_->exception(), isolate_);
isolate_->clear_exception();
}
CHECK(in_debug_scope());
DisableBreak no_recursive_break(this);
{
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebuggerCallback);
debug_delegate_->BreakpointConditionEvaluated(
v8::Utils::ToLocal(isolate_->native_context()), break_point->id(),
exception_thrown, v8::Utils::ToLocal(maybe_exception));
}
return !result.is_null() ? Object::BooleanValue(*result, isolate_) : false;
}
bool Debug::SetBreakpoint(Handle<SharedFunctionInfo> shared,
DirectHandle<BreakPoint> break_point,
int* source_position) {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
HandleScope scope(isolate_);
// Make sure the function is compiled and has set up the debug info.
if (!EnsureBreakInfo(shared)) return false;
PrepareFunctionForDebugExecution(shared);
Handle<DebugInfo> debug_info(TryGetDebugInfo(*shared).value(), isolate_);
// Source positions starts with zero.
DCHECK_LE(0, *source_position);
// Find the break point and change it.
*source_position = FindBreakablePosition(debug_info, *source_position);
DebugInfo::SetBreakPoint(isolate_, debug_info, *source_position, break_point);
// At least one active break point now.
DCHECK_LT(0, debug_info->GetBreakPointCount(isolate_));
ClearBreakPoints(debug_info);
ApplyBreakPoints(debug_info);
return true;
}
bool Debug::SetBreakPointForScript(Handle<Script> script,
DirectHandle<String> condition,
int* source_position, int* id) {
RCS_SCOPE(isolate_, RuntimeCallCounterId::kDebugger);
*id = ++thread_local_.last_breakpoint_id_;