blob: 3af45371a3f39f3ab3322033a57e93a37ad63788 [file] [log] [blame]
Ahmed Bougachaef993562013-05-24 01:07:04 +00001//===- 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"
Ahmed Bougachaef993562013-05-24 01:07:04 +000011#include "llvm/ADT/SetVector.h"
Ahmed Bougacha05a81022013-08-21 07:28:51 +000012#include "llvm/ADT/SmallPtrSet.h"
Ahmed Bougachaef993562013-05-24 01:07:04 +000013#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"
Ahmed Bougacha0f4a5ba2013-08-21 07:28:48 +000021#include "llvm/MC/MCObjectSymbolizer.h"
Ahmed Bougacha0e83b902013-08-21 07:28:44 +000022#include "llvm/Object/MachO.h"
Ahmed Bougachaef993562013-05-24 01:07:04 +000023#include "llvm/Object/ObjectFile.h"
Ahmed Bougacha0e83b902013-08-21 07:28:44 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/MachO.h"
Ahmed Bougachaef993562013-05-24 01:07:04 +000026#include "llvm/Support/MemoryObject.h"
27#include "llvm/Support/StringRefMemoryObject.h"
28#include "llvm/Support/raw_ostream.h"
29#include <map>
Ahmed Bougacha05a81022013-08-21 07:28:51 +000030#include <vector>
Ahmed Bougachaef993562013-05-24 01:07:04 +000031
32using namespace llvm;
33using namespace object;
34
35MCObjectDisassembler::MCObjectDisassembler(const ObjectFile &Obj,
36 const MCDisassembler &Dis,
37 const MCInstrAnalysis &MIA)
Ahmed Bougacha0f4a5ba2013-08-21 07:28:48 +000038 : Obj(Obj), Dis(Dis), MIA(MIA), MOS(0) {}
Ahmed Bougachaef993562013-05-24 01:07:04 +000039
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +000040uint64_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);
Ahmed Bougacha484a6eb2013-08-21 07:28:37 +000051 return getEffectiveLoadAddr(Entrypoint);
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +000052 }
53 }
54 return 0;
55}
56
57ArrayRef<uint64_t> MCObjectDisassembler::getStaticInitFunctions() {
58 return ArrayRef<uint64_t>();
59}
60
61ArrayRef<uint64_t> MCObjectDisassembler::getStaticExitFunctions() {
62 return ArrayRef<uint64_t>();
63}
64
Ahmed Bougacha484a6eb2013-08-21 07:28:37 +000065uint64_t MCObjectDisassembler::getEffectiveLoadAddr(uint64_t Addr) {
66 return Addr;
67}
68
69uint64_t MCObjectDisassembler::getOriginalLoadAddr(uint64_t Addr) {
70 return Addr;
71}
72
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +000073MCModule *MCObjectDisassembler::buildEmptyModule() {
Ahmed Bougachaef993562013-05-24 01:07:04 +000074 MCModule *Module = new MCModule;
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +000075 Module->Entrypoint = getEntrypoint();
76 return Module;
77}
78
79MCModule *MCObjectDisassembler::buildModule(bool withCFG) {
80 MCModule *Module = buildEmptyModule();
81
Ahmed Bougachaef993562013-05-24 01:07:04 +000082 buildSectionAtoms(Module);
83 if (withCFG)
84 buildCFG(Module);
85 return Module;
86}
87
88void 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;
Ahmed Bougacha484a6eb2013-08-21 07:28:37 +0000105 StartAddr = getEffectiveLoadAddr(StartAddr);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000106
107 StringRef Contents; SI->getContents(Contents);
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +0000108 StringRefMemoryObject memoryObject(Contents, StartAddr);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000109
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) {
Ahmed Bougacha46937272013-08-21 07:28:32 +0000118 MCTextAtom *Text = 0;
119 MCDataAtom *InvalidData = 0;
120
Ahmed Bougachaef993562013-05-24 01:07:04 +0000121 uint64_t InstSize;
122 for (uint64_t Index = 0; Index < SecSize; Index += InstSize) {
Ahmed Bougacha46937272013-08-21 07:28:32 +0000123 const uint64_t CurAddr = StartAddr + Index;
Ahmed Bougachaef993562013-05-24 01:07:04 +0000124 MCInst Inst;
Ahmed Bougacha46937272013-08-21 07:28:32 +0000125 if (Dis.getInstruction(Inst, InstSize, memoryObject, CurAddr, nulls(),
126 nulls())) {
127 if (!Text) {
128 Text = Module->createTextAtom(CurAddr, CurAddr);
129 Text->setName(SecName);
130 }
Ahmed Bougachaef993562013-05-24 01:07:04 +0000131 Text->addInst(Inst, InstSize);
Ahmed Bougacha46937272013-08-21 07:28:32 +0000132 InvalidData = 0;
133 } else {
134 if (!InvalidData) {
135 Text = 0;
136 InvalidData = Module->createDataAtom(CurAddr, EndAddr);
137 }
138 InvalidData->addData(Contents[Index]);
139 }
Ahmed Bougachaef993562013-05-24 01:07:04 +0000140 }
Ahmed Bougachaef993562013-05-24 01:07:04 +0000141 } 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
150namespace {
151 struct BBInfo;
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000152 typedef SmallPtrSet<BBInfo*, 2> BBInfoSetTy;
Ahmed Bougachaef993562013-05-24 01:07:04 +0000153
154 struct BBInfo {
155 MCTextAtom *Atom;
156 MCBasicBlock *BB;
157 BBInfoSetTy Succs;
158 BBInfoSetTy Preds;
159
Ahmed Bougacha46937272013-08-21 07:28:32 +0000160 BBInfo() : Atom(0), BB(0) {}
161
Ahmed Bougachaef993562013-05-24 01:07:04 +0000162 void addSucc(BBInfo &Succ) {
163 Succs.insert(&Succ);
164 Succ.Preds.insert(this);
165 }
166 };
167}
168
169void MCObjectDisassembler::buildCFG(MCModule *Module) {
170 typedef std::map<uint64_t, BBInfo> BBInfoByAddrTy;
171 BBInfoByAddrTy BBInfos;
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000172 typedef std::vector<uint64_t> AddressSetTy;
Ahmed Bougachaef993562013-05-24 01:07:04 +0000173 AddressSetTy Splits;
174 AddressSetTy Calls;
175
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +0000176 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);
Ahmed Bougacha484a6eb2013-08-21 07:28:37 +0000186 SymAddr = getEffectiveLoadAddr(SymAddr);
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000187 Calls.push_back(SymAddr);
188 Splits.push_back(SymAddr);
Ahmed Bougacha0a30ccc2013-08-21 07:28:29 +0000189 }
190 }
191
Ahmed Bougachaef993562013-05-24 01:07:04 +0000192 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;
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000201 Calls.push_back(TA->getBeginAddr());
Ahmed Bougacha7ab184a2013-06-19 20:18:59 +0000202 BBInfos[TA->getBeginAddr()].Atom = TA;
Ahmed Bougachaef993562013-05-24 01:07:04 +0000203 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
204 II != IE; ++II) {
205 if (MIA.isTerminator(II->Inst))
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000206 Splits.push_back(II->Address + II->Size);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000207 uint64_t Target;
208 if (MIA.evaluateBranch(II->Inst, II->Address, II->Size, Target)) {
209 if (MIA.isCall(II->Inst))
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000210 Calls.push_back(Target);
211 Splits.push_back(Target);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000212 }
213 }
214 }
215
Ahmed Bougacha05a81022013-08-21 07:28:51 +0000216 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
Ahmed Bougachaef993562013-05-24 01:07:04 +0000222 // 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);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000228 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);
Ahmed Bougacha46937272013-08-21 07:28:32 +0000267 for (size_t wi = 0; wi < Worklist.size(); ++wi) {
268 BBInfo *BBI = Worklist[wi];
Ahmed Bougachaef993562013-05-24 01:07:04 +0000269 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.
Ahmed Bougacha46937272013-08-21 07:28:32 +0000282 for (size_t wi = 0; wi < Worklist.size(); ++wi) {
283 BBInfo *BBI = Worklist[wi];
Ahmed Bougachaef993562013-05-24 01:07:04 +0000284 MCBasicBlock *MCBB = BBI->BB;
285 if (!MCBB)
286 continue;
287 for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
Ahmed Bougacha46937272013-08-21 07:28:32 +0000288 SI != SE; ++SI)
289 if ((*SI)->BB)
290 MCBB->addSuccessor((*SI)->BB);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000291 for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
Ahmed Bougacha46937272013-08-21 07:28:32 +0000292 PI != PE; ++PI)
293 if ((*PI)->BB)
294 MCBB->addPredecessor((*PI)->BB);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000295 }
296 }
297}
Ahmed Bougacha0e83b902013-08-21 07:28:44 +0000298
299// MachO MCObjectDisassembler implementation.
300
301MCMachOObjectDisassembler::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.
327uint64_t MCMachOObjectDisassembler::getEffectiveLoadAddr(uint64_t Addr) {
328 return Addr + VMAddrSlide;
329}
330
331uint64_t
332MCMachOObjectDisassembler::getOriginalLoadAddr(uint64_t EffectiveAddr) {
333 return EffectiveAddr - VMAddrSlide;
334}
335
336uint64_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
365ArrayRef<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
375ArrayRef<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}