MachODump.cpp revision 317d3f48fd53be5238dfba5e9fbac51a2366de0e
1//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
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"
40#include <algorithm>
41#include <cstring>
42using namespace llvm;
43using namespace object;
44
45static cl::opt<bool>
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)"));
48
49static cl::opt<bool>
50  UseDbg("g", cl::desc("Print line information from debug info if available"));
51
52static cl::opt<std::string>
53  DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
54
55static const Target *GetTarget(const MachOObjectFileBase *MachOObj) {
56  // Figure out the target triple.
57  if (TripleName.empty()) {
58    llvm::Triple TT("unknown-unknown-unknown");
59    TT.setArch(Triple::ArchType(MachOObj->getArch()));
60    TripleName = TT.str();
61  }
62
63  // Get the target specific parser.
64  std::string Error;
65  const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
66  if (TheTarget)
67    return TheTarget;
68
69  errs() << "llvm-objdump: error: unable to get target for '" << TripleName
70         << "', see --version and --triple.\n";
71  return 0;
72}
73
74struct SymbolSorter {
75  bool operator()(const SymbolRef &A, const SymbolRef &B) {
76    SymbolRef::Type AType, BType;
77    A.getType(AType);
78    B.getType(BType);
79
80    uint64_t AAddr, BAddr;
81    if (AType != SymbolRef::ST_Function)
82      AAddr = 0;
83    else
84      A.getAddress(AAddr);
85    if (BType != SymbolRef::ST_Function)
86      BAddr = 0;
87    else
88      B.getAddress(BAddr);
89    return AAddr < BAddr;
90  }
91};
92
93// Print additional information about an address, if available.
94static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
95                        const MachOObjectFileBase *MachOObj, raw_ostream &OS) {
96  for (unsigned i = 0; i != Sections.size(); ++i) {
97    uint64_t SectAddr = 0, SectSize = 0;
98    Sections[i].getAddress(SectAddr);
99    Sections[i].getSize(SectSize);
100    uint64_t addr = SectAddr;
101    if (SectAddr <= Address &&
102        SectAddr + SectSize > Address) {
103      StringRef bytes, name;
104      Sections[i].getContents(bytes);
105      Sections[i].getName(name);
106      // Print constant strings.
107      if (!name.compare("__cstring"))
108        OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
109      // Print constant CFStrings.
110      if (!name.compare("__cfstring"))
111        OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
112    }
113  }
114}
115
116typedef std::map<uint64_t, MCFunction*> FunctionMapTy;
117typedef SmallVector<MCFunction, 16> FunctionListTy;
118static void createMCFunctionAndSaveCalls(StringRef Name,
119                                         const MCDisassembler *DisAsm,
120                                         MemoryObject &Object, uint64_t Start,
121                                         uint64_t End,
122                                         MCInstrAnalysis *InstrAnalysis,
123                                         uint64_t Address,
124                                         raw_ostream &DebugOut,
125                                         FunctionMapTy &FunctionMap,
126                                         FunctionListTy &Functions) {
127  SmallVector<uint64_t, 16> Calls;
128  MCFunction f =
129    MCFunction::createFunctionFromMC(Name, DisAsm, Object, Start, End,
130                                     InstrAnalysis, DebugOut, Calls);
131  Functions.push_back(f);
132  FunctionMap[Address] = &Functions.back();
133
134  // Add the gathered callees to the map.
135  for (unsigned i = 0, e = Calls.size(); i != e; ++i)
136    FunctionMap.insert(std::make_pair(Calls[i], (MCFunction*)0));
137}
138
139// Write a graphviz file for the CFG inside an MCFunction.
140static void emitDOTFile(const char *FileName, const MCFunction &f,
141                        MCInstPrinter *IP) {
142  // Start a new dot file.
143  std::string Error;
144  raw_fd_ostream Out(FileName, Error);
145  if (!Error.empty()) {
146    errs() << "llvm-objdump: warning: " << Error << '\n';
147    return;
148  }
149
150  Out << "digraph " << f.getName() << " {\n";
151  Out << "graph [ rankdir = \"LR\" ];\n";
152  for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
153    bool hasPreds = false;
154    // Only print blocks that have predecessors.
155    // FIXME: Slow.
156    for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
157        ++pi)
158      if (pi->second.contains(i->first)) {
159        hasPreds = true;
160        break;
161      }
162
163    if (!hasPreds && i != f.begin())
164      continue;
165
166    Out << '"' << i->first << "\" [ label=\"<a>";
167    // Print instructions.
168    for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
169        ++ii) {
170      // Escape special chars and print the instruction in mnemonic form.
171      std::string Str;
172      raw_string_ostream OS(Str);
173      IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
174      Out << DOT::EscapeString(OS.str()) << '|';
175    }
176    Out << "<o>\" shape=\"record\" ];\n";
177
178    // Add edges.
179    for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
180        se = i->second.succ_end(); si != se; ++si)
181      Out << i->first << ":o -> " << *si <<":a\n";
182  }
183  Out << "}\n";
184}
185
186static void getSectionsAndSymbols(const MachOObjectFileBase::Header *Header,
187                                  MachOObjectFileBase *MachOObj,
188                                  std::vector<SectionRef> &Sections,
189                                  std::vector<SymbolRef> &Symbols,
190                                  SmallVectorImpl<uint64_t> &FoundFns) {
191  error_code ec;
192  for (symbol_iterator SI = MachOObj->begin_symbols(),
193       SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
194    Symbols.push_back(*SI);
195
196  for (section_iterator SI = MachOObj->begin_sections(),
197       SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
198    SectionRef SR = *SI;
199    StringRef SectName;
200    SR.getName(SectName);
201    Sections.push_back(*SI);
202  }
203
204  for (unsigned i = 0; i != Header->NumLoadCommands; ++i) {
205    const MachOObjectFileBase::LoadCommand *Command =
206      MachOObj->getLoadCommandInfo(i);
207    if (Command->Type == macho::LCT_FunctionStarts) {
208      // We found a function starts segment, parse the addresses for later
209      // consumption.
210      const MachOObjectFileBase::LinkeditDataLoadCommand *LLC =
211 reinterpret_cast<const MachOObjectFileBase::LinkeditDataLoadCommand*>(Command);
212
213      MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
214    }
215  }
216}
217
218void llvm::DisassembleInputMachO(StringRef Filename) {
219  OwningPtr<MemoryBuffer> Buff;
220
221  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
222    errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
223    return;
224  }
225
226  OwningPtr<MachOObjectFileBase> MachOOF(static_cast<MachOObjectFileBase*>(
227        ObjectFile::createMachOObjectFile(Buff.take())));
228
229  const Target *TheTarget = GetTarget(MachOOF.get());
230  if (!TheTarget) {
231    // GetTarget prints out stuff.
232    return;
233  }
234  OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
235  OwningPtr<MCInstrAnalysis>
236    InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
237
238  // Set up disassembler.
239  OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
240  OwningPtr<const MCSubtargetInfo>
241    STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
242  OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
243  OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
244  int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
245  OwningPtr<MCInstPrinter>
246    IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
247                                      *MRI, *STI));
248
249  if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
250    errs() << "error: couldn't initialize disassembler for target "
251           << TripleName << '\n';
252    return;
253  }
254
255  outs() << '\n' << Filename << ":\n\n";
256
257  const MachOObjectFileBase::Header *Header = MachOOF->getHeader();
258
259  std::vector<SectionRef> Sections;
260  std::vector<SymbolRef> Symbols;
261  SmallVector<uint64_t, 8> FoundFns;
262
263  getSectionsAndSymbols(Header, MachOOF.get(), Sections, Symbols, FoundFns);
264
265  // Make a copy of the unsorted symbol list. FIXME: duplication
266  std::vector<SymbolRef> UnsortedSymbols(Symbols);
267  // Sort the symbols by address, just in case they didn't come in that way.
268  std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
269
270#ifndef NDEBUG
271  raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
272#else
273  raw_ostream &DebugOut = nulls();
274#endif
275
276  OwningPtr<DIContext> diContext;
277  ObjectFile *DbgObj = MachOOF.get();
278  // Try to find debug info and set up the DIContext for it.
279  if (UseDbg) {
280    // A separate DSym file path was specified, parse it as a macho file,
281    // get the sections and supply it to the section name parsing machinery.
282    if (!DSYMFile.empty()) {
283      OwningPtr<MemoryBuffer> Buf;
284      if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile.c_str(), Buf)) {
285        errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
286        return;
287      }
288      DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
289    }
290
291    // Setup the DIContext
292    diContext.reset(DIContext::getDWARFContext(DbgObj));
293  }
294
295  FunctionMapTy FunctionMap;
296  FunctionListTy Functions;
297
298  for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
299    StringRef SectName;
300    if (Sections[SectIdx].getName(SectName) ||
301        SectName != "__text")
302      continue; // Skip non-text sections
303
304    DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
305    StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
306    if (SegmentName != "__TEXT")
307      continue;
308
309    // Insert the functions from the function starts segment into our map.
310    uint64_t VMAddr;
311    Sections[SectIdx].getAddress(VMAddr);
312    for (unsigned i = 0, e = FoundFns.size(); i != e; ++i) {
313      StringRef SectBegin;
314      Sections[SectIdx].getContents(SectBegin);
315      uint64_t Offset = (uint64_t)SectBegin.data();
316      FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
317                                        (MCFunction*)0));
318    }
319
320    StringRef Bytes;
321    Sections[SectIdx].getContents(Bytes);
322    StringRefMemoryObject memoryObject(Bytes);
323    bool symbolTableWorked = false;
324
325    // Parse relocations.
326    std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
327    error_code ec;
328    for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
329         RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
330      uint64_t RelocOffset, SectionAddress;
331      RI->getAddress(RelocOffset);
332      Sections[SectIdx].getAddress(SectionAddress);
333      RelocOffset -= SectionAddress;
334
335      SymbolRef RelocSym;
336      RI->getSymbol(RelocSym);
337
338      Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
339    }
340    array_pod_sort(Relocs.begin(), Relocs.end());
341
342    // Disassemble symbol by symbol.
343    for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
344      StringRef SymName;
345      Symbols[SymIdx].getName(SymName);
346
347      SymbolRef::Type ST;
348      Symbols[SymIdx].getType(ST);
349      if (ST != SymbolRef::ST_Function)
350        continue;
351
352      // Make sure the symbol is defined in this section.
353      bool containsSym = false;
354      Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
355      if (!containsSym)
356        continue;
357
358      // Start at the address of the symbol relative to the section's address.
359      uint64_t SectionAddress = 0;
360      uint64_t Start = 0;
361      Sections[SectIdx].getAddress(SectionAddress);
362      Symbols[SymIdx].getAddress(Start);
363      Start -= SectionAddress;
364
365      // Stop disassembling either at the beginning of the next symbol or at
366      // the end of the section.
367      bool containsNextSym = false;
368      uint64_t NextSym = 0;
369      uint64_t NextSymIdx = SymIdx+1;
370      while (Symbols.size() > NextSymIdx) {
371        SymbolRef::Type NextSymType;
372        Symbols[NextSymIdx].getType(NextSymType);
373        if (NextSymType == SymbolRef::ST_Function) {
374          Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
375                                           containsNextSym);
376          Symbols[NextSymIdx].getAddress(NextSym);
377          NextSym -= SectionAddress;
378          break;
379        }
380        ++NextSymIdx;
381      }
382
383      uint64_t SectSize;
384      Sections[SectIdx].getSize(SectSize);
385      uint64_t End = containsNextSym ?  NextSym : SectSize;
386      uint64_t Size;
387
388      symbolTableWorked = true;
389
390      if (!CFG) {
391        // Normal disassembly, print addresses, bytes and mnemonic form.
392        StringRef SymName;
393        Symbols[SymIdx].getName(SymName);
394
395        outs() << SymName << ":\n";
396        DILineInfo lastLine;
397        for (uint64_t Index = Start; Index < End; Index += Size) {
398          MCInst Inst;
399
400          if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
401                                     DebugOut, nulls())) {
402            uint64_t SectAddress = 0;
403            Sections[SectIdx].getAddress(SectAddress);
404            outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
405
406            DumpBytes(StringRef(Bytes.data() + Index, Size));
407            IP->printInst(&Inst, outs(), "");
408
409            // Print debug info.
410            if (diContext) {
411              DILineInfo dli =
412                diContext->getLineInfoForAddress(SectAddress + Index);
413              // Print valid line info if it changed.
414              if (dli != lastLine && dli.getLine() != 0)
415                outs() << "\t## " << dli.getFileName() << ':'
416                       << dli.getLine() << ':' << dli.getColumn();
417              lastLine = dli;
418            }
419            outs() << "\n";
420          } else {
421            errs() << "llvm-objdump: warning: invalid instruction encoding\n";
422            if (Size == 0)
423              Size = 1; // skip illegible bytes
424          }
425        }
426      } else {
427        // Create CFG and use it for disassembly.
428        StringRef SymName;
429        Symbols[SymIdx].getName(SymName);
430        createMCFunctionAndSaveCalls(
431            SymName, DisAsm.get(), memoryObject, Start, End,
432            InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
433      }
434    }
435    if (!CFG && !symbolTableWorked) {
436      // Reading the symbol table didn't work, disassemble the whole section.
437      uint64_t SectAddress;
438      Sections[SectIdx].getAddress(SectAddress);
439      uint64_t SectSize;
440      Sections[SectIdx].getSize(SectSize);
441      uint64_t InstSize;
442      for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
443        MCInst Inst;
444
445        if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
446                                   DebugOut, nulls())) {
447          outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
448          DumpBytes(StringRef(Bytes.data() + Index, InstSize));
449          IP->printInst(&Inst, outs(), "");
450          outs() << "\n";
451        } else {
452          errs() << "llvm-objdump: warning: invalid instruction encoding\n";
453          if (InstSize == 0)
454            InstSize = 1; // skip illegible bytes
455        }
456      }
457    }
458
459    if (CFG) {
460      if (!symbolTableWorked) {
461        // Reading the symbol table didn't work, create a big __TEXT symbol.
462        uint64_t SectSize = 0, SectAddress = 0;
463        Sections[SectIdx].getSize(SectSize);
464        Sections[SectIdx].getAddress(SectAddress);
465        createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
466                                     0, SectSize,
467                                     InstrAnalysis.get(),
468                                     SectAddress, DebugOut,
469                                     FunctionMap, Functions);
470      }
471      for (std::map<uint64_t, MCFunction*>::iterator mi = FunctionMap.begin(),
472           me = FunctionMap.end(); mi != me; ++mi)
473        if (mi->second == 0) {
474          // Create functions for the remaining callees we have gathered,
475          // but we didn't find a name for them.
476          uint64_t SectSize = 0;
477          Sections[SectIdx].getSize(SectSize);
478
479          SmallVector<uint64_t, 16> Calls;
480          MCFunction f =
481            MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
482                                             memoryObject, mi->first,
483                                             SectSize,
484                                             InstrAnalysis.get(), DebugOut,
485                                             Calls);
486          Functions.push_back(f);
487          mi->second = &Functions.back();
488          for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
489            std::pair<uint64_t, MCFunction*> p(Calls[i], (MCFunction*)0);
490            if (FunctionMap.insert(p).second)
491              mi = FunctionMap.begin();
492          }
493        }
494
495      DenseSet<uint64_t> PrintedBlocks;
496      for (unsigned ffi = 0, ffe = Functions.size(); ffi != ffe; ++ffi) {
497        MCFunction &f = Functions[ffi];
498        for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
499          if (!PrintedBlocks.insert(fi->first).second)
500            continue; // We already printed this block.
501
502          // We assume a block has predecessors when it's the first block after
503          // a symbol.
504          bool hasPreds = FunctionMap.find(fi->first) != FunctionMap.end();
505
506          // See if this block has predecessors.
507          // FIXME: Slow.
508          for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
509              ++pi)
510            if (pi->second.contains(fi->first)) {
511              hasPreds = true;
512              break;
513            }
514
515          uint64_t SectSize = 0, SectAddress;
516          Sections[SectIdx].getSize(SectSize);
517          Sections[SectIdx].getAddress(SectAddress);
518
519          // No predecessors, this is a data block. Print as .byte directives.
520          if (!hasPreds) {
521            uint64_t End = llvm::next(fi) == fe ? SectSize :
522                                                  llvm::next(fi)->first;
523            outs() << "# " << End-fi->first << " bytes of data:\n";
524            for (unsigned pos = fi->first; pos != End; ++pos) {
525              outs() << format("%8x:\t", SectAddress + pos);
526              DumpBytes(StringRef(Bytes.data() + pos, 1));
527              outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
528            }
529            continue;
530          }
531
532          if (fi->second.contains(fi->first)) // Print a header for simple loops
533            outs() << "# Loop begin:\n";
534
535          DILineInfo lastLine;
536          // Walk over the instructions and print them.
537          for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
538               ++ii) {
539            const MCDecodedInst &Inst = fi->second.getInsts()[ii];
540
541            // If there's a symbol at this address, print its name.
542            if (FunctionMap.find(SectAddress + Inst.Address) !=
543                FunctionMap.end())
544              outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
545                     << ":\n";
546
547            outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address);
548            DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
549
550            if (fi->second.contains(fi->first)) // Indent simple loops.
551              outs() << '\t';
552
553            IP->printInst(&Inst.Inst, outs(), "");
554
555            // Look for relocations inside this instructions, if there is one
556            // print its target and additional information if available.
557            for (unsigned j = 0; j != Relocs.size(); ++j)
558              if (Relocs[j].first >= SectAddress + Inst.Address &&
559                  Relocs[j].first < SectAddress + Inst.Address + Inst.Size) {
560                StringRef SymName;
561                uint64_t Addr;
562                Relocs[j].second.getAddress(Addr);
563                Relocs[j].second.getName(SymName);
564
565                outs() << "\t# " << SymName << ' ';
566                DumpAddress(Addr, Sections, MachOOF.get(), outs());
567              }
568
569            // If this instructions contains an address, see if we can evaluate
570            // it and print additional information.
571            uint64_t targ = InstrAnalysis->evaluateBranch(Inst.Inst,
572                                                          Inst.Address,
573                                                          Inst.Size);
574            if (targ != -1ULL)
575              DumpAddress(targ, Sections, MachOOF.get(), outs());
576
577            // Print debug info.
578            if (diContext) {
579              DILineInfo dli =
580                diContext->getLineInfoForAddress(SectAddress + Inst.Address);
581              // Print valid line info if it changed.
582              if (dli != lastLine && dli.getLine() != 0)
583                outs() << "\t## " << dli.getFileName() << ':'
584                       << dli.getLine() << ':' << dli.getColumn();
585              lastLine = dli;
586            }
587
588            outs() << '\n';
589          }
590        }
591
592        emitDOTFile((f.getName().str() + ".dot").c_str(), f, IP.get());
593      }
594    }
595  }
596}
597