blob: 6b3ad836429b91d0db3bbddd034f6b37734441dd [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"
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"
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>
30#include <set>
31
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;
152 typedef std::set<BBInfo*> BBInfoSetTy;
153
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;
172 typedef std::set<uint64_t> AddressSetTy;
173 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 Bougacha0a30ccc2013-08-21 07:28:29 +0000187 Calls.insert(SymAddr);
188 Splits.insert(SymAddr);
189 }
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;
201 Calls.insert(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))
206 Splits.insert(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.insert(Target);
211 Splits.insert(Target);
212 }
213 }
214 }
215
216 // Split text atoms into basic block atoms.
217 for (AddressSetTy::const_iterator SI = Splits.begin(), SE = Splits.end();
218 SI != SE; ++SI) {
219 MCAtom *A = Module->findAtomContaining(*SI);
220 if (!A) continue;
221 MCTextAtom *TA = cast<MCTextAtom>(A);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000222 if (TA->getBeginAddr() == *SI)
223 continue;
224 MCTextAtom *NewAtom = TA->split(*SI);
225 BBInfos[NewAtom->getBeginAddr()].Atom = NewAtom;
226 StringRef BBName = TA->getName();
227 BBName = BBName.substr(0, BBName.find_last_of(':'));
228 NewAtom->setName((BBName + ":" + utohexstr(*SI)).str());
229 }
230
231 // Compute succs/preds.
232 for (MCModule::atom_iterator AI = Module->atom_begin(),
233 AE = Module->atom_end();
234 AI != AE; ++AI) {
235 MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI);
236 if (!TA) continue;
237 BBInfo &CurBB = BBInfos[TA->getBeginAddr()];
238 const MCDecodedInst &LI = TA->back();
239 if (MIA.isBranch(LI.Inst)) {
240 uint64_t Target;
241 if (MIA.evaluateBranch(LI.Inst, LI.Address, LI.Size, Target))
242 CurBB.addSucc(BBInfos[Target]);
243 if (MIA.isConditionalBranch(LI.Inst))
244 CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
245 } else if (!MIA.isTerminator(LI.Inst))
246 CurBB.addSucc(BBInfos[LI.Address + LI.Size]);
247 }
248
249
250 // Create functions and basic blocks.
251 for (AddressSetTy::const_iterator CI = Calls.begin(), CE = Calls.end();
252 CI != CE; ++CI) {
253 BBInfo &BBI = BBInfos[*CI];
254 if (!BBI.Atom) continue;
255
256 MCFunction &MCFN = *Module->createFunction(BBI.Atom->getName());
257
258 // Create MCBBs.
259 SmallSetVector<BBInfo*, 16> Worklist;
260 Worklist.insert(&BBI);
Ahmed Bougacha46937272013-08-21 07:28:32 +0000261 for (size_t wi = 0; wi < Worklist.size(); ++wi) {
262 BBInfo *BBI = Worklist[wi];
Ahmed Bougachaef993562013-05-24 01:07:04 +0000263 if (!BBI->Atom)
264 continue;
265 BBI->BB = &MCFN.createBlock(*BBI->Atom);
266 // Add all predecessors and successors to the worklist.
267 for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
268 SI != SE; ++SI)
269 Worklist.insert(*SI);
270 for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
271 PI != PE; ++PI)
272 Worklist.insert(*PI);
273 }
274
275 // Set preds/succs.
Ahmed Bougacha46937272013-08-21 07:28:32 +0000276 for (size_t wi = 0; wi < Worklist.size(); ++wi) {
277 BBInfo *BBI = Worklist[wi];
Ahmed Bougachaef993562013-05-24 01:07:04 +0000278 MCBasicBlock *MCBB = BBI->BB;
279 if (!MCBB)
280 continue;
281 for (BBInfoSetTy::iterator SI = BBI->Succs.begin(), SE = BBI->Succs.end();
Ahmed Bougacha46937272013-08-21 07:28:32 +0000282 SI != SE; ++SI)
283 if ((*SI)->BB)
284 MCBB->addSuccessor((*SI)->BB);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000285 for (BBInfoSetTy::iterator PI = BBI->Preds.begin(), PE = BBI->Preds.end();
Ahmed Bougacha46937272013-08-21 07:28:32 +0000286 PI != PE; ++PI)
287 if ((*PI)->BB)
288 MCBB->addPredecessor((*PI)->BB);
Ahmed Bougachaef993562013-05-24 01:07:04 +0000289 }
290 }
291}
Ahmed Bougacha0e83b902013-08-21 07:28:44 +0000292
293// MachO MCObjectDisassembler implementation.
294
295MCMachOObjectDisassembler::MCMachOObjectDisassembler(
296 const MachOObjectFile &MOOF, const MCDisassembler &Dis,
297 const MCInstrAnalysis &MIA, uint64_t VMAddrSlide,
298 uint64_t HeaderLoadAddress)
299 : MCObjectDisassembler(MOOF, Dis, MIA), MOOF(MOOF),
300 VMAddrSlide(VMAddrSlide), HeaderLoadAddress(HeaderLoadAddress) {
301
302 error_code ec;
303 for (section_iterator SI = MOOF.begin_sections(), SE = MOOF.end_sections();
304 SI != SE; SI.increment(ec)) {
305 if (ec)
306 break;
307 StringRef Name;
308 SI->getName(Name);
309 // FIXME: We should use the S_ section type instead of the name.
310 if (Name == "__mod_init_func") {
311 DEBUG(dbgs() << "Found __mod_init_func section!\n");
312 SI->getContents(ModInitContents);
313 } else if (Name == "__mod_exit_func") {
314 DEBUG(dbgs() << "Found __mod_exit_func section!\n");
315 SI->getContents(ModExitContents);
316 }
317 }
318}
319
320// FIXME: Only do the translations for addresses actually inside the object.
321uint64_t MCMachOObjectDisassembler::getEffectiveLoadAddr(uint64_t Addr) {
322 return Addr + VMAddrSlide;
323}
324
325uint64_t
326MCMachOObjectDisassembler::getOriginalLoadAddr(uint64_t EffectiveAddr) {
327 return EffectiveAddr - VMAddrSlide;
328}
329
330uint64_t MCMachOObjectDisassembler::getEntrypoint() {
331 uint64_t EntryFileOffset = 0;
332
333 // Look for LC_MAIN.
334 {
335 uint32_t LoadCommandCount = MOOF.getHeader().NumLoadCommands;
336 MachOObjectFile::LoadCommandInfo Load = MOOF.getFirstLoadCommandInfo();
337 for (unsigned I = 0;; ++I) {
338 if (Load.C.Type == MachO::LoadCommandMain) {
339 EntryFileOffset =
340 ((const MachO::entry_point_command *)Load.Ptr)->entryoff;
341 break;
342 }
343
344 if (I == LoadCommandCount - 1)
345 break;
346 else
347 Load = MOOF.getNextLoadCommandInfo(Load);
348 }
349 }
350
351 // If we didn't find anything, default to the common implementation.
352 // FIXME: Maybe we could also look at LC_UNIXTHREAD and friends?
353 if (EntryFileOffset)
354 return MCObjectDisassembler::getEntrypoint();
355
356 return EntryFileOffset + HeaderLoadAddress;
357}
358
359ArrayRef<uint64_t> MCMachOObjectDisassembler::getStaticInitFunctions() {
360 // FIXME: We only handle 64bit mach-o
361 assert(MOOF.is64Bit());
362
363 size_t EntrySize = 8;
364 size_t EntryCount = ModInitContents.size() / EntrySize;
365 return ArrayRef<uint64_t>(
366 reinterpret_cast<const uint64_t *>(ModInitContents.data()), EntryCount);
367}
368
369ArrayRef<uint64_t> MCMachOObjectDisassembler::getStaticExitFunctions() {
370 // FIXME: We only handle 64bit mach-o
371 assert(MOOF.is64Bit());
372
373 size_t EntrySize = 8;
374 size_t EntryCount = ModExitContents.size() / EntrySize;
375 return ArrayRef<uint64_t>(
376 reinterpret_cast<const uint64_t *>(ModExitContents.data()), EntryCount);
377}