blob: e4d9ce2498560411fdae5148a4d665a26468a050 [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 Espindolafd7aa382013-04-18 18:08:55 +000056static const Target *GetTarget(const MachOObjectFile *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 Espindolafd7aa382013-04-18 18:08:55 +000096 const MachOObjectFile *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 +0000187static void
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000188getSectionsAndSymbols(const macho::Header Header,
189 MachOObjectFile *MachOObj,
Rafael Espindolada2a2372013-04-13 01:45:40 +0000190 std::vector<SectionRef> &Sections,
191 std::vector<SymbolRef> &Symbols,
192 SmallVectorImpl<uint64_t> &FoundFns) {
Owen Anderson481837a2011-10-17 21:37:35 +0000193 error_code ec;
194 for (symbol_iterator SI = MachOObj->begin_symbols(),
195 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
196 Symbols.push_back(*SI);
197
198 for (section_iterator SI = MachOObj->begin_sections(),
199 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
200 SectionRef SR = *SI;
201 StringRef SectName;
202 SR.getName(SectName);
203 Sections.push_back(*SI);
204 }
205
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000206 MachOObjectFile::LoadCommandInfo Command =
207 MachOObj->getFirstLoadCommandInfo();
208 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
209 if (Command.C.Type == macho::LCT_FunctionStarts) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000210 // We found a function starts segment, parse the addresses for later
211 // consumption.
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000212 macho::LinkeditDataLoadCommand LLC =
213 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000214
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000215 MachOObj->ReadULEB128s(LLC.DataOffset, FoundFns);
Benjamin Kramerafbaf482011-09-21 22:16:43 +0000216 }
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000217 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramerafbaf482011-09-21 22:16:43 +0000218 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000219}
220
Rafael Espindolada2a2372013-04-13 01:45:40 +0000221static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000222 MachOObjectFile *MachOOF);
Rafael Espindolada2a2372013-04-13 01:45:40 +0000223
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000224void llvm::DisassembleInputMachO(StringRef Filename) {
225 OwningPtr<MemoryBuffer> Buff;
226
227 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
228 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
229 return;
230 }
231
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000232 OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
Owen Anderson481837a2011-10-17 21:37:35 +0000233 ObjectFile::createMachOObjectFile(Buff.take())));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000234
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000235 DisassembleInputMachO2(Filename, MachOOF.get());
Rafael Espindolada2a2372013-04-13 01:45:40 +0000236}
237
Rafael Espindolada2a2372013-04-13 01:45:40 +0000238static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000239 MachOObjectFile *MachOOF) {
Rafael Espindolada2a2372013-04-13 01:45:40 +0000240 const Target *TheTarget = GetTarget(MachOOF);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000241 if (!TheTarget) {
242 // GetTarget prints out stuff.
243 return;
244 }
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000245 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000246 OwningPtr<MCInstrAnalysis>
Benjamin Kramerd226ed712011-10-10 13:10:09 +0000247 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000248
249 // Set up disassembler.
250 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000251 OwningPtr<const MCSubtargetInfo>
252 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000253 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Jim Grosbachc6449b62012-03-05 19:33:20 +0000254 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000255 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Craig Topper17463b32012-04-02 06:09:36 +0000256 OwningPtr<MCInstPrinter>
257 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
258 *MRI, *STI));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000259
260 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000261 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000262 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000263 return;
264 }
265
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000266 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000267
Rafael Espindolafd7aa382013-04-18 18:08:55 +0000268 macho::Header Header = MachOOF->getHeader();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000269
Owen Anderson481837a2011-10-17 21:37:35 +0000270 std::vector<SectionRef> Sections;
271 std::vector<SymbolRef> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000272 SmallVector<uint64_t, 8> FoundFns;
273
Rafael Espindolada2a2372013-04-13 01:45:40 +0000274 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000275
Benjamin Kramer8c930972011-09-21 01:13:19 +0000276 // Make a copy of the unsorted symbol list. FIXME: duplication
Owen Anderson481837a2011-10-17 21:37:35 +0000277 std::vector<SymbolRef> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000278 // Sort the symbols by address, just in case they didn't come in that way.
Owen Anderson481837a2011-10-17 21:37:35 +0000279 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000280
281#ifndef NDEBUG
282 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
283#else
284 raw_ostream &DebugOut = nulls();
285#endif
286
Benjamin Kramer8c930972011-09-21 01:13:19 +0000287 OwningPtr<DIContext> diContext;
Rafael Espindolada2a2372013-04-13 01:45:40 +0000288 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000289 // Try to find debug info and set up the DIContext for it.
290 if (UseDbg) {
Benjamin Kramer8c930972011-09-21 01:13:19 +0000291 // A separate DSym file path was specified, parse it as a macho file,
292 // get the sections and supply it to the section name parsing machinery.
293 if (!DSYMFile.empty()) {
294 OwningPtr<MemoryBuffer> Buf;
295 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
296 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
297 return;
298 }
Eric Christopherd1726a42012-11-12 21:40:38 +0000299 DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
Benjamin Kramer8c930972011-09-21 01:13:19 +0000300 }
301
Eric Christopherd1726a42012-11-12 21:40:38 +0000302 // Setup the DIContext
303 diContext.reset(DIContext::getDWARFContext(DbgObj));
Benjamin Kramer8c930972011-09-21 01:13:19 +0000304 }
305
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000306 FunctionMapTy FunctionMap;
307 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000308
309 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000310 StringRef SectName;
311 if (Sections[SectIdx].getName(SectName) ||
Rafael Espindolacef81b32012-12-21 03:47:03 +0000312 SectName != "__text")
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000313 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000314
Rafael Espindolacef81b32012-12-21 03:47:03 +0000315 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Rafael Espindolaf16c2bb2013-04-05 15:15:22 +0000316 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
317 if (SegmentName != "__TEXT")
Rafael Espindolacef81b32012-12-21 03:47:03 +0000318 continue;
319
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000320 // Insert the functions from the function starts segment into our map.
Owen Anderson481837a2011-10-17 21:37:35 +0000321 uint64_t VMAddr;
322 Sections[SectIdx].getAddress(VMAddr);
323 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
324 StringRef SectBegin;
325 Sections[SectIdx].getContents(SectBegin);
326 uint64_t Offset = (uint64_t)SectBegin.data();
327 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
328 (MCFunction*)0));
329 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000330
Owen Anderson481837a2011-10-17 21:37:35 +0000331 StringRef Bytes;
332 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000333 StringRefMemoryObject memoryObject(Bytes);
334 bool symbolTableWorked = false;
335
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000336 // Parse relocations.
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000337 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
Owen Anderson481837a2011-10-17 21:37:35 +0000338 error_code ec;
339 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
340 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
341 uint64_t RelocOffset, SectionAddress;
342 RI->getAddress(RelocOffset);
343 Sections[SectIdx].getAddress(SectionAddress);
344 RelocOffset -= SectionAddress;
345
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000346 SymbolRef RelocSym;
347 RI->getSymbol(RelocSym);
Owen Anderson481837a2011-10-17 21:37:35 +0000348
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000349 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000350 }
351 array_pod_sort(Relocs.begin(), Relocs.end());
352
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000353 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000354 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000355 StringRef SymName;
356 Symbols[SymIdx].getName(SymName);
357
358 SymbolRef::Type ST;
359 Symbols[SymIdx].getType(ST);
360 if (ST != SymbolRef::ST_Function)
361 continue;
362
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000363 // Make sure the symbol is defined in this section.
Owen Anderson481837a2011-10-17 21:37:35 +0000364 bool containsSym = false;
365 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
366 if (!containsSym)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000367 continue;
368
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000369 // Start at the address of the symbol relative to the section's address.
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000370 uint64_t SectionAddress = 0;
Owen Anderson481837a2011-10-17 21:37:35 +0000371 uint64_t Start = 0;
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000372 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000373 Symbols[SymIdx].getAddress(Start);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000374 Start -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000375
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000376 // Stop disassembling either at the beginning of the next symbol or at
377 // the end of the section.
Kevin Enderby41854ae2012-05-15 18:57:14 +0000378 bool containsNextSym = false;
Owen Anderson481837a2011-10-17 21:37:35 +0000379 uint64_t NextSym = 0;
380 uint64_t NextSymIdx = SymIdx+1;
381 while (Symbols.size() > NextSymIdx) {
382 SymbolRef::Type NextSymType;
383 Symbols[NextSymIdx].getType(NextSymType);
384 if (NextSymType == SymbolRef::ST_Function) {
385 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
386 containsNextSym);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000387 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000388 NextSym -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000389 break;
390 }
391 ++NextSymIdx;
392 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000393
Owen Anderson481837a2011-10-17 21:37:35 +0000394 uint64_t SectSize;
395 Sections[SectIdx].getSize(SectSize);
396 uint64_t End = containsNextSym ? NextSym : SectSize;
397 uint64_t Size;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000398
399 symbolTableWorked = true;
400
401 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000402 // Normal disassembly, print addresses, bytes and mnemonic form.
Owen Anderson481837a2011-10-17 21:37:35 +0000403 StringRef SymName;
404 Symbols[SymIdx].getName(SymName);
405
406 outs() << SymName << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000407 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000408 for (uint64_t Index = Start; Index < End; Index += Size) {
409 MCInst Inst;
410
411 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
412 DebugOut, nulls())) {
Owen Anderson481837a2011-10-17 21:37:35 +0000413 uint64_t SectAddress = 0;
414 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramer41a96492011-11-05 08:57:40 +0000415 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
Owen Anderson481837a2011-10-17 21:37:35 +0000416
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000417 DumpBytes(StringRef(Bytes.data() + Index, Size));
418 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000419
420 // Print debug info.
421 if (diContext) {
422 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000423 diContext->getLineInfoForAddress(SectAddress + Index);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000424 // Print valid line info if it changed.
425 if (dli != lastLine && dli.getLine() != 0)
426 outs() << "\t## " << dli.getFileName() << ':'
427 << dli.getLine() << ':' << dli.getColumn();
428 lastLine = dli;
429 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000430 outs() << "\n";
431 } else {
432 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
433 if (Size == 0)
434 Size = 1; // skip illegible bytes
435 }
436 }
437 } else {
438 // Create CFG and use it for disassembly.
Owen Anderson481837a2011-10-17 21:37:35 +0000439 StringRef SymName;
440 Symbols[SymIdx].getName(SymName);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000441 createMCFunctionAndSaveCalls(
Owen Anderson481837a2011-10-17 21:37:35 +0000442 SymName, DisAsm.get(), memoryObject, Start, End,
443 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000444 }
445 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000446 if (!CFG && !symbolTableWorked) {
447 // Reading the symbol table didn't work, disassemble the whole section.
448 uint64_t SectAddress;
449 Sections[SectIdx].getAddress(SectAddress);
450 uint64_t SectSize;
451 Sections[SectIdx].getSize(SectSize);
452 uint64_t InstSize;
453 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendlingf59083c2012-07-19 00:17:40 +0000454 MCInst Inst;
Kevin Enderby59c15e92012-05-18 00:13:56 +0000455
Bill Wendlingf59083c2012-07-19 00:17:40 +0000456 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
457 DebugOut, nulls())) {
458 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
459 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
460 IP->printInst(&Inst, outs(), "");
461 outs() << "\n";
462 } else {
463 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
464 if (InstSize == 0)
465 InstSize = 1; // skip illegible bytes
466 }
Kevin Enderby59c15e92012-05-18 00:13:56 +0000467 }
468 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000469
470 if (CFG) {
471 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000472 // Reading the symbol table didn't work, create a big __TEXT symbol.
Owen Anderson481837a2011-10-17 21:37:35 +0000473 uint64_t SectSize = 0, SectAddress = 0;
474 Sections[SectIdx].getSize(SectSize);
475 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000476 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
Owen Anderson481837a2011-10-17 21:37:35 +0000477 0, SectSize,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000478 InstrAnalysis.get(),
Owen Anderson481837a2011-10-17 21:37:35 +0000479 SectAddress, DebugOut,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000480 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000481 }
482 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
483 me = FunctionMap.end(); mi != me; ++mi)
484 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000485 // Create functions for the remaining callees we have gathered,
486 // but we didn't find a name for them.
Owen Anderson481837a2011-10-17 21:37:35 +0000487 uint64_t SectSize = 0;
488 Sections[SectIdx].getSize(SectSize);
489
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000490 SmallVector<uint64_t, 16> Calls;
491 MCFunction f =
492 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
493 memoryObject, mi->first,
Owen Anderson481837a2011-10-17 21:37:35 +0000494 SectSize,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000495 InstrAnalysis.get(), DebugOut,
496 Calls);
497 Functions.push_back(f);
498 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000499 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
500 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
501 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000502 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000503 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000504 }
505
506 DenseSet<uint64_t> PrintedBlocks;
507 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
508 MCFunction &f = Functions[ffi];
509 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
510 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000511 continue; // We already printed this block.
512
513 // We assume a block has predecessors when it's the first block after
514 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000515 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
516
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000517 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000518 // FIXME: Slow.
519 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
520 ++pi)
521 if (pi->second.contains(fi->first)) {
522 hasPreds = true;
523 break;
524 }
525
Owen Anderson481837a2011-10-17 21:37:35 +0000526 uint64_t SectSize = 0, SectAddress;
527 Sections[SectIdx].getSize(SectSize);
528 Sections[SectIdx].getAddress(SectAddress);
529
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000530 // No predecessors, this is a data block. Print as .byte directives.
531 if (!hasPreds) {
Owen Anderson481837a2011-10-17 21:37:35 +0000532 uint64_t End = llvm::next(fi) == fe ? SectSize :
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000533 llvm::next(fi)->first;
534 outs() << "# " << End-fi->first << " bytes of data:\n";
535 for (unsigned pos = fi->first; pos != End; ++pos) {
Owen Anderson481837a2011-10-17 21:37:35 +0000536 outs() << format("%8x:\t", SectAddress + pos);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000537 DumpBytes(StringRef(Bytes.data() + pos, 1));
538 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
539 }
540 continue;
541 }
542
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000543 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000544 outs() << "# Loop begin:\n";
545
Benjamin Kramer8c930972011-09-21 01:13:19 +0000546 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000547 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000548 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
549 ++ii) {
550 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000551
552 // If there's a symbol at this address, print its name.
Owen Anderson481837a2011-10-17 21:37:35 +0000553 if (FunctionMap.find(SectAddress + Inst.Address) !=
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000554 FunctionMap.end())
Owen Anderson481837a2011-10-17 21:37:35 +0000555 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
556 << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000557
Benjamin Kramer41a96492011-11-05 08:57:40 +0000558 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000559 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000560
561 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000562 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000563
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000564 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000565
566 // Look for relocations inside this instructions, if there is one
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000567 // print its target and additional information if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000568 for (unsigned j = 0; j != Relocs.size(); ++j)
Owen Anderson481837a2011-10-17 21:37:35 +0000569 if (Relocs[j].first >= SectAddress + Inst.Address &&
570 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
571 StringRef SymName;
572 uint64_t Addr;
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000573 Relocs[j].second.getAddress(Addr);
574 Relocs[j].second.getName(SymName);
Owen Anderson481837a2011-10-17 21:37:35 +0000575
576 outs() << "\t# " << SymName << ' ';
Rafael Espindolada2a2372013-04-13 01:45:40 +0000577 DumpAddress(Addr, Sections, MachOOF, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000578 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000579
580 // If this instructions contains an address, see if we can evaluate
581 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000582 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
583 Inst.Address,
584 Inst.Size);
585 if (targ != -1ULL)
Rafael Espindolada2a2372013-04-13 01:45:40 +0000586 DumpAddress(targ, Sections, MachOOF, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000587
Benjamin Kramer8c930972011-09-21 01:13:19 +0000588 // Print debug info.
589 if (diContext) {
590 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000591 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000592 // Print valid line info if it changed.
593 if (dli != lastLine && dli.getLine() != 0)
594 outs() << "\t## " << dli.getFileName() << ':'
595 << dli.getLine() << ':' << dli.getColumn();
596 lastLine = dli;
597 }
598
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000599 outs() << '\n';
600 }
601 }
602
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000603 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000604 }
605 }
606 }
607}