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/MachOObject.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";
94 uint64_t RelocTableOffset;
100 uint8_t SectionIndex;
101 bool operator<(const Symbol &RHS) const { return Value < RHS.Value; }
104 template <typename T>
105 static Section copySection(const T &Sect) {
107 memcpy(S.Name, Sect->Name, 16);
108 S.Address = Sect->Address;
110 S.Offset = Sect->Offset;
111 S.NumRelocs = Sect->NumRelocationTableEntries;
112 S.RelocTableOffset = Sect->RelocationTableOffset;
116 template <typename T>
117 static Symbol copySymbol(const T &STE) {
119 S.StringIndex = STE->StringIndex;
120 S.SectionIndex = STE->SectionIndex;
121 S.Value = STE->Value;
125 // Print addtitional information about an address, if available.
126 static void DumpAddress(uint64_t Address, ArrayRef<Section> Sections,
127 MachOObject *MachOObj, raw_ostream &OS) {
128 for (unsigned i = 0; i != Sections.size(); ++i) {
129 uint64_t addr = Address-Sections[i].Address;
130 if (Sections[i].Address <= Address &&
131 Sections[i].Address + Sections[i].Size > Address) {
132 StringRef bytes = MachOObj->getData(Sections[i].Offset,
134 // Print constant strings.
135 if (!strcmp(Sections[i].Name, "__cstring"))
136 OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
137 // Print constant CFStrings.
138 if (!strcmp(Sections[i].Name, "__cfstring"))
139 OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
144 typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
145 typedef SmallVector<MCFunction, 16> FunctionListTy;
146 static void createMCFunctionAndSaveCalls(StringRef Name,
147 const MCDisassembler *DisAsm,
148 MemoryObject &Object, uint64_t Start,
150 MCInstrAnalysis *InstrAnalysis,
152 raw_ostream &DebugOut,
153 FunctionMapTy &FunctionMap,
154 FunctionListTy &Functions) {
155 SmallVector<uint64_t, 16> Calls;
157 MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
158 InstrAnalysis, DebugOut, Calls);
159 Functions.push_back(f);
160 FunctionMap[Address] = &Functions.back();
162 // Add the gathered callees to the map.
163 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
164 FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
167 // Write a graphviz file for the CFG inside an MCFunction.
168 static void emitDOTFile(const char *FileName, const MCFunction &f,
170 // Start a new dot file.
172 raw_fd_ostream Out(FileName, Error);
173 if (!Error.empty()) {
174 errs() << "llvm-objdump: warning: " << Error << '\n';
178 Out << "digraph " << f.getName() << " {\n";
179 Out << "graph [ rankdir = \"LR\" ];\n";
180 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
181 bool hasPreds = false;
182 // Only print blocks that have predecessors.
184 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
186 if (pi->second.contains(i->first)) {
191 if (!hasPreds && i != f.begin())
194 Out << '"' << i->first << "\" [ label=\"<a>";
195 // Print instructions.
196 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
198 // Escape special chars and print the instruction in mnemonic form.
200 raw_string_ostream OS(Str);
201 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
202 Out << DOT::EscapeString(OS.str()) << '|';
204 Out << "<o>\" shape=\"record\" ];\n";
207 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
208 se = i->second.succ_end(); si != se; ++si)
209 Out << i->first << ":o -> " << *si <<":a\n";
214 static void getSectionsAndSymbols(const macho::Header &Header,
215 MachOObject *MachOObj,
216 InMemoryStruct<macho::SymtabLoadCommand> *SymtabLC,
217 std::vector<Section> &Sections,
218 std::vector<Symbol> &Symbols,
219 SmallVectorImpl<uint64_t> &FoundFns) {
220 // Make a list of all symbols in the object file.
221 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
222 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
223 if (LCI.Command.Type == macho::LCT_Segment) {
224 InMemoryStruct<macho::SegmentLoadCommand> SegmentLC;
225 MachOObj->ReadSegmentLoadCommand(LCI, SegmentLC);
227 // Store the sections in this segment.
228 for (unsigned SectNum = 0; SectNum != SegmentLC->NumSections; ++SectNum) {
229 InMemoryStruct<macho::Section> Sect;
230 MachOObj->ReadSection(LCI, SectNum, Sect);
231 Sections.push_back(copySection(Sect));
233 // Store the symbols in this section.
235 for (unsigned i = 0; i != (*SymtabLC)->NumSymbolTableEntries; ++i) {
236 InMemoryStruct<macho::SymbolTableEntry> STE;
237 MachOObj->ReadSymbolTableEntry((*SymtabLC)->SymbolTableOffset, i,
239 Symbols.push_back(copySymbol(STE));
243 } else if (LCI.Command.Type == macho::LCT_Segment64) {
244 InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
245 MachOObj->ReadSegment64LoadCommand(LCI, Segment64LC);
247 // Store the sections in this segment.
248 for (unsigned SectNum = 0; SectNum != Segment64LC->NumSections;
250 InMemoryStruct<macho::Section64> Sect64;
251 MachOObj->ReadSection64(LCI, SectNum, Sect64);
252 Sections.push_back(copySection(Sect64));
254 // Store the symbols in this section.
256 for (unsigned i = 0; i != (*SymtabLC)->NumSymbolTableEntries; ++i) {
257 InMemoryStruct<macho::Symbol64TableEntry> STE;
258 MachOObj->ReadSymbol64TableEntry((*SymtabLC)->SymbolTableOffset, i,
260 Symbols.push_back(copySymbol(STE));
264 } else if (LCI.Command.Type == macho::LCT_FunctionStarts) {
265 // We found a function starts segment, parse the addresses for later
267 InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
268 MachOObj->ReadLinkeditDataLoadCommand(LCI, LLC);
270 MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
275 void llvm::DisassembleInputMachO(StringRef Filename) {
276 OwningPtr<MemoryBuffer> Buff;
278 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
279 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
283 OwningPtr<MachOObject> MachOObj(MachOObject::LoadFromBuffer(Buff.take()));
285 const Target *TheTarget = GetTarget(MachOObj.get());
287 // GetTarget prints out stuff.
290 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
291 OwningPtr<MCInstrAnalysis>
292 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
294 // Set up disassembler.
295 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
296 OwningPtr<const MCSubtargetInfo>
297 STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
298 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
299 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
300 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
301 AsmPrinterVariant, *AsmInfo, *STI));
303 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
304 errs() << "error: couldn't initialize disassmbler for target "
305 << TripleName << '\n';
309 outs() << '\n' << Filename << ":\n\n";
311 const macho::Header &Header = MachOObj->getHeader();
313 const MachOObject::LoadCommandInfo *SymtabLCI = 0;
314 // First, find the symbol table segment.
315 for (unsigned i = 0; i != Header.NumLoadCommands; ++i) {
316 const MachOObject::LoadCommandInfo &LCI = MachOObj->getLoadCommandInfo(i);
317 if (LCI.Command.Type == macho::LCT_Symtab) {
323 // Read and register the symbol table data.
324 InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
325 MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
326 MachOObj->RegisterStringTable(*SymtabLC);
328 std::vector<Section> Sections;
329 std::vector<Symbol> Symbols;
330 SmallVector<uint64_t, 8> FoundFns;
332 getSectionsAndSymbols(Header, MachOObj.get(), &SymtabLC, Sections, Symbols,
335 // Make a copy of the unsorted symbol list. FIXME: duplication
336 std::vector<Symbol> UnsortedSymbols(Symbols);
337 // Sort the symbols by address, just in case they didn't come in that way.
338 array_pod_sort(Symbols.begin(), Symbols.end());
341 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
343 raw_ostream &DebugOut = nulls();
346 StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
347 DebugLineSection, DebugStrSection;
348 OwningPtr<DIContext> diContext;
349 // Try to find debug info and set up the DIContext for it.
351 ArrayRef<Section> DebugSections = Sections;
352 std::vector<Section> DSYMSections;
353 OwningPtr<MachOObject> DSYMObj;
355 // A separate DSym file path was specified, parse it as a macho file,
356 // get the sections and supply it to the section name parsing machinery.
357 if (!DSYMFile.empty()) {
358 OwningPtr<MemoryBuffer> Buf;
359 if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
360 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
363 DSYMObj.reset(MachOObject::LoadFromBuffer(Buf.take()));
364 const macho::Header &Header = DSYMObj->getHeader();
366 std::vector<Symbol> Symbols;
367 SmallVector<uint64_t, 8> FoundFns;
368 getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbols,
370 DebugSections = DSYMSections;
373 // Find the named debug info sections.
374 for (unsigned SectIdx = 0; SectIdx != DebugSections.size(); SectIdx++) {
375 if (!strcmp(DebugSections[SectIdx].Name, "__debug_abbrev"))
376 DebugAbbrevSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
377 DebugSections[SectIdx].Size);
378 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_info"))
379 DebugInfoSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
380 DebugSections[SectIdx].Size);
381 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_aranges"))
382 DebugArangesSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
383 DebugSections[SectIdx].Size);
384 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_line"))
385 DebugLineSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
386 DebugSections[SectIdx].Size);
387 else if (!strcmp(DebugSections[SectIdx].Name, "__debug_str"))
388 DebugStrSection = DSYMObj->getData(DebugSections[SectIdx].Offset,
389 DebugSections[SectIdx].Size);
392 // Setup the DIContext.
393 diContext.reset(DIContext::getDWARFContext(MachOObj->isLittleEndian(),
401 FunctionMapTy FunctionMap;
402 FunctionListTy Functions;
404 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
405 if (strcmp(Sections[SectIdx].Name, "__text"))
406 continue; // Skip non-text sections
408 // Insert the functions from the function starts segment into our map.
409 uint64_t VMAddr = Sections[SectIdx].Address - Sections[SectIdx].Offset;
410 for (unsigned i = 0, e = FoundFns.size(); i != e; ++i)
411 FunctionMap.insert(std::make_pair(FoundFns[i]+VMAddr, (MCFunction*)0));
413 StringRef Bytes = MachOObj->getData(Sections[SectIdx].Offset,
414 Sections[SectIdx].Size);
415 StringRefMemoryObject memoryObject(Bytes);
416 bool symbolTableWorked = false;
418 // Parse relocations.
419 std::vector<std::pair<uint64_t, uint32_t> > Relocs;
420 for (unsigned j = 0; j != Sections[SectIdx].NumRelocs; ++j) {
421 InMemoryStruct<macho::RelocationEntry> RE;
422 MachOObj->ReadRelocationEntry(Sections[SectIdx].RelocTableOffset, j, RE);
423 Relocs.push_back(std::make_pair(RE->Word0, RE->Word1 & 0xffffff));
425 array_pod_sort(Relocs.begin(), Relocs.end());
427 // Disassemble symbol by symbol.
428 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
429 // Make sure the symbol is defined in this section.
430 if ((unsigned)Symbols[SymIdx].SectionIndex - 1 != SectIdx)
433 // Start at the address of the symbol relative to the section's address.
434 uint64_t Start = Symbols[SymIdx].Value - Sections[SectIdx].Address;
435 // Stop disassembling either at the beginning of the next symbol or at
436 // the end of the section.
437 uint64_t End = (SymIdx+1 == Symbols.size() ||
438 Symbols[SymIdx].SectionIndex != Symbols[SymIdx+1].SectionIndex) ?
439 Sections[SectIdx].Size :
440 Symbols[SymIdx+1].Value - Sections[SectIdx].Address;
446 symbolTableWorked = true;
449 // Normal disassembly, print addresses, bytes and mnemonic form.
450 outs() << MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex)
453 for (uint64_t Index = Start; Index < End; Index += Size) {
456 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
457 DebugOut, nulls())) {
458 outs() << format("%8llx:\t", Sections[SectIdx].Address + Index);
459 DumpBytes(StringRef(Bytes.data() + Index, Size));
460 IP->printInst(&Inst, outs(), "");
465 diContext->getLineInfoForAddress(Sections[SectIdx].Address +
467 // Print valid line info if it changed.
468 if (dli != lastLine && dli.getLine() != 0)
469 outs() << "\t## " << dli.getFileName() << ':'
470 << dli.getLine() << ':' << dli.getColumn();
475 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
477 Size = 1; // skip illegible bytes
481 // Create CFG and use it for disassembly.
482 createMCFunctionAndSaveCalls(
483 MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex),
484 DisAsm.get(), memoryObject, Start, End, InstrAnalysis.get(),
485 Start, DebugOut, FunctionMap, Functions);
490 if (!symbolTableWorked) {
491 // Reading the symbol table didn't work, create a big __TEXT symbol.
492 createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
493 0, Sections[SectIdx].Size,
495 Sections[SectIdx].Offset, DebugOut,
496 FunctionMap, Functions);
498 for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
499 me = FunctionMap.end(); mi != me; ++mi)
500 if (mi->second == 0) {
501 // Create functions for the remaining callees we have gathered,
502 // but we didn't find a name for them.
503 SmallVector<uint64_t, 16> Calls;
505 MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
506 memoryObject, mi->first,
507 Sections[SectIdx].Size,
508 InstrAnalysis.get(), DebugOut,
510 Functions.push_back(f);
511 mi->second = &Functions.back();
512 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
513 std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
514 if (FunctionMap.insert(p).second)
515 mi = FunctionMap.begin();
519 DenseSet<uint64_t> PrintedBlocks;
520 for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
521 MCFunction &f = Functions[ffi];
522 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
523 if (!PrintedBlocks.insert(fi->first).second)
524 continue; // We already printed this block.
526 // We assume a block has predecessors when it's the first block after
528 bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
530 // See if this block has predecessors.
532 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
534 if (pi->second.contains(fi->first)) {
539 // No predecessors, this is a data block. Print as .byte directives.
541 uint64_t End = llvm::next(fi) == fe ? Sections[SectIdx].Size :
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", Sections[SectIdx].Address + 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(Sections[SectIdx].Address + Inst.Address) !=
564 outs() << FunctionMap[Sections[SectIdx].Address + Inst.Address]->
567 outs() << format("%8llx:\t", Sections[SectIdx].Address +
569 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
571 if (fi->second.contains(fi->first)) // Indent simple loops.
574 IP->printInst(&Inst.Inst, outs(), "");
576 // Look for relocations inside this instructions, if there is one
577 // print its target and additional information if availbable.
578 for (unsigned j = 0; j != Relocs.size(); ++j)
579 if (Relocs[j].first >= Sections[SectIdx].Address + Inst.Address &&
580 Relocs[j].first < Sections[SectIdx].Address + Inst.Address +
583 << MachOObj->getStringAtIndex(
584 UnsortedSymbols[Relocs[j].second].StringIndex)
586 DumpAddress(UnsortedSymbols[Relocs[j].second].Value, Sections,
587 MachOObj.get(), outs());
590 // If this instructions contains an address, see if we can evaluate
591 // it and print additional information.
592 uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
596 DumpAddress(targ, Sections, MachOObj.get(), outs());
601 diContext->getLineInfoForAddress(Sections[SectIdx].Address +
603 // Print valid line info if it changed.
604 if (dli != lastLine && dli.getLine() != 0)
605 outs() << "\t## " << dli.getFileName() << ':'
606 << dli.getLine() << ':' << dli.getColumn();
614 emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());