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/ADT/OwningPtr.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/DebugInfo/DIContext.h"
20 #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"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Object/MachO.h"
30 #include "llvm/Support/Casting.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/MachO.h"
36 #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"
44 using namespace object;
47 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
48 " write it to a graphviz file (MachO-only)"));
51 UseDbg("g", cl::desc("Print line information from debug info if available"));
53 static cl::opt<std::string>
54 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
56 static const Target *GetTarget(const MachOObjectFileBase *MachOObj) {
57 // Figure out the target triple.
58 if (TripleName.empty()) {
59 llvm::Triple TT("unknown-unknown-unknown");
60 TT.setArch(Triple::ArchType(MachOObj->getArch()));
61 TripleName = TT.str();
64 // Get the target specific parser.
66 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
70 errs() << "llvm-objdump: error: unable to get target for '" << TripleName
71 << "', see --version and --triple.\n";
76 bool operator()(const SymbolRef &A, const SymbolRef &B) {
77 SymbolRef::Type AType, BType;
81 uint64_t AAddr, BAddr;
82 if (AType != SymbolRef::ST_Function)
86 if (BType != SymbolRef::ST_Function)
94 // Print additional information about an address, if available.
95 static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
96 const MachOObjectFileBase *MachOObj, raw_ostream &OS) {
97 for (unsigned i = 0; i != Sections.size(); ++i) {
98 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);
107 // Print constant strings.
108 if (!name.compare("__cstring"))
109 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
110 // Print constant CFStrings.
111 if (!name.compare("__cfstring"))
112 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
117 typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
118 typedef SmallVector<MCFunction, 16> FunctionListTy;
119 static void createMCFunctionAndSaveCalls(StringRef Name,
120 const MCDisassembler *DisAsm,
121 MemoryObject &Object, uint64_t Start,
123 MCInstrAnalysis *InstrAnalysis,
125 raw_ostream &DebugOut,
126 FunctionMapTy &FunctionMap,
127 FunctionListTy &Functions) {
128 SmallVector<uint64_t, 16> Calls;
130 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
131 InstrAnalysis, DebugOut, Calls);
132 Functions.push_back(f);
133 FunctionMap[Address] = &Functions.back();
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));
140 // Write a graphviz file for the CFG inside an MCFunction.
141 static void emitDOTFile(const char *FileName, const MCFunction &f,
143 // Start a new dot file.
145 raw_fd_ostream Out(FileName, Error);
146 if (!Error.empty()) {
147 errs() << "llvm-objdump: warning: " << Error << '\n';
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.
157 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
159 if (pi->second.contains(i->first)) {
164 if (!hasPreds && i != f.begin())
167 Out << '"' << i->first << "\" [ label=\"<a>";
168 // Print instructions.
169 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
171 // Escape special chars and print the instruction in mnemonic form.
173 raw_string_ostream OS(Str);
174 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
175 Out << DOT::EscapeString(OS.str()) << '|';
177 Out << "<o>\" shape=\"record\" ];\n";
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";
187 template<endianness E>
189 getSectionsAndSymbols(const typename MachOObjectFileMiddle<E>::Header *Header,
190 const MachOObjectFileMiddle<E> *MachOObj,
191 std::vector<SectionRef> &Sections,
192 std::vector<SymbolRef> &Symbols,
193 SmallVectorImpl<uint64_t> &FoundFns) {
194 typedef MachOObjectFileMiddle<E> ObjType;
196 for (symbol_iterator SI = MachOObj->begin_symbols(),
197 SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
198 Symbols.push_back(*SI);
200 for (section_iterator SI = MachOObj->begin_sections(),
201 SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
204 SR.getName(SectName);
205 Sections.push_back(*SI);
208 for (unsigned i = 0; i != Header->NumLoadCommands; ++i) {
209 const typename ObjType::LoadCommand *Command =
210 MachOObj->getLoadCommandInfo(i);
211 if (Command->Type == macho::LCT_FunctionStarts) {
212 // We found a function starts segment, parse the addresses for later
214 const typename ObjType::LinkeditDataLoadCommand *LLC =
215 reinterpret_cast<const typename ObjType::LinkeditDataLoadCommand*>(Command);
217 MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
222 template<endianness E>
223 static void DisassembleInputMachO2(StringRef Filename,
224 MachOObjectFileMiddle<E> *MachOOF);
226 void llvm::DisassembleInputMachO(StringRef Filename) {
227 OwningPtr<MemoryBuffer> Buff;
229 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
230 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
234 OwningPtr<MachOObjectFileBase> MachOOF(static_cast<MachOObjectFileBase*>(
235 ObjectFile::createMachOObjectFile(Buff.take())));
237 if (MachOObjectFileLE *O = dyn_cast<MachOObjectFileLE>(MachOOF.get())) {
238 DisassembleInputMachO2(Filename, O);
241 MachOObjectFileBE *O = cast<MachOObjectFileBE>(MachOOF.get());
242 DisassembleInputMachO2(Filename, O);
245 template<endianness E>
246 static void DisassembleInputMachO2(StringRef Filename,
247 MachOObjectFileMiddle<E> *MachOOF) {
248 const Target *TheTarget = GetTarget(MachOOF);
250 // GetTarget prints out stuff.
253 OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
254 OwningPtr<MCInstrAnalysis>
255 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
257 // Set up disassembler.
258 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
259 OwningPtr<const MCSubtargetInfo>
260 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
261 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
262 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
263 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
264 OwningPtr<MCInstPrinter>
265 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
268 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
269 errs() << "error: couldn't initialize disassembler for target "
270 << TripleName << '\n';
274 outs() << '\n' << Filename << ":\n\n";
276 const typename MachOObjectFileMiddle<E>::Header *Header =
277 MachOOF->getHeader();
279 std::vector<SectionRef> Sections;
280 std::vector<SymbolRef> Symbols;
281 SmallVector<uint64_t, 8> FoundFns;
283 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns);
285 // Make a copy of the unsorted symbol list. FIXME: duplication
286 std::vector<SymbolRef> UnsortedSymbols(Symbols);
287 // Sort the symbols by address, just in case they didn't come in that way.
288 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
291 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
293 raw_ostream &DebugOut = nulls();
296 OwningPtr<DIContext> diContext;
297 ObjectFile *DbgObj = MachOOF;
298 // Try to find debug info and set up the DIContext for it.
300 // A separate DSym file path was specified, parse it as a macho file,
301 // get the sections and supply it to the section name parsing machinery.
302 if (!DSYMFile.empty()) {
303 OwningPtr<MemoryBuffer> Buf;
304 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
305 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
308 DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
311 // Setup the DIContext
312 diContext.reset(DIContext::getDWARFContext(DbgObj));
315 FunctionMapTy FunctionMap;
316 FunctionListTy Functions;
318 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
320 if (Sections[SectIdx].getName(SectName) ||
321 SectName != "__text")
322 continue; // Skip non-text sections
324 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
325 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
326 if (SegmentName != "__TEXT")
329 // Insert the functions from the function starts segment into our map.
331 Sections[SectIdx].getAddress(VMAddr);
332 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
334 Sections[SectIdx].getContents(SectBegin);
335 uint64_t Offset = (uint64_t)SectBegin.data();
336 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
341 Sections[SectIdx].getContents(Bytes);
342 StringRefMemoryObject memoryObject(Bytes);
343 bool symbolTableWorked = false;
345 // Parse relocations.
346 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
348 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
349 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
350 uint64_t RelocOffset, SectionAddress;
351 RI->getAddress(RelocOffset);
352 Sections[SectIdx].getAddress(SectionAddress);
353 RelocOffset -= SectionAddress;
356 RI->getSymbol(RelocSym);
358 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
360 array_pod_sort(Relocs.begin(), Relocs.end());
362 // Disassemble symbol by symbol.
363 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
365 Symbols[SymIdx].getName(SymName);
368 Symbols[SymIdx].getType(ST);
369 if (ST != SymbolRef::ST_Function)
372 // Make sure the symbol is defined in this section.
373 bool containsSym = false;
374 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
378 // Start at the address of the symbol relative to the section's address.
379 uint64_t SectionAddress = 0;
381 Sections[SectIdx].getAddress(SectionAddress);
382 Symbols[SymIdx].getAddress(Start);
383 Start -= SectionAddress;
385 // Stop disassembling either at the beginning of the next symbol or at
386 // the end of the section.
387 bool containsNextSym = false;
388 uint64_t NextSym = 0;
389 uint64_t NextSymIdx = SymIdx+1;
390 while (Symbols.size() > NextSymIdx) {
391 SymbolRef::Type NextSymType;
392 Symbols[NextSymIdx].getType(NextSymType);
393 if (NextSymType == SymbolRef::ST_Function) {
394 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
396 Symbols[NextSymIdx].getAddress(NextSym);
397 NextSym -= SectionAddress;
404 Sections[SectIdx].getSize(SectSize);
405 uint64_t End = containsNextSym ? NextSym : SectSize;
408 symbolTableWorked = true;
411 // Normal disassembly, print addresses, bytes and mnemonic form.
413 Symbols[SymIdx].getName(SymName);
415 outs() << SymName << ":\n";
417 for (uint64_t Index = Start; Index < End; Index += Size) {
420 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
421 DebugOut, nulls())) {
422 uint64_t SectAddress = 0;
423 Sections[SectIdx].getAddress(SectAddress);
424 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
426 DumpBytes(StringRef(Bytes.data() + Index, Size));
427 IP->printInst(&Inst, outs(), "");
432 diContext->getLineInfoForAddress(SectAddress + Index);
433 // Print valid line info if it changed.
434 if (dli != lastLine && dli.getLine() != 0)
435 outs() << "\t## " << dli.getFileName() << ':'
436 << dli.getLine() << ':' << dli.getColumn();
441 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
443 Size = 1; // skip illegible bytes
447 // Create CFG and use it for disassembly.
449 Symbols[SymIdx].getName(SymName);
450 createMCFunctionAndSaveCalls(
451 SymName, DisAsm.get(), memoryObject, Start, End,
452 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
455 if (!CFG && !symbolTableWorked) {
456 // Reading the symbol table didn't work, disassemble the whole section.
457 uint64_t SectAddress;
458 Sections[SectIdx].getAddress(SectAddress);
460 Sections[SectIdx].getSize(SectSize);
462 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
465 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
466 DebugOut, nulls())) {
467 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
468 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
469 IP->printInst(&Inst, outs(), "");
472 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
474 InstSize = 1; // skip illegible bytes
480 if (!symbolTableWorked) {
481 // Reading the symbol table didn't work, create a big __TEXT symbol.
482 uint64_t SectSize = 0, SectAddress = 0;
483 Sections[SectIdx].getSize(SectSize);
484 Sections[SectIdx].getAddress(SectAddress);
485 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
488 SectAddress, DebugOut,
489 FunctionMap, Functions);
491 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
492 me = FunctionMap.end(); mi != me; ++mi)
493 if (mi->second == 0) {
494 // Create functions for the remaining callees we have gathered,
495 // but we didn't find a name for them.
496 uint64_t SectSize = 0;
497 Sections[SectIdx].getSize(SectSize);
499 SmallVector<uint64_t, 16> Calls;
501 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
502 memoryObject, mi->first,
504 InstrAnalysis.get(), DebugOut,
506 Functions.push_back(f);
507 mi->second = &Functions.back();
508 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
509 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
510 if (FunctionMap.insert(p).second)
511 mi = FunctionMap.begin();
515 DenseSet<uint64_t> PrintedBlocks;
516 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
517 MCFunction &f = Functions[ffi];
518 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
519 if (!PrintedBlocks.insert(fi->first).second)
520 continue; // We already printed this block.
522 // We assume a block has predecessors when it's the first block after
524 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
526 // See if this block has predecessors.
528 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
530 if (pi->second.contains(fi->first)) {
535 uint64_t SectSize = 0, SectAddress;
536 Sections[SectIdx].getSize(SectSize);
537 Sections[SectIdx].getAddress(SectAddress);
539 // No predecessors, this is a data block. Print as .byte directives.
541 uint64_t End = llvm::next(fi) == fe ? SectSize :
542 llvm::next(fi)->first;
543 outs() << "# " << End-fi->first << " bytes of data:\n";
544 for (unsigned pos = fi->first; pos != End; ++pos) {
545 outs() << format("%8x:\t", SectAddress + pos);
546 DumpBytes(StringRef(Bytes.data() + pos, 1));
547 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
552 if (fi->second.contains(fi->first)) // Print a header for simple loops
553 outs() << "# Loop begin:\n";
556 // Walk over the instructions and print them.
557 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
559 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
561 // If there's a symbol at this address, print its name.
562 if (FunctionMap.find(SectAddress + Inst.Address) !=
564 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
567 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
568 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
570 if (fi->second.contains(fi->first)) // Indent simple loops.
573 IP->printInst(&Inst.Inst, outs(), "");
575 // Look for relocations inside this instructions, if there is one
576 // print its target and additional information if available.
577 for (unsigned j = 0; j != Relocs.size(); ++j)
578 if (Relocs[j].first >= SectAddress + Inst.Address &&
579 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
582 Relocs[j].second.getAddress(Addr);
583 Relocs[j].second.getName(SymName);
585 outs() << "\t# " << SymName << ' ';
586 DumpAddress(Addr, Sections, MachOOF, outs());
589 // If this instructions contains an address, see if we can evaluate
590 // it and print additional information.
591 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
595 DumpAddress(targ, Sections, MachOOF, outs());
600 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
601 // Print valid line info if it changed.
602 if (dli != lastLine && dli.getLine() != 0)
603 outs() << "\t## " << dli.getFileName() << ':'
604 << dli.getLine() << ':' << dli.getColumn();
612 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());