Skip to content
Navigation Menu
{{ message }}
forked from TJAndHisStudents/TaintFlowAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataDepGraph.cpp
More file actions
2525 lines (2043 loc) · 95.8 KB
/
Copy pathDataDepGraph.cpp
File metadata and controls
2525 lines (2043 loc) · 95.8 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
#include "DataDepGraph.h"
//#include "dsa/DataStructure.h"
//#include "dsa/DSGraph.h"
#include "llvm/ADT/PostOrderIterator.h"
#define debug false
#define code false
bool useCallStrings =true;
bool AddControlEdges = false;
#define ProcessCallSiteFrequency 5
using namespace llvm;
///Calss CallSiteMap
///
CallSiteMap::CallSiteMap()
{
}
///Class RelevantFields
///
RelevantFields::RelevantFields()
{
}
cl::opt<std::string> CallPathFile("callPath", cl::desc("<Source sink call path functions>"), cl::init("-"));
cl::opt<std::string> Fields("fields", cl::desc("<Relevant fields file>"), cl::init("-"));
static cl::opt<bool, false> fullAnalysis("fullAnalysis", cl::desc("Long analysis"), cl::NotHidden);
//Class functionDepGraph
void functionDepGraph::getAnalysisUsage(AnalysisUsage &AU) const {
// if (USE_ALIAS_SETS)
// AU.addRequired<AliasSets> ();
AU.setPreservesAll();
}
bool functionDepGraph::runOnFunction(Function &F) {
// AliasSets* AS = NULL;
// if (USE_ALIAS_SETS)
// AS = &(getAnalysis<AliasSets> ());
//Making dependency graph
depGraph = new llvm::Graph();
//Insert instructions in the graph
for (Function::iterator BBit = F.begin(), BBend = F.end(); BBit != BBend; ++BBit) {
for (BasicBlock::iterator Iit = BBit->begin(), Iend = BBit->end(); Iit
!= Iend; ++Iit) {
depGraph->addInst_new(Iit);
}
}
//We don't modify anything, so we must return false
return false;
}
char functionDepGraph::ID = 0;
static RegisterPass<functionDepGraph> X("functionDepGraph",
"Function Dependence Graph");
//Class moduleDepGraph
void moduleDepGraph::getAnalysisUsage(AnalysisUsage &AU) const {
// if (USE_ALIAS_SETS)
// AU.addRequired<AliasSets> ();
AU.addRequired<CallGraphWrapperPass> ();
AU.addRequired<CallGraphWrapper> ();
//AU.addRequiredTransitive<AliasAnalysis>();
AU.addRequired<MemoryDependenceAnalysis>();
AU.addRequired<PostDominatorTree>();
//AU.addRequired<MemDepPrinter>();
AU.addRequired<InputDep> ();
//if(USE_DSA1)
AU.addRequired<BUDataStructures> ();
AU.setPreservesAll();
}
bool moduleDepGraph::runOnModule(Module &M) {
//Get results from all the previous analysis:
CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
InputDep &IV = getAnalysis<InputDep> ();
inputDepValues = IV.getInputDepValues();
CallGraphWrapper &cgWrapper = getAnalysis<CallGraphWrapper> ();
callPaths = cgWrapper.getCallPaths();
IndMap = cgWrapper.getIndirectMap();
//Initalize all the config params.
configData = IV.getConfigInfo();
useCallStrings = configData.useCallString;
//Read the relevant tainted fields supplied to the code to make it field sensitive.
//TODO :NT: once the struct is found in parsing--update the struct and field Types
ReadRelevantFields();
//if(USE_DSA1) //need to do this irrespective of the flag, null initialize not allowed.
BUDataStructures &BU_ds = getAnalysis<BUDataStructures>();
//Making dependency graph
depGraph = new Graph();
TopDownGraph = new Graph();
FullGraph = new Graph();
//depGraph->toDot("base","../../AliasSetGraph.dot");
//Get the relevant functions on the call path.. approach before the call strings approach.
//Check if the option provided..
//getcallPathFunctions();
//Initialize DSA pointsto graph for each function.
InitializePointtoGraphs(M, BU_ds);
//Process Global variables... it handles the globals when they are used, no need to add seperately unless source.
// ProcessGlobals(M,TopDownGraph);
//Generate the flow graph for all the funcitons:
for (Module::iterator Fit = M.begin(), Fend = M.end(); Fit != Fend; ++Fit) {
Function *F = Fit;
if (F && !F->isDeclaration()) {
Graph* Fdep = new Graph();
// if(code) errs()<<"\n\n Processing function fdep graph.. for "<<F->getName();
// Process_Functions(F,Fdep,SensitivityDepth);
if(code) errs()<<"\n Processing function topdown graph.. for "<<F->getName()<<"\n";
Process_Functions(F,TopDownGraph,SensitivityDepth);
FuncDepGraphs[F] = Fdep;
std::string tmp = F->getName();
// replace(tmp.begin(), tmp.end(), '\\', '_');
std::string Filename = "../../demo1_" + tmp + ".dot";
//string fileName = "../../"+F->getName()+"_graph.dot";
// errs()<<"\n Processing Function ******************* "<<F->getName();
// Fdep->toDot(F->getName(),Filename);
}
}
//Process each call site in sequence..
Graph * moduleGraph = new Graph();
errs()<<"\n Process the call inst in each function..";
for (Module::iterator Fit = M.begin(), Fend = M.end(); Fit != Fend; ++Fit) {
//Check if function in callstrings, parse to connect callsites to targets that are in callstrings.
if(configData.useCallString && !(callPaths.size()==0) && isFunctiononCallString(Fit))
{
// errs()<<"\ncalstring funct.. "<<Fit->getName();
ProcessCSinFunc(Fit,true,TopDownGraph);
}
else
{
//errs()<<"\n Call process.. "<<Fit->getName();
ProcessCSinFunc(Fit,false,TopDownGraph);
}
}
//Assiging to depgraph for taint --- temporarily
depGraph = TopDownGraph;
std::string Filename = "../../noConstTopDownGraph.dot";
errs()<<"\n Writing dot for **************** ..TopDownGraph";
// TopDownGraph->toDot("TopDown",Filename);
//We don't modify anything, so we must return false
return false;
}
///Merge function in Flow graph.
//void moduleDepGraph::MergeGRaphs(Graph * fullGraph, Graph * funcGraph)
//{
// for(GraphNode::iterator gNode = funcGraph->begin(); )
//put all nodes and edges from funcGRaph to full graph... this function should be in FlowGRaph.
//}
bool moduleDepGraph::isCallProcessed(CallInst* CI, Function* calledFunc)
{
bool isProcessed = false;
for(vector<instructionCallSite*>::iterator csIt = ProcessedCallsites.begin(); csIt != ProcessedCallsites.end();++csIt)
{
if((*csIt)->callInst == CI && (*csIt)->function == calledFunc)
{
isProcessed = true;
continue;
}
}
return isProcessed;
}
void moduleDepGraph::ConnectCallerCallee(CallInst* CI, Function* Callee, Graph * modGraph)
{
Function * caller = CI->getParent()->getParent();
if (Callee->isVarArg() || !Callee->hasNUsesOrMore(1)) {
return;
}
FuncParamInfo* paramInfo = modGraph->functionParamMap[Callee];
if(paramInfo)
{
CallSite cs(CI);
GraphNode* callSiteNode = modGraph->findInstNode(CI);
if(!callSiteNode)
callSiteNode = modGraph->addNode(CI,ntInst);
//Add control edge to function entry node:
if(GraphNode * entryNode = paramInfo->entryNode){
if(AddControlEdges)
callSiteNode->connect(entryNode,etCall);
}
//iterate over the args and find the nodes in caller func...
//connect act in to formal in... formal out to act in from callsite..
//return nodes to the call stmt.
// Data structure which contains the matches between formal and real parameters
// First: formal parameter
// Second: real parameter
SmallVector<std::pair<GraphNode*, GraphNode*>, 4> FormalIns(Callee->arg_size());
SmallVector<std::pair<GraphNode*, GraphNode*>, 4> FormalOuts(Callee->arg_size());
// Fetch the function arguments (formal parameters) into the data structure
Function::arg_iterator argptr;
Function::arg_iterator e;
unsigned i;
//Create the PHI nodes for the formal parameters
for (i = 0, argptr = Callee->arg_begin(), e = Callee->arg_end(); argptr != e; ++i, ++argptr) {
// OpNode* argPHI = new OpNode(Instruction::PHI);
Value *argValue = argptr;
//GraphNode* formArg = NULL;
GraphNode* formArg = paramInfo->FormalInMap[argValue];
//
if(!formArg)
formArg = modGraph->findInstNode(argValue); //,-1,Callee);
if(!formArg)
if(Instruction *inst = dyn_cast<Instruction>(argValue))
formArg = modGraph->addNode(inst,ntFormalIn);
//
FormalIns[i].second = formArg;
// errs()<<"\n Formal args : "<<formArg->getLabel();
//Collect corresponding formal out params..
GraphNode* formArgout = paramInfo->FormalOutMap[argValue];
//
if(!formArgout)
formArgout = modGraph->findInstNode(argValue); //,-1,Callee);
if(!formArgout)
if(Instruction *inst = dyn_cast<Instruction>(argValue))
formArgout = modGraph->addNode(inst,ntFormalIn);
FormalOuts[i].first = formArgout;
}
// Check if the function returns a supported value type. If not, no return value matching is done
bool noReturn = Callee->getReturnType()->isVoidTy();
// Creates the data structure which receives the return values of the function, if there is any
SmallPtrSet<llvm::Value*, 8> ReturnValues;
if (!noReturn) {
// Iterate over the basic blocks to fetch all possible return values
for (Function::iterator bb = Callee->begin(), bbend = Callee->end(); bb != bbend; ++bb) {
// Get the terminator instruction of the basic block and check if it's
// a return instruction: if it's not, continue to next basic block
Instruction *terminator = bb->getTerminator();
ReturnInst *RI = dyn_cast<ReturnInst> (terminator);
if (!RI)
continue;
// Get the return value and insert in the data structure
ReturnValues.insert(RI->getReturnValue());
}
}
//Get all correspoding graph nodes for rturns and connect it to the callsite node..
for(SmallPtrSet<Value*,8>::iterator retVals = ReturnValues.begin(); retVals != ReturnValues.end();++retVals)
{
Value * retval = *retVals;
if(GraphNode* retNode = paramInfo->RetValMap[retval]){
//errs()<<"\n retnode : "<<retNode->getLabel()<<" to -- call site "<<callSiteNode->getLabel();
retNode->connect(callSiteNode,etData);
}
else{
if(Instruction *inst = dyn_cast<Instruction>(retval)){
if(GraphNode * retNode = modGraph->findInstNode(inst)){
//errs()<<"\n inst node retnode : "<<retNode->getLabel()<<" to -- call site "<<callSiteNode->getLabel();
retNode->connect(callSiteNode,etData);
}
}
}
}
//Get actual param nodes.
CallSite::arg_iterator AI;
CallSite::arg_iterator EI;
for (i = 0, AI = cs.arg_begin(), EI = cs.arg_end(); AI != EI; ++i, ++AI) {
if(Instruction * argin = dyn_cast<Instruction>(*AI)){
if(GraphNode* argNode = modGraph->findInstNode(argin)){
FormalIns[i].first = argNode;
FormalOuts[i].second = argNode;
}
}
// Parameters[i].second = F_Graph->addInst(*AI,-1,Callee);
}
for (i = 0; i < FormalIns.size(); ++i) {
if(FormalIns[i].first && FormalIns[i].second){
FormalIns[i].first->connect(FormalIns[i].second,etParam);
}
// modGraph->addEdge(Parameters[i].second, Parameters[i].first);
// if(debug) errs()<<"\nAdding Edge between "<< Parameters[i].second->getLabel()<<" -- "<<Parameters[i].first->getLabel();
}
//Connecting the formal outs to actual vars from the call site..to capture the sideeffects.
for (i = 0; i < FormalOuts.size(); ++i) {
if(FormalOuts[i].first && FormalOuts[i].second){
FormalOuts[i].first->connect(FormalOuts[i].second,etParam);
}
// modGraph->addEdge(Parameters[i].second, Parameters[i].first);
// if(debug) errs()<<"\nAdding Edge between "<< Parameters[i].second->getLabel()<<" -- "<<Parameters[i].first->getLabel();
}
// // for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
// for (Value::user_iterator UI = Callee->user_begin(), E = Callee->user_end(); UI != E; ++UI) {
// User *U = *UI;
// // Use *BU = &UI.getUse();
// // Value::const_user_iterator & CUI =UI::reference;
// // const Use CU = UI.getUse();
// // Use *U = &*UI;
// // Ignore blockaddress uses
// //NT: TODO: Solve the error in the following:
// if (isa<BlockAddress> (U))
// continue;
// // Used by a non-instruction, or not the callee of a function, do not
// // match.
// if (!isa<CallInst> (U) && !isa<InvokeInst> (U))
// continue;
// Instruction *caller = cast<Instruction> (U);
// CallSite CS(caller);
// if (!CS.isCallee(&UI.getUse()))
// continue;
// // Iterate over the real parameters and put them in the data structure
// CallSite::arg_iterator AI;
// CallSite::arg_iterator EI;
// for (i = 0, AI = CS.arg_begin(), EI = CS.arg_end(); AI != EI; ++i, ++AI) {
// Parameters[i].second = F_Graph->addInst(*AI,-1,Callee);
// }
// // Match formal and real parameters
// for (i = 0; i < Parameters.size(); ++i) {
// F_Graph->addEdge(Parameters[i].second, Parameters[i].first);
// if(debug) errs()<<"\nAdding Edge between "<< Parameters[i].second->getLabel()<<" -- "<<Parameters[i].first->getLabel();
// }
// // Match return values
// if (!noReturn) {
// OpNode* retPHI = new OpNode(Instruction::PHI);
// GraphNode* callerNode = F_Graph->addInst(caller,-1,Callee);
// F_Graph->addEdge(retPHI, callerNode);
// for (SmallPtrSetIterator<llvm::Value*> ri = ReturnValues.begin(),
// re = ReturnValues.end(); ri != re; ++ri) {
// GraphNode* retNode = F_Graph->addInst(*ri,-1,Callee);
// F_Graph->addEdge(retNode, retPHI);
// }
// }
// // Real parameters are cleaned before moving to the next use (for safety's sake)
// for (i = 0; i < Parameters.size(); ++i)
// Parameters[i].second = NULL;
// }
// F_Graph->deleteCallNodes(Callee);
}
}
void moduleDepGraph::ProcessCSinFunc(Function * F, bool callString, Graph * modGraph)
{
for (Function::iterator BBit = F->begin(), BBend = F->end(); BBit
!= BBend; ++BBit) {
for (BasicBlock::iterator Iit = BBit->begin(), Iend = BBit->end(); Iit
!= Iend; ++Iit) {
if(isa<CallInst>(Iit)) // handle the call inst.
{
CallInst *CI = dyn_cast<CallInst>(Iit);
CallSite cs(Iit);
Function * calledFunc = CI->getCalledFunction();
//errs()<<"\n Check called func and callstring...";
if(calledFunc && (!callString || (callString && isFunctiononCallString(F))))
{
//errs()<<"\n check if processed...CalledFunc : "<<calledFunc->getName();
//Process only if not processed....
if(isCallProcessed(CI,calledFunc))
continue;
//Check if library/external function
//errs()<<"\n Called func cs, not processed....";
if(calledFunc->isDeclaration())
{
if(calledFunc->getName().equals("llvm.dbg.declare"))
continue;
//ToDO: Process the library functions..
HandleLibraryFunctions(CI,F);
}
else
{
//Handle the call connect here...
ConnectCallerCallee(CI,calledFunc,modGraph);
}
//errs()<<"\n push back processed cs..)";
instructionCallSite* processedcall = new instructionCallSite();
processedcall->callInst = CI;
processedcall->function = calledFunc;
ProcessedCallsites.push_back(processedcall);
//errs()<<"\n done push back processed cs..";
} //end of if function to be procesed..
//ToDo: Check for indirect calls.. calledFunc will be empty..
if(!calledFunc)
{
Type *ty = cs.getCalledValue()->getType();
if(ty->isPointerTy())
{
if(ty->getPointerElementType()->isFunctionTy())
{
vector<Function*> targetFunctions = IndMap[cs];
for(vector<Function*>::iterator tfunc = targetFunctions.begin();tfunc != targetFunctions.end();++tfunc)
{
Function * targetF = (*tfunc);
//Check if the called function is defined and is in call string
if(targetF && (!callString || (callString && isFunctiononCallString(targetF))))
{
//check if callsite with the given target processed.
if(isCallProcessed(CI,targetF))
continue;
//Handle the call connect here...
ConnectCallerCallee(CI,targetF,modGraph);
}
else if(!targetF)
{
//ToDo: handle indirect call to external function....
}
instructionCallSite* processedcall = new instructionCallSite();
processedcall->callInst = CI;
processedcall->function = targetF;
ProcessedCallsites.push_back(processedcall);
}
}
}
}
} //end if of isa<callisnt>
} //end for bb iterator
}
}
void moduleDepGraph::Process_CallSite(Instruction* inst, Function *F)
{
//at a call site which needs to be processed...
//get the actual params for the function.. .. check the function map params..
for (Function::arg_iterator Arg = F->arg_begin(), aEnd = F->arg_end(); Arg != aEnd; Arg++) {
// Arg->dump();
//
}
//Create the graph add edges in the graph for the given function..!!
Process_Functions(F,TopDownGraph,SensitivityDepth);
}
//Add the global values that are defined in the graph if the uses if not empty
void moduleDepGraph::ProcessGlobals(Module& M, Graph* TopDownGraph)
{
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = GVI++;
// Global variables without names cannot be referenced outside this module.
if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
GV->setLinkage(GlobalValue::InternalLinkage);
//Process the GV to add node in topdowngraph.
Value * GV_Val = GV;
//GV->dump();
//get val make node.. what all nodes to make and what all to eliminate.. nodes with no use delete..
// can run globalopt before...
if(!GV->use_empty())
{
// errs()<<"\n Adding global value: ";
// GV->dump();
TopDownGraph->addGlobalVal(GV);
}
}
}
void moduleDepGraph::TopDownProcessing(Function * F)
{
//Processing the Function, generate the data flow graph.
Process_Functions(F,TopDownGraph,SensitivityDepth);
//Iterating over the function blocks to look for next call sites and process the targets.
for (Function::iterator BBit = F->begin(), BBend = F->end(); BBit
!= BBend; ++BBit) {
for (BasicBlock::iterator Iit = BBit->begin(), Iend = BBit->end(); Iit
!= Iend; ++Iit) {
//TODO: also handle if && !isa<InvokeInst>(U) check how is it different.
Instruction *Inst = &*Iit;
if(CallInst * CI = dyn_cast<CallInst>(Inst))
{
CallSite cs(CI);
Function * calledFunc = CI->getCalledFunction();
if(calledFunc && !calledFunc->isDeclaration())
{
// errs()<<"\nPROPAGATE: Call Site with called func and not delaration.. !!";
// CI->dump();
//Update the callSite structs;
CallSiteMap* cs_data = new CallSiteMap();
cs_data->cs = &cs;
cs_data->CalledFunc = calledFunc;
int processFreq = isCallSiteProcessed(cs_data);
if(processFreq == 0 || processFreq <= ProcessCallSiteFrequency)
{
Process_CallSite(Inst,calledFunc);
Graph * CallF_Graph = FuncDepGraphs[calledFunc];
// map params and merge graph..
}
} //if called func
// errs()<<"\n";
if(calledFunc && calledFunc->isDeclaration())
{
// errs()<<"\nPROPAGATE: Call Site with called func and IS delaration.. !!";
// CI->dump();
HandleLibraryFunctions(CI,F);
}
//TODO: else if indirect call then process for all target calls.
if(!calledFunc)
{
// errs()<<"\nPROPAGATE: in !calledFunc i.e no Func Body";
// CI->dump();
Type *ty = cs.getCalledValue()->getType();
if(ty->isPointerTy())
{
// errs()<<"\nPROPAGATE: Call Site with no Func Body and is pointer type.. indirect call";
// CI->dump();
if(ty->getPointerElementType()->isFunctionTy())
{
//Check if we have the targets identified for this..
vector<Function*> targetFunctions = IndMap[cs];
// errs()<<"\nPROPAGATE: Function pointer type !! : "<<targetFunctions.size();
// CI->dump();
for(vector<Function*>::iterator funit = targetFunctions.begin(); funit != targetFunctions.end();++funit)
{
CallSiteMap* cs_data = new CallSiteMap();
cs_data->cs = &cs;
cs_data->CalledFunc = (*funit);
int processFreq = isCallSiteProcessed(cs_data);
if(processFreq == 0 || processFreq <= ProcessCallSiteFrequency)
{
Process_CallSite(Inst,(*funit));
}
}
}
}
if((ty->isPointerTy() && IndMap[cs].size()==0 ))
{
//Library call case:: -- where the if(!calledfunc && (isdeclaration || (if pointer..then pointer targets==0) ))
// Hnalde lib call-- default way and then add more specifications.
// errs()<<"\n\n Handling LIBRARY CALL for: ";
// CI->dump();
HandleLibraryFunctions(CI,F);
}
} //end of indirect function check.
} //if call inst
}
}
}
void moduleDepGraph::HandleLibraryFunctions(CallInst * CI, Function * F)
{
//Default case : Adding edge from the callsite params to return variable. done by default
//handle special library functions here..
//Handle specific cases:
}
int moduleDepGraph::isCallSiteProcessed(CallSiteMap* csm)
{
int freq = 0;
for(set<CallSiteMap*>::iterator csIT = CallSitesProcessed.begin(), csITEnd = CallSitesProcessed.end(); csIT != csITEnd; ++csIT)
{
if((csm->cs == (*csIT)->cs) && (csm->CalledFunc == (*csIT)->CalledFunc))
{
return (*csIT)->frequency;
}
}
return freq;
}
//Additional function to wrap the queue so that it will only add unique elements.
void moduleDepGraph::AddUniqueQueueItem(set<BasicBlock*> &setBlock, queue<BasicBlock*> &queueBlock, BasicBlock * bb)
{
// queue<BasicBlock*>::iterator it = find(queueBlock.begin(),queueBlock.end(),bb);
if (setBlock.find(bb) == setBlock.end())
{
queueBlock.push(bb);
setBlock.insert(queueBlock.back()); // or "s.emplace(q.back());"
}
}
///Function to initialize the points to graph for each function from the the DSA points to analysis.
///Stores the result in funcPointsToMap[F]
/// Also initialize global points to graph.
void moduleDepGraph::InitializePointtoGraphs(Module &M,BUDataStructures &BU_ds)
{
//initlialize global points to graph.
globalPointsToGraph = BU_ds.getGlobalsGraph();
//initialize functions points to graphs.
for (Module::iterator F = M.begin(), endF = M.end(); F != endF; ++F) {
if (F && !F->isDeclaration())
{
DSGraph *PointstoGraph = BU_ds.getDSGraph(*F);
funcPointsToMap[F] = PointstoGraph;
//Writes the Points to graph in dot files..
// std::string ErrorInfo;
// std::string fileName = "DSGraphInfo.txt";
// raw_fd_ostream File(fileName.c_str(), ErrorInfo,sys::fs::F_None);
// if (!ErrorInfo.empty()) {
// errs() << "Error opening file " << fileName
// << " for writing! Error Info: " << ErrorInfo << " \n";
// return;
// }
// std::string funcNames = PointstoGraph->getFunctionNames();
// PointstoGraph->writeGraphToFile(File,"../../TestFiles/"+funcNames);
}
}
}
bool moduleDepGraph::isPathProcessed(Function* F, vector<Function*> callPath, CallSite callSite)
{
callStringFunctions.push_back(F);
// currentCallString = currentCallString +","+F->getName();
currentCallString.append(",");
currentCallString.append(F->getName());
set< vector<Function*> > callStringFunc = ProcessedCallStringFunctions[F];
set<string> callStrings = ProcessedCallStrings[F];
errs()<<"\n\n Current Path:"<<currentCallString;
for(set<string>::iterator callst = callStrings.begin(); callst != callStrings.end(); ++callst)
{
string callstring = (*callst);
errs()<<"\n call string for function : "<<callstring;
// if(strcmp(currentCallString.c_str(),callstring.c_str()) == 0)
if(currentCallString.compare(callstring) == 0)
{
errs()<<"\n Path already processsed" << currentCallString;
return true;
}
}
callStrings.insert(currentCallString);
ProcessedCallStrings[F] = callStrings;
callStringFunc.insert(callStringFunctions);
ProcessedCallStringFunctions[F] = callStringFunc;
return false;
}
void moduleDepGraph::Process_Functions(Function* F, Graph* F_Graph, int SensDepth)
{
//Check if call path already processed if yes, dont process and return, else process with the appropriate context.
// if(debug)
errs()<<"\n Processing funtion recursive.. "<< F->getName() <<" ";
MDA = &getAnalysis<MemoryDependenceAnalysis>((*F));
//Make individual graphs for each functions..
// Graph* F_Graph = new Graph();
// FuncGraphMap[F] = F_Graph;
F_Graph->graph_type = gtFunctionData;
//Initialize the function paraminfo even if no parameters
FuncParamInfo* funcParam;
funcParam = F_Graph->functionParamMap[F];
if(!funcParam)
funcParam = new FuncParamInfo();
//Reset F_graph's store node map.
F_Graph->StoreNodeMap.clear();
//Add nodes for function parameters.. Actuals will be added at call statements.
// errs()<<"\n Generating Formal in and out nodes...";
for (Function::arg_iterator Arg = F->arg_begin(), aEnd = F->arg_end(); Arg != aEnd; Arg++) {
// Arg->dump();
GraphNode * pinNode = F_Graph->addParamNode(Arg ,F,ntFormalIn);
// errs()<<"\n Param added form in-- "<<pinNode->getLabel()<<pinNode->getId();
GraphNode * poutNode = F_Graph->addParamNode(Arg ,F,ntFormalOut);
// errs()<<"\n Param added form out-- "<<poutNode->getLabel()<<poutNode->getId();
}
// errs()<<"\n After Generating actual in and out nodes...";
//Add the ret val node..
//F provides return type..not the return value directly.. for each block check if return, ad node and push back in retmap.
//Get first block to process:
set<BasicBlock*> affected_BB;
queue<BasicBlock*> WorkList;
std::set<BasicBlock*> setBlock;
//Add all the instruction nodes for the function..
addNodes(F,F_Graph);
//Get the entry block in the function.
Function::iterator bbit = F->begin();
if(bbit)
{
WorkList.push(bbit);
// errs()<<"Processing the block now :"<<bbit->getName()<< " ";
while(!WorkList.empty())
{
BasicBlock *BBproc = WorkList.front();
WorkList.pop();
//Trial.. also try and remove the element from set as well.. will get only recursive elements..
// setBlock.erase(BBproc); dont process loop blocks again..
//TODO: reprocess the loop blocks only if context changes
//Process the popped block
affected_BB.clear();
affected_BB = Process_Block(BBproc, F_Graph);
//Iterate over the affected blocks and add them in worklist.
for(set<BasicBlock*>::iterator afB = affected_BB.begin(); afB != affected_BB.end();++afB)
{
WorkList.push(*afB);
//TODO: need some base condition to stop adding the affected blocks recursively., update: handle at proc block
}
//Iterate over the successors of the block and add them in the worklist.
TerminatorInst *TermInt = BBproc->getTerminator();
int SuccNum = TermInt->getNumSuccessors();
for(int i =0;i<SuccNum;i++)
{
BasicBlock *BBnext = TermInt->getSuccessor(i);
// WorkList.push(BBnext);
AddUniqueQueueItem(setBlock,WorkList,BBnext);
// errs()<<"\n\n Adding Block.. "<< BBnext->getName()<<" worklist Size "<<WorkList.size();
// errs()<<" = "<<setBlock.size();
}
}
}
//Mark Graph generated for the function
FunctionGraphGen[F] = 1;
//AddControl DEp edges for the Function...
if(AddControlEdges)
addControlDependencies(F,F_Graph);
///Bakward processing pass to process all loads..
// if(fullAnalysis)
// {
// // BasicBlock* TermBlock = &F->back();
// map<Value*, set< Value*> > LoadQueue;
// // LoadStoreMap(LoadQueue,TermBlock,F_Graph);
// // errs()<<"\n CAlling BFS for function "<< F->getName();
// BFSLoadStoreMap(LoadQueue,F,F_Graph);
// }
// //Print just the function GRaph....--
// std::string funcName = F->getName();
// std::string Filename = "graph_" + funcName + "_data.dot";
// F_Graph->toDot("M_getModuleIdentifier",Filename);
}
void moduleDepGraph::addControlDependencies(Function* F,Graph * F_Graph)
{
//Add an entry node for the Function.
GraphNode *entryNode = F_Graph->addEntryNode(F);
//Add entry node in funcparam info for further reference.
FuncParamInfo* funcParam;
funcParam = F_Graph->functionParamMap[F];
if(!funcParam)
funcParam = new FuncParamInfo();
funcParam->entryNode = entryNode;
F_Graph->functionParamMap[F] = funcParam;
PostDominatorTree &PDT = getAnalysis<PostDominatorTree>(*F);
// // BasicBlock * BB = ;
DomTreeNode *node = PDT[&F->getEntryBlock()];
//F_Graph->nodes.insert(entryNode);
while (node && node->getBlock())
{
/*
* Walking the path backward and adding dependencies.
*/
addControlDep(entryNode, node->getBlock(), F_Graph,etControl);
node = node->getIDom();
}
std::vector<std::pair<BasicBlock *, BasicBlock *> > EdgeSet;
for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
{
///Zhiyuan comment: find adjacent BasicBlock pairs in CFG, but the predecessor does not dominate successor.
for (succ_iterator SI = succ_begin(I), SE = succ_end(I); SI != SE; ++SI)
{
assert(I && *SI);
if (!PDT.dominates(*SI, I)) {
// errs() << I->getName() << "\n";
// errs() << "I: " << I << "\n";
// errs() << "*SI: " << (*SI)->getName() << "\n";
// errs() << "Added to (A, B) edge set.\n";
EdgeSet.push_back(std::make_pair(I, *SI));
}
}
}
typedef std::vector<std::pair<BasicBlock *, BasicBlock *> >::iterator EdgeItr;
///Zhiyuan comment: find nearest common ancestor in Post Dominator Tree for the BasicBlock pair.
for (EdgeItr I = EdgeSet.begin(), E = EdgeSet.end(); I != E; ++I)
{
std::pair<BasicBlock *, BasicBlock *> Edge = *I;
BasicBlock *L = PDT.findNearestCommonDominator(Edge.first, Edge.second);
// int type = getDependenceType(Edge.first, Edge.second);
// BasicBlockWrapper *A = BasicBlockWrapper::bbMap[Edge.first];
// capture loop dependence
if (L == Edge.first) {
errs() << "\t find A == L: " << L->getName() << "\n";
addControlDep(Edge.first, L, F_Graph,etControl);
// errs() << "DepType: " << type << "\n";
}
DomTreeNode *domNode = PDT[Edge.second];
while (domNode->getBlock() != L)
{
addControlDep(Edge.first, domNode->getBlock(),F_Graph, etControl);
domNode = domNode->getIDom();
}
}
return;
}
void moduleDepGraph::addControlDep(GraphNode* from,BasicBlock *to, Graph * F_Graph, edgeType eType)
{
for (llvm::BasicBlock::iterator ii = to->begin(), ie = to->end(); ii != ie; ++ii) {
if (llvm::Instruction* Ins = llvm::dyn_cast<llvm::Instruction>(ii) ) {
if (llvm::DebugFlag) {
llvm::errs() << "[i_cdg debug] dependence from type (" << from->getLabel() << ") to instruction (" << *Ins << ")\n";
}
if(GraphNode *iw = F_Graph->findInstNode(Ins))
from->connect(iw,eType);
}
}
}
void moduleDepGraph::addControlDep(BasicBlock* from,BasicBlock *to, Graph * F_Graph, edgeType eType)
{
Instruction *Ins = from->getTerminator();
assert(Ins);
if(GraphNode *iw = F_Graph->findInstNode(Ins))
{
//self loop
if (from == to) {
if (llvm::DebugFlag) {
llvm::errs() << "[i_cdg debug] loop dependence from (" << *from << ") to (" << *to << ")\n";
llvm::errs() << "Terminator: " << *Ins << "\n";
}
/// Zhiyuan: Bug Fix 04/23/2015: in a "while condition" basic block, all the instructions
/// before the br inst including the branch inst control depend on the br inst.
for (llvm::BasicBlock::iterator ii = from->begin(), ie = from->end(); ii != ie; ++ii) {
if(GraphNode *iwFrom = F_Graph->findInstNode(ii))
{
iwFrom->connect(iw,eType);
//CDG->addDependency(iwFrom, iw, type);
}
}
} else {
if (llvm::DebugFlag) {
llvm::errs() << "[i_cdg debug] dependence from (" << *from << ") to (" << *to << ")\n";
llvm::errs() << "Terminator: " << *Ins << "\n";
}
for (llvm::BasicBlock::iterator ii = to->begin(), ie = to->end(); ii != ie; ++ii) {
if(GraphNode *iwTo = F_Graph->findInstNode(ii))
{
iw->connect(iwTo,eType);
}
}
}
}
}
void moduleDepGraph::addNodes(Function* F, Graph * F_Graph)
{
for (llvm::Function::iterator bi = F->begin(), be = F->end(); bi != be; ++bi)
{
llvm::BasicBlock &BB = *bi;
for (llvm::BasicBlock::iterator ii = BB.begin(), ie = BB.end(); ii != ie; ++ii)
{
if(isa<CallInst>(&*ii)) // handle the call inst.
{
CallInst *CI = dyn_cast<CallInst>(&*ii);
CallSite cs(&*ii);
You can’t perform that action at this time.
