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 llvm::Triple TT("unknown-unknown-unknown");
57 switch (MachOObj->getHeader().CPUType) {
58 case llvm::MachO::CPUTypeI386:
59 TT.setArch(Triple::ArchType(Triple::x86));
61 case llvm::MachO::CPUTypeX86_64:
62 TT.setArch(Triple::ArchType(Triple::x86_64));
64 case llvm::MachO::CPUTypeARM:
65 TT.setArch(Triple::ArchType(Triple::arm));
67 case llvm::MachO::CPUTypePowerPC:
68 TT.setArch(Triple::ArchType(Triple::ppc));
70 case llvm::MachO::CPUTypePowerPC64:
71 TT.setArch(Triple::ArchType(Triple::ppc64));
75 TripleName = TT.str();
77 // Get the target specific parser.
79 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
83 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
84 << "', see --version and --triple.\n";
89 bool operator()(const SymbolRef &A, const SymbolRef &B) {
90 SymbolRef::Type AType, BType;
94 uint64_t AAddr, BAddr;
95 if (AType != SymbolRef::ST_Function)
99 if (BType != SymbolRef::ST_Function)
103 return AAddr < BAddr;
107 // Print additional information about an address, if available.
108 static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
109 MachOObject *MachOObj, raw_ostream &OS) {
110 for (unsigned i = 0; i != Sections.size(); ++i) {
111 uint64_t SectAddr = 0, SectSize = 0;
112 Sections[i].getAddress(SectAddr);
113 Sections[i].getSize(SectSize);
114 uint64_t addr = SectAddr;
115 if (SectAddr <= Address &&
116 SectAddr + SectSize > Address) {
117 StringRef bytes, name;
118 Sections[i].getContents(bytes);
119 Sections[i].getName(name);
120 // Print constant strings.
121 if (!name.compare("__cstring"))
122 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
123 // Print constant CFStrings.
124 if (!name.compare("__cfstring"))
125 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
130 typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
131 typedef SmallVector<MCFunction, 16> FunctionListTy;
132 static void createMCFunctionAndSaveCalls(StringRef Name,
133 const MCDisassembler *DisAsm,
134 MemoryObject &Object, uint64_t Start,
136 MCInstrAnalysis *InstrAnalysis,
138 raw_ostream &DebugOut,
139 FunctionMapTy &FunctionMap,
140 FunctionListTy &Functions) {
141 SmallVector<uint64_t, 16> Calls;
143 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
144 InstrAnalysis, DebugOut, Calls);
145 Functions.push_back(f);
146 FunctionMap[Address] = &Functions.back();
148 // Add the gathered callees to the map.
149 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
150 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
153 // Write a graphviz file for the CFG inside an MCFunction.
154 static void emitDOTFile(const char *FileName, const MCFunction &f,
156 // Start a new dot file.
158 raw_fd_ostream Out(FileName, Error);
159 if (!Error.empty()) {
160 errs() << "llvm-objdump: warning: " << Error << '\n';
164 Out << "digraph " << f.getName() << " {\n";
165 Out << "graph [ rankdir = \"LR\" ];\n";
166 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
167 bool hasPreds = false;
168 // Only print blocks that have predecessors.
170 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
172 if (pi->second.contains(i->first)) {
177 if (!hasPreds && i != f.begin())
180 Out << '"' << i->first << "\" [ label=\"<a>";
181 // Print instructions.
182 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
184 // Escape special chars and print the instruction in mnemonic form.
186 raw_string_ostream OS(Str);
187 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
188 Out << DOT::EscapeString(OS.str()) << '|';
190 Out << "<o>\" shape=\"record\" ];\n";
193 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
194 se = i->second.succ_end(); si != se; ++si)
195 Out << i->first << ":o -> " << *si <<":a\n";
200 static void getSectionsAndSymbols(const macho::Header &Header,
201 MachOObjectFile *MachOObj,
202 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
203 std::vector<SectionRef> &Sections,
204 std::vector<SymbolRef> &Symbols,
205 SmallVectorImpl<uint64_t> &FoundFns) {
207 for (symbol_iterator SI = MachOObj->begin_symbols(),
208 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
209 Symbols.push_back(*SI);
211 for (section_iterator SI = MachOObj->begin_sections(),
212 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
215 SR.getName(SectName);
216 Sections.push_back(*SI);
219 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
220 const MachOObject::LoadCommandInfo &LCI =
221 MachOObj->getObject()->getLoadCommandInfo(i);
222 if (LCI.Command.Type == macho::LCT_FunctionStarts) {
223 // We found a function starts segment, parse the addresses for later
225 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
226 MachOObj->getObject()->ReadLinkeditDataLoadCommand(LCI, LLC);
228 MachOObj->getObject()->ReadULEB128s(LLC->DataOffset, FoundFns);
233 void llvm::DisassembleInputMachO(StringRef Filename) {
234 OwningPtr<MemoryBuffer> Buff;
236 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
237 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
241 OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
242 ObjectFile::createMachOObjectFile(Buff.take())));
243 MachOObject *MachOObj = MachOOF->getObject();
245 const Target *TheTarget = GetTarget(MachOObj);
247 // GetTarget prints out stuff.
250 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
251 OwningPtr<MCInstrAnalysis>
252 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
254 // Set up disassembler.
255 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
256 OwningPtr<const MCSubtargetInfo>
257 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
258 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
259 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
260 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
261 AsmPrinterVariant, *AsmInfo, *STI));
263 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
264 errs() << "error: couldn't initialize disassembler for target "
265 << TripleName << '\n';
269 outs() << '\n' << Filename << ":\n\n";
271 const macho::Header &Header = MachOObj->getHeader();
273 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
274 // First, find the symbol table segment.
275 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
276 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
277 if (LCI.Command.Type == macho::LCT_Symtab) {
283 // Read and register the symbol table data.
284 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
285 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
286 MachOObj->RegisterStringTable(*SymtabLC);
288 std::vector<SectionRef> Sections;
289 std::vector<SymbolRef> Symbols;
290 SmallVector<uint64_t, 8> FoundFns;
292 getSectionsAndSymbols(Header, MachOOF.get(), &SymtabLC, Sections, Symbols,
295 // Make a copy of the unsorted symbol list. FIXME: duplication
296 std::vector<SymbolRef> UnsortedSymbols(Symbols);
297 // Sort the symbols by address, just in case they didn't come in that way.
298 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
301 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
303 raw_ostream &DebugOut = nulls();
306 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
307 DebugLineSection, DebugStrSection;
308 OwningPtr<DIContext> diContext;
309 OwningPtr<MachOObjectFile> DSYMObj;
310 MachOObject *DbgInfoObj = MachOObj;
311 // Try to find debug info and set up the DIContext for it.
313 ArrayRef<SectionRef> DebugSections = Sections;
314 std::vector<SectionRef> DSYMSections;
316 // A separate DSym file path was specified, parse it as a macho file,
317 // get the sections and supply it to the section name parsing machinery.
318 if (!DSYMFile.empty()) {
319 OwningPtr<MemoryBuffer> Buf;
320 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
321 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
324 DSYMObj.reset(static_cast<MachOObjectFile*>(
325 ObjectFile::createMachOObjectFile(Buf.take())));
326 const macho::Header &Header = DSYMObj->getObject()->getHeader();
328 std::vector<SymbolRef> Symbols;
329 SmallVector<uint64_t, 8> FoundFns;
330 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
332 DebugSections = DSYMSections;
333 DbgInfoObj = DSYMObj.get()->getObject();
336 // Find the named debug info sections.
337 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
339 if (!DebugSections[SectIdx].getName(SectName)) {
340 if (SectName.equals("__DWARF,__debug_abbrev"))
341 DebugSections[SectIdx].getContents(DebugAbbrevSection);
342 else if (SectName.equals("__DWARF,__debug_info"))
343 DebugSections[SectIdx].getContents(DebugInfoSection);
344 else if (SectName.equals("__DWARF,__debug_aranges"))
345 DebugSections[SectIdx].getContents(DebugArangesSection);
346 else if (SectName.equals("__DWARF,__debug_line"))
347 DebugSections[SectIdx].getContents(DebugLineSection);
348 else if (SectName.equals("__DWARF,__debug_str"))
349 DebugSections[SectIdx].getContents(DebugStrSection);
353 // Setup the DIContext.
354 diContext.reset(DIContext::getDWARFContext(DbgInfoObj->isLittleEndian(),
362 FunctionMapTy FunctionMap;
363 FunctionListTy Functions;
365 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
367 if (Sections[SectIdx].getName(SectName) ||
368 SectName.compare("__TEXT,__text"))
369 continue; // Skip non-text sections
371 // Insert the functions from the function starts segment into our map.
373 Sections[SectIdx].getAddress(VMAddr);
374 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
376 Sections[SectIdx].getContents(SectBegin);
377 uint64_t Offset = (uint64_t)SectBegin.data();
378 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
383 Sections[SectIdx].getContents(Bytes);
384 StringRefMemoryObject memoryObject(Bytes);
385 bool symbolTableWorked = false;
387 // Parse relocations.
388 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
390 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
391 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
392 uint64_t RelocOffset, SectionAddress;
393 RI->getAddress(RelocOffset);
394 Sections[SectIdx].getAddress(SectionAddress);
395 RelocOffset -= SectionAddress;
398 RI->getSymbol(RelocSym);
400 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
402 array_pod_sort(Relocs.begin(), Relocs.end());
404 // Disassemble symbol by symbol.
405 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
407 Symbols[SymIdx].getName(SymName);
410 Symbols[SymIdx].getType(ST);
411 if (ST != SymbolRef::ST_Function)
414 // Make sure the symbol is defined in this section.
415 bool containsSym = false;
416 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
420 // Start at the address of the symbol relative to the section's address.
421 uint64_t SectionAddress = 0;
423 Sections[SectIdx].getAddress(SectionAddress);
424 Symbols[SymIdx].getAddress(Start);
425 Start -= SectionAddress;
427 // Stop disassembling either at the beginning of the next symbol or at
428 // the end of the section.
429 bool containsNextSym = true;
430 uint64_t NextSym = 0;
431 uint64_t NextSymIdx = SymIdx+1;
432 while (Symbols.size() > NextSymIdx) {
433 SymbolRef::Type NextSymType;
434 Symbols[NextSymIdx].getType(NextSymType);
435 if (NextSymType == SymbolRef::ST_Function) {
436 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
438 Symbols[NextSymIdx].getAddress(NextSym);
439 NextSym -= SectionAddress;
446 Sections[SectIdx].getSize(SectSize);
447 uint64_t End = containsNextSym ? NextSym : SectSize;
450 symbolTableWorked = true;
453 // Normal disassembly, print addresses, bytes and mnemonic form.
455 Symbols[SymIdx].getName(SymName);
457 outs() << SymName << ":\n";
459 for (uint64_t Index = Start; Index < End; Index += Size) {
462 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
463 DebugOut, nulls())) {
464 uint64_t SectAddress = 0;
465 Sections[SectIdx].getAddress(SectAddress);
466 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
468 DumpBytes(StringRef(Bytes.data() + Index, Size));
469 IP->printInst(&Inst, outs(), "");
474 diContext->getLineInfoForAddress(SectAddress + Index);
475 // Print valid line info if it changed.
476 if (dli != lastLine && dli.getLine() != 0)
477 outs() << "\t## " << dli.getFileName() << ':'
478 << dli.getLine() << ':' << dli.getColumn();
483 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
485 Size = 1; // skip illegible bytes
489 // Create CFG and use it for disassembly.
491 Symbols[SymIdx].getName(SymName);
492 createMCFunctionAndSaveCalls(
493 SymName, DisAsm.get(), memoryObject, Start, End,
494 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
499 if (!symbolTableWorked) {
500 // Reading the symbol table didn't work, create a big __TEXT symbol.
501 uint64_t SectSize = 0, SectAddress = 0;
502 Sections[SectIdx].getSize(SectSize);
503 Sections[SectIdx].getAddress(SectAddress);
504 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
507 SectAddress, DebugOut,
508 FunctionMap, Functions);
510 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
511 me = FunctionMap.end(); mi != me; ++mi)
512 if (mi->second == 0) {
513 // Create functions for the remaining callees we have gathered,
514 // but we didn't find a name for them.
515 uint64_t SectSize = 0;
516 Sections[SectIdx].getSize(SectSize);
518 SmallVector<uint64_t, 16> Calls;
520 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
521 memoryObject, mi->first,
523 InstrAnalysis.get(), DebugOut,
525 Functions.push_back(f);
526 mi->second = &Functions.back();
527 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
528 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
529 if (FunctionMap.insert(p).second)
530 mi = FunctionMap.begin();
534 DenseSet<uint64_t> PrintedBlocks;
535 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
536 MCFunction &f = Functions[ffi];
537 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
538 if (!PrintedBlocks.insert(fi->first).second)
539 continue; // We already printed this block.
541 // We assume a block has predecessors when it's the first block after
543 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
545 // See if this block has predecessors.
547 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
549 if (pi->second.contains(fi->first)) {
554 uint64_t SectSize = 0, SectAddress;
555 Sections[SectIdx].getSize(SectSize);
556 Sections[SectIdx].getAddress(SectAddress);
558 // No predecessors, this is a data block. Print as .byte directives.
560 uint64_t End = llvm::next(fi) == fe ? SectSize :
561 llvm::next(fi)->first;
562 outs() << "# " << End-fi->first << " bytes of data:\n";
563 for (unsigned pos = fi->first; pos != End; ++pos) {
564 outs() << format("%8x:\t", SectAddress + pos);
565 DumpBytes(StringRef(Bytes.data() + pos, 1));
566 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
571 if (fi->second.contains(fi->first)) // Print a header for simple loops
572 outs() << "# Loop begin:\n";
575 // Walk over the instructions and print them.
576 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
578 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
580 // If there's a symbol at this address, print its name.
581 if (FunctionMap.find(SectAddress + Inst.Address) !=
583 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
586 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
587 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
589 if (fi->second.contains(fi->first)) // Indent simple loops.
592 IP->printInst(&Inst.Inst, outs(), "");
594 // Look for relocations inside this instructions, if there is one
595 // print its target and additional information if available.
596 for (unsigned j = 0; j != Relocs.size(); ++j)
597 if (Relocs[j].first >= SectAddress + Inst.Address &&
598 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
601 Relocs[j].second.getAddress(Addr);
602 Relocs[j].second.getName(SymName);
604 outs() << "\t# " << SymName << ' ';
605 DumpAddress(Addr, Sections, MachOObj, outs());
608 // If this instructions contains an address, see if we can evaluate
609 // it and print additional information.
610 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
614 DumpAddress(targ, Sections, MachOObj, outs());
619 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
620 // Print valid line info if it changed.
621 if (dli != lastLine && dli.getLine() != 0)
622 outs() << "\t## " << dli.getFileName() << ':'
623 << dli.getLine() << ':' << dli.getColumn();
631 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());