blob: 4b6cb5f54c6e188e434bf3ad09021df5375092d7 [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"
Rafael Espindolada2a2372013-04-13 01:45:40 +000030#include "llvm/Support/Casting.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/Format.h"
34#include "llvm/Support/GraphWriter.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000035#include "llvm/Support/MachO.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000036#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/TargetRegistry.h"
38#include "llvm/Support/TargetSelect.h"
39#include "llvm/Support/raw_ostream.h"
40#include "llvm/Support/system_error.h"
41#include <algorithm>
42#include <cstring>
43using namespace llvm;
44using namespace object;
45
46static cl::opt<bool>
47 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
Evan Chengc698a442012-07-02 19:45:42 +000048 " write it to a graphviz file (MachO-only)"));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000049
Benjamin Kramer8c930972011-09-21 01:13:19 +000050static cl::opt<bool>
51 UseDbg("g", cl::desc("Print line information from debug info if available"));
52
53static cl::opt<std::string>
54 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
55
Rafael Espindolaf6cfc152013-04-09 14:49:08 +000056static const Target *GetTarget(const MachOObjectFileBase *MachOObj) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000057 // Figure out the target triple.
Cameron Zwaricha9935052012-02-03 06:35:22 +000058 if (TripleName.empty()) {
59 llvm::Triple TT("unknown-unknown-unknown");
Rafael Espindola317d3f42013-04-11 03:34:37 +000060 TT.setArch(Triple::ArchType(MachOObj->getArch()));
Cameron Zwaricha9935052012-02-03 06:35:22 +000061 TripleName = TT.str();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000062 }
63
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000064 // Get the target specific parser.
65 std::string Error;
66 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
67 if (TheTarget)
68 return TheTarget;
69
70 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
71 << "', see --version and --triple.\n";
72 return 0;
73}
74
Owen Anderson481837a2011-10-17 21:37:35 +000075struct SymbolSorter {
76 bool operator()(const SymbolRef &A, const SymbolRef &B) {
77 SymbolRef::Type AType, BType;
78 A.getType(AType);
79 B.getType(BType);
80
81 uint64_t AAddr, BAddr;
82 if (AType != SymbolRef::ST_Function)
83 AAddr = 0;
84 else
85 A.getAddress(AAddr);
86 if (BType != SymbolRef::ST_Function)
87 BAddr = 0;
88 else
89 B.getAddress(BAddr);
90 return AAddr < BAddr;
91 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000092};
93
Michael J. Spencer3773fb42011-10-07 19:25:47 +000094// Print additional information about an address, if available.
Owen Anderson481837a2011-10-17 21:37:35 +000095static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
Rafael Espindolaf6cfc152013-04-09 14:49:08 +000096 const MachOObjectFileBase *MachOObj, raw_ostream &OS) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000097 for (unsigned i = 0; i != Sections.size(); ++i) {
Owen Anderson481837a2011-10-17 21:37:35 +000098 uint64_t SectAddr = 0, SectSize = 0;
99 Sections[i].getAddress(SectAddr);
100 Sections[i].getSize(SectSize);
101 uint64_t addr = SectAddr;
102 if (SectAddr <= Address &&
103 SectAddr + SectSize > Address) {
104 StringRef bytes, name;
105 Sections[i].getContents(bytes);
106 Sections[i].getName(name);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000107 // Print constant strings.
Owen Anderson481837a2011-10-17 21:37:35 +0000108 if (!name.compare("__cstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000109 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000110 // Print constant CFStrings.
Owen Anderson481837a2011-10-17 21:37:35 +0000111 if (!name.compare("__cfstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000112 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
113 }
114 }
115}
116
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000117typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
118typedef SmallVector<MCFunction, 16> FunctionListTy;
119static void createMCFunctionAndSaveCalls(StringRef Name,
120 const MCDisassembler *DisAsm,
121 MemoryObject &Object, uint64_t Start,
122 uint64_t End,
123 MCInstrAnalysis *InstrAnalysis,
124 uint64_t Address,
125 raw_ostream &DebugOut,
126 FunctionMapTy &FunctionMap,
127 FunctionListTy &Functions) {
128 SmallVector<uint64_t, 16> Calls;
129 MCFunction f =
130 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
131 InstrAnalysis, DebugOut, Calls);
132 Functions.push_back(f);
133 FunctionMap[Address] = &Functions.back();
134
135 // Add the gathered callees to the map.
136 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
137 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
138}
139
140// Write a graphviz file for the CFG inside an MCFunction.
141static void emitDOTFile(const char *FileName, const MCFunction &f,
142 MCInstPrinter *IP) {
143 // Start a new dot file.
144 std::string Error;
145 raw_fd_ostream Out(FileName, Error);
146 if (!Error.empty()) {
147 errs() << "llvm-objdump: warning: " << Error << '\n';
148 return;
149 }
150
151 Out << "digraph " << f.getName() << " {\n";
152 Out << "graph [ rankdir = \"LR\" ];\n";
153 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
154 bool hasPreds = false;
155 // Only print blocks that have predecessors.
156 // FIXME: Slow.
157 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
158 ++pi)
159 if (pi->second.contains(i->first)) {
160 hasPreds = true;
161 break;
162 }
163
164 if (!hasPreds && i != f.begin())
165 continue;
166
167 Out << '"' << i->first << "\" [ label=\"<a>";
168 // Print instructions.
169 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
170 ++ii) {
171 // Escape special chars and print the instruction in mnemonic form.
172 std::string Str;
173 raw_string_ostream OS(Str);
174 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
175 Out << DOT::EscapeString(OS.str()) << '|';
176 }
177 Out << "<o>\" shape=\"record\" ];\n";
178
179 // Add edges.
180 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
181 se = i->second.succ_end(); si != se; ++si)
182 Out << i->first << ":o -> " << *si <<":a\n";
183 }
184 Out << "}\n";
185}
186
Rafael Espindolada2a2372013-04-13 01:45:40 +0000187template<endianness E>
188static void
189getSectionsAndSymbols(const typename MachOObjectFileMiddle<E>::Header *Header,
190 const MachOObjectFileMiddle<E> *MachOObj,
191 std::vector<SectionRef> &Sections,
192 std::vector<SymbolRef> &Symbols,
193 SmallVectorImpl<uint64_t> &FoundFns) {
194 typedef MachOObjectFileMiddle<E> ObjType;
Owen Anderson481837a2011-10-17 21:37:35 +0000195 error_code ec;
196 for (symbol_iterator SI = MachOObj->begin_symbols(),
197 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
198 Symbols.push_back(*SI);
199
200 for (section_iterator SI = MachOObj->begin_sections(),
201 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
202 SectionRef SR = *SI;
203 StringRef SectName;
204 SR.getName(SectName);
205 Sections.push_back(*SI);
206 }
207
Rafael Espindola433611b2013-04-07 19:26:57 +0000208 for (unsigned i = 0; i != Header->NumLoadCommands; ++i) {
Rafael Espindolada2a2372013-04-13 01:45:40 +0000209 const typename ObjType::LoadCommand *Command =
Rafael Espindolaa2561a02013-04-10 03:48:25 +0000210 MachOObj->getLoadCommandInfo(i);
Rafael Espindola6ab85a82013-04-07 18:42:06 +0000211 if (Command->Type == macho::LCT_FunctionStarts) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000212 // We found a function starts segment, parse the addresses for later
213 // consumption.
Rafael Espindolada2a2372013-04-13 01:45:40 +0000214 const typename ObjType::LinkeditDataLoadCommand *LLC =
215 reinterpret_cast<const typename ObjType::LinkeditDataLoadCommand*>(Command);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000216
Rafael Espindola3eff3182013-04-07 16:07:35 +0000217 MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
Benjamin Kramerafbaf482011-09-21 22:16:43 +0000218 }
219 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000220}
221
Rafael Espindolada2a2372013-04-13 01:45:40 +0000222template<endianness E>
223static void DisassembleInputMachO2(StringRef Filename,
224 MachOObjectFileMiddle<E> *MachOOF);
225
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000226void llvm::DisassembleInputMachO(StringRef Filename) {
227 OwningPtr<MemoryBuffer> Buff;
228
229 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
230 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
231 return;
232 }
233
Rafael Espindolaf6cfc152013-04-09 14:49:08 +0000234 OwningPtr<MachOObjectFileBase> MachOOF(static_cast<MachOObjectFileBase*>(
Owen Anderson481837a2011-10-17 21:37:35 +0000235 ObjectFile::createMachOObjectFile(Buff.take())));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000236
Rafael Espindolada2a2372013-04-13 01:45:40 +0000237 if (MachOObjectFileLE *O = dyn_cast<MachOObjectFileLE>(MachOOF.get())) {
238 DisassembleInputMachO2(Filename, O);
239 return;
240 }
241 MachOObjectFileBE *O = cast<MachOObjectFileBE>(MachOOF.get());
242 DisassembleInputMachO2(Filename, O);
243}
244
245template<endianness E>
246static void DisassembleInputMachO2(StringRef Filename,
247 MachOObjectFileMiddle<E> *MachOOF) {
248 const Target *TheTarget = GetTarget(MachOOF);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000249 if (!TheTarget) {
250 // GetTarget prints out stuff.
251 return;
252 }
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000253 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000254 OwningPtr<MCInstrAnalysis>
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000255 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000256
257 // Set up disassembler.
258 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000259 OwningPtr<const MCSubtargetInfo>
260 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000261 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Jim Grosbachc6449b62012-03-05 19:33:20 +0000262 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000263 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Craig Topper17463b32012-04-02 06:09:36 +0000264 OwningPtr<MCInstPrinter>
265 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
266 *MRI, *STI));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000267
268 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000269 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000270 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000271 return;
272 }
273
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000274 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000275
Rafael Espindolada2a2372013-04-13 01:45:40 +0000276 const typename MachOObjectFileMiddle<E>::Header *Header =
277 MachOOF->getHeader();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000278
Owen Anderson481837a2011-10-17 21:37:35 +0000279 std::vector<SectionRef> Sections;
280 std::vector<SymbolRef> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000281 SmallVector<uint64_t, 8> FoundFns;
282
Rafael Espindolada2a2372013-04-13 01:45:40 +0000283 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000284
Benjamin Kramer8c930972011-09-21 01:13:19 +0000285 // Make a copy of the unsorted symbol list. FIXME: duplication
Owen Anderson481837a2011-10-17 21:37:35 +0000286 std::vector<SymbolRef> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000287 // Sort the symbols by address, just in case they didn't come in that way.
Owen Anderson481837a2011-10-17 21:37:35 +0000288 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000289
290#ifndef NDEBUG
291 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
292#else
293 raw_ostream &DebugOut = nulls();
294#endif
295
Benjamin Kramer8c930972011-09-21 01:13:19 +0000296 OwningPtr<DIContext> diContext;
Rafael Espindolada2a2372013-04-13 01:45:40 +0000297 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000298 // Try to find debug info and set up the DIContext for it.
299 if (UseDbg) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000300 // A separate DSym file path was specified, parse it as a macho file,
301 // get the sections and supply it to the section name parsing machinery.
302 if (!DSYMFile.empty()) {
303 OwningPtr<MemoryBuffer> Buf;
304 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
305 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
306 return;
307 }
Eric Christopherd1726a42012-11-12 21:40:38 +0000308 DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
Benjamin Kramer8c930972011-09-21 01:13:19 +0000309 }
310
Eric Christopherd1726a42012-11-12 21:40:38 +0000311 // Setup the DIContext
312 diContext.reset(DIContext::getDWARFContext(DbgObj));
Benjamin Kramer8c930972011-09-21 01:13:19 +0000313 }
314
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000315 FunctionMapTy FunctionMap;
316 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000317
318 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000319 StringRef SectName;
320 if (Sections[SectIdx].getName(SectName) ||
Rafael Espindolacef81b32012-12-21 03:47:03 +0000321 SectName != "__text")
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000322 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000323
Rafael Espindolacef81b32012-12-21 03:47:03 +0000324 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Rafael Espindolaf16c2bb2013-04-05 15:15:22 +0000325 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
326 if (SegmentName != "__TEXT")
Rafael Espindolacef81b32012-12-21 03:47:03 +0000327 continue;
328
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000329 // Insert the functions from the function starts segment into our map.
Owen Anderson481837a2011-10-17 21:37:35 +0000330 uint64_t VMAddr;
331 Sections[SectIdx].getAddress(VMAddr);
332 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
333 StringRef SectBegin;
334 Sections[SectIdx].getContents(SectBegin);
335 uint64_t Offset = (uint64_t)SectBegin.data();
336 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
337 (MCFunction*)0));
338 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000339
Owen Anderson481837a2011-10-17 21:37:35 +0000340 StringRef Bytes;
341 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000342 StringRefMemoryObject memoryObject(Bytes);
343 bool symbolTableWorked = false;
344
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000345 // Parse relocations.
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000346 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
Owen Anderson481837a2011-10-17 21:37:35 +0000347 error_code ec;
348 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
349 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
350 uint64_t RelocOffset, SectionAddress;
351 RI->getAddress(RelocOffset);
352 Sections[SectIdx].getAddress(SectionAddress);
353 RelocOffset -= SectionAddress;
354
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000355 SymbolRef RelocSym;
356 RI->getSymbol(RelocSym);
Owen Anderson481837a2011-10-17 21:37:35 +0000357
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000358 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000359 }
360 array_pod_sort(Relocs.begin(), Relocs.end());
361
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000362 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000363 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000364 StringRef SymName;
365 Symbols[SymIdx].getName(SymName);
366
367 SymbolRef::Type ST;
368 Symbols[SymIdx].getType(ST);
369 if (ST != SymbolRef::ST_Function)
370 continue;
371
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000372 // Make sure the symbol is defined in this section.
Owen Anderson481837a2011-10-17 21:37:35 +0000373 bool containsSym = false;
374 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
375 if (!containsSym)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000376 continue;
377
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000378 // Start at the address of the symbol relative to the section's address.
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000379 uint64_t SectionAddress = 0;
Owen Anderson481837a2011-10-17 21:37:35 +0000380 uint64_t Start = 0;
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000381 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000382 Symbols[SymIdx].getAddress(Start);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000383 Start -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000384
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000385 // Stop disassembling either at the beginning of the next symbol or at
386 // the end of the section.
Kevin Enderby41854ae2012-05-15 18:57:14 +0000387 bool containsNextSym = false;
Owen Anderson481837a2011-10-17 21:37:35 +0000388 uint64_t NextSym = 0;
389 uint64_t NextSymIdx = SymIdx+1;
390 while (Symbols.size() > NextSymIdx) {
391 SymbolRef::Type NextSymType;
392 Symbols[NextSymIdx].getType(NextSymType);
393 if (NextSymType == SymbolRef::ST_Function) {
394 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
395 containsNextSym);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000396 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000397 NextSym -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000398 break;
399 }
400 ++NextSymIdx;
401 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000402
Owen Anderson481837a2011-10-17 21:37:35 +0000403 uint64_t SectSize;
404 Sections[SectIdx].getSize(SectSize);
405 uint64_t End = containsNextSym ? NextSym : SectSize;
406 uint64_t Size;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000407
408 symbolTableWorked = true;
409
410 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000411 // Normal disassembly, print addresses, bytes and mnemonic form.
Owen Anderson481837a2011-10-17 21:37:35 +0000412 StringRef SymName;
413 Symbols[SymIdx].getName(SymName);
414
415 outs() << SymName << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000416 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000417 for (uint64_t Index = Start; Index < End; Index += Size) {
418 MCInst Inst;
419
420 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
421 DebugOut, nulls())) {
Owen Anderson481837a2011-10-17 21:37:35 +0000422 uint64_t SectAddress = 0;
423 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramer41a96492011-11-05 08:57:40 +0000424 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
Owen Anderson481837a2011-10-17 21:37:35 +0000425
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000426 DumpBytes(StringRef(Bytes.data() + Index, Size));
427 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000428
429 // Print debug info.
430 if (diContext) {
431 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000432 diContext->getLineInfoForAddress(SectAddress + Index);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000433 // Print valid line info if it changed.
434 if (dli != lastLine && dli.getLine() != 0)
435 outs() << "\t## " << dli.getFileName() << ':'
436 << dli.getLine() << ':' << dli.getColumn();
437 lastLine = dli;
438 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000439 outs() << "\n";
440 } else {
441 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
442 if (Size == 0)
443 Size = 1; // skip illegible bytes
444 }
445 }
446 } else {
447 // Create CFG and use it for disassembly.
Owen Anderson481837a2011-10-17 21:37:35 +0000448 StringRef SymName;
449 Symbols[SymIdx].getName(SymName);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000450 createMCFunctionAndSaveCalls(
Owen Anderson481837a2011-10-17 21:37:35 +0000451 SymName, DisAsm.get(), memoryObject, Start, End,
452 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000453 }
454 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000455 if (!CFG && !symbolTableWorked) {
456 // Reading the symbol table didn't work, disassemble the whole section.
457 uint64_t SectAddress;
458 Sections[SectIdx].getAddress(SectAddress);
459 uint64_t SectSize;
460 Sections[SectIdx].getSize(SectSize);
461 uint64_t InstSize;
462 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendlingf59083c2012-07-19 00:17:40 +0000463 MCInst Inst;
Kevin Enderby59c15e92012-05-18 00:13:56 +0000464
Bill Wendlingf59083c2012-07-19 00:17:40 +0000465 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
466 DebugOut, nulls())) {
467 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
468 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
469 IP->printInst(&Inst, outs(), "");
470 outs() << "\n";
471 } else {
472 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
473 if (InstSize == 0)
474 InstSize = 1; // skip illegible bytes
475 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000476 }
477 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000478
479 if (CFG) {
480 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000481 // Reading the symbol table didn't work, create a big __TEXT symbol.
Owen Anderson481837a2011-10-17 21:37:35 +0000482 uint64_t SectSize = 0, SectAddress = 0;
483 Sections[SectIdx].getSize(SectSize);
484 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000485 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
Owen Anderson481837a2011-10-17 21:37:35 +0000486 0, SectSize,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000487 InstrAnalysis.get(),
Owen Anderson481837a2011-10-17 21:37:35 +0000488 SectAddress, DebugOut,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000489 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000490 }
491 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
492 me = FunctionMap.end(); mi != me; ++mi)
493 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000494 // Create functions for the remaining callees we have gathered,
495 // but we didn't find a name for them.
Owen Anderson481837a2011-10-17 21:37:35 +0000496 uint64_t SectSize = 0;
497 Sections[SectIdx].getSize(SectSize);
498
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000499 SmallVector<uint64_t, 16> Calls;
500 MCFunction f =
501 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
502 memoryObject, mi->first,
Owen Anderson481837a2011-10-17 21:37:35 +0000503 SectSize,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000504 InstrAnalysis.get(), DebugOut,
505 Calls);
506 Functions.push_back(f);
507 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000508 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
509 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
510 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000511 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000512 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000513 }
514
515 DenseSet<uint64_t> PrintedBlocks;
516 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
517 MCFunction &f = Functions[ffi];
518 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
519 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000520 continue; // We already printed this block.
521
522 // We assume a block has predecessors when it's the first block after
523 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000524 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
525
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000526 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000527 // FIXME: Slow.
528 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
529 ++pi)
530 if (pi->second.contains(fi->first)) {
531 hasPreds = true;
532 break;
533 }
534
Owen Anderson481837a2011-10-17 21:37:35 +0000535 uint64_t SectSize = 0, SectAddress;
536 Sections[SectIdx].getSize(SectSize);
537 Sections[SectIdx].getAddress(SectAddress);
538
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000539 // No predecessors, this is a data block. Print as .byte directives.
540 if (!hasPreds) {
Owen Anderson481837a2011-10-17 21:37:35 +0000541 uint64_t End = llvm::next(fi) == fe ? SectSize :
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000542 llvm::next(fi)->first;
543 outs() << "# " << End-fi->first << " bytes of data:\n";
544 for (unsigned pos = fi->first; pos != End; ++pos) {
Owen Anderson481837a2011-10-17 21:37:35 +0000545 outs() << format("%8x:\t", SectAddress + pos);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000546 DumpBytes(StringRef(Bytes.data() + pos, 1));
547 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
548 }
549 continue;
550 }
551
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000552 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000553 outs() << "# Loop begin:\n";
554
Benjamin Kramer8c930972011-09-21 01:13:19 +0000555 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000556 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000557 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
558 ++ii) {
559 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000560
561 // If there's a symbol at this address, print its name.
Owen Anderson481837a2011-10-17 21:37:35 +0000562 if (FunctionMap.find(SectAddress + Inst.Address) !=
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000563 FunctionMap.end())
Owen Anderson481837a2011-10-17 21:37:35 +0000564 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
565 << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000566
Benjamin Kramer41a96492011-11-05 08:57:40 +0000567 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000568 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000569
570 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000571 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000572
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000573 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000574
575 // Look for relocations inside this instructions, if there is one
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000576 // print its target and additional information if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000577 for (unsigned j = 0; j != Relocs.size(); ++j)
Owen Anderson481837a2011-10-17 21:37:35 +0000578 if (Relocs[j].first >= SectAddress + Inst.Address &&
579 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
580 StringRef SymName;
581 uint64_t Addr;
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000582 Relocs[j].second.getAddress(Addr);
583 Relocs[j].second.getName(SymName);
Owen Anderson481837a2011-10-17 21:37:35 +0000584
585 outs() << "\t# " << SymName << ' ';
Rafael Espindolada2a2372013-04-13 01:45:40 +0000586 DumpAddress(Addr, Sections, MachOOF, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000587 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000588
589 // If this instructions contains an address, see if we can evaluate
590 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000591 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
592 Inst.Address,
593 Inst.Size);
594 if (targ != -1ULL)
Rafael Espindolada2a2372013-04-13 01:45:40 +0000595 DumpAddress(targ, Sections, MachOOF, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000596
Benjamin Kramer8c930972011-09-21 01:13:19 +0000597 // Print debug info.
598 if (diContext) {
599 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000600 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000601 // Print valid line info if it changed.
602 if (dli != lastLine && dli.getLine() != 0)
603 outs() << "\t## " << dli.getFileName() << ':'
604 << dli.getLine() << ':' << dli.getColumn();
605 lastLine = dli;
606 }
607
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000608 outs() << '\n';
609 }
610 }
611
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000612 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000613 }
614 }
615 }
616}