MC CFG: Use data structures more appropriate than std::set.
[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/SetVector.h"
12 #include "llvm/ADT/SmallPtrSet.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/MC/MCObjectSymbolizer.h"
22 #include "llvm/Object/MachO.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MachO.h"
26 #include "llvm/Support/MemoryObject.h"
27 #include "llvm/Support/StringRefMemoryObject.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <map>
30 #include <vector>
31
32 using namespace llvm;
33 using namespace object;
34
35 MCObjectDisassembler::MCObjectDisassembler(const ObjectFile &Obj,
36                                            const MCDisassembler &Dis,
37                                            const MCInstrAnalysis &MIA)
38     : Obj(Obj), Dis(Dis), MIA(MIA), MOS(0) {}
39
40 uint64_t MCObjectDisassembler::getEntrypoint() {
41   error_code ec;
42   for (symbol_iterator SI = Obj.begin_symbols(), SE = Obj.end_symbols();
43        SI != SE; SI.increment(ec)) {
44     if (ec)
45       break;
46     StringRef Name;
47     SI->getName(Name);
48     if (Name == "main" || Name == "_main") {
49       uint64_t Entrypoint;
50       SI->getAddress(Entrypoint);
51       return getEffectiveLoadAddr(Entrypoint);
52     }
53   }
54   return 0;
55 }
56
57 ArrayRef<uint64_t> MCObjectDisassembler::getStaticInitFunctions() {
58   return ArrayRef<uint64_t>();
59 }
60
61 ArrayRef<uint64_t> MCObjectDisassembler::getStaticExitFunctions() {
62   return ArrayRef<uint64_t>();
63 }
64
65 uint64_t MCObjectDisassembler::getEffectiveLoadAddr(uint64_t Addr) {
66   return Addr;
67 }
68
69 uint64_t MCObjectDisassembler::getOriginalLoadAddr(uint64_t Addr) {
70   return Addr;
71 }
72
73 MCModule *MCObjectDisassembler::buildEmptyModule() {
74   MCModule *Module = new MCModule;
75   Module->Entrypoint = getEntrypoint();
76   return Module;
77 }
78
79 MCModule *MCObjectDisassembler::buildModule(bool withCFG) {
80   MCModule *Module = buildEmptyModule();
81
82   buildSectionAtoms(Module);
83   if (withCFG)
84     buildCFG(Module);
85   return Module;
86 }
87
88 void MCObjectDisassembler::buildSectionAtoms(MCModule *Module) {
89   error_code ec;
90   for (section_iterator SI = Obj.begin_sections(),
91                         SE = Obj.end_sections();
92                         SI != SE;
93                         SI.increment(ec)) {
94     if (ec) break;
95
96     bool isText; SI->isText(isText);
97     bool isData; SI->isData(isData);
98     if (!isData && !isText)
99       continue;
100
101     uint64_t StartAddr; SI->getAddress(StartAddr);
102     uint64_t SecSize; SI->getSize(SecSize);
103     if (StartAddr == UnknownAddressOrSize || SecSize == UnknownAddressOrSize)
104       continue;
105     StartAddr = getEffectiveLoadAddr(StartAddr);
106
107     StringRef Contents; SI->getContents(Contents);
108     StringRefMemoryObject memoryObject(Contents, StartAddr);
109
110     // We don't care about things like non-file-backed sections yet.
111     if (Contents.size() != SecSize || !SecSize)
112       continue;
113     uint64_t EndAddr = StartAddr + SecSize - 1;
114
115     StringRef SecName; SI->getName(SecName);
116
117     if (isText) {
118       MCTextAtom *Text = 0;
119       MCDataAtom *InvalidData = 0;
120
121       uint64_t InstSize;
122       for (uint64_t Index = 0; Index < SecSize; Index += InstSize) {
123         const uint64_t CurAddr = StartAddr + Index;
124         MCInst Inst;
125         if (Dis.getInstruction(Inst, InstSize, memoryObject, CurAddr, nulls(),
126                                nulls())) {
127           if (!Text) {
128             Text = Module->createTextAtom(CurAddr, CurAddr);
129             Text->setName(SecName);
130           }
131           Text->addInst(Inst, InstSize);
132           InvalidData = 0;
133         } else {
134           if (!InvalidData) {
135             Text = 0;
136             InvalidData = Module->createDataAtom(CurAddr, EndAddr);
137           }
138           InvalidData->addData(Contents[Index]);
139         }
140       }
141     } else {
142       MCDataAtom *Data = Module->createDataAtom(StartAddr, EndAddr);
143       Data->setName(SecName);
144       for (uint64_t Index = 0; Index < SecSize; ++Index)
145         Data->addData(Contents[Index]);
146     }
147   }
148 }
149
150 namespace {
151   struct BBInfo;
152   typedef SmallPtrSet<BBInfo*, 2> BBInfoSetTy;
153
154   struct BBInfo {
155     MCTextAtom *Atom;
156     MCBasicBlock *BB;
157     BBInfoSetTy Succs;
158     BBInfoSetTy Preds;
159
160     BBInfo() : Atom(0), BB(0) {}
161
162     void addSucc(BBInfo &Succ) {
163       Succs.insert(&Succ);
164       Succ.Preds.insert(this);
165     }
166   };
167 }
168
169 void MCObjectDisassembler::buildCFG(MCModule *Module) {
170   typedef std::map<uint64_t, BBInfo> BBInfoByAddrTy;
171   BBInfoByAddrTy BBInfos;
172   typedef std::vector<uint64_t> AddressSetTy;
173   AddressSetTy Splits;
174   AddressSetTy Calls;
175
176   error_code ec;
177   for (symbol_iterator SI = Obj.begin_symbols(), SE = Obj.end_symbols();
178        SI != SE; SI.increment(ec)) {
179     if (ec)
180       break;
181     SymbolRef::Type SymType;
182     SI->getType(SymType);
183     if (SymType == SymbolRef::ST_Function) {
184       uint64_t SymAddr;
185       SI->getAddress(SymAddr);
186       SymAddr = getEffectiveLoadAddr(SymAddr);
187       Calls.push_back(SymAddr);
188       Splits.push_back(SymAddr);
189     }
190   }
191
192   assert(Module->func_begin() == Module->func_end()
193          && "Module already has a CFG!");
194
195   // First, determine the basic block boundaries and call targets.
196   for (MCModule::atom_iterator AI = Module->atom_begin(),
197                                AE = Module->atom_end();
198        AI != AE; ++AI) {
199     MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
200     if (!TA) continue;
201     Calls.push_back(TA->getBeginAddr());
202     BBInfos[TA->getBeginAddr()].Atom = TA;
203     for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
204          II != IE; ++II) {
205       if (MIA.isTerminator(II->Inst))
206         Splits.push_back(II->Address + II->Size);
207       uint64_t Target;
208       if (MIA.evaluateBranch(II->Inst, II->Address, II->Size, Target)) {
209         if (MIA.isCall(II->Inst))
210           Calls.push_back(Target);
211         Splits.push_back(Target);
212       }
213     }
214   }
215
216   std::sort(Splits.begin(), Splits.end());
217   Splits.erase(std::unique(Splits.begin(), Splits.end()), Splits.end());
218
219   std::sort(Calls.begin(), Calls.end());
220   Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
221
222   // Split text atoms into basic block atoms.
223   for (AddressSetTy::const_iterator SI = Splits.begin(), SE = Splits.end();
224        SI != SE; ++SI) {
225     MCAtom *A = Module->findAtomContaining(*SI);
226     if (!A) continue;
227     MCTextAtom *TA = cast<MCTextAtom>(A);
228     if (TA->getBeginAddr() == *SI)
229       continue;
230     MCTextAtom *NewAtom = TA->split(*SI);
231     BBInfos[NewAtom->getBeginAddr()].Atom = NewAtom;
232     StringRef BBName = TA->getName();
233     BBName = BBName.substr(0, BBName.find_last_of(':'));
234     NewAtom->setName((BBName + ":" + utohexstr(*SI)).str());
235   }
236
237   // Compute succs/preds.
238   for (MCModule::atom_iterator AI = Module->atom_begin(),
239                                AE = Module->atom_end();
240                                AI != AE; ++AI) {
241     MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
242     if (!TA) continue;
243     BBInfo &CurBB = BBInfos[TA->getBeginAddr()];
244     const MCDecodedInst &LI = TA->back();
245     if (MIA.isBranch(LI.Inst)) {
246       uint64_t Target;
247       if (MIA.evaluateBranch(LI.Inst, LI.Address, LI.Size, Target))
248         CurBB.addSucc(BBInfos[Target]);
249       if (MIA.isConditionalBranch(LI.Inst))
250         CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
251     } else if (!MIA.isTerminator(LI.Inst))
252       CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
253   }
254
255
256   // Create functions and basic blocks.
257   for (AddressSetTy::const_iterator CI = Calls.begin(), CE = Calls.end();
258        CI != CE; ++CI) {
259     BBInfo &BBI = BBInfos[*CI];
260     if (!BBI.Atom) continue;
261
262     MCFunction &MCFN = *Module->createFunction(BBI.Atom->getName());
263
264     // Create MCBBs.
265     SmallSetVector<BBInfo*, 16> Worklist;
266     Worklist.insert(&BBI);
267     for (size_t wi = 0; wi < Worklist.size(); ++wi) {
268       BBInfo *BBI = Worklist[wi];
269       if (!BBI->Atom)
270         continue;
271       BBI->BB = &MCFN.createBlock(*BBI->Atom);
272       // Add all predecessors and successors to the worklist.
273       for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
274                                  SI != SE; ++SI)
275         Worklist.insert(*SI);
276       for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
277                                  PI != PE; ++PI)
278         Worklist.insert(*PI);
279     }
280
281     // Set preds/succs.
282     for (size_t wi = 0; wi < Worklist.size(); ++wi) {
283       BBInfo *BBI = Worklist[wi];
284       MCBasicBlock *MCBB = BBI->BB;
285       if (!MCBB)
286         continue;
287       for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
288            SI != SE; ++SI)
289         if ((*SI)->BB)
290           MCBB->addSuccessor((*SI)->BB);
291       for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
292            PI != PE; ++PI)
293         if ((*PI)->BB)
294           MCBB->addPredecessor((*PI)->BB);
295     }
296   }
297 }
298
299 // MachO MCObjectDisassembler implementation.
300
301 MCMachOObjectDisassembler::MCMachOObjectDisassembler(
302     const MachOObjectFile &MOOF, const MCDisassembler &Dis,
303     const MCInstrAnalysis &MIA, uint64_t VMAddrSlide,
304     uint64_t HeaderLoadAddress)
305     : MCObjectDisassembler(MOOF, Dis, MIA), MOOF(MOOF),
306       VMAddrSlide(VMAddrSlide), HeaderLoadAddress(HeaderLoadAddress) {
307
308   error_code ec;
309   for (section_iterator SI = MOOF.begin_sections(), SE = MOOF.end_sections();
310        SI != SE; SI.increment(ec)) {
311     if (ec)
312       break;
313     StringRef Name;
314     SI->getName(Name);
315     // FIXME: We should use the S_ section type instead of the name.
316     if (Name == "__mod_init_func") {
317       DEBUG(dbgs() << "Found __mod_init_func section!\n");
318       SI->getContents(ModInitContents);
319     } else if (Name == "__mod_exit_func") {
320       DEBUG(dbgs() << "Found __mod_exit_func section!\n");
321       SI->getContents(ModExitContents);
322     }
323   }
324 }
325
326 // FIXME: Only do the translations for addresses actually inside the object.
327 uint64_t MCMachOObjectDisassembler::getEffectiveLoadAddr(uint64_t Addr) {
328   return Addr + VMAddrSlide;
329 }
330
331 uint64_t
332 MCMachOObjectDisassembler::getOriginalLoadAddr(uint64_t EffectiveAddr) {
333   return EffectiveAddr - VMAddrSlide;
334 }
335
336 uint64_t MCMachOObjectDisassembler::getEntrypoint() {
337   uint64_t EntryFileOffset = 0;
338
339   // Look for LC_MAIN.
340   {
341     uint32_t LoadCommandCount = MOOF.getHeader().NumLoadCommands;
342     MachOObjectFile::LoadCommandInfo Load = MOOF.getFirstLoadCommandInfo();
343     for (unsigned I = 0;; ++I) {
344       if (Load.C.Type == MachO::LoadCommandMain) {
345         EntryFileOffset =
346             ((const MachO::entry_point_command *)Load.Ptr)->entryoff;
347         break;
348       }
349
350       if (I == LoadCommandCount - 1)
351         break;
352       else
353         Load = MOOF.getNextLoadCommandInfo(Load);
354     }
355   }
356
357   // If we didn't find anything, default to the common implementation.
358   // FIXME: Maybe we could also look at LC_UNIXTHREAD and friends?
359   if (EntryFileOffset)
360     return MCObjectDisassembler::getEntrypoint();
361
362   return EntryFileOffset + HeaderLoadAddress;
363 }
364
365 ArrayRef<uint64_t> MCMachOObjectDisassembler::getStaticInitFunctions() {
366   // FIXME: We only handle 64bit mach-o
367   assert(MOOF.is64Bit());
368
369   size_t EntrySize = 8;
370   size_t EntryCount = ModInitContents.size() / EntrySize;
371   return ArrayRef<uint64_t>(
372       reinterpret_cast<const uint64_t *>(ModInitContents.data()), EntryCount);
373 }
374
375 ArrayRef<uint64_t> MCMachOObjectDisassembler::getStaticExitFunctions() {
376   // FIXME: We only handle 64bit mach-o
377   assert(MOOF.is64Bit());
378
379   size_t EntrySize = 8;
380   size_t EntryCount = ModExitContents.size() / EntrySize;
381   return ArrayRef<uint64_t>(
382       reinterpret_cast<const uint64_t *>(ModExitContents.data()), EntryCount);
383 }