blob: 89847d04999977b399a2a9ece6b18786d4fe3d44 [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
Rafael Espindolaf6cfc152013-04-09 14:49:08 +000055static const Target *GetTarget(const MachOObjectFileBase *MachOObj) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000056 // Figure out the target triple.
Cameron Zwaricha9935052012-02-03 06:35:22 +000057 if (TripleName.empty()) {
58 llvm::Triple TT("unknown-unknown-unknown");
Rafael Espindola317d3f42013-04-11 03:34:37 +000059 TT.setArch(Triple::ArchType(MachOObj->getArch()));
Cameron Zwaricha9935052012-02-03 06:35:22 +000060 TripleName = TT.str();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000061 }
62
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000063 // Get the target specific parser.
64 std::string Error;
65 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
66 if (TheTarget)
67 return TheTarget;
68
69 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
70 << "', see --version and --triple.\n";
71 return 0;
72}
73
Owen Anderson481837a2011-10-17 21:37:35 +000074struct SymbolSorter {
75 bool operator()(const SymbolRef &A, const SymbolRef &B) {
76 SymbolRef::Type AType, BType;
77 A.getType(AType);
78 B.getType(BType);
79
80 uint64_t AAddr, BAddr;
81 if (AType != SymbolRef::ST_Function)
82 AAddr = 0;
83 else
84 A.getAddress(AAddr);
85 if (BType != SymbolRef::ST_Function)
86 BAddr = 0;
87 else
88 B.getAddress(BAddr);
89 return AAddr < BAddr;
90 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000091};
92
Michael J. Spencer3773fb42011-10-07 19:25:47 +000093// Print additional information about an address, if available.
Owen Anderson481837a2011-10-17 21:37:35 +000094static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
Rafael Espindolaf6cfc152013-04-09 14:49:08 +000095 const MachOObjectFileBase *MachOObj, raw_ostream &OS) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000096 for (unsigned i = 0; i != Sections.size(); ++i) {
Owen Anderson481837a2011-10-17 21:37:35 +000097 uint64_t SectAddr = 0, SectSize = 0;
98 Sections[i].getAddress(SectAddr);
99 Sections[i].getSize(SectSize);
100 uint64_t addr = SectAddr;
101 if (SectAddr <= Address &&
102 SectAddr + SectSize > Address) {
103 StringRef bytes, name;
104 Sections[i].getContents(bytes);
105 Sections[i].getName(name);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000106 // Print constant strings.
Owen Anderson481837a2011-10-17 21:37:35 +0000107 if (!name.compare("__cstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000108 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000109 // Print constant CFStrings.
Owen Anderson481837a2011-10-17 21:37:35 +0000110 if (!name.compare("__cfstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000111 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
112 }
113 }
114}
115
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000116typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
117typedef SmallVector<MCFunction, 16> FunctionListTy;
118static void createMCFunctionAndSaveCalls(StringRef Name,
119 const MCDisassembler *DisAsm,
120 MemoryObject &Object, uint64_t Start,
121 uint64_t End,
122 MCInstrAnalysis *InstrAnalysis,
123 uint64_t Address,
124 raw_ostream &DebugOut,
125 FunctionMapTy &FunctionMap,
126 FunctionListTy &Functions) {
127 SmallVector<uint64_t, 16> Calls;
128 MCFunction f =
129 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
130 InstrAnalysis, DebugOut, Calls);
131 Functions.push_back(f);
132 FunctionMap[Address] = &Functions.back();
133
134 // Add the gathered callees to the map.
135 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
136 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
137}
138
139// Write a graphviz file for the CFG inside an MCFunction.
140static void emitDOTFile(const char *FileName, const MCFunction &f,
141 MCInstPrinter *IP) {
142 // Start a new dot file.
143 std::string Error;
144 raw_fd_ostream Out(FileName, Error);
145 if (!Error.empty()) {
146 errs() << "llvm-objdump: warning: " << Error << '\n';
147 return;
148 }
149
150 Out << "digraph " << f.getName() << " {\n";
151 Out << "graph [ rankdir = \"LR\" ];\n";
152 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
153 bool hasPreds = false;
154 // Only print blocks that have predecessors.
155 // FIXME: Slow.
156 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
157 ++pi)
158 if (pi->second.contains(i->first)) {
159 hasPreds = true;
160 break;
161 }
162
163 if (!hasPreds && i != f.begin())
164 continue;
165
166 Out << '"' << i->first << "\" [ label=\"<a>";
167 // Print instructions.
168 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
169 ++ii) {
170 // Escape special chars and print the instruction in mnemonic form.
171 std::string Str;
172 raw_string_ostream OS(Str);
173 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
174 Out << DOT::EscapeString(OS.str()) << '|';
175 }
176 Out << "<o>\" shape=\"record\" ];\n";
177
178 // Add edges.
179 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
180 se = i->second.succ_end(); si != se; ++si)
181 Out << i->first << ":o -> " << *si <<":a\n";
182 }
183 Out << "}\n";
184}
185
Rafael Espindolaa2561a02013-04-10 03:48:25 +0000186static void getSectionsAndSymbols(const MachOObjectFileBase::Header *Header,
Rafael Espindolaf6cfc152013-04-09 14:49:08 +0000187 MachOObjectFileBase *MachOObj,
Owen Anderson481837a2011-10-17 21:37:35 +0000188 std::vector<SectionRef> &Sections,
189 std::vector<SymbolRef> &Symbols,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000190 SmallVectorImpl<uint64_t> &FoundFns) {
Owen Anderson481837a2011-10-17 21:37:35 +0000191 error_code ec;
192 for (symbol_iterator SI = MachOObj->begin_symbols(),
193 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
194 Symbols.push_back(*SI);
195
196 for (section_iterator SI = MachOObj->begin_sections(),
197 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
198 SectionRef SR = *SI;
199 StringRef SectName;
200 SR.getName(SectName);
201 Sections.push_back(*SI);
202 }
203
Rafael Espindola433611b2013-04-07 19:26:57 +0000204 for (unsigned i = 0; i != Header->NumLoadCommands; ++i) {
Rafael Espindolaa2561a02013-04-10 03:48:25 +0000205 const MachOObjectFileBase::LoadCommand *Command =
206 MachOObj->getLoadCommandInfo(i);
Rafael Espindola6ab85a82013-04-07 18:42:06 +0000207 if (Command->Type == macho::LCT_FunctionStarts) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000208 // We found a function starts segment, parse the addresses for later
209 // consumption.
Rafael Espindolaa2561a02013-04-10 03:48:25 +0000210 const MachOObjectFileBase::LinkeditDataLoadCommand *LLC =
211 reinterpret_cast<const MachOObjectFileBase::LinkeditDataLoadCommand*>(Command);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000212
Rafael Espindola3eff3182013-04-07 16:07:35 +0000213 MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
Benjamin Kramerafbaf482011-09-21 22:16:43 +0000214 }
215 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000216}
217
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000218void llvm::DisassembleInputMachO(StringRef Filename) {
219 OwningPtr<MemoryBuffer> Buff;
220
221 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
222 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
223 return;
224 }
225
Rafael Espindolaf6cfc152013-04-09 14:49:08 +0000226 OwningPtr<MachOObjectFileBase> MachOOF(static_cast<MachOObjectFileBase*>(
Owen Anderson481837a2011-10-17 21:37:35 +0000227 ObjectFile::createMachOObjectFile(Buff.take())));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000228
Rafael Espindola3eff3182013-04-07 16:07:35 +0000229 const Target *TheTarget = GetTarget(MachOOF.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000230 if (!TheTarget) {
231 // GetTarget prints out stuff.
232 return;
233 }
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000234 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000235 OwningPtr<MCInstrAnalysis>
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000236 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000237
238 // Set up disassembler.
239 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000240 OwningPtr<const MCSubtargetInfo>
241 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000242 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Jim Grosbachc6449b62012-03-05 19:33:20 +0000243 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000244 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Craig Topper17463b32012-04-02 06:09:36 +0000245 OwningPtr<MCInstPrinter>
246 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
247 *MRI, *STI));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000248
249 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000250 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000251 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000252 return;
253 }
254
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000255 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000256
Rafael Espindolaa2561a02013-04-10 03:48:25 +0000257 const MachOObjectFileBase::Header *Header = MachOOF->getHeader();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000258
Owen Anderson481837a2011-10-17 21:37:35 +0000259 std::vector<SectionRef> Sections;
260 std::vector<SymbolRef> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000261 SmallVector<uint64_t, 8> FoundFns;
262
Rafael Espindolaeb721c02013-04-07 14:25:39 +0000263 getSectionsAndSymbols(Header, MachOOF.get(), Sections, Symbols, FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000264
Benjamin Kramer8c930972011-09-21 01:13:19 +0000265 // Make a copy of the unsorted symbol list. FIXME: duplication
Owen Anderson481837a2011-10-17 21:37:35 +0000266 std::vector<SymbolRef> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000267 // Sort the symbols by address, just in case they didn't come in that way.
Owen Anderson481837a2011-10-17 21:37:35 +0000268 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000269
270#ifndef NDEBUG
271 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
272#else
273 raw_ostream &DebugOut = nulls();
274#endif
275
Benjamin Kramer8c930972011-09-21 01:13:19 +0000276 OwningPtr<DIContext> diContext;
Eric Christopherd1726a42012-11-12 21:40:38 +0000277 ObjectFile *DbgObj = MachOOF.get();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000278 // Try to find debug info and set up the DIContext for it.
279 if (UseDbg) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000280 // A separate DSym file path was specified, parse it as a macho file,
281 // get the sections and supply it to the section name parsing machinery.
282 if (!DSYMFile.empty()) {
283 OwningPtr<MemoryBuffer> Buf;
284 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
285 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
286 return;
287 }
Eric Christopherd1726a42012-11-12 21:40:38 +0000288 DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
Benjamin Kramer8c930972011-09-21 01:13:19 +0000289 }
290
Eric Christopherd1726a42012-11-12 21:40:38 +0000291 // Setup the DIContext
292 diContext.reset(DIContext::getDWARFContext(DbgObj));
Benjamin Kramer8c930972011-09-21 01:13:19 +0000293 }
294
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000295 FunctionMapTy FunctionMap;
296 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000297
298 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000299 StringRef SectName;
300 if (Sections[SectIdx].getName(SectName) ||
Rafael Espindolacef81b32012-12-21 03:47:03 +0000301 SectName != "__text")
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000302 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000303
Rafael Espindolacef81b32012-12-21 03:47:03 +0000304 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Rafael Espindolaf16c2bb2013-04-05 15:15:22 +0000305 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
306 if (SegmentName != "__TEXT")
Rafael Espindolacef81b32012-12-21 03:47:03 +0000307 continue;
308
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000309 // Insert the functions from the function starts segment into our map.
Owen Anderson481837a2011-10-17 21:37:35 +0000310 uint64_t VMAddr;
311 Sections[SectIdx].getAddress(VMAddr);
312 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
313 StringRef SectBegin;
314 Sections[SectIdx].getContents(SectBegin);
315 uint64_t Offset = (uint64_t)SectBegin.data();
316 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
317 (MCFunction*)0));
318 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000319
Owen Anderson481837a2011-10-17 21:37:35 +0000320 StringRef Bytes;
321 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000322 StringRefMemoryObject memoryObject(Bytes);
323 bool symbolTableWorked = false;
324
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000325 // Parse relocations.
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000326 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
Owen Anderson481837a2011-10-17 21:37:35 +0000327 error_code ec;
328 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
329 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
330 uint64_t RelocOffset, SectionAddress;
331 RI->getAddress(RelocOffset);
332 Sections[SectIdx].getAddress(SectionAddress);
333 RelocOffset -= SectionAddress;
334
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000335 SymbolRef RelocSym;
336 RI->getSymbol(RelocSym);
Owen Anderson481837a2011-10-17 21:37:35 +0000337
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000338 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000339 }
340 array_pod_sort(Relocs.begin(), Relocs.end());
341
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000342 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000343 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000344 StringRef SymName;
345 Symbols[SymIdx].getName(SymName);
346
347 SymbolRef::Type ST;
348 Symbols[SymIdx].getType(ST);
349 if (ST != SymbolRef::ST_Function)
350 continue;
351
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000352 // Make sure the symbol is defined in this section.
Owen Anderson481837a2011-10-17 21:37:35 +0000353 bool containsSym = false;
354 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
355 if (!containsSym)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000356 continue;
357
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000358 // Start at the address of the symbol relative to the section's address.
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000359 uint64_t SectionAddress = 0;
Owen Anderson481837a2011-10-17 21:37:35 +0000360 uint64_t Start = 0;
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000361 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000362 Symbols[SymIdx].getAddress(Start);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000363 Start -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000364
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000365 // Stop disassembling either at the beginning of the next symbol or at
366 // the end of the section.
Kevin Enderby41854ae2012-05-15 18:57:14 +0000367 bool containsNextSym = false;
Owen Anderson481837a2011-10-17 21:37:35 +0000368 uint64_t NextSym = 0;
369 uint64_t NextSymIdx = SymIdx+1;
370 while (Symbols.size() > NextSymIdx) {
371 SymbolRef::Type NextSymType;
372 Symbols[NextSymIdx].getType(NextSymType);
373 if (NextSymType == SymbolRef::ST_Function) {
374 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
375 containsNextSym);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000376 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000377 NextSym -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000378 break;
379 }
380 ++NextSymIdx;
381 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000382
Owen Anderson481837a2011-10-17 21:37:35 +0000383 uint64_t SectSize;
384 Sections[SectIdx].getSize(SectSize);
385 uint64_t End = containsNextSym ? NextSym : SectSize;
386 uint64_t Size;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000387
388 symbolTableWorked = true;
389
390 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000391 // Normal disassembly, print addresses, bytes and mnemonic form.
Owen Anderson481837a2011-10-17 21:37:35 +0000392 StringRef SymName;
393 Symbols[SymIdx].getName(SymName);
394
395 outs() << SymName << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000396 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000397 for (uint64_t Index = Start; Index < End; Index += Size) {
398 MCInst Inst;
399
400 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
401 DebugOut, nulls())) {
Owen Anderson481837a2011-10-17 21:37:35 +0000402 uint64_t SectAddress = 0;
403 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramer41a96492011-11-05 08:57:40 +0000404 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
Owen Anderson481837a2011-10-17 21:37:35 +0000405
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000406 DumpBytes(StringRef(Bytes.data() + Index, Size));
407 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000408
409 // Print debug info.
410 if (diContext) {
411 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000412 diContext->getLineInfoForAddress(SectAddress + Index);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000413 // Print valid line info if it changed.
414 if (dli != lastLine && dli.getLine() != 0)
415 outs() << "\t## " << dli.getFileName() << ':'
416 << dli.getLine() << ':' << dli.getColumn();
417 lastLine = dli;
418 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000419 outs() << "\n";
420 } else {
421 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
422 if (Size == 0)
423 Size = 1; // skip illegible bytes
424 }
425 }
426 } else {
427 // Create CFG and use it for disassembly.
Owen Anderson481837a2011-10-17 21:37:35 +0000428 StringRef SymName;
429 Symbols[SymIdx].getName(SymName);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000430 createMCFunctionAndSaveCalls(
Owen Anderson481837a2011-10-17 21:37:35 +0000431 SymName, DisAsm.get(), memoryObject, Start, End,
432 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000433 }
434 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000435 if (!CFG && !symbolTableWorked) {
436 // Reading the symbol table didn't work, disassemble the whole section.
437 uint64_t SectAddress;
438 Sections[SectIdx].getAddress(SectAddress);
439 uint64_t SectSize;
440 Sections[SectIdx].getSize(SectSize);
441 uint64_t InstSize;
442 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendlingf59083c2012-07-19 00:17:40 +0000443 MCInst Inst;
Kevin Enderby59c15e92012-05-18 00:13:56 +0000444
Bill Wendlingf59083c2012-07-19 00:17:40 +0000445 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
446 DebugOut, nulls())) {
447 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
448 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
449 IP->printInst(&Inst, outs(), "");
450 outs() << "\n";
451 } else {
452 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
453 if (InstSize == 0)
454 InstSize = 1; // skip illegible bytes
455 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000456 }
457 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000458
459 if (CFG) {
460 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000461 // Reading the symbol table didn't work, create a big __TEXT symbol.
Owen Anderson481837a2011-10-17 21:37:35 +0000462 uint64_t SectSize = 0, SectAddress = 0;
463 Sections[SectIdx].getSize(SectSize);
464 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000465 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
Owen Anderson481837a2011-10-17 21:37:35 +0000466 0, SectSize,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000467 InstrAnalysis.get(),
Owen Anderson481837a2011-10-17 21:37:35 +0000468 SectAddress, DebugOut,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000469 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000470 }
471 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
472 me = FunctionMap.end(); mi != me; ++mi)
473 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000474 // Create functions for the remaining callees we have gathered,
475 // but we didn't find a name for them.
Owen Anderson481837a2011-10-17 21:37:35 +0000476 uint64_t SectSize = 0;
477 Sections[SectIdx].getSize(SectSize);
478
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000479 SmallVector<uint64_t, 16> Calls;
480 MCFunction f =
481 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
482 memoryObject, mi->first,
Owen Anderson481837a2011-10-17 21:37:35 +0000483 SectSize,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000484 InstrAnalysis.get(), DebugOut,
485 Calls);
486 Functions.push_back(f);
487 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000488 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
489 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
490 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000491 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000492 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000493 }
494
495 DenseSet<uint64_t> PrintedBlocks;
496 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
497 MCFunction &f = Functions[ffi];
498 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
499 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000500 continue; // We already printed this block.
501
502 // We assume a block has predecessors when it's the first block after
503 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000504 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
505
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000506 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000507 // FIXME: Slow.
508 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
509 ++pi)
510 if (pi->second.contains(fi->first)) {
511 hasPreds = true;
512 break;
513 }
514
Owen Anderson481837a2011-10-17 21:37:35 +0000515 uint64_t SectSize = 0, SectAddress;
516 Sections[SectIdx].getSize(SectSize);
517 Sections[SectIdx].getAddress(SectAddress);
518
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000519 // No predecessors, this is a data block. Print as .byte directives.
520 if (!hasPreds) {
Owen Anderson481837a2011-10-17 21:37:35 +0000521 uint64_t End = llvm::next(fi) == fe ? SectSize :
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000522 llvm::next(fi)->first;
523 outs() << "# " << End-fi->first << " bytes of data:\n";
524 for (unsigned pos = fi->first; pos != End; ++pos) {
Owen Anderson481837a2011-10-17 21:37:35 +0000525 outs() << format("%8x:\t", SectAddress + pos);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000526 DumpBytes(StringRef(Bytes.data() + pos, 1));
527 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
528 }
529 continue;
530 }
531
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000532 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000533 outs() << "# Loop begin:\n";
534
Benjamin Kramer8c930972011-09-21 01:13:19 +0000535 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000536 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000537 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
538 ++ii) {
539 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000540
541 // If there's a symbol at this address, print its name.
Owen Anderson481837a2011-10-17 21:37:35 +0000542 if (FunctionMap.find(SectAddress + Inst.Address) !=
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000543 FunctionMap.end())
Owen Anderson481837a2011-10-17 21:37:35 +0000544 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
545 << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000546
Benjamin Kramer41a96492011-11-05 08:57:40 +0000547 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000548 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000549
550 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000551 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000552
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000553 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000554
555 // Look for relocations inside this instructions, if there is one
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000556 // print its target and additional information if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000557 for (unsigned j = 0; j != Relocs.size(); ++j)
Owen Anderson481837a2011-10-17 21:37:35 +0000558 if (Relocs[j].first >= SectAddress + Inst.Address &&
559 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
560 StringRef SymName;
561 uint64_t Addr;
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000562 Relocs[j].second.getAddress(Addr);
563 Relocs[j].second.getName(SymName);
Owen Anderson481837a2011-10-17 21:37:35 +0000564
565 outs() << "\t# " << SymName << ' ';
Rafael Espindola3eff3182013-04-07 16:07:35 +0000566 DumpAddress(Addr, Sections, MachOOF.get(), outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000567 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000568
569 // If this instructions contains an address, see if we can evaluate
570 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000571 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
572 Inst.Address,
573 Inst.Size);
574 if (targ != -1ULL)
Rafael Espindola3eff3182013-04-07 16:07:35 +0000575 DumpAddress(targ, Sections, MachOOF.get(), outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000576
Benjamin Kramer8c930972011-09-21 01:13:19 +0000577 // Print debug info.
578 if (diContext) {
579 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000580 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000581 // Print valid line info if it changed.
582 if (dli != lastLine && dli.getLine() != 0)
583 outs() << "\t## " << dli.getFileName() << ':'
584 << dli.getLine() << ':' << dli.getColumn();
585 lastLine = dli;
586 }
587
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000588 outs() << '\n';
589 }
590 }
591
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000592 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000593 }
594 }
595 }
596}