MC CFG: When disassembly is impossible, fallback to data bytes.
[oota-llvm.git] / lib / MC / MCObjectDisassembler.cpp
1 //===- lib/MC/MCObjectDisassembler.cpp ------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCObjectDisassembler.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCAtom.h"
17 #include "llvm/MC/MCDisassembler.h"
18 #include "llvm/MC/MCFunction.h"
19 #include "llvm/MC/MCInstrAnalysis.h"
20 #include "llvm/MC/MCModule.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/MemoryObject.h"
23 #include "llvm/Support/StringRefMemoryObject.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <map>
26 #include <set>
27
28 using namespace llvm;
29 using namespace object;
30
31 MCObjectDisassembler::MCObjectDisassembler(const ObjectFile &Obj,
32                                            const MCDisassembler &Dis,
33                                            const MCInstrAnalysis &MIA)
34   : Obj(Obj), Dis(Dis), MIA(MIA) {}
35
36 uint64_t MCObjectDisassembler::getEntrypoint() {
37   error_code ec;
38   for (symbol_iterator SI = Obj.begin_symbols(), SE = Obj.end_symbols();
39        SI != SE; SI.increment(ec)) {
40     if (ec)
41       break;
42     StringRef Name;
43     SI->getName(Name);
44     if (Name == "main" || Name == "_main") {
45       uint64_t Entrypoint;
46       SI->getAddress(Entrypoint);
47       return Entrypoint;
48     }
49   }
50   return 0;
51 }
52
53 ArrayRef<uint64_t> MCObjectDisassembler::getStaticInitFunctions() {
54   return ArrayRef<uint64_t>();
55 }
56
57 ArrayRef<uint64_t> MCObjectDisassembler::getStaticExitFunctions() {
58   return ArrayRef<uint64_t>();
59 }
60
61 MCModule *MCObjectDisassembler::buildEmptyModule() {
62   MCModule *Module = new MCModule;
63   Module->Entrypoint = getEntrypoint();
64   return Module;
65 }
66
67 MCModule *MCObjectDisassembler::buildModule(bool withCFG) {
68   MCModule *Module = buildEmptyModule();
69
70   buildSectionAtoms(Module);
71   if (withCFG)
72     buildCFG(Module);
73   return Module;
74 }
75
76 void MCObjectDisassembler::buildSectionAtoms(MCModule *Module) {
77   error_code ec;
78   for (section_iterator SI = Obj.begin_sections(),
79                         SE = Obj.end_sections();
80                         SI != SE;
81                         SI.increment(ec)) {
82     if (ec) break;
83
84     bool isText; SI->isText(isText);
85     bool isData; SI->isData(isData);
86     if (!isData && !isText)
87       continue;
88
89     uint64_t StartAddr; SI->getAddress(StartAddr);
90     uint64_t SecSize; SI->getSize(SecSize);
91     if (StartAddr == UnknownAddressOrSize || SecSize == UnknownAddressOrSize)
92       continue;
93
94     StringRef Contents; SI->getContents(Contents);
95     StringRefMemoryObject memoryObject(Contents, StartAddr);
96
97     // We don't care about things like non-file-backed sections yet.
98     if (Contents.size() != SecSize || !SecSize)
99       continue;
100     uint64_t EndAddr = StartAddr + SecSize - 1;
101
102     StringRef SecName; SI->getName(SecName);
103
104     if (isText) {
105       MCTextAtom *Text = 0;
106       MCDataAtom *InvalidData = 0;
107
108       uint64_t InstSize;
109       for (uint64_t Index = 0; Index < SecSize; Index += InstSize) {
110         const uint64_t CurAddr = StartAddr + Index;
111         MCInst Inst;
112         if (Dis.getInstruction(Inst, InstSize, memoryObject, CurAddr, nulls(),
113                                nulls())) {
114           if (!Text) {
115             Text = Module->createTextAtom(CurAddr, CurAddr);
116             Text->setName(SecName);
117           }
118           Text->addInst(Inst, InstSize);
119           InvalidData = 0;
120         } else {
121           if (!InvalidData) {
122             Text = 0;
123             InvalidData = Module->createDataAtom(CurAddr, EndAddr);
124           }
125           InvalidData->addData(Contents[Index]);
126         }
127       }
128     } else {
129       MCDataAtom *Data = Module->createDataAtom(StartAddr, EndAddr);
130       Data->setName(SecName);
131       for (uint64_t Index = 0; Index < SecSize; ++Index)
132         Data->addData(Contents[Index]);
133     }
134   }
135 }
136
137 namespace {
138   struct BBInfo;
139   typedef std::set<BBInfo*> BBInfoSetTy;
140
141   struct BBInfo {
142     MCTextAtom *Atom;
143     MCBasicBlock *BB;
144     BBInfoSetTy Succs;
145     BBInfoSetTy Preds;
146
147     BBInfo() : Atom(0), BB(0) {}
148
149     void addSucc(BBInfo &Succ) {
150       Succs.insert(&Succ);
151       Succ.Preds.insert(this);
152     }
153   };
154 }
155
156 void MCObjectDisassembler::buildCFG(MCModule *Module) {
157   typedef std::map<uint64_t, BBInfo> BBInfoByAddrTy;
158   BBInfoByAddrTy BBInfos;
159   typedef std::set<uint64_t> AddressSetTy;
160   AddressSetTy Splits;
161   AddressSetTy Calls;
162
163   error_code ec;
164   for (symbol_iterator SI = Obj.begin_symbols(), SE = Obj.end_symbols();
165        SI != SE; SI.increment(ec)) {
166     if (ec)
167       break;
168     SymbolRef::Type SymType;
169     SI->getType(SymType);
170     if (SymType == SymbolRef::ST_Function) {
171       uint64_t SymAddr;
172       SI->getAddress(SymAddr);
173       Calls.insert(SymAddr);
174       Splits.insert(SymAddr);
175     }
176   }
177
178   assert(Module->func_begin() == Module->func_end()
179          && "Module already has a CFG!");
180
181   // First, determine the basic block boundaries and call targets.
182   for (MCModule::atom_iterator AI = Module->atom_begin(),
183                                AE = Module->atom_end();
184        AI != AE; ++AI) {
185     MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
186     if (!TA) continue;
187     Calls.insert(TA->getBeginAddr());
188     BBInfos[TA->getBeginAddr()].Atom = TA;
189     for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
190          II != IE; ++II) {
191       if (MIA.isTerminator(II->Inst))
192         Splits.insert(II->Address + II->Size);
193       uint64_t Target;
194       if (MIA.evaluateBranch(II->Inst, II->Address, II->Size, Target)) {
195         if (MIA.isCall(II->Inst))
196           Calls.insert(Target);
197         Splits.insert(Target);
198       }
199     }
200   }
201
202   // Split text atoms into basic block atoms.
203   for (AddressSetTy::const_iterator SI = Splits.begin(), SE = Splits.end();
204        SI != SE; ++SI) {
205     MCAtom *A = Module->findAtomContaining(*SI);
206     if (!A) continue;
207     MCTextAtom *TA = cast<MCTextAtom>(A);
208     if (TA->getBeginAddr() == *SI)
209       continue;
210     MCTextAtom *NewAtom = TA->split(*SI);
211     BBInfos[NewAtom->getBeginAddr()].Atom = NewAtom;
212     StringRef BBName = TA->getName();
213     BBName = BBName.substr(0, BBName.find_last_of(':'));
214     NewAtom->setName((BBName + ":" + utohexstr(*SI)).str());
215   }
216
217   // Compute succs/preds.
218   for (MCModule::atom_iterator AI = Module->atom_begin(),
219                                AE = Module->atom_end();
220                                AI != AE; ++AI) {
221     MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
222     if (!TA) continue;
223     BBInfo &CurBB = BBInfos[TA->getBeginAddr()];
224     const MCDecodedInst &LI = TA->back();
225     if (MIA.isBranch(LI.Inst)) {
226       uint64_t Target;
227       if (MIA.evaluateBranch(LI.Inst, LI.Address, LI.Size, Target))
228         CurBB.addSucc(BBInfos[Target]);
229       if (MIA.isConditionalBranch(LI.Inst))
230         CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
231     } else if (!MIA.isTerminator(LI.Inst))
232       CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
233   }
234
235
236   // Create functions and basic blocks.
237   for (AddressSetTy::const_iterator CI = Calls.begin(), CE = Calls.end();
238        CI != CE; ++CI) {
239     BBInfo &BBI = BBInfos[*CI];
240     if (!BBI.Atom) continue;
241
242     MCFunction &MCFN = *Module->createFunction(BBI.Atom->getName());
243
244     // Create MCBBs.
245     SmallSetVector<BBInfo*, 16> Worklist;
246     Worklist.insert(&BBI);
247     for (size_t wi = 0; wi < Worklist.size(); ++wi) {
248       BBInfo *BBI = Worklist[wi];
249       if (!BBI->Atom)
250         continue;
251       BBI->BB = &MCFN.createBlock(*BBI->Atom);
252       // Add all predecessors and successors to the worklist.
253       for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
254                                  SI != SE; ++SI)
255         Worklist.insert(*SI);
256       for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
257                                  PI != PE; ++PI)
258         Worklist.insert(*PI);
259     }
260
261     // Set preds/succs.
262     for (size_t wi = 0; wi < Worklist.size(); ++wi) {
263       BBInfo *BBI = Worklist[wi];
264       MCBasicBlock *MCBB = BBI->BB;
265       if (!MCBB)
266         continue;
267       for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
268            SI != SE; ++SI)
269         if ((*SI)->BB)
270           MCBB->addSuccessor((*SI)->BB);
271       for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
272            PI != PE; ++PI)
273         if ((*PI)->BB)
274           MCBB->addPredecessor((*PI)->BB);
275     }
276   }
277 }