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/MCRegisterInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/GraphWriter.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/system_error.h"
43 using namespace object;
46 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
47 "write it to a graphviz file (MachO-only)"));
50 UseDbg("g", cl::desc("Print line information from debug info if available"));
52 static cl::opt<std::string>
53 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
55 static const Target *GetTarget(const MachOObject *MachOObj) {
56 // Figure out the target triple.
57 if (TripleName.empty()) {
58 llvm::Triple TT("unknown-unknown-unknown");
59 switch (MachOObj->getHeader().CPUType) {
60 case llvm::MachO::CPUTypeI386:
61 TT.setArch(Triple::ArchType(Triple::x86));
63 case llvm::MachO::CPUTypeX86_64:
64 TT.setArch(Triple::ArchType(Triple::x86_64));
66 case llvm::MachO::CPUTypeARM:
67 TT.setArch(Triple::ArchType(Triple::arm));
69 case llvm::MachO::CPUTypePowerPC:
70 TT.setArch(Triple::ArchType(Triple::ppc));
72 case llvm::MachO::CPUTypePowerPC64:
73 TT.setArch(Triple::ArchType(Triple::ppc64));
76 TripleName = TT.str();
79 // Get the target specific parser.
81 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
85 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
86 << "', see --version and --triple.\n";
91 bool operator()(const SymbolRef &A, const SymbolRef &B) {
92 SymbolRef::Type AType, BType;
96 uint64_t AAddr, BAddr;
97 if (AType != SymbolRef::ST_Function)
101 if (BType != SymbolRef::ST_Function)
105 return AAddr < BAddr;
109 // Print additional information about an address, if available.
110 static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
111 MachOObject *MachOObj, raw_ostream &OS) {
112 for (unsigned i = 0; i != Sections.size(); ++i) {
113 uint64_t SectAddr = 0, SectSize = 0;
114 Sections[i].getAddress(SectAddr);
115 Sections[i].getSize(SectSize);
116 uint64_t addr = SectAddr;
117 if (SectAddr <= Address &&
118 SectAddr + SectSize > Address) {
119 StringRef bytes, name;
120 Sections[i].getContents(bytes);
121 Sections[i].getName(name);
122 // Print constant strings.
123 if (!name.compare("__cstring"))
124 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
125 // Print constant CFStrings.
126 if (!name.compare("__cfstring"))
127 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
132 typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
133 typedef SmallVector<MCFunction, 16> FunctionListTy;
134 static void createMCFunctionAndSaveCalls(StringRef Name,
135 const MCDisassembler *DisAsm,
136 MemoryObject &Object, uint64_t Start,
138 MCInstrAnalysis *InstrAnalysis,
140 raw_ostream &DebugOut,
141 FunctionMapTy &FunctionMap,
142 FunctionListTy &Functions) {
143 SmallVector<uint64_t, 16> Calls;
145 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
146 InstrAnalysis, DebugOut, Calls);
147 Functions.push_back(f);
148 FunctionMap[Address] = &Functions.back();
150 // Add the gathered callees to the map.
151 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
152 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
155 // Write a graphviz file for the CFG inside an MCFunction.
156 static void emitDOTFile(const char *FileName, const MCFunction &f,
158 // Start a new dot file.
160 raw_fd_ostream Out(FileName, Error);
161 if (!Error.empty()) {
162 errs() << "llvm-objdump: warning: " << Error << '\n';
166 Out << "digraph " << f.getName() << " {\n";
167 Out << "graph [ rankdir = \"LR\" ];\n";
168 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
169 bool hasPreds = false;
170 // Only print blocks that have predecessors.
172 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
174 if (pi->second.contains(i->first)) {
179 if (!hasPreds && i != f.begin())
182 Out << '"' << i->first << "\" [ label=\"<a>";
183 // Print instructions.
184 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
186 // Escape special chars and print the instruction in mnemonic form.
188 raw_string_ostream OS(Str);
189 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
190 Out << DOT::EscapeString(OS.str()) << '|';
192 Out << "<o>\" shape=\"record\" ];\n";
195 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
196 se = i->second.succ_end(); si != se; ++si)
197 Out << i->first << ":o -> " << *si <<":a\n";
202 static void getSectionsAndSymbols(const macho::Header &Header,
203 MachOObjectFile *MachOObj,
204 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
205 std::vector<SectionRef> &Sections,
206 std::vector<SymbolRef> &Symbols,
207 SmallVectorImpl<uint64_t> &FoundFns) {
209 for (symbol_iterator SI = MachOObj->begin_symbols(),
210 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
211 Symbols.push_back(*SI);
213 for (section_iterator SI = MachOObj->begin_sections(),
214 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
217 SR.getName(SectName);
218 Sections.push_back(*SI);
221 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
222 const MachOObject::LoadCommandInfo &LCI =
223 MachOObj->getObject()->getLoadCommandInfo(i);
224 if (LCI.Command.Type == macho::LCT_FunctionStarts) {
225 // We found a function starts segment, parse the addresses for later
227 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
228 MachOObj->getObject()->ReadLinkeditDataLoadCommand(LCI, LLC);
230 MachOObj->getObject()->ReadULEB128s(LLC->DataOffset, FoundFns);
235 void llvm::DisassembleInputMachO(StringRef Filename) {
236 OwningPtr<MemoryBuffer> Buff;
238 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
239 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
243 OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
244 ObjectFile::createMachOObjectFile(Buff.take())));
245 MachOObject *MachOObj = MachOOF->getObject();
247 const Target *TheTarget = GetTarget(MachOObj);
249 // GetTarget prints out stuff.
252 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
253 OwningPtr<MCInstrAnalysis>
254 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
256 // Set up disassembler.
257 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
258 OwningPtr<const MCSubtargetInfo>
259 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
260 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
261 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
262 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
263 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
264 AsmPrinterVariant, *AsmInfo, *MRI, *STI));
266 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
267 errs() << "error: couldn't initialize disassembler for target "
268 << TripleName << '\n';
272 outs() << '\n' << Filename << ":\n\n";
274 const macho::Header &Header = MachOObj->getHeader();
276 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
277 // First, find the symbol table segment.
278 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
279 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
280 if (LCI.Command.Type == macho::LCT_Symtab) {
286 // Read and register the symbol table data.
287 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
288 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
289 MachOObj->RegisterStringTable(*SymtabLC);
291 std::vector<SectionRef> Sections;
292 std::vector<SymbolRef> Symbols;
293 SmallVector<uint64_t, 8> FoundFns;
295 getSectionsAndSymbols(Header, MachOOF.get(), &SymtabLC, Sections, Symbols,
298 // Make a copy of the unsorted symbol list. FIXME: duplication
299 std::vector<SymbolRef> UnsortedSymbols(Symbols);
300 // Sort the symbols by address, just in case they didn't come in that way.
301 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
304 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
306 raw_ostream &DebugOut = nulls();
309 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
310 DebugLineSection, DebugStrSection;
311 OwningPtr<DIContext> diContext;
312 OwningPtr<MachOObjectFile> DSYMObj;
313 MachOObject *DbgInfoObj = MachOObj;
314 // Try to find debug info and set up the DIContext for it.
316 ArrayRef<SectionRef> DebugSections = Sections;
317 std::vector<SectionRef> DSYMSections;
319 // A separate DSym file path was specified, parse it as a macho file,
320 // get the sections and supply it to the section name parsing machinery.
321 if (!DSYMFile.empty()) {
322 OwningPtr<MemoryBuffer> Buf;
323 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
324 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
327 DSYMObj.reset(static_cast<MachOObjectFile*>(
328 ObjectFile::createMachOObjectFile(Buf.take())));
329 const macho::Header &Header = DSYMObj->getObject()->getHeader();
331 std::vector<SymbolRef> Symbols;
332 SmallVector<uint64_t, 8> FoundFns;
333 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
335 DebugSections = DSYMSections;
336 DbgInfoObj = DSYMObj.get()->getObject();
339 // Find the named debug info sections.
340 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
342 if (!DebugSections[SectIdx].getName(SectName)) {
343 if (SectName.equals("__DWARF,__debug_abbrev"))
344 DebugSections[SectIdx].getContents(DebugAbbrevSection);
345 else if (SectName.equals("__DWARF,__debug_info"))
346 DebugSections[SectIdx].getContents(DebugInfoSection);
347 else if (SectName.equals("__DWARF,__debug_aranges"))
348 DebugSections[SectIdx].getContents(DebugArangesSection);
349 else if (SectName.equals("__DWARF,__debug_line"))
350 DebugSections[SectIdx].getContents(DebugLineSection);
351 else if (SectName.equals("__DWARF,__debug_str"))
352 DebugSections[SectIdx].getContents(DebugStrSection);
356 // Setup the DIContext.
357 diContext.reset(DIContext::getDWARFContext(DbgInfoObj->isLittleEndian(),
365 FunctionMapTy FunctionMap;
366 FunctionListTy Functions;
368 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
370 if (Sections[SectIdx].getName(SectName) ||
371 SectName.compare("__TEXT,__text"))
372 continue; // Skip non-text sections
374 // Insert the functions from the function starts segment into our map.
376 Sections[SectIdx].getAddress(VMAddr);
377 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
379 Sections[SectIdx].getContents(SectBegin);
380 uint64_t Offset = (uint64_t)SectBegin.data();
381 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
386 Sections[SectIdx].getContents(Bytes);
387 StringRefMemoryObject memoryObject(Bytes);
388 bool symbolTableWorked = false;
390 // Parse relocations.
391 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
393 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
394 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
395 uint64_t RelocOffset, SectionAddress;
396 RI->getAddress(RelocOffset);
397 Sections[SectIdx].getAddress(SectionAddress);
398 RelocOffset -= SectionAddress;
401 RI->getSymbol(RelocSym);
403 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
405 array_pod_sort(Relocs.begin(), Relocs.end());
407 // Disassemble symbol by symbol.
408 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
410 Symbols[SymIdx].getName(SymName);
413 Symbols[SymIdx].getType(ST);
414 if (ST != SymbolRef::ST_Function)
417 // Make sure the symbol is defined in this section.
418 bool containsSym = false;
419 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
423 // Start at the address of the symbol relative to the section's address.
424 uint64_t SectionAddress = 0;
426 Sections[SectIdx].getAddress(SectionAddress);
427 Symbols[SymIdx].getAddress(Start);
428 Start -= SectionAddress;
430 // Stop disassembling either at the beginning of the next symbol or at
431 // the end of the section.
432 bool containsNextSym = true;
433 uint64_t NextSym = 0;
434 uint64_t NextSymIdx = SymIdx+1;
435 while (Symbols.size() > NextSymIdx) {
436 SymbolRef::Type NextSymType;
437 Symbols[NextSymIdx].getType(NextSymType);
438 if (NextSymType == SymbolRef::ST_Function) {
439 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
441 Symbols[NextSymIdx].getAddress(NextSym);
442 NextSym -= SectionAddress;
449 Sections[SectIdx].getSize(SectSize);
450 uint64_t End = containsNextSym ? NextSym : SectSize;
453 symbolTableWorked = true;
456 // Normal disassembly, print addresses, bytes and mnemonic form.
458 Symbols[SymIdx].getName(SymName);
460 outs() << SymName << ":\n";
462 for (uint64_t Index = Start; Index < End; Index += Size) {
465 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
466 DebugOut, nulls())) {
467 uint64_t SectAddress = 0;
468 Sections[SectIdx].getAddress(SectAddress);
469 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
471 DumpBytes(StringRef(Bytes.data() + Index, Size));
472 IP->printInst(&Inst, outs(), "");
477 diContext->getLineInfoForAddress(SectAddress + Index);
478 // Print valid line info if it changed.
479 if (dli != lastLine && dli.getLine() != 0)
480 outs() << "\t## " << dli.getFileName() << ':'
481 << dli.getLine() << ':' << dli.getColumn();
486 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
488 Size = 1; // skip illegible bytes
492 // Create CFG and use it for disassembly.
494 Symbols[SymIdx].getName(SymName);
495 createMCFunctionAndSaveCalls(
496 SymName, DisAsm.get(), memoryObject, Start, End,
497 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
502 if (!symbolTableWorked) {
503 // Reading the symbol table didn't work, create a big __TEXT symbol.
504 uint64_t SectSize = 0, SectAddress = 0;
505 Sections[SectIdx].getSize(SectSize);
506 Sections[SectIdx].getAddress(SectAddress);
507 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
510 SectAddress, DebugOut,
511 FunctionMap, Functions);
513 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
514 me = FunctionMap.end(); mi != me; ++mi)
515 if (mi->second == 0) {
516 // Create functions for the remaining callees we have gathered,
517 // but we didn't find a name for them.
518 uint64_t SectSize = 0;
519 Sections[SectIdx].getSize(SectSize);
521 SmallVector<uint64_t, 16> Calls;
523 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
524 memoryObject, mi->first,
526 InstrAnalysis.get(), DebugOut,
528 Functions.push_back(f);
529 mi->second = &Functions.back();
530 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
531 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
532 if (FunctionMap.insert(p).second)
533 mi = FunctionMap.begin();
537 DenseSet<uint64_t> PrintedBlocks;
538 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
539 MCFunction &f = Functions[ffi];
540 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
541 if (!PrintedBlocks.insert(fi->first).second)
542 continue; // We already printed this block.
544 // We assume a block has predecessors when it's the first block after
546 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
548 // See if this block has predecessors.
550 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
552 if (pi->second.contains(fi->first)) {
557 uint64_t SectSize = 0, SectAddress;
558 Sections[SectIdx].getSize(SectSize);
559 Sections[SectIdx].getAddress(SectAddress);
561 // No predecessors, this is a data block. Print as .byte directives.
563 uint64_t End = llvm::next(fi) == fe ? SectSize :
564 llvm::next(fi)->first;
565 outs() << "# " << End-fi->first << " bytes of data:\n";
566 for (unsigned pos = fi->first; pos != End; ++pos) {
567 outs() << format("%8x:\t", SectAddress + pos);
568 DumpBytes(StringRef(Bytes.data() + pos, 1));
569 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
574 if (fi->second.contains(fi->first)) // Print a header for simple loops
575 outs() << "# Loop begin:\n";
578 // Walk over the instructions and print them.
579 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
581 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
583 // If there's a symbol at this address, print its name.
584 if (FunctionMap.find(SectAddress + Inst.Address) !=
586 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
589 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
590 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
592 if (fi->second.contains(fi->first)) // Indent simple loops.
595 IP->printInst(&Inst.Inst, outs(), "");
597 // Look for relocations inside this instructions, if there is one
598 // print its target and additional information if available.
599 for (unsigned j = 0; j != Relocs.size(); ++j)
600 if (Relocs[j].first >= SectAddress + Inst.Address &&
601 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
604 Relocs[j].second.getAddress(Addr);
605 Relocs[j].second.getName(SymName);
607 outs() << "\t# " << SymName << ' ';
608 DumpAddress(Addr, Sections, MachOObj, outs());
611 // If this instructions contains an address, see if we can evaluate
612 // it and print additional information.
613 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
617 DumpAddress(targ, Sections, MachOObj, outs());
622 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
623 // Print valid line info if it changed.
624 if (dli != lastLine && dli.getLine() != 0)
625 outs() << "\t## " << dli.getFileName() << ':'
626 << dli.getLine() << ':' << dli.getColumn();
634 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());