blob: 272dedf3ef44b95d18c721f89d581c9cb82c9273 [file] [log] [blame]
Benjamin Kramer0b8b7712011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
15#include "MCFunction.h"
16#include "llvm/Support/MachO.h"
Owen Anderson481837a2011-10-17 21:37:35 +000017#include "llvm/Object/MachO.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/ADT/STLExtras.h"
Benjamin Kramer8c930972011-09-21 01:13:19 +000021#include "llvm/DebugInfo/DIContext.h"
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000022#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCDisassembler.h"
24#include "llvm/MC/MCInst.h"
25#include "llvm/MC/MCInstPrinter.h"
26#include "llvm/MC/MCInstrAnalysis.h"
27#include "llvm/MC/MCInstrDesc.h"
28#include "llvm/MC/MCInstrInfo.h"
29#include "llvm/MC/MCSubtargetInfo.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/Format.h"
33#include "llvm/Support/GraphWriter.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/TargetSelect.h"
37#include "llvm/Support/raw_ostream.h"
38#include "llvm/Support/system_error.h"
39#include <algorithm>
40#include <cstring>
41using namespace llvm;
42using namespace object;
43
44static cl::opt<bool>
45 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
46 "write it to a graphviz file (MachO-only)"));
47
Benjamin Kramer8c930972011-09-21 01:13:19 +000048static cl::opt<bool>
49 UseDbg("g", cl::desc("Print line information from debug info if available"));
50
51static cl::opt<std::string>
52 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
53
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000054static const Target *GetTarget(const MachOObject *MachOObj) {
55 // Figure out the target triple.
Cameron Zwaricha9935052012-02-03 06:35:22 +000056 if (TripleName.empty()) {
57 llvm::Triple TT("unknown-unknown-unknown");
58 switch (MachOObj->getHeader().CPUType) {
59 case llvm::MachO::CPUTypeI386:
60 TT.setArch(Triple::ArchType(Triple::x86));
61 break;
62 case llvm::MachO::CPUTypeX86_64:
63 TT.setArch(Triple::ArchType(Triple::x86_64));
64 break;
65 case llvm::MachO::CPUTypeARM:
66 TT.setArch(Triple::ArchType(Triple::arm));
67 break;
68 case llvm::MachO::CPUTypePowerPC:
69 TT.setArch(Triple::ArchType(Triple::ppc));
70 break;
71 case llvm::MachO::CPUTypePowerPC64:
72 TT.setArch(Triple::ArchType(Triple::ppc64));
73 break;
74 }
75 TripleName = TT.str();
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000076 }
77
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000078 // Get the target specific parser.
79 std::string Error;
80 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
81 if (TheTarget)
82 return TheTarget;
83
84 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
85 << "', see --version and --triple.\n";
86 return 0;
87}
88
Owen Anderson481837a2011-10-17 21:37:35 +000089struct SymbolSorter {
90 bool operator()(const SymbolRef &A, const SymbolRef &B) {
91 SymbolRef::Type AType, BType;
92 A.getType(AType);
93 B.getType(BType);
94
95 uint64_t AAddr, BAddr;
96 if (AType != SymbolRef::ST_Function)
97 AAddr = 0;
98 else
99 A.getAddress(AAddr);
100 if (BType != SymbolRef::ST_Function)
101 BAddr = 0;
102 else
103 B.getAddress(BAddr);
104 return AAddr < BAddr;
105 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000106};
107
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000108// Print additional information about an address, if available.
Owen Anderson481837a2011-10-17 21:37:35 +0000109static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000110 MachOObject *MachOObj, raw_ostream &OS) {
111 for (unsigned i = 0; i != Sections.size(); ++i) {
Owen Anderson481837a2011-10-17 21:37:35 +0000112 uint64_t SectAddr = 0, SectSize = 0;
113 Sections[i].getAddress(SectAddr);
114 Sections[i].getSize(SectSize);
115 uint64_t addr = SectAddr;
116 if (SectAddr <= Address &&
117 SectAddr + SectSize > Address) {
118 StringRef bytes, name;
119 Sections[i].getContents(bytes);
120 Sections[i].getName(name);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000121 // Print constant strings.
Owen Anderson481837a2011-10-17 21:37:35 +0000122 if (!name.compare("__cstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000123 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000124 // Print constant CFStrings.
Owen Anderson481837a2011-10-17 21:37:35 +0000125 if (!name.compare("__cfstring"))
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000126 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
127 }
128 }
129}
130
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000131typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
132typedef SmallVector<MCFunction, 16> FunctionListTy;
133static void createMCFunctionAndSaveCalls(StringRef Name,
134 const MCDisassembler *DisAsm,
135 MemoryObject &Object, uint64_t Start,
136 uint64_t End,
137 MCInstrAnalysis *InstrAnalysis,
138 uint64_t Address,
139 raw_ostream &DebugOut,
140 FunctionMapTy &FunctionMap,
141 FunctionListTy &Functions) {
142 SmallVector<uint64_t, 16> Calls;
143 MCFunction f =
144 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
145 InstrAnalysis, DebugOut, Calls);
146 Functions.push_back(f);
147 FunctionMap[Address] = &Functions.back();
148
149 // Add the gathered callees to the map.
150 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
151 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
152}
153
154// Write a graphviz file for the CFG inside an MCFunction.
155static void emitDOTFile(const char *FileName, const MCFunction &f,
156 MCInstPrinter *IP) {
157 // Start a new dot file.
158 std::string Error;
159 raw_fd_ostream Out(FileName, Error);
160 if (!Error.empty()) {
161 errs() << "llvm-objdump: warning: " << Error << '\n';
162 return;
163 }
164
165 Out << "digraph " << f.getName() << " {\n";
166 Out << "graph [ rankdir = \"LR\" ];\n";
167 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
168 bool hasPreds = false;
169 // Only print blocks that have predecessors.
170 // FIXME: Slow.
171 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
172 ++pi)
173 if (pi->second.contains(i->first)) {
174 hasPreds = true;
175 break;
176 }
177
178 if (!hasPreds && i != f.begin())
179 continue;
180
181 Out << '"' << i->first << "\" [ label=\"<a>";
182 // Print instructions.
183 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
184 ++ii) {
185 // Escape special chars and print the instruction in mnemonic form.
186 std::string Str;
187 raw_string_ostream OS(Str);
188 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
189 Out << DOT::EscapeString(OS.str()) << '|';
190 }
191 Out << "<o>\" shape=\"record\" ];\n";
192
193 // Add edges.
194 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
195 se = i->second.succ_end(); si != se; ++si)
196 Out << i->first << ":o -> " << *si <<":a\n";
197 }
198 Out << "}\n";
199}
200
Benjamin Kramer8c930972011-09-21 01:13:19 +0000201static void getSectionsAndSymbols(const macho::Header &Header,
Owen Anderson481837a2011-10-17 21:37:35 +0000202 MachOObjectFile *MachOObj,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000203 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
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.
226 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
Owen Anderson481837a2011-10-17 21:37:35 +0000227 MachOObj->getObject()->ReadLinkeditDataLoadCommand(LCI, LLC);
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));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000260 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
261 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000262 AsmPrinterVariant, *AsmInfo, *STI));
263
264 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000265 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000266 << TripleName << '\n';
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000267 return;
268 }
269
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000270 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000271
272 const macho::Header &Header = MachOObj->getHeader();
273
274 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000275 // First, find the symbol table segment.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000276 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
277 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000278 if (LCI.Command.Type == macho::LCT_Symtab) {
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000279 SymtabLCI = &LCI;
280 break;
281 }
282 }
283
284 // Read and register the symbol table data.
285 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
286 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
287 MachOObj->RegisterStringTable(*SymtabLC);
288
Owen Anderson481837a2011-10-17 21:37:35 +0000289 std::vector<SectionRef> Sections;
290 std::vector<SymbolRef> Symbols;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000291 SmallVector<uint64_t, 8> FoundFns;
292
Owen Anderson481837a2011-10-17 21:37:35 +0000293 getSectionsAndSymbols(Header, MachOOF.get(), &SymtabLC, Sections, Symbols,
Benjamin Kramer8c930972011-09-21 01:13:19 +0000294 FoundFns);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000295
Benjamin Kramer8c930972011-09-21 01:13:19 +0000296 // Make a copy of the unsorted symbol list. FIXME: duplication
Owen Anderson481837a2011-10-17 21:37:35 +0000297 std::vector<SymbolRef> UnsortedSymbols(Symbols);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000298 // Sort the symbols by address, just in case they didn't come in that way.
Owen Anderson481837a2011-10-17 21:37:35 +0000299 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000300
301#ifndef NDEBUG
302 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
303#else
304 raw_ostream &DebugOut = nulls();
305#endif
306
Benjamin Kramer8c930972011-09-21 01:13:19 +0000307 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
308 DebugLineSection, DebugStrSection;
309 OwningPtr<DIContext> diContext;
Owen Anderson481837a2011-10-17 21:37:35 +0000310 OwningPtr<MachOObjectFile> DSYMObj;
311 MachOObject *DbgInfoObj = MachOObj;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000312 // Try to find debug info and set up the DIContext for it.
313 if (UseDbg) {
Owen Anderson481837a2011-10-17 21:37:35 +0000314 ArrayRef<SectionRef> DebugSections = Sections;
315 std::vector<SectionRef> DSYMSections;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000316
317 // A separate DSym file path was specified, parse it as a macho file,
318 // get the sections and supply it to the section name parsing machinery.
319 if (!DSYMFile.empty()) {
320 OwningPtr<MemoryBuffer> Buf;
321 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
322 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
323 return;
324 }
Owen Anderson481837a2011-10-17 21:37:35 +0000325 DSYMObj.reset(static_cast<MachOObjectFile*>(
326 ObjectFile::createMachOObjectFile(Buf.take())));
327 const macho::Header &Header = DSYMObj->getObject()->getHeader();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000328
Owen Anderson481837a2011-10-17 21:37:35 +0000329 std::vector<SymbolRef> Symbols;
Benjamin Kramer8c930972011-09-21 01:13:19 +0000330 SmallVector<uint64_t, 8> FoundFns;
331 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
332 FoundFns);
333 DebugSections = DSYMSections;
Owen Anderson481837a2011-10-17 21:37:35 +0000334 DbgInfoObj = DSYMObj.get()->getObject();
Benjamin Kramer8c930972011-09-21 01:13:19 +0000335 }
336
337 // Find the named debug info sections.
338 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000339 StringRef SectName;
340 if (!DebugSections[SectIdx].getName(SectName)) {
341 if (SectName.equals("__DWARF,__debug_abbrev"))
342 DebugSections[SectIdx].getContents(DebugAbbrevSection);
343 else if (SectName.equals("__DWARF,__debug_info"))
344 DebugSections[SectIdx].getContents(DebugInfoSection);
345 else if (SectName.equals("__DWARF,__debug_aranges"))
346 DebugSections[SectIdx].getContents(DebugArangesSection);
347 else if (SectName.equals("__DWARF,__debug_line"))
348 DebugSections[SectIdx].getContents(DebugLineSection);
349 else if (SectName.equals("__DWARF,__debug_str"))
350 DebugSections[SectIdx].getContents(DebugStrSection);
351 }
Benjamin Kramer8c930972011-09-21 01:13:19 +0000352 }
353
354 // Setup the DIContext.
Benjamin Kramer91c603b2011-09-21 18:18:53 +0000355 diContext.reset(DIContext::getDWARFContext(DbgInfoObj->isLittleEndian(),
Benjamin Kramer8c930972011-09-21 01:13:19 +0000356 DebugInfoSection,
357 DebugAbbrevSection,
358 DebugArangesSection,
359 DebugLineSection,
360 DebugStrSection));
361 }
362
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000363 FunctionMapTy FunctionMap;
364 FunctionListTy Functions;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000365
366 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000367 StringRef SectName;
368 if (Sections[SectIdx].getName(SectName) ||
369 SectName.compare("__TEXT,__text"))
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000370 continue; // Skip non-text sections
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000371
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000372 // Insert the functions from the function starts segment into our map.
Owen Anderson481837a2011-10-17 21:37:35 +0000373 uint64_t VMAddr;
374 Sections[SectIdx].getAddress(VMAddr);
375 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
376 StringRef SectBegin;
377 Sections[SectIdx].getContents(SectBegin);
378 uint64_t Offset = (uint64_t)SectBegin.data();
379 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
380 (MCFunction*)0));
381 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000382
Owen Anderson481837a2011-10-17 21:37:35 +0000383 StringRef Bytes;
384 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000385 StringRefMemoryObject memoryObject(Bytes);
386 bool symbolTableWorked = false;
387
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000388 // Parse relocations.
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000389 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
Owen Anderson481837a2011-10-17 21:37:35 +0000390 error_code ec;
391 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
392 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
393 uint64_t RelocOffset, SectionAddress;
394 RI->getAddress(RelocOffset);
395 Sections[SectIdx].getAddress(SectionAddress);
396 RelocOffset -= SectionAddress;
397
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000398 SymbolRef RelocSym;
399 RI->getSymbol(RelocSym);
Owen Anderson481837a2011-10-17 21:37:35 +0000400
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000401 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000402 }
403 array_pod_sort(Relocs.begin(), Relocs.end());
404
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000405 // Disassemble symbol by symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000406 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Anderson481837a2011-10-17 21:37:35 +0000407 StringRef SymName;
408 Symbols[SymIdx].getName(SymName);
409
410 SymbolRef::Type ST;
411 Symbols[SymIdx].getType(ST);
412 if (ST != SymbolRef::ST_Function)
413 continue;
414
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000415 // Make sure the symbol is defined in this section.
Owen Anderson481837a2011-10-17 21:37:35 +0000416 bool containsSym = false;
417 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
418 if (!containsSym)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000419 continue;
420
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000421 // Start at the address of the symbol relative to the section's address.
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000422 uint64_t SectionAddress = 0;
Owen Anderson481837a2011-10-17 21:37:35 +0000423 uint64_t Start = 0;
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000424 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000425 Symbols[SymIdx].getAddress(Start);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000426 Start -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000427
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000428 // Stop disassembling either at the beginning of the next symbol or at
429 // the end of the section.
Owen Anderson481837a2011-10-17 21:37:35 +0000430 bool containsNextSym = true;
431 uint64_t NextSym = 0;
432 uint64_t NextSymIdx = SymIdx+1;
433 while (Symbols.size() > NextSymIdx) {
434 SymbolRef::Type NextSymType;
435 Symbols[NextSymIdx].getType(NextSymType);
436 if (NextSymType == SymbolRef::ST_Function) {
437 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
438 containsNextSym);
Danil Malyshevb0436a72011-11-29 17:40:10 +0000439 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarichec8eac62012-02-03 05:42:17 +0000440 NextSym -= SectionAddress;
Owen Anderson481837a2011-10-17 21:37:35 +0000441 break;
442 }
443 ++NextSymIdx;
444 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000445
Owen Anderson481837a2011-10-17 21:37:35 +0000446 uint64_t SectSize;
447 Sections[SectIdx].getSize(SectSize);
448 uint64_t End = containsNextSym ? NextSym : SectSize;
449 uint64_t Size;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000450
451 symbolTableWorked = true;
452
453 if (!CFG) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000454 // Normal disassembly, print addresses, bytes and mnemonic form.
Owen Anderson481837a2011-10-17 21:37:35 +0000455 StringRef SymName;
456 Symbols[SymIdx].getName(SymName);
457
458 outs() << SymName << ":\n";
Benjamin Kramer8c930972011-09-21 01:13:19 +0000459 DILineInfo lastLine;
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000460 for (uint64_t Index = Start; Index < End; Index += Size) {
461 MCInst Inst;
462
463 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
464 DebugOut, nulls())) {
Owen Anderson481837a2011-10-17 21:37:35 +0000465 uint64_t SectAddress = 0;
466 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramer41a96492011-11-05 08:57:40 +0000467 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
Owen Anderson481837a2011-10-17 21:37:35 +0000468
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000469 DumpBytes(StringRef(Bytes.data() + Index, Size));
470 IP->printInst(&Inst, outs(), "");
Benjamin Kramer8c930972011-09-21 01:13:19 +0000471
472 // Print debug info.
473 if (diContext) {
474 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000475 diContext->getLineInfoForAddress(SectAddress + Index);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000476 // Print valid line info if it changed.
477 if (dli != lastLine && dli.getLine() != 0)
478 outs() << "\t## " << dli.getFileName() << ':'
479 << dli.getLine() << ':' << dli.getColumn();
480 lastLine = dli;
481 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000482 outs() << "\n";
483 } else {
484 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
485 if (Size == 0)
486 Size = 1; // skip illegible bytes
487 }
488 }
489 } else {
490 // Create CFG and use it for disassembly.
Owen Anderson481837a2011-10-17 21:37:35 +0000491 StringRef SymName;
492 Symbols[SymIdx].getName(SymName);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000493 createMCFunctionAndSaveCalls(
Owen Anderson481837a2011-10-17 21:37:35 +0000494 SymName, DisAsm.get(), memoryObject, Start, End,
495 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000496 }
497 }
498
499 if (CFG) {
500 if (!symbolTableWorked) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000501 // Reading the symbol table didn't work, create a big __TEXT symbol.
Owen Anderson481837a2011-10-17 21:37:35 +0000502 uint64_t SectSize = 0, SectAddress = 0;
503 Sections[SectIdx].getSize(SectSize);
504 Sections[SectIdx].getAddress(SectAddress);
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000505 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
Owen Anderson481837a2011-10-17 21:37:35 +0000506 0, SectSize,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000507 InstrAnalysis.get(),
Owen Anderson481837a2011-10-17 21:37:35 +0000508 SectAddress, DebugOut,
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000509 FunctionMap, Functions);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000510 }
511 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
512 me = FunctionMap.end(); mi != me; ++mi)
513 if (mi->second == 0) {
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000514 // Create functions for the remaining callees we have gathered,
515 // but we didn't find a name for them.
Owen Anderson481837a2011-10-17 21:37:35 +0000516 uint64_t SectSize = 0;
517 Sections[SectIdx].getSize(SectSize);
518
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000519 SmallVector<uint64_t, 16> Calls;
520 MCFunction f =
521 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
522 memoryObject, mi->first,
Owen Anderson481837a2011-10-17 21:37:35 +0000523 SectSize,
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000524 InstrAnalysis.get(), DebugOut,
525 Calls);
526 Functions.push_back(f);
527 mi->second = &Functions.back();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000528 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
529 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
530 if (FunctionMap.insert(p).second)
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000531 mi = FunctionMap.begin();
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000532 }
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000533 }
534
535 DenseSet<uint64_t> PrintedBlocks;
536 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
537 MCFunction &f = Functions[ffi];
538 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
539 if (!PrintedBlocks.insert(fi->first).second)
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000540 continue; // We already printed this block.
541
542 // We assume a block has predecessors when it's the first block after
543 // a symbol.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000544 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
545
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000546 // See if this block has predecessors.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000547 // FIXME: Slow.
548 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
549 ++pi)
550 if (pi->second.contains(fi->first)) {
551 hasPreds = true;
552 break;
553 }
554
Owen Anderson481837a2011-10-17 21:37:35 +0000555 uint64_t SectSize = 0, SectAddress;
556 Sections[SectIdx].getSize(SectSize);
557 Sections[SectIdx].getAddress(SectAddress);
558
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000559 // No predecessors, this is a data block. Print as .byte directives.
560 if (!hasPreds) {
Owen Anderson481837a2011-10-17 21:37:35 +0000561 uint64_t End = llvm::next(fi) == fe ? SectSize :
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000562 llvm::next(fi)->first;
563 outs() << "# " << End-fi->first << " bytes of data:\n";
564 for (unsigned pos = fi->first; pos != End; ++pos) {
Owen Anderson481837a2011-10-17 21:37:35 +0000565 outs() << format("%8x:\t", SectAddress + pos);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000566 DumpBytes(StringRef(Bytes.data() + pos, 1));
567 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
568 }
569 continue;
570 }
571
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000572 if (fi->second.contains(fi->first)) // Print a header for simple loops
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000573 outs() << "# Loop begin:\n";
574
Benjamin Kramer8c930972011-09-21 01:13:19 +0000575 DILineInfo lastLine;
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000576 // Walk over the instructions and print them.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000577 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
578 ++ii) {
579 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000580
581 // If there's a symbol at this address, print its name.
Owen Anderson481837a2011-10-17 21:37:35 +0000582 if (FunctionMap.find(SectAddress + Inst.Address) !=
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000583 FunctionMap.end())
Owen Anderson481837a2011-10-17 21:37:35 +0000584 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
585 << ":\n";
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000586
Benjamin Kramer41a96492011-11-05 08:57:40 +0000587 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000588 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000589
590 if (fi->second.contains(fi->first)) // Indent simple loops.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000591 outs() << '\t';
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000592
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000593 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000594
595 // Look for relocations inside this instructions, if there is one
Michael J. Spencer3773fb42011-10-07 19:25:47 +0000596 // print its target and additional information if available.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000597 for (unsigned j = 0; j != Relocs.size(); ++j)
Owen Anderson481837a2011-10-17 21:37:35 +0000598 if (Relocs[j].first >= SectAddress + Inst.Address &&
599 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
600 StringRef SymName;
601 uint64_t Addr;
Owen Anderson7d3f8b82011-11-07 17:21:36 +0000602 Relocs[j].second.getAddress(Addr);
603 Relocs[j].second.getName(SymName);
Owen Anderson481837a2011-10-17 21:37:35 +0000604
605 outs() << "\t# " << SymName << ' ';
606 DumpAddress(Addr, Sections, MachOObj, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000607 }
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000608
609 // If this instructions contains an address, see if we can evaluate
610 // it and print additional information.
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000611 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
612 Inst.Address,
613 Inst.Size);
614 if (targ != -1ULL)
Owen Anderson481837a2011-10-17 21:37:35 +0000615 DumpAddress(targ, Sections, MachOObj, outs());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000616
Benjamin Kramer8c930972011-09-21 01:13:19 +0000617 // Print debug info.
618 if (diContext) {
619 DILineInfo dli =
Owen Anderson481837a2011-10-17 21:37:35 +0000620 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
Benjamin Kramer8c930972011-09-21 01:13:19 +0000621 // Print valid line info if it changed.
622 if (dli != lastLine && dli.getLine() != 0)
623 outs() << "\t## " << dli.getFileName() << ':'
624 << dli.getLine() << ':' << dli.getColumn();
625 lastLine = dli;
626 }
627
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000628 outs() << '\n';
629 }
630 }
631
Benjamin Kramera894c8e2011-09-20 17:53:01 +0000632 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000633 }
634 }
635 }
636}