When we encounter instructions without instruction semantics, we should stop jump...
[dyninst.git] / parseAPI / src / JumpTablePred.C
1 #include "dyntypes.h"
2 #include "Node.h"
3 #include "Graph.h"
4
5 #include "debug_parse.h"
6 #include "CodeObject.h"
7 #include "JumpTablePred.h"
8 #include "IndirectASTVisitor.h"
9
10 #include "Instruction.h"
11 #include "InstructionDecoder.h"
12
13 #include "AbslocInterface.h"
14 #include "SymEval.h"
15
16 using namespace Dyninst;
17 using namespace Dyninst::DataflowAPI;
18 using namespace Dyninst::ParseAPI;
19 using namespace Dyninst::InstructionAPI;
20 #define SIGNEX_64_32 0xffffffff00000000LL
21 #define SIGNEX_64_16 0xffffffffffff0000LL
22 #define SIGNEX_64_8  0xffffffffffffff00LL
23 #define SIGNEX_32_16 0xffff0000
24 #define SIGNEX_32_8 0xffffff00
25
26 // Assume the table contain less than this many entries.
27 #define MAX_TABLE_ENTRY 1000000
28 static void BuildEdgesAux(SliceNode::Ptr srcNode,
29                           ParseAPI::Block* curBlock,
30                           map<ParseAPI::Block*, map<AssignmentPtr, SliceNode::Ptr> > &targetMap,
31                           GraphPtr newG,
32                           set<ParseAPI::Block*> &visit,
33                           EdgeTypeEnum t,
34                           set<ParseAPI::Edge*> allowedEdges) {                   
35     if (targetMap.find(curBlock) != targetMap.end()) {
36         // This block contains at least one silce node 
37         // that is reachable from the source DFS node
38         map<AssignmentPtr, SliceNode::Ptr> &candNodes = targetMap[curBlock];
39         Address addr = 0;
40         for (auto cit = candNodes.begin(); cit != candNodes.end(); ++cit)
41             // The node has to be either in a different block from the source node
42             // or in the same block but has a larger address to be considered 
43             // reachable from the source node
44             if (cit->first->addr() > srcNode->addr() || curBlock != srcNode->block())
45                 if (addr == 0 || addr > cit->first->addr()) {
46                     addr = cit->first->addr();
47                 }
48         if (addr != 0) {
49             // There may be several assignments locating 
50             // at the same address. Need to connecting all.
51             if (t == _edgetype_end_) t = FALLTHROUGH;
52             for (auto cit = candNodes.begin(); cit != candNodes.end(); ++cit)
53                 if (cit->first->addr() > srcNode->addr() || curBlock != srcNode->block())
54                     if (addr == cit->first->addr()) {
55                         newG->insertPair(srcNode, cit->second, TypedSliceEdge::create(srcNode, cit->second, t));
56                     }
57             return;
58         }
59     }
60
61     if (visit.find(curBlock) != visit.end()) return;
62     visit.insert(curBlock);
63     for (auto eit = curBlock->targets().begin(); eit != curBlock->targets().end(); ++eit) {
64         // Xiaozhu:
65         // Our current slicing code ignores tail calls 
66         // (the slice code only checks if an edge type is CALL or not)
67         // so, I should be consistent here.
68         // If the slice code considers tail calls, need to change
69         // the predicate to (*eit)->interproc()
70         if ((*eit)->type() != CALL && (*eit)->type() != RET && allowedEdges.find(*eit) != allowedEdges.end()) {
71             EdgeTypeEnum newT = t; 
72             if (t == _edgetype_end_) {
73                 if ((*eit)->type() == COND_TAKEN || (*eit)->type() == COND_NOT_TAKEN) 
74                     newT = (*eit)->type();
75                 else 
76                     newT = FALLTHROUGH;
77             } 
78             BuildEdgesAux(srcNode, (*eit)->trg(), targetMap, newG, visit, newT, allowedEdges);     
79         }
80     }
81 }                         
82
83
84 static void BuildEdges(SliceNode::Ptr curNode,
85                        map<ParseAPI::Block*, map<AssignmentPtr, SliceNode::Ptr> > &targetMap,
86                        GraphPtr newG,
87                        set<ParseAPI::Edge*> &allowedEdges) {
88     set<ParseAPI::Block*> visit;                     
89     BuildEdgesAux(curNode, curNode->block(), targetMap, newG, visit, _edgetype_end_, allowedEdges);
90 }                      
91
92 static bool AssignIsZF(Assignment::Ptr a) {
93     return a->out().absloc().type() == Absloc::Register &&
94            (a->out().absloc().reg() == MachRegister::getZeroFlag(a->out().absloc().reg().getArchitecture()));
95 }
96
97 static bool IsPushAndChangeSP(Assignment::Ptr a) {
98     entryID id = a->insn()->getOperation().getID();
99     if (id != e_push) return false;
100     Absloc aloc = a->out().absloc();
101     if (aloc.type() == Absloc::Register && aloc.reg().isStackPointer()) return true;
102     return false;;
103
104 }
105
106 static int AdjustGraphEntryAndExit(GraphPtr gp) {
107     int nodeCount = 0;
108     NodeIterator gbegin, gend;
109     gp->allNodes(gbegin, gend);
110     for (; gbegin != gend; ++gbegin) {
111         ++nodeCount;
112         Node::Ptr ptr = *gbegin;
113         if (!ptr->hasInEdges()) gp->insertEntryNode(ptr);
114         if (!ptr->hasOutEdges()) gp->insertExitNode(ptr);
115     }
116     return nodeCount;
117 }
118
119 GraphPtr JumpTablePred::BuildAnalysisGraph(set<ParseAPI::Edge*> &visitedEdges) {
120     GraphPtr newG = Graph::createGraph();
121     
122     NodeIterator gbegin, gend;
123     parsing_printf("\t\t start to build analysis graph\n");
124
125     // Create a map to help find whether we have reached a node
126     map<ParseAPI::Block*, map<AssignmentPtr, SliceNode::Ptr> > targetMap;
127
128     // Assignments that are at these addresses have flag assignment colocated
129     set<Address> shouldSkip;
130     for (auto ait = currentAssigns.begin(); ait != currentAssigns.end(); ++ait) {
131         if (AssignIsZF(*ait))
132             shouldSkip.insert((*ait)->addr());
133     }
134     parsing_printf("\t\t calculate skipped nodes\n");
135
136     // We only need one assignment from xchg instruction at each address
137     set<Address> xchgCount;
138     set<Assignment::Ptr> xchgAssign;
139     for (auto ait = currentAssigns.begin(); ait != currentAssigns.end(); ++ait) {
140         if ((*ait)->insn()->getOperation().getID() == e_xchg) {
141             if (xchgCount.find( (*ait)->addr() ) != xchgCount.end() ) continue;
142             xchgCount.insert((*ait)->addr());
143             xchgAssign.insert(*ait);
144         }
145     }
146     parsing_printf("\t\t calculate xchg assignments\n");
147    
148     for (auto ait = currentAssigns.begin(); ait != currentAssigns.end(); ++ait) {
149         Assignment::Ptr a = *ait;
150         if (   (AssignIsZF(a) || shouldSkip.find(a->addr()) == shouldSkip.end()) 
151             && !IsPushAndChangeSP(a)
152             && (!a->insn()->writesMemory() || MatchReadAST(a))) {
153             if (a->insn()->getOperation().getID() == e_xchg && xchgAssign.find(a) == xchgAssign.end()) continue;
154             SliceNode::Ptr newNode = SliceNode::create(a, a->block(), a->func());
155             targetMap[a->block()][a] = newNode;
156             newG->addNode(newNode);
157         }
158     }
159     parsing_printf("\t\t calculate nodes in the new graph\n");
160     // Start from each node to do DFS and build edges
161     newG->allNodes(gbegin, gend);
162     for (; gbegin != gend; ++gbegin) {
163         SliceNode::Ptr node = boost::static_pointer_cast<SliceNode>(*gbegin);
164         BuildEdges(node, targetMap, newG, visitedEdges);
165     }
166     parsing_printf("\t\t calculate edges in the new graph\n");
167
168     // Build a virtual exit node
169     SliceNode::Ptr virtualExit = SliceNode::create(Assignment::Ptr(), NULL, NULL);
170     newG->addNode(virtualExit);
171     newG->allNodes(gbegin, gend);
172     for (; gbegin != gend; ++gbegin) {
173         SliceNode::Ptr cur = boost::static_pointer_cast<SliceNode>(*gbegin);
174         if (!cur->hasOutEdges() && cur != virtualExit) {
175             newG->insertPair(cur, virtualExit, TypedSliceEdge::create(cur, virtualExit, FALLTHROUGH));
176         }
177     }
178     parsing_printf("\t\t calculate virtual nodes in the new graph\n");
179
180     AdjustGraphEntryAndExit(newG);
181
182
183     return newG;
184
185 }
186
187
188 bool JumpTablePred::addNodeCallback(AssignmentPtr ap, set<ParseAPI::Edge*> &visitedEdges) {
189     if (!jumpTableFormat) return false;
190     if (unknownInstruction) return false;
191     if (currentAssigns.find(ap) != currentAssigns.end()) return true;
192     if (currentAssigns.size() > 50) return false; 
193     // For flags, we only analyze zf
194     if (ap->out().absloc().type() == Absloc::Register) {
195         MachRegister reg = ap->out().absloc().reg();
196         if (reg.isFlag() && reg != MachRegister::getZeroFlag(reg.getArchitecture())) {
197             return true;
198         }
199     }
200     pair<AST::Ptr, bool> expandRet = ExpandAssignment(ap);
201
202     currentAssigns.insert(ap);
203
204     parsing_printf("Adding assignment %s in instruction %s at %lx, total %d\n", ap->format().c_str(), ap->insn()->format().c_str(), ap->addr(), currentAssigns.size());
205 /*
206     if (ap->insn() && ap->insn()->readsMemory() && firstMemoryRead) {
207         firstMemoryRead = false;
208         parsing_printf("\tThe first memory read, check if format is correct\n");
209         if 
210     }
211 */
212
213     if (!expandRet.second || expandRet.first == NULL) {
214         unknownInstruction = true;
215         return true;
216     }
217
218     // If this assignment writes memory,
219     // we only want to analyze it when it writes to 
220     // an AST we have seen before and potentially
221     // can used for aliasing
222     if (ap->insn()->writesMemory()) {
223         if (!MatchReadAST(ap)) return true;
224     }
225
226     // If this assignment reads memory,
227     // we record the AST of the read so
228     // that in the future we can match a
229     // corresponding write to identify aliasing
230     if (ap->insn()->readsMemory() && expandRet.first->getID() == AST::V_RoseAST) {
231         RoseAST::Ptr roseAST = boost::static_pointer_cast<RoseAST>(expandRet.first);
232         if (roseAST->val().op == ROSEOperation::derefOp) {
233             readAST.push_back(expandRet.first);
234         }
235     }
236     // I really do not want to redo the analysis from scratch,
237     // but it seems like with newly added edges and nodes,
238     // it is necessary to redo.
239
240     // We create the CFG based on the found nodes
241     GraphPtr g = BuildAnalysisGraph(visitedEdges);
242     BoundFactsCalculator bfc(func, g, func->entry() == block, rf, thunks, block->last(), false, expandCache);
243     bfc.CalculateBoundedFacts();
244
245     BoundValue target;
246     bool ijt = IsJumpTable(g, bfc, target);
247     if (ijt) {
248         bool ret = !FillInOutEdges(target, outEdges) || outEdges.empty();
249         // Now we have stopped slicing in advance, so the cache contents are not complete any more.
250         if (!ret) setClearCache(true);
251         return ret;
252     } else {
253         return true;
254     }   
255
256
257
258 }
259 bool JumpTablePred::FillInOutEdges(BoundValue &target, 
260                                                  vector<pair< Address, Dyninst::ParseAPI::EdgeTypeEnum > >& outEdges) {
261     set<Address> jumpTargets;                                            
262     outEdges.clear();
263     Address tableBase = target.interval.low;
264     Address tableLastEntry = target.interval.high;
265     int addressWidth = block->obj()->cs()->getAddressWidth();
266     if (addressWidth == 4) {
267         tableBase &= 0xffffffff;
268         tableLastEntry &= 0xffffffff;
269     }
270
271 #if defined(os_windows)
272     tableBase -= block->obj()->cs()->loadAddress();
273     tableLastEntry -= block->obj()->cs()->loadAddress();
274 #endif
275
276     parsing_printf("The final target bound fact:\n");
277     target.Print();
278     if (!block->obj()->cs()->isCode(tableBase) && !block->obj()->cs()->isData(tableBase)) {
279         parsing_printf("\ttableBase 0x%lx invalid, returning false\n", tableBase);
280         jumpTableFormat = false;
281         parsing_printf("Not jump table format!\n");
282         return false;
283     }
284     if (!block->obj()->cs()->isReadOnly(tableBase)) {
285         parsing_printf("\ttableBase 0x%lx not read only, returning false\n", tableBase);
286         jumpTableFormat = false;
287         parsing_printf("Not jump table format!\n");
288         return false;
289     }
290
291
292     for (Address tableEntry = tableBase; tableEntry <= tableLastEntry; tableEntry += target.interval.stride) {
293         if (!block->obj()->cs()->isCode(tableEntry) && !block->obj()->cs()->isData(tableEntry)) continue;
294         if (!block->obj()->cs()->isReadOnly(tableEntry)) continue;
295         int targetAddress = 0;
296         if (target.tableReadSize > 0) {
297             switch (target.tableReadSize) {
298                 case 8:
299                     targetAddress = *(const uint64_t *) block->obj()->cs()->getPtrToInstruction(tableEntry);
300                     break;
301                 case 4:
302                     targetAddress = *(const uint32_t *) block->obj()->cs()->getPtrToInstruction(tableEntry);
303                     if (target.isZeroExtend) break;
304                     if ((addressWidth == 8) && (targetAddress & 0x80000000)) {
305                         targetAddress |= SIGNEX_64_32;
306                     }
307                     break;
308                 case 2:
309                     targetAddress = *(const uint16_t *) block->obj()->cs()->getPtrToInstruction(tableEntry);
310                     if (target.isZeroExtend) break;
311                     if ((addressWidth == 8) && (targetAddress & 0x8000)) {
312                         targetAddress |= SIGNEX_64_16;
313                     }
314                     if ((addressWidth == 4) && (targetAddress & 0x8000)) {
315                         targetAddress |= SIGNEX_32_16;
316                     }
317
318                     break;
319                 case 1:
320                     targetAddress = *(const uint8_t *) block->obj()->cs()->getPtrToInstruction(tableEntry);
321                     if (target.isZeroExtend) break;
322                     if ((addressWidth == 8) && (targetAddress & 0x80)) {
323                         targetAddress |= SIGNEX_64_8;
324                     }
325                     if ((addressWidth == 4) && (targetAddress & 0x80)) {
326                         targetAddress |= SIGNEX_32_8;
327                     }
328
329                     break;
330
331                 default:
332                     parsing_printf("Invalid memory read size %d\n", target.tableReadSize);
333                     return false;
334             }
335             targetAddress *= target.multiply;
336             if (target.targetBase != 0) {
337                 if (target.isSubReadContent) 
338                     targetAddress = target.targetBase - targetAddress;
339                 else 
340                     targetAddress += target.targetBase; 
341
342             }
343 #if defined(os_windows)
344             targetAddress -= block->obj()->cs()->loadAddress();
345 #endif
346         } else targetAddress = tableEntry;
347
348         if (addressWidth == 4) targetAddress &= 0xffffffff;
349         parsing_printf("Jumping to target %lx,", targetAddress);
350         if (block->obj()->cs()->isCode(targetAddress)) {
351             // Jump tables may contain may repetitious entries.
352             // We only want to create one edge for disctinct each jump target.
353             jumpTargets.insert(targetAddress);
354             parsing_printf(" is code.\n" );
355         } else {
356             parsing_printf(" not code.\n");
357         }
358         // If the jump target is resolved to be a constant, 
359         if (target.interval.stride == 0) break;
360     }
361     for (auto tit = jumpTargets.begin(); tit != jumpTargets.end(); ++tit) {
362         outEdges.push_back(make_pair(*tit, INDIRECT));
363     }
364     return true;
365 }
366 bool JumpTablePred::IsJumpTable(GraphPtr slice, 
367                                               BoundFactsCalculator &bfc,
368                                               BoundValue &target) {
369     NodeIterator exitBegin, exitEnd, srcBegin, srcEnd;
370     slice->exitNodes(exitBegin, exitEnd);
371     SliceNode::Ptr virtualExit = boost::static_pointer_cast<SliceNode>(*exitBegin);
372     virtualExit->ins(srcBegin, srcEnd);
373     SliceNode::Ptr jumpNode = boost::static_pointer_cast<SliceNode>(*srcBegin);
374     
375     const Absloc &loc = jumpNode->assign()->out().absloc();
376     parsing_printf("Checking final bound fact for %s\n",loc.format().c_str()); 
377     BoundFact *bf = bfc.GetBoundFactOut(virtualExit);
378     VariableAST::Ptr ip = VariableAST::create(Variable(loc));
379     BoundValue *tarBoundValue = bf->GetBound(ip);
380     if (tarBoundValue != NULL) {
381         target = *(tarBoundValue);
382         uint64_t s = target.interval.size();
383         if (s > 0 && s <= MAX_TABLE_ENTRY) return true;
384     }
385     AST::Ptr ipExp = bf->GetAlias(ip);
386     if (ipExp) {
387         parsing_printf("\t jump target expression %s\n", ipExp->format().c_str());
388         JumpTableFormatVisitor jtfv(block);
389         ipExp->accept(&jtfv);
390         if (!jtfv.format) {
391             parsing_printf("\t Not jump table format!\n");
392             jumpTableFormat = false;
393         }
394     }
395
396     return false;
397 }
398
399 bool JumpTablePred::MatchReadAST(Assignment::Ptr a) {
400     pair<AST::Ptr, bool> expandRet = ExpandAssignment(a);
401     if (!expandRet.second || expandRet.first == NULL) return false;
402     if (a->out().generator() == NULL) return false;
403     AST::Ptr write = SimplifyAnAST(RoseAST::create(ROSEOperation(ROSEOperation::derefOp, a->out().size()), a->out().generator()), 
404                                    PCValue(a->addr(),
405                                            a->insn()->size(),
406                                            a->block()->obj()->cs()->getArch()));
407
408     if (write == NULL) return false;
409     for (auto ait = readAST.begin(); ait != readAST.end(); ++ait) 
410         if (*write == **ait) return true;
411     return false;
412 }
413
414 pair<AST::Ptr, bool> JumpTablePred::ExpandAssignment(Assignment::Ptr assign) {
415     if (expandCache.find(assign) != expandCache.end()) {
416         AST::Ptr ast = expandCache[assign];
417         if (ast) return make_pair(ast, true); else return make_pair(ast, false);
418
419     } else {
420                 parsing_printf("\t\tExpanding instruction @ %x: %s\n", assign->addr(), assign->insn()->format().c_str());
421         pair<AST::Ptr, bool> expandRet = SymEval::expand(assign, false);
422         if (expandRet.second && expandRet.first) {
423 parsing_printf("Original expand: %s\n", expandRet.first->format().c_str());
424
425             AST::Ptr calculation = SimplifyAnAST(expandRet.first, 
426                                                  PCValue(assign->addr(),
427                                                          assign->insn()->size(),
428                                                          assign->block()->obj()->cs()->getArch()));
429             expandCache[assign] = calculation;
430         } else {
431             expandCache[assign] = AST::Ptr();
432         }
433         return make_pair( expandCache[assign], expandRet.second );
434     }
435 }
436