forked from revng/revng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jumptargetmanager.cpp
1370 lines (1163 loc) · 45.5 KB
/
jumptargetmanager.cpp
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
/// \file jumptargetmanager.cpp
/// \brief This file handles the possible jump targets encountered during
/// translation and the creation and management of the respective
/// BasicBlock.
//
// This file is distributed under the MIT License. See LICENSE.md for details.
//
// Standard includes
#include <cassert>
#include <cstdint>
#include <fstream>
#include <queue>
#include <sstream>
// Boost includes
#include <boost/icl/interval_set.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/icl/right_open_interval.hpp>
// LLVM includes
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Endian.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
// Local includes
#include "datastructures.h"
#include "debug.h"
#include "generatedcodebasicinfo.h"
#include "ir-helpers.h"
#include "jumptargetmanager.h"
#include "revamb.h"
#include "set.h"
#include "simplifycomparisons.h"
#include "subgraph.h"
using namespace llvm;
static bool isSumJump(StoreInst *PCWrite);
char TranslateDirectBranchesPass::ID = 0;
static RegisterPass<TranslateDirectBranchesPass> X("translate-db",
"Translate Direct Branches"
" Pass",
false,
false);
void TranslateDirectBranchesPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addUsedIfAvailable<SETPass>();
AU.setPreservesAll();
}
/// \brief Purges everything is after a call to exitTB (except the call itself)
static void exitTBCleanup(Instruction *ExitTBCall) {
BasicBlock *BB = ExitTBCall->getParent();
// Cleanup everything it's aftewards starting from the end
Instruction *ToDelete = &*(--BB->end());
while (ToDelete != ExitTBCall) {
if (auto DeadBranch = dyn_cast<BranchInst>(ToDelete))
purgeBranch(BasicBlock::iterator(DeadBranch));
else
ToDelete->eraseFromParent();
ToDelete = &*(--BB->end());
}
}
bool TranslateDirectBranchesPass::pinJTs(Function &F) {
const auto *SET = getAnalysisIfAvailable<SETPass>();
if (SET == nullptr || SET->jumps().size() == 0)
return false;
LLVMContext &Context = getContext(&F);
Value *PCReg = JTM->pcReg();
auto *RegType = cast<IntegerType>(PCReg->getType()->getPointerElementType());
auto C = [RegType] (uint64_t A) { return ConstantInt::get(RegType, A); };
BasicBlock *AnyPC = JTM->anyPC();
BasicBlock *UnexpectedPC = JTM->unexpectedPC();
// TODO: enforce CFG
for (const auto &Jump : SET->jumps()) {
StoreInst *PCWrite = Jump.Instruction;
bool Approximate = Jump.Approximate;
const std::vector<uint64_t> &Destinations = Jump.Destinations;
// We don't care if we already handled this call too exitTB in the past,
// information should become progressively more precise, so let's just
// remove everything after this call and put a new handler
CallInst *CallExitTB = JTM->findNextExitTB(PCWrite);
assert(CallExitTB != nullptr);
assert(PCWrite->getParent()->getParent() == &F);
assert(JTM->isPCReg(PCWrite->getPointerOperand()));
assert(Destinations.size() != 0);
auto *ExitTBArg = ConstantInt::get(Type::getInt32Ty(Context),
Destinations.size());
uint64_t OldTargetsCount = getLimitedValue(CallExitTB->getArgOperand(0));
// TODO: we should check Destinations.size() >= OldTargetsCount
// TODO: we should also check the destinations are actually the same
BasicBlock *FailBB = Approximate ? AnyPC : UnexpectedPC;
BasicBlock *BB = CallExitTB->getParent();
// Kill everything is after the call to exitTB
exitTBCleanup(CallExitTB);
// Mark this call to exitTB as handled
CallExitTB->setArgOperand(0, ExitTBArg);
IRBuilder<> Builder(BB);
auto PCLoad = Builder.CreateLoad(PCReg);
if (Destinations.size() == 1) {
auto *Comparison = Builder.CreateICmpEQ(C(Destinations[0]), PCLoad);
Builder.CreateCondBr(Comparison,
JTM->getBlockAt(Destinations[0]),
FailBB);
} else {
auto *Switch = Builder.CreateSwitch(PCLoad, FailBB, Destinations.size());
for (uint64_t Destination : Destinations)
Switch->addCase(C(Destination), JTM->getBlockAt(Destination));
}
// Notify new branches only if the amount of possible targets actually
// increased
if (Destinations.size() > OldTargetsCount)
JTM->newBranch();
}
return true;
}
bool TranslateDirectBranchesPass::pinConstantStore(Function &F) {
auto &Context = F.getParent()->getContext();
Function *ExitTB = JTM->exitTB();
auto ExitTBIt = ExitTB->use_begin();
while (ExitTBIt != ExitTB->use_end()) {
// Take note of the use and increment the iterator immediately: this allows
// us to erase the call to exit_tb without unexpected behaviors
Use &ExitTBUse = *ExitTBIt++;
if (auto Call = dyn_cast<CallInst>(ExitTBUse.getUser())) {
if (Call->getCalledFunction() == ExitTB) {
// Look for the last write to the PC
StoreInst *PCWrite = JTM->getPrevPCWrite(Call);
// Is destination a constant?
if (PCWrite == nullptr) {
forceFallthroughAfterHelper(Call);
} else {
uint64_t NextPC = JTM->getNextPC(PCWrite);
if (NextPC != 0 && JTM->isOSRAEnabled() && isSumJump(PCWrite))
JTM->registerJT(NextPC, JumpTargetManager::SumJump);
auto *Address = dyn_cast<ConstantInt>(PCWrite->getValueOperand());
if (Address != nullptr) {
// Compute the actual PC and get the associated BasicBlock
uint64_t TargetPC = Address->getSExtValue();
auto *TargetBlock = JTM->registerJT(TargetPC,
JumpTargetManager::DirectJump);
// Remove unreachable right after the exit_tb
BasicBlock::iterator CallIt(Call);
BasicBlock::iterator BlockEnd = Call->getParent()->end();
CallIt++;
assert(CallIt != BlockEnd && isa<UnreachableInst>(&*CallIt));
CallIt->eraseFromParent();
// Cleanup of what's afterwards (only a unconditional jump is
// allowed)
CallIt = BasicBlock::iterator(Call);
BlockEnd = Call->getParent()->end();
if (++CallIt != BlockEnd)
purgeBranch(CallIt);
if (TargetBlock != nullptr) {
// A target was found, jump there
BranchInst::Create(TargetBlock, Call);
JTM->newBranch();
} else {
// We're jumping to an invalid location, abort everything
// TODO: emit a warning
CallInst::Create(F.getParent()->getFunction("abort"), { }, Call);
new UnreachableInst(Context, Call);
}
Call->eraseFromParent();
}
}
} else
llvm_unreachable("Unexpected instruction using the PC");
} else
llvm_unreachable("Unhandled usage of the PC");
}
return true;
}
bool TranslateDirectBranchesPass::forceFallthroughAfterHelper(CallInst *Call) {
// If someone else already took care of the situation, quit
if (getLimitedValue(Call->getArgOperand(0)) > 0)
return false;
auto *PCReg = JTM->pcReg();
auto PCRegTy = PCReg->getType()->getPointerElementType();
bool ForceFallthrough = false;
BasicBlock::reverse_iterator It(make_reverse_iterator(Call));
auto *BB = Call->getParent();
auto EndIt = BB->rend();
while (!ForceFallthrough) {
while (It != EndIt) {
Instruction *I = &*It;
if (auto *Store = dyn_cast<StoreInst>(I)) {
if (Store->getPointerOperand() == PCReg) {
// We found a PC-store, give up
return false;
}
} else if (auto *Call = dyn_cast<CallInst>(I)) {
if (Function *Callee = Call->getCalledFunction()) {
if (Callee->getName().startswith("helper_")) {
// We found a call to an helper
ForceFallthrough = true;
break;
}
}
}
It++;
}
if (!ForceFallthrough) {
// Proceed only to unique predecessor, if present
if (auto *Pred = BB->getUniquePredecessor()) {
BB = Pred;
It = BB->rbegin();
EndIt = BB->rend();
} else {
// We have multiple predecessors, give up
return false;
}
}
}
exitTBCleanup(Call);
JTM->newBranch();
IRBuilder<> Builder(Call->getParent());
Call->setArgOperand(0, Builder.getInt32(1));
// Create the fallthrough jump
uint64_t NextPC = JTM->getNextPC(Call);
Value *NextPCConst = Builder.getIntN(PCRegTy->getIntegerBitWidth(), NextPC);
Builder.CreateCondBr(Builder.CreateICmpEQ(Builder.CreateLoad(PCReg),
NextPCConst),
JTM->registerJT(NextPC, JumpTargetManager::PostHelper),
JTM->anyPC());
return true;
}
bool TranslateDirectBranchesPass::runOnFunction(Function &F) {
pinConstantStore(F);
pinJTs(F);
return true;
}
uint64_t TranslateDirectBranchesPass::getNextPC(Instruction *TheInstruction) {
DominatorTree& DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
BasicBlock *Block = TheInstruction->getParent();
BasicBlock::reverse_iterator It(make_reverse_iterator(TheInstruction));
while (true) {
BasicBlock::reverse_iterator Begin(Block->rend());
// Go back towards the beginning of the basic block looking for a call to
// newpc
CallInst *Marker = nullptr;
for (; It != Begin; It++) {
if ((Marker = dyn_cast<CallInst>(&*It))) {
// TODO: comparing strings is not very elegant
if (Marker->getCalledFunction()->getName() == "newpc") {
uint64_t PC = getLimitedValue(Marker->getArgOperand(0));
uint64_t Size = getLimitedValue(Marker->getArgOperand(1));
assert(Size != 0);
return PC + Size;
}
}
}
auto *Node = DT.getNode(Block);
assert(Node != nullptr &&
"BasicBlock not in the dominator tree, is it reachable?" );
Block = Node->getIDom()->getBlock();
It = Block->rbegin();
}
llvm_unreachable("Can't find the PC marker");
}
Optional<uint64_t>
JumpTargetManager::readRawValue(uint64_t Address,
unsigned Size,
Endianess ReadEndianess) const {
bool IsLittleEndian;
if (ReadEndianess == OriginalEndianess) {
IsLittleEndian = Binary.architecture().isLittleEndian();
} else if (ReadEndianess == DestinationEndianess) {
IsLittleEndian = TheModule.getDataLayout().isLittleEndian();
} else {
abort();
}
for (auto &Segment : Binary.segments()) {
// Note: we also consider writeable memory areas because, despite being
// modifiable, can contain useful information
if (Segment.contains(Address, Size) && Segment.IsReadable) {
auto *Array = cast<ConstantDataArray>(Segment.Variable->getInitializer());
StringRef RawData = Array->getRawDataValues();
const unsigned char *RawDataPtr = RawData.bytes_begin();
uint64_t Offset = Address - Segment.StartVirtualAddress;
const unsigned char *Start = RawDataPtr + Offset;
using support::endian::read;
using support::endianness;
switch (Size) {
case 1:
return read<uint8_t, endianness::little, 1>(Start);
case 2:
if (IsLittleEndian)
return read<uint16_t, endianness::little, 1>(Start);
else
return read<uint16_t, endianness::big, 1>(Start);
case 4:
if (IsLittleEndian)
return read<uint32_t, endianness::little, 1>(Start);
else
return read<uint32_t, endianness::big, 1>(Start);
case 8:
if (IsLittleEndian)
return read<uint64_t, endianness::little, 1>(Start);
else
return read<uint64_t, endianness::big, 1>(Start);
default:
assert(false && "Unexpected read size");
}
}
}
return Optional<uint64_t>();
}
Constant *JumpTargetManager::readConstantPointer(Constant *Address,
Type *PointerTy,
Endianess ReadEndianess) {
auto *Value = readConstantInt(Address,
Binary.architecture().pointerSize() / 8,
ReadEndianess);
if (Value != nullptr) {
return ConstantExpr::getIntToPtr(Value, PointerTy);
} else {
return nullptr;
}
}
ConstantInt *JumpTargetManager::readConstantInt(Constant *ConstantAddress,
unsigned Size,
Endianess ReadEndianess) {
const DataLayout &DL = TheModule.getDataLayout();
if (ConstantAddress->getType()->isPointerTy()) {
using CE = ConstantExpr;
auto IntPtrTy = Type::getIntNTy(Context,
Binary.architecture().pointerSize());
ConstantAddress = CE::getPtrToInt(ConstantAddress, IntPtrTy);
}
uint64_t Address = getZExtValue(ConstantAddress, DL);
UnusedCodePointers.erase(Address);
registerReadRange(Address, Size);
auto Result = readRawValue(Address, Size, ReadEndianess);
if (Result.hasValue())
return ConstantInt::get(IntegerType::get(Context, Size * 8),
Result.getValue());
else
return nullptr;
}
template<typename T>
static cl::opt<T> *getOption(StringMap<cl::Option *>& Options,
const char *Name) {
return static_cast<cl::opt<T> *>(Options[Name]);
}
JumpTargetManager::JumpTargetManager(Function *TheFunction,
Value *PCReg,
const BinaryFile &Binary,
bool EnableOSRA) :
TheModule(*TheFunction->getParent()),
Context(TheModule.getContext()),
TheFunction(TheFunction),
OriginalInstructionAddresses(),
JumpTargets(),
PCReg(PCReg),
ExitTB(nullptr),
Dispatcher(nullptr),
DispatcherSwitch(nullptr),
Binary(Binary),
EnableOSRA(EnableOSRA),
NoReturn(Binary.architecture()),
CurrentCFGForm(UnknownFormCFG) {
FunctionType *ExitTBTy = FunctionType::get(Type::getVoidTy(Context),
{ Type::getInt32Ty(Context) },
false);
ExitTB = cast<Function>(TheModule.getOrInsertFunction("exitTB", ExitTBTy));
createDispatcher(TheFunction, PCReg, true);
for (auto &Segment : Binary.segments())
Segment.insertExecutableRanges(std::back_inserter(ExecutableRanges));
initializeSymbolMap();
// Configure GlobalValueNumbering
StringMap<cl::Option *>& Options(cl::getRegisteredOptions());
getOption<bool>(Options, "enable-load-pre")->setInitialValue(false);
getOption<unsigned>(Options, "memdep-block-scan-limit")->setInitialValue(100);
// getOption<bool>(Options, "enable-pre")->setInitialValue(false);
// getOption<uint32_t>(Options, "max-recurse-depth")->setInitialValue(10);
}
void JumpTargetManager::initializeSymbolMap() {
// Collect how many times each name is used
std::map<std::string, unsigned> SeenCount;
for (const SymbolInfo &Symbol : Binary.symbols())
SeenCount[std::string(Symbol.Name)]++;
for (const SymbolInfo &Symbol : Binary.symbols()) {
// Discard symbols pointing to 0, with zero-sized names or present multiple
// times. Note that we keep zero-size symbols.
if (Symbol.Address == 0
|| Symbol.Name.size() == 0
|| SeenCount[std::string(Symbol.Name)] > 1)
continue;
// Associate to this interval the symbol
unsigned Size = std::max(1UL, Symbol.Size);
auto NewInterval = interval::right_open(Symbol.Address,
Symbol.Address + Size);
SymbolMap += make_pair(NewInterval, SymbolInfoSet { &Symbol });
}
}
// TODO: move this in BinaryFile?
std::string JumpTargetManager::nameForAddress(uint64_t Address) const {
std::stringstream Result;
// Take the interval greater than [Address, Address + 1[
auto It = SymbolMap.upper_bound(interval::right_open(Address, Address + 1));
if (It != SymbolMap.begin()) {
// Go back one position
It--;
// In case we have multiple matching symbols, take the closest one
const SymbolInfoSet &Matching = It->second;
auto MaxIt = std::max_element(Matching.begin(), Matching.end());
const SymbolInfo *const BestMatch = *MaxIt;
// Use the symbol name
Result << BestMatch->Name.str();
// And, if necessary, an offset
if (Address != BestMatch->Address)
Result << ".0x" << std::hex << (Address - BestMatch->Address);
} else {
// We don't have a symbol to use, just return the address
Result << "0x" << std::hex << Address;
}
return Result.str();
}
void JumpTargetManager::harvestGlobalData() {
// Register landing pads, if available
// TODO: should register them in UnusedCodePointers?
for (uint64_t LandingPad : Binary.landingPads())
registerJT(LandingPad, GlobalData);
for (auto& Segment : Binary.segments()) {
auto *Data = cast<ConstantDataArray>(Segment.Variable->getInitializer());
uint64_t StartVirtualAddress = Segment.StartVirtualAddress;
const unsigned char *DataStart = Data->getRawDataValues().bytes_begin();
const unsigned char *DataEnd = Data->getRawDataValues().bytes_end();
using endianness = support::endianness;
if (Binary.architecture().pointerSize() == 64) {
if (Binary.architecture().isLittleEndian())
findCodePointers<uint64_t, endianness::little>(StartVirtualAddress,
DataStart,
DataEnd);
else
findCodePointers<uint64_t, endianness::big>(StartVirtualAddress,
DataStart,
DataEnd);
} else if (Binary.architecture().pointerSize() == 32) {
if (Binary.architecture().isLittleEndian())
findCodePointers<uint32_t, endianness::little>(StartVirtualAddress,
DataStart,
DataEnd);
else
findCodePointers<uint32_t, endianness::big>(StartVirtualAddress,
DataStart,
DataEnd);
}
}
DBG("jtcount", dbg
<< "JumpTargets found in global data: " << std::dec
<< Unexplored.size() << "\n");
}
template<typename value_type, unsigned endian>
void JumpTargetManager::findCodePointers(uint64_t StartVirtualAddress,
const unsigned char *Start,
const unsigned char *End) {
using support::endian::read;
using support::endianness;
for (auto Pos = Start; Pos < End - sizeof(value_type); Pos++) {
uint64_t Value = read<value_type,
static_cast<endianness>(endian),
1>(Pos);
BasicBlock *Result = registerJT(Value, GlobalData);
if (Result != nullptr)
UnusedCodePointers.insert(StartVirtualAddress + (Pos - Start));
}
}
/// Handle a new program counter. We might already have a basic block for that
/// program counter, or we could even have a translation for it. Return one of
/// these, if appropriate.
///
/// \param PC the new program counter.
/// \param ShouldContinue an out parameter indicating whether the returned
/// basic block was just a placeholder or actually contains a
/// translation.
///
/// \return the basic block to use from now on, or null if the program counter
/// is not associated to a basic block.
// TODO: make this return a pair
BasicBlock *JumpTargetManager::newPC(uint64_t PC, bool& ShouldContinue) {
// Did we already meet this PC?
auto JTIt = JumpTargets.find(PC);
if (JTIt != JumpTargets.end()) {
// If it was planned to explore it in the future, just to do it now
for (auto UnexploredIt = Unexplored.begin();
UnexploredIt != Unexplored.end();
UnexploredIt++) {
if (UnexploredIt->first == PC) {
auto Result = UnexploredIt->second;
Unexplored.erase(UnexploredIt);
ShouldContinue = true;
assert(Result->empty());
return Result;
}
}
// It wasn't planned to visit it, so we've already been there, just jump
// there
BasicBlock *BB = JTIt->second.head();
assert(!BB->empty());
ShouldContinue = false;
return BB;
}
// Check if we already translated this PC even if it's not associated to a
// basic block (i.e., we have to split its basic block). This typically
// happens with variable-length instruction encodings.
if (OriginalInstructionAddresses.count(PC) != 0) {
ShouldContinue = false;
return registerJT(PC, AmbigousInstruction);
}
// We don't know anything about this PC
return nullptr;
}
/// Save the PC-Instruction association for future use (jump target)
void JumpTargetManager::registerInstruction(uint64_t PC,
Instruction *Instruction) {
// Never save twice a PC
assert(!OriginalInstructionAddresses.count(PC));
OriginalInstructionAddresses[PC] = Instruction;
}
CallInst *JumpTargetManager::findNextExitTB(Instruction *Start) {
CallInst *Result = nullptr;
visitSuccessors(Start,
make_blacklist(*this),
[this,&Result] (BasicBlockRange Range) {
for (Instruction &I : Range) {
if (auto *Call = dyn_cast<CallInst>(&I)) {
assert(!(Call->getCalledFunction()->getName() == "newpc"));
if (Call->getCalledFunction() == ExitTB) {
assert(Result == nullptr);
Result = Call;
return ExhaustQueueAndStop;
}
}
}
return Continue;
});
return Result;
}
StoreInst *JumpTargetManager::getPrevPCWrite(Instruction *TheInstruction) {
// Look for the last write to the PC
BasicBlock::iterator I(TheInstruction);
BasicBlock::iterator Begin(TheInstruction->getParent()->begin());
while (I != Begin) {
I--;
Instruction *Current = &*I;
auto *Store = dyn_cast<StoreInst>(Current);
if (Store != nullptr && Store->getPointerOperand() == PCReg)
return Store;
// If we meet a call to an helper, return nullptr
// TODO: for now we just make calls to helpers, is this is OK even if we
// split the translated function in multiple functions?
if (isa<CallInst>(Current))
return nullptr;
}
// TODO: handle the following case:
// pc = x
// brcond ?, a, b
// a:
// pc = y
// br b
// b:
// exitTB
// TODO: emit warning
return nullptr;
}
// TODO: this is outdated and we should drop it, we now have OSRA and friends
/// \brief Tries to detect pc += register In general, we assume what we're
/// translating is code emitted by a compiler. This means that usually all the
/// possible jump targets are explicit jump to a constant or are stored
/// somewhere in memory (e.g. jump tables and vtables). However, in certain
/// cases, mainly due to handcrafted assembly we can have a situation like the
/// following:
///
/// addne pc, pc, \curbit, lsl #2
///
/// (taken from libgcc ARM's lib1funcs.S, specifically line 592 of
/// `libgcc/config/arm/lib1funcs.S` at commit
/// `f1717362de1e56fe1ffab540289d7d0c6ed48b20`)
///
/// This code basically jumps forward a number of instructions depending on a
/// run-time value. Therefore, without further analysis, potentially, all the
/// coming instructions are jump targets.
///
/// To workaround this issue we use a simple heuristics, which basically
/// consists in making all the coming instructions possible jump targets until
/// the next write to the PC. In the future, we could extend this until the end
/// of the function.
static bool isSumJump(StoreInst *PCWrite) {
// * Follow the written value recursively
// * Is it a `load` or a `constant`? Fine. Don't proceed.
// * Is it an `and`? Enqueue the operands in the worklist.
// * Is it an `add`? Make all the coming instructions jump targets.
//
// This approach has a series of problems:
//
// * It doesn't work with delay slots. Delay slots are handled by libtinycode
// as follows:
//
// jump lr
// store btarget, lr
// store 3, r0
// store 3, r0
// store btarget, pc
//
// Clearly, if we don't follow the loads we miss the situation we're trying
// to handle.
// * It is unclear how this would perform without EarlyCSE and SROA.
std::queue<Value *> WorkList;
WorkList.push(PCWrite->getValueOperand());
while (!WorkList.empty()) {
Value *V = WorkList.front();
WorkList.pop();
if (isa<Constant>(V) || isa<LoadInst>(V)) {
// Fine
} else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) {
switch (BinOp->getOpcode()) {
case Instruction::Add:
case Instruction::Or:
return true;
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::And:
for (auto& Operand : BinOp->operands())
if (!isa<Constant>(Operand.get()))
WorkList.push(Operand.get());
break;
default:
// TODO: emit warning
return false;
}
} else {
// TODO: emit warning
return false;
}
}
return false;
}
std::pair<uint64_t, uint64_t>
JumpTargetManager::getPC(Instruction *TheInstruction) const {
CallInst *NewPCCall = nullptr;
std::set<BasicBlock *> Visited;
std::queue<BasicBlock::reverse_iterator> WorkList;
if (TheInstruction->getIterator() == TheInstruction->getParent()->begin())
WorkList.push(--TheInstruction->getParent()->rend());
else
WorkList.push(make_reverse_iterator(TheInstruction));
while (!WorkList.empty()) {
auto I = WorkList.front();
WorkList.pop();
auto *BB = I->getParent();
auto End = BB->rend();
// Go through the instructions looking for calls to newpc
for (; I != End; I++) {
if (auto Marker = dyn_cast<CallInst>(&*I)) {
// TODO: comparing strings is not very elegant
auto *Callee = Marker->getCalledFunction();
if (Callee != nullptr && Callee->getName() == "newpc") {
// We found two distinct newpc leading to the requested instruction
if (NewPCCall != nullptr)
return { 0, 0 };
NewPCCall = Marker;
break;
}
}
}
// If we haven't find a newpc call yet, continue exploration backward
if (NewPCCall == nullptr) {
// If one of the predecessors is the dispatcher, don't explore any further
for (BasicBlock *Predecessor : predecessors(BB)) {
// Assert we didn't reach the almighty dispatcher
assert(!(NewPCCall == nullptr && Predecessor == Dispatcher));
if (Predecessor == Dispatcher)
continue;
}
for (BasicBlock *Predecessor : predecessors(BB)) {
// Ignore already visited or empty BBs
if (!Predecessor->empty()
&& Visited.find(Predecessor) == Visited.end()) {
WorkList.push(Predecessor->rbegin());
Visited.insert(Predecessor);
}
}
}
}
// Couldn't find the current PC
if (NewPCCall == nullptr)
return { 0, 0 };
uint64_t PC = getLimitedValue(NewPCCall->getArgOperand(0));
uint64_t Size = getLimitedValue(NewPCCall->getArgOperand(1));
assert(Size != 0);
return { PC, Size };
}
void JumpTargetManager::handleSumJump(Instruction *SumJump) {
// Take the next PC
uint64_t NextPC = getNextPC(SumJump);
assert(NextPC != 0);
BasicBlock *BB = registerJT(NextPC, JumpTargetManager::SumJump);
assert(BB && !BB->empty());
std::set<BasicBlock *> Visited;
Visited.insert(Dispatcher);
std::queue<BasicBlock *> WorkList;
WorkList.push(BB);
while (!WorkList.empty()) {
BB = WorkList.front();
Visited.insert(BB);
WorkList.pop();
BasicBlock::iterator I(BB->begin());
BasicBlock::iterator End(BB->end());
while (I != End) {
// Is it a new PC marker?
if (auto *Call = dyn_cast<CallInst>(&*I)) {
Function *Callee = Call->getCalledFunction();
// TODO: comparing strings is not very elegant
if (Callee != nullptr && Callee->getName() == "newpc") {
uint64_t PC = getLimitedValue(Call->getArgOperand(0));
// If we've found a (direct or indirect) jump, stop
if (PC != NextPC)
return;
// Split and update iterators to proceed
BB = registerJT(PC, JumpTargetManager::SumJump);
// Do we have a block?
if (BB == nullptr)
return;
I = BB->begin();
End = BB->end();
// Updated the expectation for the next PC
NextPC = PC + getLimitedValue(Call->getArgOperand(1));
} else if (Call->getCalledFunction() == ExitTB) {
// We've found an unparsed indirect jump
return;
}
}
// Proceed to next instruction
I++;
}
// Inspect and enqueue successors
for (BasicBlock *Successor : successors(BB))
if (Visited.find(Successor) == Visited.end())
WorkList.push(Successor);
}
}
/// \brief Class to iterate over all the BBs associated to a translated PC
class BasicBlockVisitor {
public:
BasicBlockVisitor(const SwitchInst *Dispatcher) :
Dispatcher(Dispatcher),
JumpTargetIndex(0),
JumpTargetsCount(Dispatcher->getNumSuccessors()),
DL(Dispatcher->getParent()->getParent()->getParent()->getDataLayout()) { }
void enqueue(BasicBlock *BB) {
if (Visited.count(BB))
return;
Visited.insert(BB);
uint64_t PC = getPC(BB);
if (PC == 0)
SamePC.push(BB);
else
NewPC.push({ BB, PC });
}
// TODO: this function assumes 0 is not a valid PC
std::pair<BasicBlock *, uint64_t> pop() {
if (!SamePC.empty()) {
auto Result = SamePC.front();
SamePC.pop();
return { Result, 0 };
} else if (!NewPC.empty()) {
auto Result = NewPC.front();
NewPC.pop();
return Result;
} else if (JumpTargetIndex < JumpTargetsCount) {
BasicBlock *BB = Dispatcher->getSuccessor(JumpTargetIndex);
JumpTargetIndex++;
return { BB, getPC(BB) };
} else {
return { nullptr, 0 };
}
}
private:
// TODO: this function assumes 0 is not a valid PC
uint64_t getPC(BasicBlock *BB) {
if (!BB->empty()) {
if (auto *Call = dyn_cast<CallInst>(&*BB->begin())) {
Function *Callee = Call->getCalledFunction();
// TODO: comparing with "newpc" string is sad
if (Callee != nullptr && Callee->getName() == "newpc") {
Constant *PCOperand = cast<Constant>(Call->getArgOperand(0));
return getZExtValue(PCOperand, DL);
}
}
}
return 0;
}
private:
const SwitchInst *Dispatcher;
unsigned JumpTargetIndex;
unsigned JumpTargetsCount;
const DataLayout &DL;
std::set<BasicBlock *> Visited;
std::queue<BasicBlock *> SamePC;
std::queue<std::pair<BasicBlock *, uint64_t>> NewPC;
};
void JumpTargetManager::translateIndirectJumps() {
if (ExitTB->use_empty())
return;
auto I = ExitTB->use_begin();
while (I != ExitTB->use_end()) {
Use& ExitTBUse = *I++;
if (auto *Call = dyn_cast<CallInst>(ExitTBUse.getUser())) {
if (Call->getCalledFunction() == ExitTB) {
// Look for the last write to the PC
StoreInst *PCWrite = getPrevPCWrite(Call);
assert((PCWrite == nullptr
|| !isa<ConstantInt>(PCWrite->getValueOperand()))
&& "Direct jumps should not be handled here");
if (PCWrite != nullptr && EnableOSRA && isSumJump(PCWrite))
handleSumJump(PCWrite);
if (getLimitedValue(Call->getArgOperand(0)) == 0) {
exitTBCleanup(Call);
BranchInst::Create(Dispatcher, Call);
}
Call->eraseFromParent();
}
}
}
}
JumpTargetManager::BlockWithAddress JumpTargetManager::peek() {
harvest();
// Purge all the partial translations we know might be wrong
for (BasicBlock *BB : ToPurge)
purgeTranslation(BB);
ToPurge.clear();
if (Unexplored.empty())
return NoMoreTargets;
else {
BlockWithAddress Result = Unexplored.back();
Unexplored.pop_back();
return Result;
}
}
void JumpTargetManager::unvisit(BasicBlock *BB) {
if (Visited.find(BB) != Visited.end()) {
std::vector<BasicBlock *> WorkList;
WorkList.push_back(BB);
while (!WorkList.empty()) {
BasicBlock *Current = WorkList.back();
WorkList.pop_back();
Visited.erase(Current);
for (BasicBlock *Successor : successors(BB)) {
if (Visited.find(Successor) != Visited.end()
&& !Successor->empty()) {
auto *Call = dyn_cast<CallInst>(&*Successor->begin());
if (Call == nullptr