blob: 60c33f27892313e3396c08bae9212da81c90ec92 [file] [log] [blame]
Benjamin Kramer0b8b7712011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
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// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
15#include "MCFunction.h"
16#include "llvm/Support/MachO.h"
Owen Anderson481837a2011-10-17 21:37:35 +000017#include "llvm/Object/MachO.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/ADT/STLExtras.h"
Benjamin Kramer8c930972011-09-21 01:13:19 +000021#include "llvm/DebugInfo/DIContext.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000022#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
26#include "llvm/MC/MCInstrAnalysis.h"
27#include "llvm/MC/MCInstrDesc.h"
28#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachc6449b62012-03-05 19:33:20 +000029#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000030#include "llvm/MC/MCSubtargetInfo.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/Format.h"
34#include "llvm/Support/GraphWriter.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Support/TargetSelect.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Support/system_error.h"
40#include <algorithm>
41#include <cstring>
42using namespace llvm;
43using namespace object;
44
45static cl::opt<bool>
46 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
47 "write it to a graphviz file (MachO-only)"));
48
Benjamin Kramer8c930972011-09-21 01:13:19 +000049static cl::opt<bool>
50 UseDbg("g", cl::desc("Print line information from debug info if available"));
51
52static cl::opt<std::string>
53 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
54
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000055static const Target *GetTarget(const MachOObject *MachOObj) {
56 // Figure out the target triple.
Cameron Zwaricha9935052012-02-03 06:35:22 +000057 if (TripleName.empty()) {
58 llvm::Triple TT("unknown-unknown-unknown");
59 switch (MachOObj->getHeader().CPUType) {
60 case llvm::MachO::CPUTypeI386:
61 TT.setArch(Triple::ArchType(Triple::x86));
62 break;
63 case llvm::MachO::CPUTypeX86_64:
64 TT.setArch(Triple::ArchType(Triple::x86_64));
65 break;
66 case llvm::MachO::CPUTypeARM:
67 TT.setArch(Triple::ArchType(Triple::arm));
68 break;
69 case llvm::MachO::CPUTypePowerPC:
70 TT.setArch(Triple::ArchType(Triple::ppc));
71 break;
72 case llvm::MachO::CPUTypePowerPC64:
73 TT.setArch(Triple::ArchType(Triple::ppc64));
74 break;
75 }
76 TripleName = TT.str();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000077 }
78
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000079 // Get the target specific parser.
80 std::string Error;
81 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
82 if (TheTarget)
83 return TheTarget;
84
85 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
86 << "', see --version and --triple.\n";
87 return 0;
88}
89
Owen Anderson481837a2011-10-17 21:37:35 +000090struct SymbolSorter {
91 bool operator()(const SymbolRef &A, const SymbolRef &B) {
92 SymbolRef::Type AType, BType;
93 A.getType(AType);
94 B.getType(BType);
95
96 uint64_t AAddr, BAddr;
97 if (AType != SymbolRef::ST_Function)
98 AAddr = 0;
99 else
100 A.getAddress(AAddr);
101 if (BType != SymbolRef::ST_Function)
102 BAddr = 0;
103 else
104 B.getAddress(BAddr);
105 return AAddr < BAddr;
106 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000107};
108
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000109// Print additional information about an address, if available.
Owen Anderson481837a2011-10-17 21:37:35 +0000110static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000111 MachOObject *MachOObj, raw_ostream &OS) {
112 for (unsigned i = 0; i != Sections.size(); ++i) {
Owen Anderson481837a2011-10-17 21:37:35 +0000113 uint64_t SectAddr = 0, SectSize = 0;
114 Sections[i].getAddress(SectAddr);
115 Sections[i].getSize(SectSize);
116 uint64_t addr = SectAddr;
117 if (SectAddr <= Address &&
118 SectAddr + SectSize > Address) {
119 StringRef bytes, name;
120 Sections[i].getContents(bytes);
121 Sections[i].getName(name);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000122 // Print constant strings.
Owen Anderson481837a2011-10-17 21:37:35 +0000123 if (!name.compare("__cstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000124 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000125 // Print constant CFStrings.
Owen Anderson481837a2011-10-17 21:37:35 +0000126 if (!name.compare("__cfstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000127 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
128 }
129 }
130}
131
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000132typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
133typedef SmallVector<MCFunction, 16> FunctionListTy;
134static void createMCFunctionAndSaveCalls(StringRef Name,
135 const MCDisassembler *DisAsm,
136 MemoryObject &Object, uint64_t Start,
137 uint64_t End,
138 MCInstrAnalysis *InstrAnalysis,
139 uint64_t Address,
140 raw_ostream &DebugOut,
141 FunctionMapTy &FunctionMap,
142 FunctionListTy &Functions) {
143 SmallVector<uint64_t, 16> Calls;
144 MCFunction f =
145 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
146 InstrAnalysis, DebugOut, Calls);
147 Functions.push_back(f);
148 FunctionMap[Address] = &Functions.back();
149
150 // Add the gathered callees to the map.
151 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
152 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
153}
154
155// Write a graphviz file for the CFG inside an MCFunction.
156static void emitDOTFile(const char *FileName, const MCFunction &f,
157 MCInstPrinter *IP) {
158 // Start a new dot file.
159 std::string Error;
160 raw_fd_ostream Out(FileName, Error);
161 if (!Error.empty()) {
162 errs() << "llvm-objdump: warning: " << Error << '\n';
163 return;
164 }
165
166 Out << "digraph " << f.getName() << " {\n";
167 Out << "graph [ rankdir = \"LR\" ];\n";
168 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
169 bool hasPreds = false;
170 // Only print blocks that have predecessors.
171 // FIXME: Slow.
172 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
173 ++pi)
174 if (pi->second.contains(i->first)) {
175 hasPreds = true;
176 break;
177 }
178
179 if (!hasPreds && i != f.begin())
180 continue;
181
182 Out << '"' << i->first << "\" [ label=\"<a>";
183 // Print instructions.
184 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
185 ++ii) {
186 // Escape special chars and print the instruction in mnemonic form.
187 std::string Str;
188 raw_string_ostream OS(Str);
189 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
190 Out << DOT::EscapeString(OS.str()) << '|';
191 }
192 Out << "<o>\" shape=\"record\" ];\n";
193
194 // Add edges.
195 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
196 se = i->second.succ_end(); si != se; ++si)
197 Out << i->first << ":o -> " << *si <<":a\n";
198 }
199 Out << "}\n";
200}
201
Benjamin Kramer8c930972011-09-21 01:13:19 +0000202static void getSectionsAndSymbols(const macho::Header &Header,
Owen Anderson481837a2011-10-17 21:37:35 +0000203 MachOObjectFile *MachOObj,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000204 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
Owen Anderson481837a2011-10-17 21:37:35 +0000205 std::vector<SectionRef> &Sections,
206 std::vector<SymbolRef> &Symbols,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000207 SmallVectorImpl<uint64_t> &FoundFns) {
Owen Anderson481837a2011-10-17 21:37:35 +0000208 error_code ec;
209 for (symbol_iterator SI = MachOObj->begin_symbols(),
210 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
211 Symbols.push_back(*SI);
212
213 for (section_iterator SI = MachOObj->begin_sections(),
214 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
215 SectionRef SR = *SI;
216 StringRef SectName;
217 SR.getName(SectName);
218 Sections.push_back(*SI);
219 }
220
Benjamin Kramer8c930972011-09-21 01:13:19 +0000221 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
Owen Anderson481837a2011-10-17 21:37:35 +0000222 const MachOObject::LoadCommandInfo &LCI =
223 MachOObj->getObject()->getLoadCommandInfo(i);
224 if (LCI.Command.Type == macho::LCT_FunctionStarts) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000225 // We found a function starts segment, parse the addresses for later
226 // consumption.
227 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
Owen Anderson481837a2011-10-17 21:37:35 +0000228 MachOObj->getObject()->ReadLinkeditDataLoadCommand(LCI, LLC);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000229
Owen Anderson481837a2011-10-17 21:37:35 +0000230 MachOObj->getObject()->ReadULEB128s(LLC->DataOffset, FoundFns);
Benjamin Kramerafbaf482011-09-21 22:16:43 +0000231 }
232 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000233}
234
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000235void llvm::DisassembleInputMachO(StringRef Filename) {
236 OwningPtr<MemoryBuffer> Buff;
237
238 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
239 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
240 return;
241 }
242
Owen Anderson481837a2011-10-17 21:37:35 +0000243 OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
244 ObjectFile::createMachOObjectFile(Buff.take())));
245 MachOObject *MachOObj = MachOOF->getObject();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000246
Owen Anderson481837a2011-10-17 21:37:35 +0000247 const Target *TheTarget = GetTarget(MachOObj);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000248 if (!TheTarget) {
249 // GetTarget prints out stuff.
250 return;
251 }
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000252 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000253 OwningPtr<MCInstrAnalysis>
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000254 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000255
256 // Set up disassembler.
257 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000258 OwningPtr<const MCSubtargetInfo>
259 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000260 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Jim Grosbachc6449b62012-03-05 19:33:20 +0000261 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000262 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Craig Topper17463b32012-04-02 06:09:36 +0000263 OwningPtr<MCInstPrinter>
264 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
265 *MRI, *STI));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000266
267 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000268 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000269 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000270 return;
271 }
272
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000273 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000274
275 const macho::Header &Header = MachOObj->getHeader();
276
277 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000278 // First, find the symbol table segment.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000279 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
280 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000281 if (LCI.Command.Type == macho::LCT_Symtab) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000282 SymtabLCI = &LCI;
283 break;
284 }
285 }
286
287 // Read and register the symbol table data.
288 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
289 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
290 MachOObj->RegisterStringTable(*SymtabLC);
291
Owen Anderson481837a2011-10-17 21:37:35 +0000292 std::vector<SectionRef> Sections;
293 std::vector<SymbolRef> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000294 SmallVector<uint64_t, 8> FoundFns;
295
Owen Anderson481837a2011-10-17 21:37:35 +0000296 getSectionsAndSymbols(Header, MachOOF.get(), &SymtabLC, Sections, Symbols,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000297 FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000298
Benjamin Kramer8c930972011-09-21 01:13:19 +0000299 // Make a copy of the unsorted symbol list. FIXME: duplication
Owen Anderson481837a2011-10-17 21:37:35 +0000300 std::vector<SymbolRef> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000301 // Sort the symbols by address, just in case they didn't come in that way.
Owen Anderson481837a2011-10-17 21:37:35 +0000302 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000303
304#ifndef NDEBUG
305 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
306#else
307 raw_ostream &DebugOut = nulls();
308#endif
309
Benjamin Kramer8c930972011-09-21 01:13:19 +0000310 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
311 DebugLineSection, DebugStrSection;
312 OwningPtr<DIContext> diContext;
Owen Anderson481837a2011-10-17 21:37:35 +0000313 OwningPtr<MachOObjectFile> DSYMObj;
314 MachOObject *DbgInfoObj = MachOObj;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000315 // Try to find debug info and set up the DIContext for it.
316 if (UseDbg) {
Owen Anderson481837a2011-10-17 21:37:35 +0000317 ArrayRef<SectionRef> DebugSections = Sections;
318 std::vector<SectionRef> DSYMSections;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000319
320 // A separate DSym file path was specified, parse it as a macho file,
321 // get the sections and supply it to the section name parsing machinery.
322 if (!DSYMFile.empty()) {
323 OwningPtr<MemoryBuffer> Buf;
324 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
325 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
326 return;
327 }
Owen Anderson481837a2011-10-17 21:37:35 +0000328 DSYMObj.reset(static_cast<MachOObjectFile*>(
329 ObjectFile::createMachOObjectFile(Buf.take())));
330 const macho::Header &Header = DSYMObj->getObject()->getHeader();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000331
Owen Anderson481837a2011-10-17 21:37:35 +0000332 std::vector<SymbolRef> Symbols;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000333 SmallVector<uint64_t, 8> FoundFns;
334 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
335 FoundFns);
336 DebugSections = DSYMSections;
Owen Anderson481837a2011-10-17 21:37:35 +0000337 DbgInfoObj = DSYMObj.get()->getObject();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000338 }
339
340 // Find the named debug info sections.
341 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000342 StringRef SectName;
343 if (!DebugSections[SectIdx].getName(SectName)) {
344 if (SectName.equals("__DWARF,__debug_abbrev"))
345 DebugSections[SectIdx].getContents(DebugAbbrevSection);
346 else if (SectName.equals("__DWARF,__debug_info"))
347 DebugSections[SectIdx].getContents(DebugInfoSection);
348 else if (SectName.equals("__DWARF,__debug_aranges"))
349 DebugSections[SectIdx].getContents(DebugArangesSection);
350 else if (SectName.equals("__DWARF,__debug_line"))
351 DebugSections[SectIdx].getContents(DebugLineSection);
352 else if (SectName.equals("__DWARF,__debug_str"))
353 DebugSections[SectIdx].getContents(DebugStrSection);
354 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000355 }
356
357 // Setup the DIContext.
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000358 diContext.reset(DIContext::getDWARFContext(DbgInfoObj->isLittleEndian(),
Benjamin Kramer8c930972011-09-21 01:13:19 +0000359 DebugInfoSection,
360 DebugAbbrevSection,
361 DebugArangesSection,
362 DebugLineSection,
363 DebugStrSection));
364 }
365
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000366 FunctionMapTy FunctionMap;
367 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000368
369 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000370 StringRef SectName;
371 if (Sections[SectIdx].getName(SectName) ||
372 SectName.compare("__TEXT,__text"))
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000373 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000374
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000375 // Insert the functions from the function starts segment into our map.
Owen Anderson481837a2011-10-17 21:37:35 +0000376 uint64_t VMAddr;
377 Sections[SectIdx].getAddress(VMAddr);
378 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
379 StringRef SectBegin;
380 Sections[SectIdx].getContents(SectBegin);
381 uint64_t Offset = (uint64_t)SectBegin.data();
382 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
383 (MCFunction*)0));
384 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000385
Owen Anderson481837a2011-10-17 21:37:35 +0000386 StringRef Bytes;
387 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000388 StringRefMemoryObject memoryObject(Bytes);
389 bool symbolTableWorked = false;
390
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000391 // Parse relocations.
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000392 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
Owen Anderson481837a2011-10-17 21:37:35 +0000393 error_code ec;
394 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
395 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
396 uint64_t RelocOffset, SectionAddress;
397 RI->getAddress(RelocOffset);
398 Sections[SectIdx].getAddress(SectionAddress);
399 RelocOffset -= SectionAddress;
400
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000401 SymbolRef RelocSym;
402 RI->getSymbol(RelocSym);
Owen Anderson481837a2011-10-17 21:37:35 +0000403
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000404 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000405 }
406 array_pod_sort(Relocs.begin(), Relocs.end());
407
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000408 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000409 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000410 StringRef SymName;
411 Symbols[SymIdx].getName(SymName);
412
413 SymbolRef::Type ST;
414 Symbols[SymIdx].getType(ST);
415 if (ST != SymbolRef::ST_Function)
416 continue;
417
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000418 // Make sure the symbol is defined in this section.
Owen Anderson481837a2011-10-17 21:37:35 +0000419 bool containsSym = false;
420 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
421 if (!containsSym)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000422 continue;
423
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000424 // Start at the address of the symbol relative to the section's address.
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000425 uint64_t SectionAddress = 0;
Owen Anderson481837a2011-10-17 21:37:35 +0000426 uint64_t Start = 0;
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000427 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000428 Symbols[SymIdx].getAddress(Start);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000429 Start -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000430
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000431 // Stop disassembling either at the beginning of the next symbol or at
432 // the end of the section.
Kevin Enderby41854ae2012-05-15 18:57:14 +0000433 bool containsNextSym = false;
Owen Anderson481837a2011-10-17 21:37:35 +0000434 uint64_t NextSym = 0;
435 uint64_t NextSymIdx = SymIdx+1;
436 while (Symbols.size() > NextSymIdx) {
437 SymbolRef::Type NextSymType;
438 Symbols[NextSymIdx].getType(NextSymType);
439 if (NextSymType == SymbolRef::ST_Function) {
440 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
441 containsNextSym);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000442 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000443 NextSym -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000444 break;
445 }
446 ++NextSymIdx;
447 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000448
Owen Anderson481837a2011-10-17 21:37:35 +0000449 uint64_t SectSize;
450 Sections[SectIdx].getSize(SectSize);
451 uint64_t End = containsNextSym ? NextSym : SectSize;
452 uint64_t Size;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000453
454 symbolTableWorked = true;
455
456 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000457 // Normal disassembly, print addresses, bytes and mnemonic form.
Owen Anderson481837a2011-10-17 21:37:35 +0000458 StringRef SymName;
459 Symbols[SymIdx].getName(SymName);
460
461 outs() << SymName << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000462 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000463 for (uint64_t Index = Start; Index < End; Index += Size) {
464 MCInst Inst;
465
466 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
467 DebugOut, nulls())) {
Owen Anderson481837a2011-10-17 21:37:35 +0000468 uint64_t SectAddress = 0;
469 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramer41a96492011-11-05 08:57:40 +0000470 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
Owen Anderson481837a2011-10-17 21:37:35 +0000471
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000472 DumpBytes(StringRef(Bytes.data() + Index, Size));
473 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000474
475 // Print debug info.
476 if (diContext) {
477 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000478 diContext->getLineInfoForAddress(SectAddress + Index);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000479 // Print valid line info if it changed.
480 if (dli != lastLine && dli.getLine() != 0)
481 outs() << "\t## " << dli.getFileName() << ':'
482 << dli.getLine() << ':' << dli.getColumn();
483 lastLine = dli;
484 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000485 outs() << "\n";
486 } else {
487 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
488 if (Size == 0)
489 Size = 1; // skip illegible bytes
490 }
491 }
492 } else {
493 // Create CFG and use it for disassembly.
Owen Anderson481837a2011-10-17 21:37:35 +0000494 StringRef SymName;
495 Symbols[SymIdx].getName(SymName);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000496 createMCFunctionAndSaveCalls(
Owen Anderson481837a2011-10-17 21:37:35 +0000497 SymName, DisAsm.get(), memoryObject, Start, End,
498 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000499 }
500 }
501
502 if (CFG) {
503 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000504 // Reading the symbol table didn't work, create a big __TEXT symbol.
Owen Anderson481837a2011-10-17 21:37:35 +0000505 uint64_t SectSize = 0, SectAddress = 0;
506 Sections[SectIdx].getSize(SectSize);
507 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000508 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
Owen Anderson481837a2011-10-17 21:37:35 +0000509 0, SectSize,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000510 InstrAnalysis.get(),
Owen Anderson481837a2011-10-17 21:37:35 +0000511 SectAddress, DebugOut,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000512 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000513 }
514 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
515 me = FunctionMap.end(); mi != me; ++mi)
516 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000517 // Create functions for the remaining callees we have gathered,
518 // but we didn't find a name for them.
Owen Anderson481837a2011-10-17 21:37:35 +0000519 uint64_t SectSize = 0;
520 Sections[SectIdx].getSize(SectSize);
521
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000522 SmallVector<uint64_t, 16> Calls;
523 MCFunction f =
524 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
525 memoryObject, mi->first,
Owen Anderson481837a2011-10-17 21:37:35 +0000526 SectSize,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000527 InstrAnalysis.get(), DebugOut,
528 Calls);
529 Functions.push_back(f);
530 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000531 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
532 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
533 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000534 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000535 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000536 }
537
538 DenseSet<uint64_t> PrintedBlocks;
539 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
540 MCFunction &f = Functions[ffi];
541 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
542 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000543 continue; // We already printed this block.
544
545 // We assume a block has predecessors when it's the first block after
546 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000547 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
548
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000549 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000550 // FIXME: Slow.
551 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
552 ++pi)
553 if (pi->second.contains(fi->first)) {
554 hasPreds = true;
555 break;
556 }
557
Owen Anderson481837a2011-10-17 21:37:35 +0000558 uint64_t SectSize = 0, SectAddress;
559 Sections[SectIdx].getSize(SectSize);
560 Sections[SectIdx].getAddress(SectAddress);
561
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000562 // No predecessors, this is a data block. Print as .byte directives.
563 if (!hasPreds) {
Owen Anderson481837a2011-10-17 21:37:35 +0000564 uint64_t End = llvm::next(fi) == fe ? SectSize :
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000565 llvm::next(fi)->first;
566 outs() << "# " << End-fi->first << " bytes of data:\n";
567 for (unsigned pos = fi->first; pos != End; ++pos) {
Owen Anderson481837a2011-10-17 21:37:35 +0000568 outs() << format("%8x:\t", SectAddress + pos);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000569 DumpBytes(StringRef(Bytes.data() + pos, 1));
570 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
571 }
572 continue;
573 }
574
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000575 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000576 outs() << "# Loop begin:\n";
577
Benjamin Kramer8c930972011-09-21 01:13:19 +0000578 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000579 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000580 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
581 ++ii) {
582 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000583
584 // If there's a symbol at this address, print its name.
Owen Anderson481837a2011-10-17 21:37:35 +0000585 if (FunctionMap.find(SectAddress + Inst.Address) !=
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000586 FunctionMap.end())
Owen Anderson481837a2011-10-17 21:37:35 +0000587 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
588 << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000589
Benjamin Kramer41a96492011-11-05 08:57:40 +0000590 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000591 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000592
593 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000594 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000595
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000596 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000597
598 // Look for relocations inside this instructions, if there is one
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000599 // print its target and additional information if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000600 for (unsigned j = 0; j != Relocs.size(); ++j)
Owen Anderson481837a2011-10-17 21:37:35 +0000601 if (Relocs[j].first >= SectAddress + Inst.Address &&
602 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
603 StringRef SymName;
604 uint64_t Addr;
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000605 Relocs[j].second.getAddress(Addr);
606 Relocs[j].second.getName(SymName);
Owen Anderson481837a2011-10-17 21:37:35 +0000607
608 outs() << "\t# " << SymName << ' ';
609 DumpAddress(Addr, Sections, MachOObj, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000610 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000611
612 // If this instructions contains an address, see if we can evaluate
613 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000614 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
615 Inst.Address,
616 Inst.Size);
617 if (targ != -1ULL)
Owen Anderson481837a2011-10-17 21:37:35 +0000618 DumpAddress(targ, Sections, MachOObj, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000619
Benjamin Kramer8c930972011-09-21 01:13:19 +0000620 // Print debug info.
621 if (diContext) {
622 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000623 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000624 // Print valid line info if it changed.
625 if (dli != lastLine && dli.getLine() != 0)
626 outs() << "\t## " << dli.getFileName() << ':'
627 << dli.getLine() << ':' << dli.getColumn();
628 lastLine = dli;
629 }
630
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000631 outs() << '\n';
632 }
633 }
634
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000635 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000636 }
637 }
638 }
639}