blob: 894e769115ccb171e01343fb60d6d3d148526597 [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"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000016#include "llvm/ADT/OwningPtr.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Benjamin Kramer8c930972011-09-21 01:13:19 +000019#include "llvm/DebugInfo/DIContext.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000020#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCDisassembler.h"
22#include "llvm/MC/MCInst.h"
23#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrAnalysis.h"
25#include "llvm/MC/MCInstrDesc.h"
26#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachc6449b62012-03-05 19:33:20 +000027#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000028#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000029#include "llvm/Object/MachO.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/Format.h"
33#include "llvm/Support/GraphWriter.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000034#include "llvm/Support/MachO.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000035#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"
Evan Chengc698a442012-07-02 19:45:42 +000047 " write it to a graphviz file (MachO-only)"));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000048
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,
Owen Anderson481837a2011-10-17 21:37:35 +0000204 std::vector<SectionRef> &Sections,
205 std::vector<SymbolRef> &Symbols,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000206 SmallVectorImpl<uint64_t> &FoundFns) {
Owen Anderson481837a2011-10-17 21:37:35 +0000207 error_code ec;
208 for (symbol_iterator SI = MachOObj->begin_symbols(),
209 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
210 Symbols.push_back(*SI);
211
212 for (section_iterator SI = MachOObj->begin_sections(),
213 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
214 SectionRef SR = *SI;
215 StringRef SectName;
216 SR.getName(SectName);
217 Sections.push_back(*SI);
218 }
219
Benjamin Kramer8c930972011-09-21 01:13:19 +0000220 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
Owen Anderson481837a2011-10-17 21:37:35 +0000221 const MachOObject::LoadCommandInfo &LCI =
222 MachOObj->getObject()->getLoadCommandInfo(i);
223 if (LCI.Command.Type == macho::LCT_FunctionStarts) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000224 // We found a function starts segment, parse the addresses for later
225 // consumption.
Rafael Espindola196abbf2013-04-07 14:40:18 +0000226 const MachOFormat::LinkeditDataLoadCommand *LLC =
227 MachOObj->getLinkeditDataLoadCommand(LCI);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000228
Owen Anderson481837a2011-10-17 21:37:35 +0000229 MachOObj->getObject()->ReadULEB128s(LLC->DataOffset, FoundFns);
Benjamin Kramerafbaf482011-09-21 22:16:43 +0000230 }
231 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000232}
233
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000234void llvm::DisassembleInputMachO(StringRef Filename) {
235 OwningPtr<MemoryBuffer> Buff;
236
237 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
238 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
239 return;
240 }
241
Owen Anderson481837a2011-10-17 21:37:35 +0000242 OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
243 ObjectFile::createMachOObjectFile(Buff.take())));
244 MachOObject *MachOObj = MachOOF->getObject();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000245
Owen Anderson481837a2011-10-17 21:37:35 +0000246 const Target *TheTarget = GetTarget(MachOObj);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000247 if (!TheTarget) {
248 // GetTarget prints out stuff.
249 return;
250 }
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000251 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000252 OwningPtr<MCInstrAnalysis>
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000253 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000254
255 // Set up disassembler.
256 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000257 OwningPtr<const MCSubtargetInfo>
258 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000259 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Jim Grosbachc6449b62012-03-05 19:33:20 +0000260 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000261 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Craig Topper17463b32012-04-02 06:09:36 +0000262 OwningPtr<MCInstPrinter>
263 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
264 *MRI, *STI));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000265
266 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000267 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000268 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000269 return;
270 }
271
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000272 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000273
274 const macho::Header &Header = MachOObj->getHeader();
275
Owen Anderson481837a2011-10-17 21:37:35 +0000276 std::vector<SectionRef> Sections;
277 std::vector<SymbolRef> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000278 SmallVector<uint64_t, 8> FoundFns;
279
Rafael Espindolaeb721c02013-04-07 14:25:39 +0000280 getSectionsAndSymbols(Header, MachOOF.get(), Sections, Symbols, FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000281
Benjamin Kramer8c930972011-09-21 01:13:19 +0000282 // Make a copy of the unsorted symbol list. FIXME: duplication
Owen Anderson481837a2011-10-17 21:37:35 +0000283 std::vector<SymbolRef> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000284 // Sort the symbols by address, just in case they didn't come in that way.
Owen Anderson481837a2011-10-17 21:37:35 +0000285 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000286
287#ifndef NDEBUG
288 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
289#else
290 raw_ostream &DebugOut = nulls();
291#endif
292
Benjamin Kramer8c930972011-09-21 01:13:19 +0000293 OwningPtr<DIContext> diContext;
Eric Christopherd1726a42012-11-12 21:40:38 +0000294 ObjectFile *DbgObj = MachOOF.get();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000295 // Try to find debug info and set up the DIContext for it.
296 if (UseDbg) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000297 // A separate DSym file path was specified, parse it as a macho file,
298 // get the sections and supply it to the section name parsing machinery.
299 if (!DSYMFile.empty()) {
300 OwningPtr<MemoryBuffer> Buf;
301 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
302 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
303 return;
304 }
Eric Christopherd1726a42012-11-12 21:40:38 +0000305 DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
Benjamin Kramer8c930972011-09-21 01:13:19 +0000306 }
307
Eric Christopherd1726a42012-11-12 21:40:38 +0000308 // Setup the DIContext
309 diContext.reset(DIContext::getDWARFContext(DbgObj));
Benjamin Kramer8c930972011-09-21 01:13:19 +0000310 }
311
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000312 FunctionMapTy FunctionMap;
313 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000314
315 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000316 StringRef SectName;
317 if (Sections[SectIdx].getName(SectName) ||
Rafael Espindolacef81b32012-12-21 03:47:03 +0000318 SectName != "__text")
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000319 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000320
Rafael Espindolacef81b32012-12-21 03:47:03 +0000321 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Rafael Espindolaf16c2bb2013-04-05 15:15:22 +0000322 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
323 if (SegmentName != "__TEXT")
Rafael Espindolacef81b32012-12-21 03:47:03 +0000324 continue;
325
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000326 // Insert the functions from the function starts segment into our map.
Owen Anderson481837a2011-10-17 21:37:35 +0000327 uint64_t VMAddr;
328 Sections[SectIdx].getAddress(VMAddr);
329 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
330 StringRef SectBegin;
331 Sections[SectIdx].getContents(SectBegin);
332 uint64_t Offset = (uint64_t)SectBegin.data();
333 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
334 (MCFunction*)0));
335 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000336
Owen Anderson481837a2011-10-17 21:37:35 +0000337 StringRef Bytes;
338 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000339 StringRefMemoryObject memoryObject(Bytes);
340 bool symbolTableWorked = false;
341
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000342 // Parse relocations.
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000343 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
Owen Anderson481837a2011-10-17 21:37:35 +0000344 error_code ec;
345 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
346 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
347 uint64_t RelocOffset, SectionAddress;
348 RI->getAddress(RelocOffset);
349 Sections[SectIdx].getAddress(SectionAddress);
350 RelocOffset -= SectionAddress;
351
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000352 SymbolRef RelocSym;
353 RI->getSymbol(RelocSym);
Owen Anderson481837a2011-10-17 21:37:35 +0000354
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000355 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000356 }
357 array_pod_sort(Relocs.begin(), Relocs.end());
358
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000359 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000360 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000361 StringRef SymName;
362 Symbols[SymIdx].getName(SymName);
363
364 SymbolRef::Type ST;
365 Symbols[SymIdx].getType(ST);
366 if (ST != SymbolRef::ST_Function)
367 continue;
368
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000369 // Make sure the symbol is defined in this section.
Owen Anderson481837a2011-10-17 21:37:35 +0000370 bool containsSym = false;
371 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
372 if (!containsSym)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000373 continue;
374
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000375 // Start at the address of the symbol relative to the section's address.
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000376 uint64_t SectionAddress = 0;
Owen Anderson481837a2011-10-17 21:37:35 +0000377 uint64_t Start = 0;
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000378 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000379 Symbols[SymIdx].getAddress(Start);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000380 Start -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000381
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000382 // Stop disassembling either at the beginning of the next symbol or at
383 // the end of the section.
Kevin Enderby41854ae2012-05-15 18:57:14 +0000384 bool containsNextSym = false;
Owen Anderson481837a2011-10-17 21:37:35 +0000385 uint64_t NextSym = 0;
386 uint64_t NextSymIdx = SymIdx+1;
387 while (Symbols.size() > NextSymIdx) {
388 SymbolRef::Type NextSymType;
389 Symbols[NextSymIdx].getType(NextSymType);
390 if (NextSymType == SymbolRef::ST_Function) {
391 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
392 containsNextSym);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000393 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000394 NextSym -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000395 break;
396 }
397 ++NextSymIdx;
398 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000399
Owen Anderson481837a2011-10-17 21:37:35 +0000400 uint64_t SectSize;
401 Sections[SectIdx].getSize(SectSize);
402 uint64_t End = containsNextSym ? NextSym : SectSize;
403 uint64_t Size;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000404
405 symbolTableWorked = true;
406
407 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000408 // Normal disassembly, print addresses, bytes and mnemonic form.
Owen Anderson481837a2011-10-17 21:37:35 +0000409 StringRef SymName;
410 Symbols[SymIdx].getName(SymName);
411
412 outs() << SymName << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000413 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000414 for (uint64_t Index = Start; Index < End; Index += Size) {
415 MCInst Inst;
416
417 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
418 DebugOut, nulls())) {
Owen Anderson481837a2011-10-17 21:37:35 +0000419 uint64_t SectAddress = 0;
420 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramer41a96492011-11-05 08:57:40 +0000421 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
Owen Anderson481837a2011-10-17 21:37:35 +0000422
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000423 DumpBytes(StringRef(Bytes.data() + Index, Size));
424 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000425
426 // Print debug info.
427 if (diContext) {
428 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000429 diContext->getLineInfoForAddress(SectAddress + Index);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000430 // Print valid line info if it changed.
431 if (dli != lastLine && dli.getLine() != 0)
432 outs() << "\t## " << dli.getFileName() << ':'
433 << dli.getLine() << ':' << dli.getColumn();
434 lastLine = dli;
435 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000436 outs() << "\n";
437 } else {
438 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
439 if (Size == 0)
440 Size = 1; // skip illegible bytes
441 }
442 }
443 } else {
444 // Create CFG and use it for disassembly.
Owen Anderson481837a2011-10-17 21:37:35 +0000445 StringRef SymName;
446 Symbols[SymIdx].getName(SymName);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000447 createMCFunctionAndSaveCalls(
Owen Anderson481837a2011-10-17 21:37:35 +0000448 SymName, DisAsm.get(), memoryObject, Start, End,
449 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000450 }
451 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000452 if (!CFG && !symbolTableWorked) {
453 // Reading the symbol table didn't work, disassemble the whole section.
454 uint64_t SectAddress;
455 Sections[SectIdx].getAddress(SectAddress);
456 uint64_t SectSize;
457 Sections[SectIdx].getSize(SectSize);
458 uint64_t InstSize;
459 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendlingf59083c2012-07-19 00:17:40 +0000460 MCInst Inst;
Kevin Enderby59c15e92012-05-18 00:13:56 +0000461
Bill Wendlingf59083c2012-07-19 00:17:40 +0000462 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
463 DebugOut, nulls())) {
464 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
465 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
466 IP->printInst(&Inst, outs(), "");
467 outs() << "\n";
468 } else {
469 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
470 if (InstSize == 0)
471 InstSize = 1; // skip illegible bytes
472 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000473 }
474 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000475
476 if (CFG) {
477 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000478 // Reading the symbol table didn't work, create a big __TEXT symbol.
Owen Anderson481837a2011-10-17 21:37:35 +0000479 uint64_t SectSize = 0, SectAddress = 0;
480 Sections[SectIdx].getSize(SectSize);
481 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000482 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
Owen Anderson481837a2011-10-17 21:37:35 +0000483 0, SectSize,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000484 InstrAnalysis.get(),
Owen Anderson481837a2011-10-17 21:37:35 +0000485 SectAddress, DebugOut,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000486 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000487 }
488 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
489 me = FunctionMap.end(); mi != me; ++mi)
490 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000491 // Create functions for the remaining callees we have gathered,
492 // but we didn't find a name for them.
Owen Anderson481837a2011-10-17 21:37:35 +0000493 uint64_t SectSize = 0;
494 Sections[SectIdx].getSize(SectSize);
495
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000496 SmallVector<uint64_t, 16> Calls;
497 MCFunction f =
498 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
499 memoryObject, mi->first,
Owen Anderson481837a2011-10-17 21:37:35 +0000500 SectSize,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000501 InstrAnalysis.get(), DebugOut,
502 Calls);
503 Functions.push_back(f);
504 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000505 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
506 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
507 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000508 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000509 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000510 }
511
512 DenseSet<uint64_t> PrintedBlocks;
513 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
514 MCFunction &f = Functions[ffi];
515 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
516 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000517 continue; // We already printed this block.
518
519 // We assume a block has predecessors when it's the first block after
520 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000521 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
522
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000523 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000524 // FIXME: Slow.
525 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
526 ++pi)
527 if (pi->second.contains(fi->first)) {
528 hasPreds = true;
529 break;
530 }
531
Owen Anderson481837a2011-10-17 21:37:35 +0000532 uint64_t SectSize = 0, SectAddress;
533 Sections[SectIdx].getSize(SectSize);
534 Sections[SectIdx].getAddress(SectAddress);
535
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000536 // No predecessors, this is a data block. Print as .byte directives.
537 if (!hasPreds) {
Owen Anderson481837a2011-10-17 21:37:35 +0000538 uint64_t End = llvm::next(fi) == fe ? SectSize :
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000539 llvm::next(fi)->first;
540 outs() << "# " << End-fi->first << " bytes of data:\n";
541 for (unsigned pos = fi->first; pos != End; ++pos) {
Owen Anderson481837a2011-10-17 21:37:35 +0000542 outs() << format("%8x:\t", SectAddress + pos);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000543 DumpBytes(StringRef(Bytes.data() + pos, 1));
544 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
545 }
546 continue;
547 }
548
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000549 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000550 outs() << "# Loop begin:\n";
551
Benjamin Kramer8c930972011-09-21 01:13:19 +0000552 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000553 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000554 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
555 ++ii) {
556 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000557
558 // If there's a symbol at this address, print its name.
Owen Anderson481837a2011-10-17 21:37:35 +0000559 if (FunctionMap.find(SectAddress + Inst.Address) !=
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000560 FunctionMap.end())
Owen Anderson481837a2011-10-17 21:37:35 +0000561 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
562 << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000563
Benjamin Kramer41a96492011-11-05 08:57:40 +0000564 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000565 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000566
567 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000568 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000569
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000570 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000571
572 // Look for relocations inside this instructions, if there is one
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000573 // print its target and additional information if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000574 for (unsigned j = 0; j != Relocs.size(); ++j)
Owen Anderson481837a2011-10-17 21:37:35 +0000575 if (Relocs[j].first >= SectAddress + Inst.Address &&
576 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
577 StringRef SymName;
578 uint64_t Addr;
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000579 Relocs[j].second.getAddress(Addr);
580 Relocs[j].second.getName(SymName);
Owen Anderson481837a2011-10-17 21:37:35 +0000581
582 outs() << "\t# " << SymName << ' ';
583 DumpAddress(Addr, Sections, MachOObj, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000584 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000585
586 // If this instructions contains an address, see if we can evaluate
587 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000588 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
589 Inst.Address,
590 Inst.Size);
591 if (targ != -1ULL)
Owen Anderson481837a2011-10-17 21:37:35 +0000592 DumpAddress(targ, Sections, MachOObj, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000593
Benjamin Kramer8c930972011-09-21 01:13:19 +0000594 // Print debug info.
595 if (diContext) {
596 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000597 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000598 // Print valid line info if it changed.
599 if (dli != lastLine && dli.getLine() != 0)
600 outs() << "\t## " << dli.getFileName() << ':'
601 << dli.getLine() << ':' << dli.getColumn();
602 lastLine = dli;
603 }
604
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000605 outs() << '\n';
606 }
607 }
608
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000609 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000610 }
611 }
612 }
613}