-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutoPatchFirstPass.cpp
executable file
·806 lines (642 loc) · 30.9 KB
/
AutoPatchFirstPass.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
// AutoPatch Instrument tool
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include <cxxabi.h>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/IR/Dominators.h"
using namespace llvm;
using namespace std;
#define __DEBUG__
// Output strings for debugging
std::string debug_str;
raw_string_ostream debug(debug_str);
// Strings for output
std::string output_str;
raw_string_ostream output(output_str);
// Define command line options
cl::opt<bool> IsPatched("is-patched",
cl::desc("Specify if the code is patched"),
cl::init(true)); // Set default value to true
cl::list<int> LineNumPatch("line-num-patch",
cl::CommaSeparated,
cl::desc("Specify the line numbers of patch"),
cl::value_desc("line numbers"));
cl::opt<std::string> FuncPatchName("func-patch-name",
cl::desc("Specify the name of the function to patch"),
cl::value_desc("function name"),
cl::init(""));
// Demangles the function name.
std::string demangle(const char *name) {
int status = -1;
std::unique_ptr<char, void (*)(void *)> res{
abi::__cxa_demangle(name, NULL, NULL, &status), std::free};
return (status == 0) ? res.get() : std::string(name);
}
void topoSortBBs(Function *F) {
vector<BasicBlock *> tempBB;
//debug<<"PrintFunction:" << F->print() << "\n";
for (scc_iterator<Function *> I = scc_begin(F), IE = scc_end(F); I != IE;
++I) {
// debug << "New SSC " <<"\n";
// Obtain the vector of BBs in this SCC and print it out.
const std::vector<BasicBlock *> &SCCBBs = *I;
for (std::vector<BasicBlock *>::const_iterator BBI = SCCBBs.begin(),
BBIE = SCCBBs.end();
BBI != BBIE; ++BBI) {
BasicBlock *b = const_cast<llvm::BasicBlock *>(*BBI);
tempBB.push_back(b);
for (BasicBlock::const_iterator It = b->begin(); It != b->end(); ++It) {
Instruction *ins = const_cast<llvm::Instruction *>(&*It);
// debug << "Instr: " << *ins <<"\n";
}
// debug<<"----------------BB endd--------------\n";
}
}
reverse(tempBB.begin(), tempBB.end());
//return tempBB;
}
// Returns the source code line number cooresponding to the LLVM instruction.
// Returns -1 if the instruction has no associated Metadata.
int getSourceCodeLine(Instruction *I) {
// Get debugInfo associated with every instruction.
llvm::DebugLoc debugInfo = I->getDebugLoc();
int line = -1;
if (debugInfo)
line = debugInfo.getLine();
return line;
}
namespace {
struct AutoPatchFirstPass : public ModulePass{
int trampolineNum = 0;
//FunctionCallee hookFunc;
//Function *hook;
static char ID;
AutoPatchFirstPass() : ModulePass(ID) {}
bool oneTimeAnalyzeLoop = true;
//std::string funcPatchName = "dummy_buggy_MQTT_packet_length_decode";
//std::string funcPatchName = "infoTransfer";
//std::string funcPatchName = "shell_spaces_trim";
// Get from USERS:
bool isPatched = IsPatched;
std::vector<int> lineNumPatch;
std::string funcPatchName = FuncPatchName;
virtual bool runOnModule(Module &M) override
{
//debug << "Start Instrumenting ...." << "\n";
if(isPatched){
lineNumPatch = LineNumPatch;
}
//iterate over the module (means iterate over functions)
for(Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
{
oneTimeAnalyzeLoop = true;
// iterate over the basicblocks whithin the function
for(Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
{
Function *func = const_cast<llvm::Function *>(&*F);
BasicBlock *BB_tempif = const_cast<llvm::BasicBlock *>(&*BB);
//topoSortBBs(func);
//****************NEW***************//
std::string funcName = demangle(func->getName().str().c_str());
// debug << "The function is " << funcName << "\n";
if (funcName == funcPatchName) { // If you insert a new function as a patch, we should not insert trampoline to it.
debug << "The Function belongs to the patch!" << "\n";
break;
}
//******At the beggining of the function****//
if (BB == F->begin()){
BasicBlock *BB_Entry = &(func->getEntryBlock());
AutoPatchFirstPass::runOnFunction(BB_Entry,M,func);//Done (I think)
}
//******After Function Calls****//
AutoPatchFirstPass::runOnBasicBlock(BB, M, func);
//******After Dynamic Loops****// //******After Complex Loops (Nested Loops)****//
if(oneTimeAnalyzeLoop){
oneTimeAnalyzeLoop = false;
//LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>(*func).getLoopInfo();
identifyNestedloops(func, M);//Done (I think)
//instrumentDynamicLoops(LI, M, func); //Working on that
//***********After Nested If*********//
identifyNestedif(func,M);
//identifyNestedif2(func, M);
}
}//End of iterate on basic blocks
}//End of iterate on functions
string Result = "Number of inserted Trampolines: " + to_string(trampolineNum) + "\n";
debug << Result;
#ifdef __DEBUG__
errs() << debug.str();
#endif
debug.flush();
errs() << output.str();
output.flush();
return false;
}
// void identifyNestedif2(Function *func, Module &M){
// for(Function::iterator BB = func->begin(), E = func->end(); BB != E; ++BB){
// for(BasicBlock::iterator I = BB->begin(), BE = BB->end(); I != BE; ++I){
// Instruction *ins = const_cast<llvm::Instruction *>(&*I);
// if(auto *br=dyn_cast<BranchInst>(ins)){
// if(!br->isConditional()){
// continue;
// }
// BasicBlock *ifTrue = br->getSuccessor(0);
// BasicBlock *ifFalse = br->getSuccessor(1);
// for (auto &II : *ifTrue) {
// if (auto *brInner = dyn_cast<BranchInst>(&II)) {
// if (!brInner->isConditional()) {
// continue;
// }
// errs() << "Found nested if statement in function "
// << func->getName() << "\n";
// IRBuilder<> IRB(ifTrue->getFirstNonPHI());
// auto Fn = func->getParent()->getOrInsertFunction(
// "TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
// IRB.CreateCall(Fn);
// trampolineNum++;
// //return false;
// }
// }
// for (auto &II : *ifFalse) {
// if (auto *brInner = dyn_cast<BranchInst>(&II)) {
// if (!brInner->isConditional()) {
// continue;
// }
// errs() << "Found nested if statement in function "
// << func->getName() << "\n";
// IRBuilder<> IRB(ifFalse->getFirstNonPHI());
// auto Fn = func->getParent()->getOrInsertFunction(
// "TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
// IRB.CreateCall(Fn);
// trampolineNum++;
// //return false;
// }
// }
// }
// }
// }
// }
bool seeNested = false;
void identifyNestedif(Function *func, Module &M){
for(Function::iterator BB = func->begin(), E = func->end(); BB != E; ++BB){
//for(BasicBlock::iterator BlI = BB->begin(), BE = BB->end(); BlI != BE; ++BlI)
//{
//debug <<"The block name is " << BB->getName() <<"\n";
StringRef BBName = BB->getName();
string BBName_temp = demangle(BBName.str().c_str());
if (BBName_temp.find("if.then") != std::string::npos){
if(seeNested){
// For cheking: if this instruction belongs to a patch, Do not insert trampoline to that part!
Instruction *instemp = BB->getFirstNonPHI();
// debug << "1 " << *instemp << "\n";
if(isPatched){
int CIlineNum = getSourceCodeLine(instemp);
bool isLineNumInPatch = std::find(std::begin(lineNumPatch), std::end(lineNumPatch), CIlineNum) != std::end(lineNumPatch);
if(isLineNumInPatch){
debug << "This instruction " << *instemp << "belongs to a patch! \n";
continue;
}
}
//**//
IRBuilder<> IRB(BB->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}else{
for(BasicBlock::iterator BlI = BB->begin(), BE = BB->end(); BlI != BE; ++BlI)
{
Instruction *ins = const_cast<llvm::Instruction *>(&*BlI);
//debug <<"Instruction is " << *ins <<"\n";
std::string str;
llvm::raw_string_ostream rso(str);
ins->print(rso);
std::size_t found = str.find("then");
if (found != std::string::npos) {
// debug << "2 \n";
//debug <<"Instruction is " << *ins <<"\n";
//This is a nested if statement
// debug<<"This is a nested if statement\n";
// For cheking: if this instruction belongs to a patch, Do not insert trampoline to that part!
Instruction *instemp = BB->getFirstNonPHI();
// debug << "1 " << *instemp << "\n";
if(isPatched){
int CIlineNum = getSourceCodeLine(instemp);
bool isLineNumInPatch = std::find(std::begin(lineNumPatch), std::end(lineNumPatch), CIlineNum) != std::end(lineNumPatch);
if(isLineNumInPatch){
debug << "This instruction " << *instemp << "belongs to a patch! \n";
continue;
}
}
//**//
IRBuilder<> IRB(BB->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
seeNested = true;
trampolineNum++;
}
}
}
}else if(seeNested){
if(BBName_temp.find("if") != std::string::npos){
// debug << "3 \n";
// For cheking: if this instruction belongs to a patch, Do not insert trampoline to that part!
Instruction *instemp = BB->getFirstNonPHI();
// debug << "1 " << *instemp << "\n";
if(isPatched){
int CIlineNum = getSourceCodeLine(instemp);
bool isLineNumInPatch = std::find(std::begin(lineNumPatch), std::end(lineNumPatch), CIlineNum) != std::end(lineNumPatch);
if(isLineNumInPatch){
debug << "This instruction " << *instemp << "belongs to a patch! \n";
continue;
}
}
//**//
IRBuilder<> IRB(BB->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
}
// Instruction *ins = const_cast<llvm::Instruction *>(&*BlI);
// //For function calls
// if (BranchInst *BI = dyn_cast<BranchInst>(&*ins)) {
// //debug <<"The if: "<<*BI<<"\n";
// if (BI->isConditional()) {
// BasicBlock *Successor = BI->getSuccessor(0);
// //if(Successor->getTerminator()->getOpcode() == Instruction::Br){
// // debug <<"This is Exit Block. Do No thing.\n";
// //}else{
// for (Instruction &InnerI : *Successor) {
// debug <<"Instruction is " << InnerI <<"\n";
// if (BranchInst *InnerBI = dyn_cast<BranchInst>(&InnerI)) {
// if (InnerBI->isConditional()) {
// // This is a nested if statement
// //debug<<"This is " << *InnerBI << " a nested if statement\n";
// IRBuilder<> IRB(InnerBI->getParent()->getFirstNonPHI());
// auto Fn = func->getParent()->getOrInsertFunction(
// "TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
// IRB.CreateCall(Fn);
// }
// }
// }
// //}
// }
// }
}
}
//}
void identifyNestedloops(Function *func, Module &M){ //****add dynamic loops here not seperate
llvm::DominatorTree DT = llvm::DominatorTree(*func);
bool isDynamic = false;
bool hasBranch = false;
//DT.recalculate(func);
auto loopinfo = new llvm::LoopInfoBase<llvm::BasicBlock, llvm::Loop>();
unordered_set<BasicBlock *> checkedSingleSuccessorSet;
loopinfo->releaseMemory();
loopinfo->analyze(DT);
// debug << "Finding Nested Loops \n";
for(auto li = loopinfo->begin(), le = loopinfo->end(); li != le; ++li){
// debug<<"Size of the loop " <<(*li)->getSubLoops().size() << " and " << (*li)->getLoopDepth() << "\n";
if((*li)->getSubLoops().size() != 0){
// debug<<"Nested Loop is here " <<(*li)->getSubLoops().size() << "\n";
//*********** I think we also have to add trampoline at the beggining of this type of loops ****//
//*************NEW PART*************//
if((*li)->getHeader() != NULL){
// debug<<"Inserted inside the nested loop.\n";
auto *BB_Header = (*li)->getHeader();
IRBuilder<> IRB(BB_Header->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
//*********** We also have to add trampoline at the beggining of the loops that are inside this loops ****//
for (auto *Loop : (*li)->getSubLoops()) {
debug<<" Going forward and inserted inside the nested loops.\n";
auto *BB_Header = Loop->getHeader();
IRBuilder<> IRB(BB_Header->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
//***********//
//debug << "ExitBlock for nested loop: " << *(*li)->getUniqueExitBlock() << "," << *(*li)->getExitBlock() <<"\n";
if((*li)->getUniqueExitBlock() != NULL){//One Exit Basic Block
IRBuilder<> IRB((*li)->getUniqueExitBlock());
IRB.SetInsertPoint(((*li)->getUniqueExitBlock())->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
else if((*li)->hasNoExitBlocks()){
// debug<<"It is infinite nested loop, " << "No BasicBlock" << "\n" ;
}
else{//(Multiple Basic Blocks)
// debug<<"It is NULL, " << "Multiple BasicBlocks"<< "\n" ;
SmallVector<BasicBlock *> ExitBlocks;
(*li)->getExitBlocks(ExitBlocks);
for (auto *Block : ExitBlocks){
// debug<<"The basicblock: " << Block->front() << "\n" ;
//debug<<"Successor of " << Block << ": " << Block->getSingleSuccessor() << "\n" ;
if(Block->getSingleSuccessor() != NULL){
if(checkedSingleSuccessorSet.find(Block->getSingleSuccessor()) == checkedSingleSuccessorSet.end()){//
// debug<<"This is the new Successor" << "\n" ;
BasicBlock *tempBB = Block->getSingleSuccessor();
checkedSingleSuccessorSet.insert(tempBB);
IRBuilder<> IRB(tempBB);
//debug<<"The Instruction point: " << tempBB->getFirstNonPHI() << "\n" ;
IRB.SetInsertPoint(tempBB->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}else{
// debug<<"This is not the new Successor" << "\n" ;
continue;
}
}
else{
IRBuilder<> IRB(Block);
// debug<<"The Instruction point: " << Block->getFirstNonPHI() << "\n" ;
IRB.SetInsertPoint(Block->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
}
}
}//End "if" for nested loops
else{
// debug<<"It is not Nested Loop\n";
if((*li)->hasNoExitBlocks()){
// debug<<"It is infinite unnested loop, " << "No BasicBlock" << "\n" ;
}
else{
//********Here we have to analyze the loop for "is it dynamic loop or static?"****//
// debug << "I am HERE! " << (*li)->getLoopDepth() << "\n";
BasicBlock *BB_temp1 = (*li)->getHeader();
BasicBlock *BB_temp2 = (*li)->getLoopLatch();
Instruction* I = BB_temp1->getFirstNonPHI();
Instruction* I_do = BB_temp2->getFirstNonPHI();//For "do" loop. It is reverse compare to "while" and "for" loop.
if (isa<llvm::LoadInst>(I)) {
LoadInst *LI_temp = cast<LoadInst>(I);
LoadInst *LI_temp_do = cast<LoadInst>(I_do);
//debug<<"Dynamic loop: "<< LI_temp->getType()->isPointerTy() << "Instruction is: " << *LI_temp << "\n";
//debug<<"Dynamic do loop: "<< LI_temp_do->getType()->isPointerTy() << "Instruction is: " << *LI_temp_do << "\n";
if(LI_temp->getType()->isPointerTy()){
//This is dynamic loop
isDynamic = true;
IRBuilder<> IRB(BB_temp2);
//debug<<"The Instruction point: " << *(BB_temp2->getFirstNonPHI()) << "\n" ;
IRB.SetInsertPoint(BB_temp2->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
//***********************************///
///Repeat from Nested Loop (for exit block) ***** I think it is the same *****//
if((*li)->getUniqueExitBlock() != NULL){//One Exit Basic Block
IRBuilder<> IRB((*li)->getUniqueExitBlock());
IRB.SetInsertPoint(((*li)->getUniqueExitBlock())->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
else if((*li)->hasNoExitBlocks()){
// debug<<"It is infinite nested loop, " << "No BasicBlock" << "\n" ;
}
else{//(Multiple Basic Blocks) ********Is this correct and works?!!********
// debug<<"It is NULL, " << "Multiple BasicBlocks"<< "\n" ;
SmallVector<BasicBlock *> ExitBlocks;
(*li)->getExitBlocks(ExitBlocks);
for (auto *Block : ExitBlocks){
// debug<<"The basicblock: " << Block->front() << "\n" ;
//debug<<"Successor of " << Block << ": " << Block->getSingleSuccessor() << "\n" ;
if(Block->getSingleSuccessor() != NULL){
if(checkedSingleSuccessorSet.find(Block->getSingleSuccessor()) == checkedSingleSuccessorSet.end()){//
// debug<<"This is the new Successor" << "\n" ;
BasicBlock *tempBB = Block->getSingleSuccessor();
checkedSingleSuccessorSet.insert(tempBB);
IRBuilder<> IRB(tempBB);
//debug<<"The Instruction point: " << tempBB->getFirstNonPHI() << "\n" ;
IRB.SetInsertPoint(tempBB->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}else{
// debug<<"This is not the new Successor" << "\n" ;
continue;
}
}
else{
IRBuilder<> IRB(Block);
// debug<<"The Instruction point: " << Block->getFirstNonPHI() << "\n" ;
IRB.SetInsertPoint(Block->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
}//End iterating on exit basic blocks
}//End multiple exit basic blocks
//***********************************///
}//End check this is dynamic loop or not for "for and while" loop
else if(LI_temp_do->getType()->isPointerTy()){
isDynamic = true;
IRBuilder<> IRB(BB_temp1);
// debug<<"The Instruction point: " << *(BB_temp1->getFirstNonPHI()) << "\n" ;
IRB.SetInsertPoint(BB_temp1->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
//***********************************///
///Repeat from Nested Loop (for exit block) ***** I think it is the same *****//
if((*li)->getUniqueExitBlock() != NULL){//One Exit Basic Block
IRBuilder<> IRB((*li)->getUniqueExitBlock());
IRB.SetInsertPoint(((*li)->getUniqueExitBlock())->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
else if((*li)->hasNoExitBlocks()){
// debug<<"It is infinite nested loop, " << "No BasicBlock" << "\n" ;
}
else{//(Multiple Basic Blocks)
// debug<<"It is NULL, " << "Multiple BasicBlocks"<< "\n" ;
SmallVector<BasicBlock *> ExitBlocks;
(*li)->getExitBlocks(ExitBlocks);
for (auto *Block : ExitBlocks){
// debug<<"The basicblock: " << Block->front() << "\n" ;
//debug<<"Successor of " << Block << ": " << Block->getSingleSuccessor() << "\n" ;
if(Block->getSingleSuccessor() != NULL){
if(checkedSingleSuccessorSet.find(Block->getSingleSuccessor()) == checkedSingleSuccessorSet.end()){//
// debug<<"This is the new Successor" << "\n" ;
BasicBlock *tempBB = Block->getSingleSuccessor();
checkedSingleSuccessorSet.insert(tempBB);
IRBuilder<> IRB(tempBB);
//debug<<"The Instruction point: " << tempBB->getFirstNonPHI() << "\n" ;
IRB.SetInsertPoint(tempBB->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}else{
// debug<<"This is not the new Successor" << "\n" ;
continue;
}
}
else{
IRBuilder<> IRB(Block);
// debug<<"The Instruction point: " << Block->getFirstNonPHI() << "\n" ;
IRB.SetInsertPoint(Block->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
}//End iterating on exit basic blocks
}//End multiple exit basic blocks
//***********************************///
}//End check this is dynamic loop or not for "do" loop
}//End check if load instruction
//debug<<"The first instruction: "<< *(BB_temp1->getFirstNonPHI()) << ", " << *(BB_temp2->getFirstNonPHI()) << "," << *(BB_temp2->getFirstNonPHIOrDbgOrAlloca()) <<"\n";
//IRBuilder<> IRB(BB_temp2);
//debug<<"The Instruction point: " << BB_temp2->getFirstNonPHI() << "\n" ;
//IRB.SetInsertPoint(BB_temp2->getFirstNonPHI());
//auto Fn = func->getParent()->getOrInsertFunction(
// "print", Type::getVoidTy(M.getContext()));
//IRB.CreateCall(Fn);
if(!isDynamic){
// debug << "The loop is not dynamic and nested, Check it has branch or not! \n";
Loop* loop = *li;
for (auto bb = loop->block_begin(), be = loop->block_end(); bb != be; ++bb) {
BasicBlock* block = *bb;
for (auto ii = block->begin(), ie = block->end(); ii != ie; ++ii) {
Instruction* inst = &*ii;
if (auto* branchInst = dyn_cast<BranchInst>(inst)) {
if (branchInst->isConditional()) {
// Found a conditional branch, which means the loop contains if branches or switch cases
hasBranch = true;
}
}
}
}
if(hasBranch){
auto *BB_Header = (*li)->getHeader();
IRBuilder<> IRB(BB_Header->getFirstNonPHI());
auto Fn = func->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
}
}
}//End "else" for unnested loops
}//End iterating on the loops
}
void instrumentDynamicLoops(LoopInfo &LoopInfo, Module &M, Function *F){
// debug << "Enter to instrumentDynamicLoop Function" << "\n";
for (auto Loop : LoopInfo){
// debug << " hasNoExitBlocks and isLoopSimplifyForm: " << Loop->hasNoExitBlocks() << Loop->isLoopSimplifyForm() <<"\n";
if (!Loop->hasNoExitBlocks()){
// debug << "This is finite loop " << "\n";
//BasicBlock* BB_temp = Loop->getExitBlock();
// debug << "ExitBlock: " << Loop->getExitBlock() <<"\n";
// IRBuilder<> IRB(BB_temp);
// IRB.SetInsertPoint(BB_temp);//Add after dynamic loop
// auto Fn = F->getParent()->getOrInsertFunction(
// "print", Type::getVoidTy(M.getContext()));
// IRB.CreateCall(Fn);
}
}
}
virtual bool runOnFunction(BasicBlock* BB_Entry, Module &M, Function *F){
IRBuilder<> IRB(BB_Entry);
IRB.SetInsertPointPastAllocas(F);
auto Fn = F->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
return true;
}
virtual bool runOnBasicBlock(Function::iterator &BB, Module &M, Function *F)
{
//iterate over the instructions within the basicblock
for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI)
{
Instruction *ins = const_cast<llvm::Instruction *>(&*BI);
//For function calls
if (auto CI = dyn_cast<CallInst>(&*ins)) {
StringRef CIFuncName = CI->getCalledFunction()->getName();
string DemangledFuncCallName = demangle(CIFuncName.str().c_str());
int CIlineNum = getSourceCodeLine(CI);
bool isLineNumInPatch = false;
if(isPatched){
isLineNumInPatch = std::find(std::begin(lineNumPatch), std::end(lineNumPatch), CIlineNum) != std::end(lineNumPatch);
}
//string DemangledFuncName = demangle(CI->getArgOperand(0)->getName().str().c_str());
//Now, I just identify "print" call function and I don't insert code after that. But We have to consider other function calls that
//We don't need to insert trampoline after them
if (DemangledFuncCallName.find("TRAMPOLINE_FUNCTION") == std::string::npos && DemangledFuncCallName.find("dbg")== std::string::npos){ //It means that if the call function is not "print" go to the if
if(DemangledFuncCallName == "printf"){
}else if (isPatched && isLineNumInPatch){ //Checking do not insert trampoline if this function call is added as a patch.
debug << "This call function belongs to the patch! \n";
}else{
// debug << "Add call after function call " << DemangledFuncCallName <<"\n";
IRBuilder<> IRB(ins->getParent());
IRB.SetInsertPoint(ins->getNextNode());//Add trampoline after function call
auto Fn = ins->getFunction()->getParent()->getOrInsertFunction(
"TRAMPOLINE_FUNCTION", Type::getVoidTy(M.getContext()));
IRB.CreateCall(Fn);
trampolineNum++;
}
}
}
}
return true;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTreeWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.setPreservesAll();
}
};
} // namespace
char AutoPatchFirstPass::ID = 0;
static RegisterPass<AutoPatchFirstPass> X("instrumentcode",
"Pass to instrument function call");