forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebugger.cpp
More file actions
1299 lines (1158 loc) · 45.5 KB
/
Debugger.cpp
File metadata and controls
1299 lines (1158 loc) · 45.5 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) Facebook, Inc. and its 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/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/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::SwitchImm;
}
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->getFilenameByID(filenameId);
}
/// \return a scope chain containing the block and all its lexical parents,
/// including the global scope.
/// \return none if the scope chain is unavailable.
static llvh::Optional<ScopeChain> scopeChainForBlock(
Runtime *runtime,
const CodeBlock *cb) {
OptValue<uint32_t> lexicalDataOffset = cb->getDebugLexicalDataOffset();
if (!lexicalDataOffset)
return llvh::None;
ScopeChain scopeChain;
RuntimeModule *runtimeModule = cb->getRuntimeModule();
const hbc::BCProvider *bytecode = runtimeModule->getBytecode();
const hbc::DebugInfo *debugInfo = bytecode->getDebugInfo();
while (lexicalDataOffset) {
GCScopeMarkerRAII marker{runtime};
scopeChain.functions.emplace_back();
auto &scopeItem = scopeChain.functions.back();
// Append a new list to the chain.
auto names = debugInfo->getVariableNames(*lexicalDataOffset);
scopeItem.variables.insert(
scopeItem.variables.end(), names.begin(), names.end());
// Get the parent item.
// Stop at the global block.
auto parentId = debugInfo->getParentFunctionId(*lexicalDataOffset);
if (!parentId)
break;
lexicalDataOffset = runtimeModule->getCodeBlockMayAllocate(*parentId)
->getDebugLexicalDataOffset();
if (!lexicalDataOffset) {
// The function has a parent, but the parent doesn't have debug info.
// This could happen when the parent is global.
// "global" doesn't have a lexical parent.
// "global" may have 0 variables, and may have no lexical info
// (which is the case for synthesized parent scopes in lazy compilation).
// In such case, BytecodeFunctionGenerator::hasDebugInfo returns false,
// resulting in no debug offset for global in the bytecode.
// Note that assert "*parentId == bytecode->getGlobalFunctionIndex()"
// will fail because the getGlobalFunctionIndex() function returns
// the entry point instead of the global function. The entry point
// is not the same as the global function in the context of
// lazy compilation.
scopeChain.functions.emplace_back();
}
}
return {std::move(scopeChain)};
}
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(InterpreterState &state) {
auto nextOffset = state.codeBlock->getNextOffset(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());
}
}
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;
}
pauseReason = PauseReason::AsyncTrigger;
} 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;
}
pauseReason = PauseReason::AsyncTrigger;
} else {
assert(runReason == RunReason::Opcode && "Unknown run reason");
// 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_ && "no step to finish");
clearTempBreakpoints();
auto locationOpt = getLocationForState(state);
if (*curStepMode_ == StepMode::Into ||
*curStepMode_ == StepMode::Over) {
// If we're not stepping out, then we need to finish the step
// in progress.
// Otherwise, we just need to stop at the breakpoint site.
while (!locationOpt.hasValue() || locationOpt->statement == 0 ||
sameStatementDifferentInstruction(state, preStepState_)) {
// Move to the next source location.
OpCode curCode = state.codeBlock->getOpCode(state.offset);
if (curCode == OpCode::Ret) {
// We're stepping out now.
breakpointCaller();
pauseOnAllCodeBlocks_ = true;
curStepMode_ = StepMode::Out;
isDebugging_ = false;
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) {
isDebugging_ = false;
return status;
}
locationOpt = getLocationForState(state);
continue;
}
// Set a breakpoint at the next instruction and continue.
breakAtPossibleNextInstructions(state);
if (*curStepMode_ == StepMode::Into) {
pauseOnAllCodeBlocks_ = true;
}
isDebugging_ = false;
return ExecutionStatus::RETURNED;
}
}
// Done stepping.
curStepMode_ = llvh::None;
pauseReason = PauseReason::StepFinish;
} 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->user.hasValue() &&
"must be stopped on a user breakpoint");
const auto &condition =
userBreakpoints_[*breakpointOpt->user].condition;
if (checkBreakpointCondition(condition)) {
pauseReason = PauseReason::Breakpoint;
breakpoint = *(breakpointOpt->user);
} else {
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;
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 = state.codeBlock->getOpCode(state.offset);
if (curCode == OpCode::Ret) {
breakpointCaller();
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) {
state.codeBlock->uninstallBreakpointAtOffset(
state.offset, breakpointOpt->opCode);
}
breakAtPossibleNextInstructions(state);
if (breakpointOpt) {
state.codeBlock->installBreakpointAtOffset(state.offset);
}
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();
status = ExecutionStatus::RETURNED;
}
// Stepping out of here is the same as continuing.
isDebugging_ = false;
curStepMode_ = StepMode::Out;
return status;
}
break;
}
}
}
}
void Debugger::willExecuteModule(RuntimeModule *module, CodeBlock *codeBlock) {
// This function should only be called on the main RuntimeModule and not on
// any "child" RuntimeModules it may create through lazy compilation.
assert(
module == module->getLazyRootModule() &&
"Expected to only run on lazy root module");
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 && userBreakpoints_.size() == 0) {
return;
}
llvh::DenseSet<CodeBlock *> unloadingBlocks;
for (auto *block : module->getFunctionMap()) {
if (block) {
unloadingBlocks.insert(block);
}
}
for (auto &bp : userBreakpoints_) {
if (unloadingBlocks.count(bp.second.codeBlock)) {
unresolveBreakpointLocation(bp.second);
}
}
auto cleanTempBreakpoint = [&](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.user.hasValue() && "Unexpected user breakpoint");
bp.codeBlock->uninstallBreakpointAtOffset(bp.offset, location.opCode);
breakpointLocations_.erase(it);
}
return true;
};
tempBreakpoints_.erase(
std::remove_if(
tempBreakpoints_.begin(),
tempBreakpoints_.end(),
cleanTempBreakpoint),
tempBreakpoints_.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::getStackTrace(InterpreterState state) const -> StackTrace {
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 initial
// one comes from the paused state.
const CodeBlock *codeBlock = state.codeBlock;
uint32_t ipOffset = state.offset;
GCScopeMarkerRAII marker2{runtime_};
for (auto cf : runtime_->getStackFrames()) {
marker2.flush();
CallFrameInfo frameInfo = getCallFrameInfo(codeBlock, ipOffset);
if (auto callableHandle = Handle<Callable>::dyn_vmcast(
Handle<>(&cf.getCalleeClosureOrCBRef()))) {
NamedPropertyDescriptor desc;
propObj = JSObject::getNamedDescriptor(
callableHandle,
runtime_,
Predefined::getSymbolID(Predefined::displayName),
desc);
if (propObj) {
displayName =
JSObject::getNamedSlotValue(propObj.get(), runtime_, desc);
if (displayName->isString()) {
llvh::SmallVector<char16_t, 64> storage;
displayName->getString()->appendUTF16String(storage);
convertUTF16ToUTF8WithReplacements(frameInfo.functionName, storage);
}
}
}
frames.push_back(frameInfo);
codeBlock = cf.getSavedCodeBlock();
const Inst *const savedIP = cf.getSavedIP();
if (!codeBlock && savedIP) {
// 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;
}
}
ipOffset = (codeBlock && savedIP) ? codeBlock->getOffsetOf(savedIP) : 0;
}
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;
if (resolved) {
auto breakpointLoc =
getBreakpointLocation(breakpoint.codeBlock, breakpoint.offset);
if (breakpointLoc.hasValue() && breakpointLoc->user) {
// Don't set duplicate user breakpoint.
return kInvalidBreakpoint;
}
breakpointId = nextBreakpointId_++;
setUserBreakpoint(breakpoint.codeBlock, breakpoint.offset, breakpointId);
} else {
breakpointId = nextBreakpointId_++;
}
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);
}
userBreakpoints_.erase(it);
}
void Debugger::deleteAllBreakpoints() {
for (auto &it : userBreakpoints_) {
auto &breakpoint = it.second;
if (breakpoint.enabled && breakpoint.isResolved()) {
unsetUserBreakpoint(breakpoint);
}
}
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);
}
}
}
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 &location =
breakpointLocations_
.try_emplace(codeBlock->getOffsetPtr(offset), opcodes[offset])
.first->second;
if (location.count() == 0) {
// count used to be 0, so patch this in now that the count > 0.
codeBlock->installBreakpointAtOffset(offset);
}
return location;
}
void Debugger::setUserBreakpoint(
CodeBlock *codeBlock,
uint32_t offset,
BreakpointID id) {
BreakpointLocation &location = installBreakpoint(codeBlock, offset);
location.user = id;
}
void Debugger::setStepBreakpoint(
CodeBlock *codeBlock,
uint32_t offset,
uint32_t callStackDepth) {
BreakpointLocation &location = installBreakpoint(codeBlock, offset);
// 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.callStackDepths.count(callStackDepth) == 0 &&
"can't set duplicate Step breakpoint");
location.callStackDepths.insert(callStackDepth);
tempBreakpoints_.push_back(breakpoint);
}
void Debugger::setOnLoadBreakpoint(CodeBlock *codeBlock, uint32_t offset) {
BreakpointLocation &location = installBreakpoint(codeBlock, offset);
// 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) {
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.user && "no user breakpoints to unset");
location.user = llvh::None;
if (location.count() == 0) {
// No more reason to keep this location around.
// Unpatch it from the opcode stream and delete it from the map.
codeBlock->uninstallBreakpointAtOffset(offset, location.opCode);
breakpointLocations_.erase(offsetPtr);
}
}
void Debugger::setEntryBreakpointForCodeBlock(CodeBlock *codeBlock) {
assert(!codeBlock->isLazy() && "can't set breakpoint on a lazy codeblock");
assert(
pauseOnAllCodeBlocks_ && "can't set temp breakpoint while not stepping");
setStepBreakpoint(codeBlock, 0, 0);
}
void Debugger::breakpointCaller() {
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->getNextOffset(codeBlock->getOffsetOf(ip));
setStepBreakpoint(codeBlock, offset, 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::clearTempBreakpoints() {
llvh::SmallVector<const Inst *, 4> toErase{};
for (const auto &breakpoint : tempBreakpoints_) {
auto *codeBlock = breakpoint.codeBlock;
auto offset = breakpoint.offset;
const Inst *inst = codeBlock->getOffsetPtr(offset);
auto it = breakpointLocations_.find(inst);
if (it == breakpointLocations_.end()) {
continue;
}
auto &location = it->second;
if (location.count()) {
location.callStackDepths.clear();
location.onLoad = false;
if (location.count() == 0) {
codeBlock->uninstallBreakpointAtOffset(offset, location.opCode);
toErase.push_back(inst);
}
}
}
for (const Inst *inst : toErase) {
breakpointLocations_.erase(inst);
}
tempBreakpoints_.clear();
pauseOnAllCodeBlocks_ = false;
}
ExecutionStatus Debugger::stepInstruction(InterpreterState &state) {
auto *codeBlock = state.codeBlock;
uint32_t offset = state.offset;
assert(
codeBlock->getOpCode(offset) != OpCode::Ret &&
"can't stepInstruction in Ret, use step-out semantics instead");
assert(
shouldSingleStep(codeBlock->getOpCode(offset)) &&
"can't stepInstruction through Call, use step-in semantics instead");
auto locationOpt = getBreakpointLocation(codeBlock, offset);
ExecutionStatus status;
InterpreterState newState{state};
if (locationOpt.hasValue()) {
// Temporarily uninstall the breakpoint so we can run the real instruction.
codeBlock->uninstallBreakpointAtOffset(offset, locationOpt->opCode);
status = runtime_->stepFunction(newState);
codeBlock->installBreakpointAtOffset(offset);
} else {
status = runtime_->stepFunction(newState);
}
if (status != ExecutionStatus::EXCEPTION)
state = newState;
return status;
}
auto Debugger::getLexicalInfoInFrame(uint32_t frame) const -> LexicalInfo {
auto frameInfo = runtime_->stackFrameInfoByIndex(frame);
assert(frameInfo && "Invalid frame");
LexicalInfo result;
if (frameInfo->isGlobal) {
// Globals not yet supported.
// TODO: support them. For now we have an empty entry for the global scope.
result.variableCountsByScope_.push_back(0);
return result;
}
const CodeBlock *cb = frameInfo->frame->getCalleeCodeBlock();
if (!cb) {
// Native functions have no saved code block.
result.variableCountsByScope_.push_back(0);
return result;
}
auto scopeChain = scopeChainForBlock(runtime_, cb);
if (!scopeChain) {
// Binary was compiled without variable debug info.
result.variableCountsByScope_.push_back(0);
return result;
}
for (const auto &func : scopeChain->functions) {
result.variableCountsByScope_.push_back(func.variables.size());
}
return result;
}
HermesValue Debugger::getVariableInFrame(
uint32_t frame,
uint32_t scopeDepth,
uint32_t variableIndex,
std::string *outName) const {
GCScope gcScope{runtime_};
auto frameInfo = runtime_->stackFrameInfoByIndex(frame);
assert(frameInfo && "Invalid frame");
const HermesValue undefined = HermesValue::encodeUndefinedValue();
// Clear the outgoing info so we don't leave stale data there.
if (outName)
outName->clear();
if (frameInfo->isGlobal) {
// Globals not yet supported.
// TODO: support them.
return undefined;
}
const CodeBlock *cb = frameInfo->frame->getCalleeCodeBlock();
assert(cb && "Unexpectedly null code block");
auto scopeChain = scopeChainForBlock(runtime_, cb);
if (!scopeChain) {
// Binary was compiled without variable debug info.
return undefined;
}
const ScopeChainItem &item = scopeChain->functions.at(scopeDepth);
if (outName)
*outName = item.variables.at(variableIndex);
// Descend the environment chain to the desired depth, or stop at null.
// We may get a null environment if it has not been created.
MutableHandle<Environment> env(
runtime_, frameInfo->frame->getDebugEnvironment());
for (uint32_t i = 0; env && i < scopeDepth; i++)
env = env->getParentEnvironment(runtime_);
// Now we can get the variable, or undefined if we have no environment.
return env ? env->slot(variableIndex) : undefined;
}
HermesValue Debugger::getThisValue(uint32_t frame) const {
const auto frameInfo = runtime_->stackFrameInfoByIndex(frame);
assert(frameInfo && "Invalid frame");
if (frameInfo->isGlobal) {
// "this" value in the global frame is the global object.
return runtime_->getGlobal().getHermesValue();
}
return frameInfo->frame.getThisArgRef();
}
HermesValue Debugger::getExceptionAsEvalResult(
EvalResultMetadata *outMetadata) {
outMetadata->isException = true;
Handle<> thrownValue = runtime_->makeHandle(runtime_->getThrownValue());
assert(!thrownValue->isEmpty() && "Runtime did not throw");
runtime_->clearThrownValue();
// Set the exceptionDetails.text to toString_RJS() of the thrown value.
// TODO: rationalize what should happen if toString_RJS() itself throws.
auto res = toString_RJS(runtime_, thrownValue);
if (res != ExecutionStatus::EXCEPTION) {
llvh::SmallVector<char16_t, 64> errorText;
res->get()->appendUTF16String(errorText);
convertUTF16ToUTF8WithReplacements(
outMetadata->exceptionDetails.text, errorText);
}
// Try to fetch the stack trace. It may not exist; for example, if the
// exception was a parse error in eval(), then the exception will be set
// directly and the stack trace will not be collected.
if (auto errorHandle = Handle<JSError>::dyn_vmcast(thrownValue)) {
if (auto stackTracePtr = errorHandle->getStackTrace()) {
// Copy the stack trace to ensure it's not moved out from under us.
const auto stackTraceCopy = *stackTracePtr;
std::vector<CallFrameInfo> frames;
frames.reserve(stackTraceCopy.size());
for (const StackTraceInfo &sti : stackTraceCopy)
frames.push_back(getCallFrameInfo(sti.codeBlock, sti.bytecodeOffset));