-
Notifications
You must be signed in to change notification settings - Fork 792
Expand file tree
/
Copy pathDebugger.cpp
More file actions
1696 lines (1516 loc) · 59.2 KB
/
Debugger.cpp
File metadata and controls
1696 lines (1516 loc) · 59.2 KB
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 (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifdef HERMES_ENABLE_DEBUGGER
#include "hermes/VM/Debugger/Debugger.h"
#include "hermes/BCGen/HBC/HBC.h"
#include "hermes/Inst/InstDecode.h"
#include "hermes/Support/UTF8.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/CodeBlock.h"
#include "hermes/VM/JSError.h"
#include "hermes/VM/JSLib.h"
#include "hermes/VM/Operations.h"
#include "hermes/VM/Profiler/SamplingProfiler.h"
#include "hermes/VM/Runtime.h"
#include "hermes/VM/RuntimeModule.h"
#include "hermes/VM/StackFrame-inline.h"
#include "hermes/VM/StringView.h"
#ifdef HERMES_ENABLE_DEBUGGER
namespace hermes {
namespace vm {
using namespace hermes::inst;
namespace fhd = ::facebook::hermes::debugger;
// These instructions won't recursively invoke the interpreter,
// and we also can't easily determine where they will jump to.
static inline bool shouldSingleStep(OpCode opCode) {
return opCode == OpCode::Throw || opCode == OpCode::UIntSwitchImm ||
opCode == OpCode::StringSwitchImm;
}
static StringView getFunctionName(
Runtime &runtime,
const CodeBlock *codeBlock) {
auto functionName = codeBlock->getNameMayAllocate();
if (functionName == Predefined::getSymbolID(Predefined::emptyString)) {
functionName = Predefined::getSymbolID(Predefined::anonymous);
}
return runtime.getIdentifierTable().getStringView(runtime, functionName);
}
static std::string getFileNameAsUTF8(
Runtime &runtime,
RuntimeModule *runtimeModule,
uint32_t filenameId) {
const auto *debugInfo = runtimeModule->getBytecode()->getDebugInfo();
return debugInfo->getUTF8FilenameByID(filenameId);
}
void Debugger::triggerAsyncPause(AsyncPauseKind kind) {
runtime_.triggerDebuggerAsyncBreak(kind);
}
llvh::Optional<uint32_t> Debugger::findJumpTarget(
CodeBlock *block,
uint32_t offset) {
const Inst *ip = block->getOffsetPtr(offset);
#define DEFINE_JUMP_LONG_VARIANT(name, nameLong) \
case OpCode::name: { \
return offset + ip->i##name.op1; \
} \
case OpCode::nameLong: { \
return offset + ip->i##nameLong.op1; \
}
switch (ip->opCode) {
#include "hermes/BCGen/HBC/BytecodeList.def"
default:
return llvh::None;
}
#undef DEFINE_JUMP_LONG_VARIANT
}
void Debugger::breakAtPossibleNextInstructions(const InterpreterState &state) {
auto nextOffset =
state.offset + getInstSize(getRealOpCode(state.codeBlock, state.offset));
// Set a breakpoint at the next instruction in the code block if this is not
// the last instruction.
if (nextOffset < state.codeBlock->getOpcodeArray().size()) {
setStepBreakpoint(
state.codeBlock, nextOffset, runtime_.getCurrentFrameOffset());
}
// If the instruction is a jump, set a break point at the possible
// jump target; otherwise, only break at the next instruction.
// This instruction could jump to itself, so this step should be after the
// previous step (otherwise the Jmp will have been overwritten by a Debugger
// inst, and we won't be able to find the target).
//
// Since we've already set a breakpoint on the next instruction, we can
// skip the case where that is also the jump target.
auto jumpTarget = findJumpTarget(state.codeBlock, state.offset);
if (jumpTarget.hasValue() && jumpTarget.getValue() != nextOffset) {
setStepBreakpoint(
state.codeBlock,
jumpTarget.getValue(),
runtime_.getCurrentFrameOffset());
}
}
inst::OpCode Debugger::getRealOpCode(CodeBlock *block, uint32_t offset) const {
auto breakpointOpt = getBreakpointLocation(block, offset);
if (breakpointOpt) {
const auto *inst =
reinterpret_cast<const inst::Inst *>(&(breakpointOpt->opCode));
return inst->opCode;
}
auto opcodes = block->getOpcodeArray();
assert(offset < opcodes.size() && "opCode offset out of bounds");
const auto *inst = reinterpret_cast<const inst::Inst *>(&opcodes[offset]);
return inst->opCode;
}
ExecutionStatus Debugger::runDebugger(
Debugger::RunReason runReason,
InterpreterState &state) {
assert(!isDebugging_ && "can't run debugger while debugging is in progress");
isDebugging_ = true;
// We're going to derive a PauseReason to pass to the event observer. OptValue
// is used to check our logic which is rather complicated.
OptValue<PauseReason> pauseReason;
// If the pause reason warrants it, this is set to be a valid breakpoint ID.
BreakpointID breakpoint = fhd::kInvalidBreakpoint;
if (runReason == RunReason::Exception) {
// We hit an exception, report that we broke because of this.
if (isUnwindingException_) {
// We're currently unwinding an exception, so don't stop here
// because we must have already reported the exception.
isDebugging_ = false;
return ExecutionStatus::EXCEPTION;
}
isUnwindingException_ = true;
clearTempBreakpoints();
pauseReason = PauseReason::Exception;
} else if (runReason == RunReason::AsyncBreakImplicit) {
if (curStepMode_.hasValue()) {
// Avoid draining the queue or corrupting step state.
isDebugging_ = false;
return ExecutionStatus::RETURNED;
}
auto res = runUntilValidPauseLocation(state);
if (res == ExecutionStatus::EXCEPTION) {
return res.getStatus();
}
if (!*res) {
// If we shouldn't run the debugger loop (because we're about to return,
// call, e.g.)
asyncTriggerPauseReason_ = PauseReason::AsyncTriggerImplicit;
return ExecutionStatus::RETURNED;
}
pauseReason = PauseReason::AsyncTriggerImplicit;
} else if (runReason == RunReason::AsyncBreakExplicit) {
// The user requested an async break, so we can clear stepping state
// with the knowledge that the inspector isn't sending an immediate
// continue.
if (curStepMode_) {
clearTempBreakpoints();
curStepMode_ = llvh::None;
}
auto res = runUntilValidPauseLocation(state);
if (res == ExecutionStatus::EXCEPTION) {
return res.getStatus();
}
if (!*res) {
// If we shouldn't run the debugger loop (because we're about to return,
// call, e.g.)
asyncTriggerPauseReason_ = PauseReason::AsyncTriggerExplicit;
return ExecutionStatus::RETURNED;
}
pauseReason = PauseReason::AsyncTriggerExplicit;
} else {
assert(runReason == RunReason::Opcode && "Unknown run reason");
// Whether we breakpoint on all CodeBlocks, or breakpoint caller, they'll
// eventually hit the installed Debugger OpCode and get here. We need to
// restore any breakpoint that we delayed restoring in
// processInstUnderDebuggerOpCode().
if (restoreBreakpointIfAny()) {
// And if we do get here and restored a breakpoint, it means that we're
// stopping here because of the Restoration breakpoint we added from
// pauseOnAllCodeBlocksToRestoreBreakpoint_ or breakpointCaller(). Clear
// them out because we're not reliant on them to handle any stepping.
clearRestorationBreakpoints();
// If after clearing Restoration breakpoints, there is no longer a
// breakpoint at the current location, then that means there isn't any
// user or temp breakpoint at this location. If the instruction is also
// not an actual debugger statement, then we can just exit out of the
// debugger loop.
auto breakpointOpt = getBreakpointLocation(state.codeBlock, state.offset);
OpCode curCode = getRealOpCode(state.codeBlock, state.offset);
if (!breakpointOpt.hasValue() && curCode != OpCode::Debugger) {
isDebugging_ = false;
return ExecutionStatus::RETURNED;
}
}
// First, check if we have to finish a step that's in progress.
auto breakpointOpt = getBreakpointLocation(state.codeBlock, state.offset);
if (breakpointOpt.hasValue() &&
(breakpointOpt->hasStepBreakpoint || breakpointOpt->onLoad)) {
// We've hit a Step, which must mean we were stepping, or
// pause-on-load if it's the first instruction of the global function.
if (breakpointOpt->onLoad) {
pauseReason = PauseReason::ScriptLoaded;
clearTempBreakpoints();
} else if (
breakpointOpt->callStackDepths.count(0) ||
breakpointOpt->callStackDepths.count(
runtime_.getCurrentFrameOffset())) {
// This is in fact a temp breakpoint we want to stop on right now.
assert(
(curStepMode_ || asyncTriggerPauseReason_) && "no step to finish");
clearTempBreakpoints();
// We need to finish the step in progress. After receiving a STEP
// command in a previous debuggerLoop execution, we might still have a
// step to finish. So now that runDebugger is executing again, we need
// to finish the step to get to a known instruction with debug location
// in order to begin the debuggerLoop again.
auto res = runUntilValidPauseLocation(state);
if (res == ExecutionStatus::EXCEPTION || !*res) {
// If we hit an exception, or we shouldn't run the debugger loop
// (because we're about to return, call, e.g.)
return res.getStatus();
}
// Continue to run the debugger loop.
// Done stepping.
pauseReason =
curStepMode_ ? PauseReason::StepFinish : *asyncTriggerPauseReason_;
curStepMode_ = llvh::None;
asyncTriggerPauseReason_ = llvh::None;
} else {
// We don't want to stop on this Step breakpoint.
isDebugging_ = false;
return ExecutionStatus::RETURNED;
}
} else {
auto checkBreakpointCondition =
[&](const std::string &condition) -> bool {
if (condition.empty()) {
// The empty condition is considered unset,
// and we always pause on such breakpoints.
return true;
}
EvalResultMetadata metadata;
EvalArgs args;
args.frameIdx = 0;
// No handle here - we will only pass the value to toBoolean,
// and no allocations should occur until then.
HermesValue conditionResult =
evalInFrame(args, condition, state, &metadata);
NoAllocScope noAlloc(runtime_);
if (metadata.isException) {
// Ignore exceptions.
// Cleanup is done by evalInFrame.
return false;
}
noAlloc.release();
return toBoolean(conditionResult);
};
// We've stopped on either a user breakpoint or a debugger statement.
// Note: if we've stopped on both (breakpoint set on a debugger statement)
// then we only report the breakpoint and move past it,
// ignoring the debugger statement.
if (breakpointOpt.hasValue()) {
assert(
!breakpointOpt->userBreakpointIDs.empty() &&
"must be stopped on a user breakpoint");
// Evaluate conditions in creation order, short-circuiting on first
// true.
bool shouldPause = false;
for (BreakpointID id : breakpointOpt->userBreakpointIDs) {
const auto &condition = userBreakpoints_[id].condition;
if (checkBreakpointCondition(condition)) {
pauseReason = PauseReason::Breakpoint;
breakpoint = id;
shouldPause = true;
break;
}
}
if (!shouldPause) {
isDebugging_ = false;
return ExecutionStatus::RETURNED;
}
} else {
pauseReason = PauseReason::DebuggerStatement;
}
// Stop stepping immediately.
if (curStepMode_) {
// If we're in a step, then the client still thinks we're debugging,
// so just clear the status and clear the temp breakpoints.
curStepMode_ = llvh::None;
clearTempBreakpoints();
}
}
}
assert(pauseReason.hasValue() && "runDebugger failed to set PauseReason");
return debuggerLoop(state, *pauseReason, breakpoint);
}
ExecutionStatus Debugger::debuggerLoop(
InterpreterState &state,
PauseReason pauseReason,
BreakpointID breakpoint) {
const InterpreterState startState = state;
const bool startException = pauseReason == PauseReason::Exception;
EvalResultMetadata evalResultMetadata;
CallResult<InterpreterState> result{ExecutionStatus::EXCEPTION};
GCScope gcScope{runtime_};
MutableHandle<> evalResult{runtime_};
// Keep the evalResult alive, even if all other handles are flushed.
static constexpr unsigned KEEP_HANDLES = 1;
#if HERMESVM_SAMPLING_PROFILER_AVAILABLE
SuspendSamplingProfilerRAII ssp{
runtime_, SamplingProfiler::SuspendFrameInfo::Kind::Debugger};
#endif // HERMESVM_SAMPLING_PROFILER_AVAILABLE
while (true) {
GCScopeMarkerRAII marker{runtime_};
auto command = getNextCommand(
state, pauseReason, *evalResult, evalResultMetadata, breakpoint);
evalResult.clear();
switch (command.type) {
case DebugCommandType::NONE:
break;
case DebugCommandType::CONTINUE:
isDebugging_ = false;
curStepMode_ = llvh::None;
return ExecutionStatus::RETURNED;
case DebugCommandType::EVAL:
evalResult = evalInFrame(
command.evalArgs, command.text, startState, &evalResultMetadata);
pauseReason = PauseReason::EvalComplete;
break;
case DebugCommandType::STEP: {
// If we pause again in this function, it will be due to a step.
pauseReason = PauseReason::StepFinish;
const StepMode stepMode = command.stepArgs.mode;
// We should only be able to step from instructions with recorded
// locations.
const auto startLocationOpt = getLocationForState(state);
(void)startLocationOpt;
assert(
startLocationOpt.hasValue() &&
"starting step from a location without debug info");
preStepState_ = state;
if (stepMode == StepMode::Into || stepMode == StepMode::Over) {
if (startException) {
// Paused because of a throw or we're about to throw.
// Breakpoint the handler if it's there, and continue.
breakpointExceptionHandler(state);
isDebugging_ = false;
curStepMode_ = stepMode;
return ExecutionStatus::RETURNED;
}
while (true) {
// NOTE: this loop doesn't actually allocate any handles presently,
// but it could, and clearing all handles is really cheap.
gcScope.flushToSmallCount(KEEP_HANDLES);
OpCode curCode = getRealOpCode(state.codeBlock, state.offset);
if (curCode == OpCode::Ret) {
breakpointCaller(/*forRestorationBreakpoint*/ false);
pauseOnAllCodeBlocks_ = true;
isDebugging_ = false;
// Equivalent to a step out.
curStepMode_ = StepMode::Out;
return ExecutionStatus::RETURNED;
}
// These instructions won't recursively invoke the interpreter,
// and we also can't easily determine where they will jump to,
// so use single-step mode.
if (shouldSingleStep(curCode)) {
ExecutionStatus status = stepInstruction(state);
if (status == ExecutionStatus::EXCEPTION) {
breakpointExceptionHandler(state);
isDebugging_ = false;
curStepMode_ = stepMode;
return status;
}
auto locationOpt = getLocationForState(state);
if (locationOpt.hasValue() && locationOpt->statement != 0 &&
!sameStatementDifferentInstruction(state, preStepState_)) {
// We've moved on from the statement that was executing.
break;
}
continue;
}
// Set a breakpoint at the next instruction and continue.
// If there is a user installed breakpoint, we need to temporarily
// uninstall the breakpoint so that we can get the correct
// offset for the next instruction.
auto breakpointOpt =
getBreakpointLocation(state.codeBlock, state.offset);
if (breakpointOpt) {
uninstallBreakpoint(
state.codeBlock, state.offset, breakpointOpt->opCode);
}
breakAtPossibleNextInstructions(state);
if (breakpointOpt) {
// Re-installing a previously-installed breakpoint: the page is
// already known writable.
bool ok =
state.codeBlock->installBreakpointAtOffset(state.offset);
(void)ok;
assert(ok && "re-installing existing breakpoint cannot fail");
}
if (stepMode == StepMode::Into) {
// Stepping in could enter another code block,
// so handle that by breakpointing all code blocks.
pauseOnAllCodeBlocks_ = true;
}
isDebugging_ = false;
curStepMode_ = stepMode;
return ExecutionStatus::RETURNED;
}
} else {
ExecutionStatus status;
if (startException) {
breakpointExceptionHandler(state);
status = ExecutionStatus::EXCEPTION;
} else {
breakpointCaller(/*forRestorationBreakpoint*/ false);
status = ExecutionStatus::RETURNED;
}
// Stepping out of here is the same as continuing.
isDebugging_ = false;
curStepMode_ = StepMode::Out;
return status;
}
break;
}
}
}
}
CallResult<bool> Debugger::runUntilValidPauseLocation(InterpreterState &state) {
auto locationOpt = getLocationForState(state);
// Stop if we're already at a valid location.
// If we're in the middle of an actual step, continue if the location
// information doesn't indicate that we're at the next step-finish point.
// Conditioned on curStepMode_ because this may be called during AsyncTrigger
// trying to find a good place to stop.
while (!locationOpt.hasValue() ||
(curStepMode_ &&
(locationOpt->statement == 0 ||
sameStatementDifferentInstruction(state, preStepState_)))) {
// Move to the next source location.
OpCode curCode = getRealOpCode(state.codeBlock, state.offset);
if (curCode == OpCode::Ret) {
// We're stepping out now.
breakpointCaller(/*forRestorationBreakpoint*/ false);
pauseOnAllCodeBlocks_ = true;
curStepMode_ = StepMode::Out;
isDebugging_ = false;
return false;
}
// These instructions won't recursively invoke the interpreter,
// and we also can't easily determine where they will jump to,
// so use single-step mode.
if (shouldSingleStep(curCode)) {
ExecutionStatus status = stepInstruction(state);
if (status == ExecutionStatus::EXCEPTION) {
breakpointExceptionHandler(state);
isDebugging_ = false;
return ExecutionStatus::EXCEPTION;
}
locationOpt = getLocationForState(state);
continue;
}
// Set a breakpoint at the next instruction and continue.
breakAtPossibleNextInstructions(state);
if (curStepMode_ && *curStepMode_ == StepMode::Into) {
pauseOnAllCodeBlocks_ = true;
}
isDebugging_ = false;
return false;
}
assert(locationOpt.hasValue());
return true;
}
void Debugger::willExecuteModule(RuntimeModule *module, CodeBlock *codeBlock) {
if (!getShouldPauseOnScriptLoad())
return;
// We want to pause on the first instruction of this module.
// Add a breakpoint on the first opcode of its global function.
auto globalFunctionIndex = module->getBytecode()->getGlobalFunctionIndex();
auto globalCode = module->getCodeBlockMayAllocate(globalFunctionIndex);
setOnLoadBreakpoint(globalCode, 0);
}
void Debugger::willUnloadModule(RuntimeModule *module) {
if (tempBreakpoints_.size() == 0 && restorationBreakpoints_.size() == 0 &&
userBreakpoints_.size() == 0) {
return;
}
llvh::DenseSet<CodeBlock *> unloadingBlocks;
for (const auto &block : module->getFunctionMap()) {
if (block) {
unloadingBlocks.insert(block.get());
}
}
for (auto &bp : userBreakpoints_) {
if (unloadingBlocks.count(bp.second.codeBlock)) {
unresolveBreakpointLocation(bp.second, bp.first);
}
}
auto cleanNonUserBreakpoint = [&](Breakpoint &bp) {
if (!unloadingBlocks.count(bp.codeBlock))
return false;
auto *ptr = bp.codeBlock->getOffsetPtr(bp.offset);
auto it = breakpointLocations_.find(ptr);
if (it != breakpointLocations_.end()) {
auto &location = it->second;
assert(
location.userBreakpointIDs.empty() && "Unexpected user breakpoint");
uninstallBreakpoint(bp.codeBlock, bp.offset, location.opCode);
breakpointLocations_.erase(it);
}
return true;
};
tempBreakpoints_.erase(
std::remove_if(
tempBreakpoints_.begin(),
tempBreakpoints_.end(),
cleanNonUserBreakpoint),
tempBreakpoints_.end());
restorationBreakpoints_.erase(
std::remove_if(
restorationBreakpoints_.begin(),
restorationBreakpoints_.end(),
cleanNonUserBreakpoint),
restorationBreakpoints_.end());
}
void Debugger::resolveBreakpoints(CodeBlock *codeBlock) {
for (auto &it : userBreakpoints_) {
auto &breakpoint = it.second;
if (!breakpoint.isResolved()) {
resolveBreakpointLocation(breakpoint);
if (breakpoint.isResolved() && breakpoint.enabled) {
setUserBreakpoint(breakpoint.codeBlock, breakpoint.offset, it.first);
if (breakpointResolvedCallback_) {
breakpointResolvedCallback_(it.first);
}
}
}
}
}
auto Debugger::getCallFrameInfo(const CodeBlock *codeBlock, uint32_t ipOffset)
const -> CallFrameInfo {
GCScopeMarkerRAII marker{runtime_};
CallFrameInfo frameInfo;
if (!codeBlock) {
frameInfo.functionName = "(native)";
} else {
// The caller doesn't expect that this function is allocating new handles,
// so make sure we aren't.
GCScopeMarkerRAII gcMarker{runtime_};
llvh::SmallVector<char16_t, 64> storage;
UTF16Ref functionName =
getFunctionName(runtime_, codeBlock).getUTF16Ref(storage);
convertUTF16ToUTF8WithReplacements(frameInfo.functionName, functionName);
auto locationOpt = codeBlock->getSourceLocation(ipOffset);
if (locationOpt) {
frameInfo.location.line = locationOpt->line;
frameInfo.location.column = locationOpt->column;
frameInfo.location.fileId = resolveScriptId(
codeBlock->getRuntimeModule(), locationOpt->filenameId);
frameInfo.location.fileName = getFileNameAsUTF8(
runtime_, codeBlock->getRuntimeModule(), locationOpt->filenameId);
}
}
return frameInfo;
}
auto Debugger::getNativeCallFrameInfo(const SHUnit *unit, SHSrcLoc loc) const
-> CallFrameInfo {
CallFrameInfo frameInfo;
// If unit is nonnull then we have a valid location and can use the fields
// in loc. Otherwise, it is an unknown location.
if (unit) {
// TODO: Set the function name if we have it.
frameInfo.functionName = "(native)";
frameInfo.location.line = loc.line;
frameInfo.location.column = loc.column;
frameInfo.location.fileId = unit->script_id;
} else {
frameInfo.functionName = "(native)";
}
return frameInfo;
}
auto Debugger::getStackTrace() const -> StackTrace {
// It's ok for the frame to be a native frame (i.e. null CodeBlock and null
// IP), but there must be a frame.
assert(
runtime_.getCurrentFrame() &&
"Must have at least one stack frame to call this function");
using fhd::CallFrameInfo;
GCScopeMarkerRAII marker{runtime_};
MutableHandle<> displayName{runtime_};
MutableHandle<JSObject> propObj{runtime_};
std::vector<CallFrameInfo> frames;
// Note that we are iterating backwards from the top.
// Also note that each frame saves its caller's code block and IP (the
// SavedCodeBlock and SavedIP). We obtain the current code location by getting
// the Callee CodeBlock of the top frame.
const CodeBlock *codeBlock = runtime_.getCurrentFrame()->getCalleeCodeBlock();
const inst::Inst *ip = runtime_.getCurrentIP();
GCScopeMarkerRAII marker2{runtime_};
for (auto cf : runtime_.getStackFrames()) {
marker2.flush();
uint32_t ipOffset = (codeBlock && ip) ? codeBlock->getOffsetOf(ip) : 0;
CallFrameInfo frameInfo = getCallFrameInfo(codeBlock, ipOffset);
if (auto callableHandle = Handle<Callable>::dyn_vmcast(
Handle<>(&cf.getCalleeClosureOrCBRef()))) {
NamedPropertyDescriptor desc;
propObj = JSObject::getNamedDescriptorPredefined(
callableHandle, runtime_, Predefined::displayName, desc);
if (propObj) {
auto displayNameRes = JSObject::getNamedSlotValue(
createPseudoHandle(*propObj), runtime_, desc);
if (LLVM_UNLIKELY(displayNameRes == ExecutionStatus::EXCEPTION)) {
displayName = HermesValue::encodeUndefinedValue();
} else {
displayName = std::move(*displayNameRes);
if (displayName->isString()) {
llvh::SmallVector<char16_t, 64> storage;
displayName->getString()->appendUTF16String(storage);
convertUTF16ToUTF8WithReplacements(frameInfo.functionName, storage);
}
}
}
}
frames.push_back(frameInfo);
codeBlock = cf.getSavedCodeBlock();
ip = cf.getSavedIP();
if (!codeBlock && ip) {
// If we have a saved IP but no saved code block, this was a bound call.
// Go up one frame and get the callee code block but use the current
// frame's saved IP.
StackFramePtr prev = cf->getPreviousFrame();
assert(prev && "bound function calls must have a caller");
if (CodeBlock *parentCB = prev->getCalleeCodeBlock()) {
codeBlock = parentCB;
}
}
}
return StackTrace(std::move(frames));
}
auto Debugger::createBreakpoint(const SourceLocation &loc) -> BreakpointID {
using fhd::kInvalidBreakpoint;
OptValue<hbc::DebugSearchResult> locationOpt{llvh::None};
Breakpoint breakpoint{};
breakpoint.requestedLocation = loc;
// Breakpoints are enabled by default.
breakpoint.enabled = true;
bool resolved = resolveBreakpointLocation(breakpoint);
BreakpointID breakpointId = nextBreakpointId_++;
if (resolved) {
setUserBreakpoint(breakpoint.codeBlock, breakpoint.offset, breakpointId);
}
userBreakpoints_[breakpointId] = std::move(breakpoint);
return breakpointId;
}
void Debugger::setBreakpointCondition(BreakpointID id, std::string condition) {
auto it = userBreakpoints_.find(id);
if (it == userBreakpoints_.end()) {
return;
}
auto &breakpoint = it->second;
breakpoint.condition = std::move(condition);
}
void Debugger::deleteBreakpoint(BreakpointID id) {
auto it = userBreakpoints_.find(id);
if (it == userBreakpoints_.end()) {
return;
}
auto &breakpoint = it->second;
if (breakpoint.enabled && breakpoint.isResolved()) {
unsetUserBreakpoint(breakpoint, id);
}
userBreakpoints_.erase(it);
}
void Debugger::deleteAllBreakpoints() {
for (auto &it : userBreakpoints_) {
auto &breakpoint = it.second;
if (breakpoint.enabled && breakpoint.isResolved()) {
unsetUserBreakpoint(breakpoint, it.first);
}
}
userBreakpoints_.clear();
}
void Debugger::setBreakpointEnabled(BreakpointID id, bool enable) {
auto it = userBreakpoints_.find(id);
if (it == userBreakpoints_.end()) {
return;
}
auto &breakpoint = it->second;
if (enable && !breakpoint.enabled) {
breakpoint.enabled = true;
if (breakpoint.isResolved()) {
setUserBreakpoint(breakpoint.codeBlock, breakpoint.offset, id);
}
} else if (!enable && breakpoint.enabled) {
breakpoint.enabled = false;
if (breakpoint.isResolved()) {
unsetUserBreakpoint(breakpoint, id);
}
}
}
llvh::Optional<const Debugger::BreakpointLocation>
Debugger::getBreakpointLocation(CodeBlock *codeBlock, uint32_t offset) const {
return getBreakpointLocation(codeBlock->getOffsetPtr(offset));
}
auto Debugger::installBreakpoint(CodeBlock *codeBlock, uint32_t offset)
-> BreakpointLocation * {
auto opcodes = codeBlock->getOpcodeArray();
assert(offset < opcodes.size() && "invalid offset to set breakpoint");
auto *opcodePtr = codeBlock->getOffsetPtr(offset);
auto emplaceResult =
breakpointLocations_.try_emplace(opcodePtr, opcodes[offset]);
auto &location = emplaceResult.first->second;
if (location.count() == 0) {
// count used to be 0, so patch this in now that the count > 0.
if (!codeBlock->installBreakpointAtOffset(offset)) {
// Patching failed (e.g. statically embedded bytecode in a read-only
// segment that the OS refuses to remap). Roll back the entry we just
// inserted so state stays consistent, and signal failure to caller.
if (emplaceResult.second) {
breakpointLocations_.erase(emplaceResult.first);
}
return nullptr;
}
}
return &location;
}
void Debugger::uninstallBreakpoint(
CodeBlock *codeBlock,
uint32_t offset,
hbc::opcode_atom_t opCode) {
// Check to see if we had temporarily kept the breakpoint uninstalled. If we
// already did, and it's to be removed, then we don't need to restore it
// anymore.
if (breakpointToRestore_.first == codeBlock &&
breakpointToRestore_.second == offset) {
breakpointToRestore_ = {nullptr, 0};
} else {
codeBlock->uninstallBreakpointAtOffset(offset, opCode);
}
}
bool Debugger::setUserBreakpoint(
CodeBlock *codeBlock,
uint32_t offset,
BreakpointID id) {
BreakpointLocation *location = installBreakpoint(codeBlock, offset);
if (!location) {
return false;
}
location->userBreakpointIDs.insert(id);
return true;
}
void Debugger::doSetNonUserBreakpoint(
CodeBlock *codeBlock,
uint32_t offset,
uint32_t callStackDepth,
bool isStepBreakpoint) {
BreakpointLocation *location = installBreakpoint(codeBlock, offset);
if (!location) {
// Best-effort: step/restoration breakpoints are an optimization for
// pause-on-entry while stepping. If the target lives in a read-only
// bytecode segment we cannot patch, just skip it -- stepping will simply
// not pause at the entry of that code block.
return;
}
std::vector<Breakpoint> &breakpoints =
isStepBreakpoint ? tempBreakpoints_ : restorationBreakpoints_;
if (location->callStackDepths.count(callStackDepth) == 0) {
location->callStackDepths.insert(callStackDepth);
}
if ((isStepBreakpoint && !location->hasStepBreakpoint) ||
(!isStepBreakpoint && !location->hasRestorationBreakpoint)) {
// Leave the resolved location empty for now,
// let the caller fill it in lazily.
Breakpoint breakpoint{};
breakpoint.codeBlock = codeBlock;
breakpoint.offset = offset;
breakpoint.enabled = true;
breakpoints.push_back(breakpoint);
}
if (isStepBreakpoint) {
location->hasStepBreakpoint = true;
} else {
location->hasRestorationBreakpoint = true;
}
}
void Debugger::setStepBreakpoint(
CodeBlock *codeBlock,
uint32_t offset,
uint32_t callStackDepth) {
doSetNonUserBreakpoint(
codeBlock, offset, callStackDepth, /*isStepBreakpoint*/ true);
}
void Debugger::setOnLoadBreakpoint(CodeBlock *codeBlock, uint32_t offset) {
BreakpointLocation *location = installBreakpoint(codeBlock, offset);
if (!location) {
// Best-effort: pauseOnScriptLoad cannot pause inside a code block whose
// bytecode page is not writable. Skip.
return;
}
// Leave the resolved location empty for now,
// let the caller fill it in lazily.
Breakpoint breakpoint{};
breakpoint.codeBlock = codeBlock;
breakpoint.offset = offset;
breakpoint.enabled = true;
assert(!location->onLoad && "can't set duplicate on-load breakpoint");
location->onLoad = true;
tempBreakpoints_.push_back(breakpoint);
assert(location->count() && "invalid count following set breakpoint");
}
void Debugger::unsetUserBreakpoint(
const Breakpoint &breakpoint,
BreakpointID id) {
#ifndef NDEBUG
auto it = userBreakpoints_.find(id);
assert(
it != userBreakpoints_.end() && &it->second == &breakpoint &&
"ID must map to the provided breakpoint");
#endif
CodeBlock *codeBlock = breakpoint.codeBlock;
uint32_t offset = breakpoint.offset;
auto opcodes = codeBlock->getOpcodeArray();
(void)opcodes;
assert(offset < opcodes.size() && "invalid offset to set breakpoint");
const Inst *offsetPtr = codeBlock->getOffsetPtr(offset);
auto locIt = breakpointLocations_.find(offsetPtr);
assert(
locIt != breakpointLocations_.end() &&
"can't unset a non-existent breakpoint");
auto &location = locIt->second;
assert(!location.userBreakpointIDs.empty() && "no user breakpoints to unset");
bool removed = location.userBreakpointIDs.remove(id);
assert(removed && "breakpoint ID not found in user set");
(void)removed;
if (location.count() == 0) {
// No more reason to keep this location around.
// Unpatch it from the opcode stream and delete it from the map.
uninstallBreakpoint(codeBlock, offset, location.opCode);
breakpointLocations_.erase(offsetPtr);
}
}
void Debugger::setEntryBreakpointForCodeBlock(CodeBlock *codeBlock) {
assert(!codeBlock->isLazy() && "can't set breakpoint on a lazy codeblock");
assert(
(pauseOnAllCodeBlocks_ || pauseOnAllCodeBlocksToRestoreBreakpoint_) &&
"can't set temp breakpoint while not stepping");
if (pauseOnAllCodeBlocks_) {
setStepBreakpoint(codeBlock, 0, 0);
}
if (pauseOnAllCodeBlocksToRestoreBreakpoint_) {
setRestorationBreakpoint(codeBlock, 0, 0);
}
}
void Debugger::breakpointCaller(bool forRestorationBreakpoint) {
auto callFrames = runtime_.getStackFrames();
assert(callFrames.begin() != callFrames.end() && "empty call stack");
// Go through the callStack backwards to find the first place we can break.
auto frameIt = callFrames.begin();
const Inst *ip = nullptr;
for (; frameIt != callFrames.end(); ++frameIt) {
ip = frameIt->getSavedIP();
if (ip) {
break;
}
}
if (!ip) {
return;
}
// If the ip was saved in the stack frame, the caller is the function
// that we want to return to. The code block might not be saved in this
// frame, so we need to find that in the frame below.
do {
frameIt++;
assert(
frameIt != callFrames.end() &&
"The frame that has saved ip cannot be the bottom frame");
} while (!frameIt->getCalleeCodeBlock());
// In the frame below, the 'calleeClosureORCB' register contains
// the code block we need.
CodeBlock *codeBlock = frameIt->getCalleeCodeBlock();
assert(codeBlock && "The code block must exist since we have ip");
// Track the call stack depth that the breakpoint would be set on.
uint32_t offset = codeBlock->getOffsetOf(ip);
uint32_t newOffset = offset + getInstSize(getRealOpCode(codeBlock, offset));
if (forRestorationBreakpoint) {
setRestorationBreakpoint(
codeBlock, newOffset, runtime_.calcFrameOffset(frameIt));
} else {
setStepBreakpoint(codeBlock, newOffset, runtime_.calcFrameOffset(frameIt));
}
}
void Debugger::breakpointExceptionHandler(const InterpreterState &state) {
auto target = findCatchTarget(state);
if (!target) {
return;
}
auto *codeBlock = target->first.codeBlock;
auto offset = target->first.offset;
setStepBreakpoint(codeBlock, offset, target->second);
}
void Debugger::doClearNonUserBreakpoints(bool isStepBreakpoint) {
llvh::SmallVector<const Inst *, 4> toErase{};
std::vector<Breakpoint> &breakpointsToClear =
isStepBreakpoint ? tempBreakpoints_ : restorationBreakpoints_;
for (const auto &breakpoint : breakpointsToClear) {
auto *codeBlock = breakpoint.codeBlock;
auto offset = breakpoint.offset;
const Inst *inst = codeBlock->getOffsetPtr(offset);