1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "MCFunction.h"
16 #include "llvm/Support/MachO.h"
17 #include "llvm/Object/MachO.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/DebugInfo/DIContext.h"
22 #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"
42 using namespace object;
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)"));
49 UseDbg("g", cl::desc("Print line information from debug info if available"));
51 static cl::opt<std::string>
52 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
54 static const Target *GetTarget(const MachOObject *MachOObj) {
55 // Figure out the target triple.
56 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));
62 case llvm::MachO::CPUTypeX86_64:
63 TT.setArch(Triple::ArchType(Triple::x86_64));
65 case llvm::MachO::CPUTypeARM:
66 TT.setArch(Triple::ArchType(Triple::arm));
68 case llvm::MachO::CPUTypePowerPC:
69 TT.setArch(Triple::ArchType(Triple::ppc));
71 case llvm::MachO::CPUTypePowerPC64:
72 TT.setArch(Triple::ArchType(Triple::ppc64));
75 TripleName = TT.str();
78 // Get the target specific parser.
80 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
84 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
85 << "', see --version and --triple.\n";
90 bool operator()(const SymbolRef &A, const SymbolRef &B) {
91 SymbolRef::Type AType, BType;
95 uint64_t AAddr, BAddr;
96 if (AType != SymbolRef::ST_Function)
100 if (BType != SymbolRef::ST_Function)
104 return AAddr < BAddr;
108 // Print additional information about an address, if available.
109 static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
110 MachOObject *MachOObj, raw_ostream &OS) {
111 for (unsigned i = 0; i != Sections.size(); ++i) {
112 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);
121 // Print constant strings.
122 if (!name.compare("__cstring"))
123 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
124 // Print constant CFStrings.
125 if (!name.compare("__cfstring"))
126 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
131 typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
132 typedef SmallVector<MCFunction, 16> FunctionListTy;
133 static void createMCFunctionAndSaveCalls(StringRef Name,
134 const MCDisassembler *DisAsm,
135 MemoryObject &Object, uint64_t Start,
137 MCInstrAnalysis *InstrAnalysis,
139 raw_ostream &DebugOut,
140 FunctionMapTy &FunctionMap,
141 FunctionListTy &Functions) {
142 SmallVector<uint64_t, 16> Calls;
144 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
145 InstrAnalysis, DebugOut, Calls);
146 Functions.push_back(f);
147 FunctionMap[Address] = &Functions.back();
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));
154 // Write a graphviz file for the CFG inside an MCFunction.
155 static void emitDOTFile(const char *FileName, const MCFunction &f,
157 // Start a new dot file.
159 raw_fd_ostream Out(FileName, Error);
160 if (!Error.empty()) {
161 errs() << "llvm-objdump: warning: " << Error << '\n';
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.
171 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
173 if (pi->second.contains(i->first)) {
178 if (!hasPreds && i != f.begin())
181 Out << '"' << i->first << "\" [ label=\"<a>";
182 // Print instructions.
183 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
185 // Escape special chars and print the instruction in mnemonic form.
187 raw_string_ostream OS(Str);
188 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
189 Out << DOT::EscapeString(OS.str()) << '|';
191 Out << "<o>\" shape=\"record\" ];\n";
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";
201 static void getSectionsAndSymbols(const macho::Header &Header,
202 MachOObjectFile *MachOObj,
203 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
204 std::vector<SectionRef> &Sections,
205 std::vector<SymbolRef> &Symbols,
206 SmallVectorImpl<uint64_t> &FoundFns) {
208 for (symbol_iterator SI = MachOObj->begin_symbols(),
209 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
210 Symbols.push_back(*SI);
212 for (section_iterator SI = MachOObj->begin_sections(),
213 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
216 SR.getName(SectName);
217 Sections.push_back(*SI);
220 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
221 const MachOObject::LoadCommandInfo &LCI =
222 MachOObj->getObject()->getLoadCommandInfo(i);
223 if (LCI.Command.Type == macho::LCT_FunctionStarts) {
224 // We found a function starts segment, parse the addresses for later
226 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
227 MachOObj->getObject()->ReadLinkeditDataLoadCommand(LCI, LLC);
229 MachOObj->getObject()->ReadULEB128s(LLC->DataOffset, FoundFns);
234 void llvm::DisassembleInputMachO(StringRef Filename) {
235 OwningPtr<MemoryBuffer> Buff;
237 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
238 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
242 OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
243 ObjectFile::createMachOObjectFile(Buff.take())));
244 MachOObject *MachOObj = MachOOF->getObject();
246 const Target *TheTarget = GetTarget(MachOObj);
248 // GetTarget prints out stuff.
251 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
252 OwningPtr<MCInstrAnalysis>
253 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
255 // Set up disassembler.
256 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
257 OwningPtr<const MCSubtargetInfo>
258 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
259 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
260 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
261 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
262 AsmPrinterVariant, *AsmInfo, *STI));
264 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
265 errs() << "error: couldn't initialize disassembler for target "
266 << TripleName << '\n';
270 outs() << '\n' << Filename << ":\n\n";
272 const macho::Header &Header = MachOObj->getHeader();
274 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
275 // First, find the symbol table segment.
276 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
277 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
278 if (LCI.Command.Type == macho::LCT_Symtab) {
284 // Read and register the symbol table data.
285 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
286 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
287 MachOObj->RegisterStringTable(*SymtabLC);
289 std::vector<SectionRef> Sections;
290 std::vector<SymbolRef> Symbols;
291 SmallVector<uint64_t, 8> FoundFns;
293 getSectionsAndSymbols(Header, MachOOF.get(), &SymtabLC, Sections, Symbols,
296 // Make a copy of the unsorted symbol list. FIXME: duplication
297 std::vector<SymbolRef> UnsortedSymbols(Symbols);
298 // Sort the symbols by address, just in case they didn't come in that way.
299 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
302 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
304 raw_ostream &DebugOut = nulls();
307 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
308 DebugLineSection, DebugStrSection;
309 OwningPtr<DIContext> diContext;
310 OwningPtr<MachOObjectFile> DSYMObj;
311 MachOObject *DbgInfoObj = MachOObj;
312 // Try to find debug info and set up the DIContext for it.
314 ArrayRef<SectionRef> DebugSections = Sections;
315 std::vector<SectionRef> DSYMSections;
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';
325 DSYMObj.reset(static_cast<MachOObjectFile*>(
326 ObjectFile::createMachOObjectFile(Buf.take())));
327 const macho::Header &Header = DSYMObj->getObject()->getHeader();
329 std::vector<SymbolRef> Symbols;
330 SmallVector<uint64_t, 8> FoundFns;
331 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
333 DebugSections = DSYMSections;
334 DbgInfoObj = DSYMObj.get()->getObject();
337 // Find the named debug info sections.
338 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
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);
354 // Setup the DIContext.
355 diContext.reset(DIContext::getDWARFContext(DbgInfoObj->isLittleEndian(),
363 FunctionMapTy FunctionMap;
364 FunctionListTy Functions;
366 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
368 if (Sections[SectIdx].getName(SectName) ||
369 SectName.compare("__TEXT,__text"))
370 continue; // Skip non-text sections
372 // Insert the functions from the function starts segment into our map.
374 Sections[SectIdx].getAddress(VMAddr);
375 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
377 Sections[SectIdx].getContents(SectBegin);
378 uint64_t Offset = (uint64_t)SectBegin.data();
379 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
384 Sections[SectIdx].getContents(Bytes);
385 StringRefMemoryObject memoryObject(Bytes);
386 bool symbolTableWorked = false;
388 // Parse relocations.
389 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
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;
399 RI->getSymbol(RelocSym);
401 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
403 array_pod_sort(Relocs.begin(), Relocs.end());
405 // Disassemble symbol by symbol.
406 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
408 Symbols[SymIdx].getName(SymName);
411 Symbols[SymIdx].getType(ST);
412 if (ST != SymbolRef::ST_Function)
415 // Make sure the symbol is defined in this section.
416 bool containsSym = false;
417 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
421 // Start at the address of the symbol relative to the section's address.
422 uint64_t SectionAddress = 0;
424 Sections[SectIdx].getAddress(SectionAddress);
425 Symbols[SymIdx].getAddress(Start);
426 Start -= SectionAddress;
428 // Stop disassembling either at the beginning of the next symbol or at
429 // the end of the section.
430 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],
439 Symbols[NextSymIdx].getAddress(NextSym);
440 NextSym -= SectionAddress;
447 Sections[SectIdx].getSize(SectSize);
448 uint64_t End = containsNextSym ? NextSym : SectSize;
451 symbolTableWorked = true;
454 // Normal disassembly, print addresses, bytes and mnemonic form.
456 Symbols[SymIdx].getName(SymName);
458 outs() << SymName << ":\n";
460 for (uint64_t Index = Start; Index < End; Index += Size) {
463 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
464 DebugOut, nulls())) {
465 uint64_t SectAddress = 0;
466 Sections[SectIdx].getAddress(SectAddress);
467 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
469 DumpBytes(StringRef(Bytes.data() + Index, Size));
470 IP->printInst(&Inst, outs(), "");
475 diContext->getLineInfoForAddress(SectAddress + Index);
476 // Print valid line info if it changed.
477 if (dli != lastLine && dli.getLine() != 0)
478 outs() << "\t## " << dli.getFileName() << ':'
479 << dli.getLine() << ':' << dli.getColumn();
484 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
486 Size = 1; // skip illegible bytes
490 // Create CFG and use it for disassembly.
492 Symbols[SymIdx].getName(SymName);
493 createMCFunctionAndSaveCalls(
494 SymName, DisAsm.get(), memoryObject, Start, End,
495 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
500 if (!symbolTableWorked) {
501 // Reading the symbol table didn't work, create a big __TEXT symbol.
502 uint64_t SectSize = 0, SectAddress = 0;
503 Sections[SectIdx].getSize(SectSize);
504 Sections[SectIdx].getAddress(SectAddress);
505 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
508 SectAddress, DebugOut,
509 FunctionMap, Functions);
511 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
512 me = FunctionMap.end(); mi != me; ++mi)
513 if (mi->second == 0) {
514 // Create functions for the remaining callees we have gathered,
515 // but we didn't find a name for them.
516 uint64_t SectSize = 0;
517 Sections[SectIdx].getSize(SectSize);
519 SmallVector<uint64_t, 16> Calls;
521 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
522 memoryObject, mi->first,
524 InstrAnalysis.get(), DebugOut,
526 Functions.push_back(f);
527 mi->second = &Functions.back();
528 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)
531 mi = FunctionMap.begin();
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)
540 continue; // We already printed this block.
542 // We assume a block has predecessors when it's the first block after
544 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
546 // See if this block has predecessors.
548 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
550 if (pi->second.contains(fi->first)) {
555 uint64_t SectSize = 0, SectAddress;
556 Sections[SectIdx].getSize(SectSize);
557 Sections[SectIdx].getAddress(SectAddress);
559 // No predecessors, this is a data block. Print as .byte directives.
561 uint64_t End = llvm::next(fi) == fe ? SectSize :
562 llvm::next(fi)->first;
563 outs() << "# " << End-fi->first << " bytes of data:\n";
564 for (unsigned pos = fi->first; pos != End; ++pos) {
565 outs() << format("%8x:\t", SectAddress + pos);
566 DumpBytes(StringRef(Bytes.data() + pos, 1));
567 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
572 if (fi->second.contains(fi->first)) // Print a header for simple loops
573 outs() << "# Loop begin:\n";
576 // Walk over the instructions and print them.
577 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
579 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
581 // If there's a symbol at this address, print its name.
582 if (FunctionMap.find(SectAddress + Inst.Address) !=
584 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
587 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
588 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
590 if (fi->second.contains(fi->first)) // Indent simple loops.
593 IP->printInst(&Inst.Inst, outs(), "");
595 // Look for relocations inside this instructions, if there is one
596 // print its target and additional information if available.
597 for (unsigned j = 0; j != Relocs.size(); ++j)
598 if (Relocs[j].first >= SectAddress + Inst.Address &&
599 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
602 Relocs[j].second.getAddress(Addr);
603 Relocs[j].second.getName(SymName);
605 outs() << "\t# " << SymName << ' ';
606 DumpAddress(Addr, Sections, MachOObj, outs());
609 // If this instructions contains an address, see if we can evaluate
610 // it and print additional information.
611 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
615 DumpAddress(targ, Sections, MachOObj, outs());
620 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
621 // Print valid line info if it changed.
622 if (dli != lastLine && dli.getLine() != 0)
623 outs() << "\t## " << dli.getFileName() << ':'
624 << dli.getLine() << ':' << dli.getColumn();
632 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());