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/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/GraphWriter.h"
34 #include "llvm/Support/MachO.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 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 const MachOFormat::LinkeditDataLoadCommand *LLC =
227 MachOObj->getLinkeditDataLoadCommand(LCI);
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 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
261 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
262 OwningPtr<MCInstPrinter>
263 IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
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 std::vector<SectionRef> Sections;
277 std::vector<SymbolRef> Symbols;
278 SmallVector<uint64_t, 8> FoundFns;
280 getSectionsAndSymbols(Header, MachOOF.get(), Sections, Symbols, FoundFns);
282 // Make a copy of the unsorted symbol list. FIXME: duplication
283 std::vector<SymbolRef> UnsortedSymbols(Symbols);
284 // Sort the symbols by address, just in case they didn't come in that way.
285 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
288 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
290 raw_ostream &DebugOut = nulls();
293 OwningPtr<DIContext> diContext;
294 ObjectFile *DbgObj = MachOOF.get();
295 // Try to find debug info and set up the DIContext for it.
297 // A separate DSym file path was specified, parse it as a macho file,
298 // get the sections and supply it to the section name parsing machinery.
299 if (!DSYMFile.empty()) {
300 OwningPtr<MemoryBuffer> Buf;
301 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
302 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
305 DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
308 // Setup the DIContext
309 diContext.reset(DIContext::getDWARFContext(DbgObj));
312 FunctionMapTy FunctionMap;
313 FunctionListTy Functions;
315 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
317 if (Sections[SectIdx].getName(SectName) ||
318 SectName != "__text")
319 continue; // Skip non-text sections
321 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
322 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
323 if (SegmentName != "__TEXT")
326 // Insert the functions from the function starts segment into our map.
328 Sections[SectIdx].getAddress(VMAddr);
329 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
331 Sections[SectIdx].getContents(SectBegin);
332 uint64_t Offset = (uint64_t)SectBegin.data();
333 FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
338 Sections[SectIdx].getContents(Bytes);
339 StringRefMemoryObject memoryObject(Bytes);
340 bool symbolTableWorked = false;
342 // Parse relocations.
343 std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
345 for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
346 RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
347 uint64_t RelocOffset, SectionAddress;
348 RI->getAddress(RelocOffset);
349 Sections[SectIdx].getAddress(SectionAddress);
350 RelocOffset -= SectionAddress;
353 RI->getSymbol(RelocSym);
355 Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
357 array_pod_sort(Relocs.begin(), Relocs.end());
359 // Disassemble symbol by symbol.
360 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
362 Symbols[SymIdx].getName(SymName);
365 Symbols[SymIdx].getType(ST);
366 if (ST != SymbolRef::ST_Function)
369 // Make sure the symbol is defined in this section.
370 bool containsSym = false;
371 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
375 // Start at the address of the symbol relative to the section's address.
376 uint64_t SectionAddress = 0;
378 Sections[SectIdx].getAddress(SectionAddress);
379 Symbols[SymIdx].getAddress(Start);
380 Start -= SectionAddress;
382 // Stop disassembling either at the beginning of the next symbol or at
383 // the end of the section.
384 bool containsNextSym = false;
385 uint64_t NextSym = 0;
386 uint64_t NextSymIdx = SymIdx+1;
387 while (Symbols.size() > NextSymIdx) {
388 SymbolRef::Type NextSymType;
389 Symbols[NextSymIdx].getType(NextSymType);
390 if (NextSymType == SymbolRef::ST_Function) {
391 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
393 Symbols[NextSymIdx].getAddress(NextSym);
394 NextSym -= SectionAddress;
401 Sections[SectIdx].getSize(SectSize);
402 uint64_t End = containsNextSym ? NextSym : SectSize;
405 symbolTableWorked = true;
408 // Normal disassembly, print addresses, bytes and mnemonic form.
410 Symbols[SymIdx].getName(SymName);
412 outs() << SymName << ":\n";
414 for (uint64_t Index = Start; Index < End; Index += Size) {
417 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
418 DebugOut, nulls())) {
419 uint64_t SectAddress = 0;
420 Sections[SectIdx].getAddress(SectAddress);
421 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
423 DumpBytes(StringRef(Bytes.data() + Index, Size));
424 IP->printInst(&Inst, outs(), "");
429 diContext->getLineInfoForAddress(SectAddress + Index);
430 // Print valid line info if it changed.
431 if (dli != lastLine && dli.getLine() != 0)
432 outs() << "\t## " << dli.getFileName() << ':'
433 << dli.getLine() << ':' << dli.getColumn();
438 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
440 Size = 1; // skip illegible bytes
444 // Create CFG and use it for disassembly.
446 Symbols[SymIdx].getName(SymName);
447 createMCFunctionAndSaveCalls(
448 SymName, DisAsm.get(), memoryObject, Start, End,
449 InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
452 if (!CFG && !symbolTableWorked) {
453 // Reading the symbol table didn't work, disassemble the whole section.
454 uint64_t SectAddress;
455 Sections[SectIdx].getAddress(SectAddress);
457 Sections[SectIdx].getSize(SectSize);
459 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
462 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
463 DebugOut, nulls())) {
464 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
465 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
466 IP->printInst(&Inst, outs(), "");
469 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
471 InstSize = 1; // skip illegible bytes
477 if (!symbolTableWorked) {
478 // Reading the symbol table didn't work, create a big __TEXT symbol.
479 uint64_t SectSize = 0, SectAddress = 0;
480 Sections[SectIdx].getSize(SectSize);
481 Sections[SectIdx].getAddress(SectAddress);
482 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
485 SectAddress, DebugOut,
486 FunctionMap, Functions);
488 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
489 me = FunctionMap.end(); mi != me; ++mi)
490 if (mi->second == 0) {
491 // Create functions for the remaining callees we have gathered,
492 // but we didn't find a name for them.
493 uint64_t SectSize = 0;
494 Sections[SectIdx].getSize(SectSize);
496 SmallVector<uint64_t, 16> Calls;
498 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
499 memoryObject, mi->first,
501 InstrAnalysis.get(), DebugOut,
503 Functions.push_back(f);
504 mi->second = &Functions.back();
505 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
506 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
507 if (FunctionMap.insert(p).second)
508 mi = FunctionMap.begin();
512 DenseSet<uint64_t> PrintedBlocks;
513 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
514 MCFunction &f = Functions[ffi];
515 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
516 if (!PrintedBlocks.insert(fi->first).second)
517 continue; // We already printed this block.
519 // We assume a block has predecessors when it's the first block after
521 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
523 // See if this block has predecessors.
525 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
527 if (pi->second.contains(fi->first)) {
532 uint64_t SectSize = 0, SectAddress;
533 Sections[SectIdx].getSize(SectSize);
534 Sections[SectIdx].getAddress(SectAddress);
536 // No predecessors, this is a data block. Print as .byte directives.
538 uint64_t End = llvm::next(fi) == fe ? SectSize :
539 llvm::next(fi)->first;
540 outs() << "# " << End-fi->first << " bytes of data:\n";
541 for (unsigned pos = fi->first; pos != End; ++pos) {
542 outs() << format("%8x:\t", SectAddress + pos);
543 DumpBytes(StringRef(Bytes.data() + pos, 1));
544 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
549 if (fi->second.contains(fi->first)) // Print a header for simple loops
550 outs() << "# Loop begin:\n";
553 // Walk over the instructions and print them.
554 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
556 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
558 // If there's a symbol at this address, print its name.
559 if (FunctionMap.find(SectAddress + Inst.Address) !=
561 outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
564 outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
565 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
567 if (fi->second.contains(fi->first)) // Indent simple loops.
570 IP->printInst(&Inst.Inst, outs(), "");
572 // Look for relocations inside this instructions, if there is one
573 // print its target and additional information if available.
574 for (unsigned j = 0; j != Relocs.size(); ++j)
575 if (Relocs[j].first >= SectAddress + Inst.Address &&
576 Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
579 Relocs[j].second.getAddress(Addr);
580 Relocs[j].second.getName(SymName);
582 outs() << "\t# " << SymName << ' ';
583 DumpAddress(Addr, Sections, MachOObj, outs());
586 // If this instructions contains an address, see if we can evaluate
587 // it and print additional information.
588 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
592 DumpAddress(targ, Sections, MachOObj, outs());
597 diContext->getLineInfoForAddress(SectAddress + Inst.Address);
598 // Print valid line info if it changed.
599 if (dli != lastLine && dli.getLine() != 0)
600 outs() << "\t## " << dli.getFileName() << ':'
601 << dli.getLine() << ':' << dli.getColumn();
609 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());