Move everything depending on Object/MachOFormat.h over to Support/MachO.h.
[oota-llvm.git] / tools / llvm-objdump / MachODump.cpp
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 "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.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"
41 #include <algorithm>
42 #include <cstring>
43 using namespace llvm;
44 using namespace object;
45
46 static cl::opt<bool>
47   UseDbg("g", cl::desc("Print line information from debug info if available"));
48
49 static cl::opt<std::string>
50   DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
51
52 static const Target *GetTarget(const MachOObjectFile *MachOObj) {
53   // Figure out the target triple.
54   if (TripleName.empty()) {
55     llvm::Triple TT("unknown-unknown-unknown");
56     TT.setArch(Triple::ArchType(MachOObj->getArch()));
57     TripleName = TT.str();
58   }
59
60   // Get the target specific parser.
61   std::string Error;
62   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
63   if (TheTarget)
64     return TheTarget;
65
66   errs() << "llvm-objdump: error: unable to get target for '" << TripleName
67          << "', see --version and --triple.\n";
68   return 0;
69 }
70
71 struct SymbolSorter {
72   bool operator()(const SymbolRef &A, const SymbolRef &B) {
73     SymbolRef::Type AType, BType;
74     A.getType(AType);
75     B.getType(BType);
76
77     uint64_t AAddr, BAddr;
78     if (AType != SymbolRef::ST_Function)
79       AAddr = 0;
80     else
81       A.getAddress(AAddr);
82     if (BType != SymbolRef::ST_Function)
83       BAddr = 0;
84     else
85       B.getAddress(BAddr);
86     return AAddr < BAddr;
87   }
88 };
89
90 // Types for the storted data in code table that is built before disassembly
91 // and the predicate function to sort them.
92 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
93 typedef std::vector<DiceTableEntry> DiceTable;
94 typedef DiceTable::iterator dice_table_iterator;
95
96 static bool
97 compareDiceTableEntries(const DiceTableEntry i,
98                         const DiceTableEntry j) {
99   return i.first == j.first;
100 }
101
102 static void DumpDataInCode(const char *bytes, uint64_t Size,
103                            unsigned short Kind) {
104   uint64_t Value;
105
106   switch (Kind) {
107   case MachO::DICE_KIND_DATA:
108     switch (Size) {
109     case 4:
110       Value = bytes[3] << 24 |
111               bytes[2] << 16 |
112               bytes[1] << 8 |
113               bytes[0];
114       outs() << "\t.long " << Value;
115       break;
116     case 2:
117       Value = bytes[1] << 8 |
118               bytes[0];
119       outs() << "\t.short " << Value;
120       break;
121     case 1:
122       Value = bytes[0];
123       outs() << "\t.byte " << Value;
124       break;
125     }
126     outs() << "\t@ KIND_DATA\n";
127     break;
128   case MachO::DICE_KIND_JUMP_TABLE8:
129     Value = bytes[0];
130     outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
131     break;
132   case MachO::DICE_KIND_JUMP_TABLE16:
133     Value = bytes[1] << 8 |
134             bytes[0];
135     outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
136     break;
137   case MachO::DICE_KIND_JUMP_TABLE32:
138     Value = bytes[3] << 24 |
139             bytes[2] << 16 |
140             bytes[1] << 8 |
141             bytes[0];
142     outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
143     break;
144   default:
145     outs() << "\t@ data in code kind = " << Kind << "\n";
146     break;
147   }
148 }
149
150 static void
151 getSectionsAndSymbols(const MachO::mach_header Header,
152                       MachOObjectFile *MachOObj,
153                       std::vector<SectionRef> &Sections,
154                       std::vector<SymbolRef> &Symbols,
155                       SmallVectorImpl<uint64_t> &FoundFns,
156                       uint64_t &BaseSegmentAddress) {
157   error_code ec;
158   for (symbol_iterator SI = MachOObj->begin_symbols(),
159        SE = MachOObj->end_symbols(); SI != SE; SI.increment(ec))
160     Symbols.push_back(*SI);
161
162   for (section_iterator SI = MachOObj->begin_sections(),
163        SE = MachOObj->end_sections(); SI != SE; SI.increment(ec)) {
164     SectionRef SR = *SI;
165     StringRef SectName;
166     SR.getName(SectName);
167     Sections.push_back(*SI);
168   }
169
170   MachOObjectFile::LoadCommandInfo Command =
171     MachOObj->getFirstLoadCommandInfo();
172   bool BaseSegmentAddressSet = false;
173   for (unsigned i = 0; ; ++i) {
174     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
175       // We found a function starts segment, parse the addresses for later
176       // consumption.
177       MachO::linkedit_data_command LLC =
178         MachOObj->getLinkeditDataLoadCommand(Command);
179
180       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
181     }
182     else if (Command.C.cmd == MachO::LC_SEGMENT ||
183              Command.C.cmd == MachO::LC_SEGMENT_64) {
184       MachO::segment_command SLC =
185         MachOObj->getSegmentLoadCommand(Command);
186       StringRef SegName = SLC.segname;
187       if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
188         BaseSegmentAddressSet = true;
189         BaseSegmentAddress = SLC.vmaddr;
190       }
191     }
192
193     if (i == Header.ncmds - 1)
194       break;
195     else
196       Command = MachOObj->getNextLoadCommandInfo(Command);
197   }
198 }
199
200 static void DisassembleInputMachO2(StringRef Filename,
201                                    MachOObjectFile *MachOOF);
202
203 void llvm::DisassembleInputMachO(StringRef Filename) {
204   OwningPtr<MemoryBuffer> Buff;
205
206   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
207     errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
208     return;
209   }
210
211   OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
212         ObjectFile::createMachOObjectFile(Buff.take())));
213
214   DisassembleInputMachO2(Filename, MachOOF.get());
215 }
216
217 static void DisassembleInputMachO2(StringRef Filename,
218                                    MachOObjectFile *MachOOF) {
219   const Target *TheTarget = GetTarget(MachOOF);
220   if (!TheTarget) {
221     // GetTarget prints out stuff.
222     return;
223   }
224   OwningPtr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
225   OwningPtr<MCInstrAnalysis>
226     InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo.get()));
227
228   // Set up disassembler.
229   OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
230   OwningPtr<const MCAsmInfo> AsmInfo(
231       TheTarget->createMCAsmInfo(*MRI, TripleName));
232   OwningPtr<const MCSubtargetInfo>
233     STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
234   OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
235   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
236   OwningPtr<MCInstPrinter>
237     IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrInfo,
238                                       *MRI, *STI));
239
240   if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
241     errs() << "error: couldn't initialize disassembler for target "
242            << TripleName << '\n';
243     return;
244   }
245
246   outs() << '\n' << Filename << ":\n\n";
247
248   MachO::mach_header Header = MachOOF->getHeader();
249
250   // FIXME: FoundFns isn't used anymore. Using symbols/LC_FUNCTION_STARTS to
251   // determine function locations will eventually go in MCObjectDisassembler.
252   // FIXME: Using the -cfg command line option, this code used to be able to
253   // annotate relocations with the referenced symbol's name, and if this was
254   // inside a __[cf]string section, the data it points to. This is now replaced
255   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
256   std::vector<SectionRef> Sections;
257   std::vector<SymbolRef> Symbols;
258   SmallVector<uint64_t, 8> FoundFns;
259   uint64_t BaseSegmentAddress;
260
261   getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
262                         BaseSegmentAddress);
263
264   // Make a copy of the unsorted symbol list. FIXME: duplication
265   std::vector<SymbolRef> UnsortedSymbols(Symbols);
266   // Sort the symbols by address, just in case they didn't come in that way.
267   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
268
269   // Build a data in code table that is sorted on by the address of each entry.
270   uint64_t BaseAddress = 0;
271   if (Header.filetype == MachO::MH_OBJECT)
272     Sections[0].getAddress(BaseAddress);
273   else
274     BaseAddress = BaseSegmentAddress;
275   DiceTable Dices;
276   error_code ec;
277   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
278        DI != DE; DI.increment(ec)){
279     uint32_t Offset;
280     DI->getOffset(Offset);
281     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
282   }
283   array_pod_sort(Dices.begin(), Dices.end());
284
285 #ifndef NDEBUG
286   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
287 #else
288   raw_ostream &DebugOut = nulls();
289 #endif
290
291   OwningPtr<DIContext> diContext;
292   ObjectFile *DbgObj = MachOOF;
293   // Try to find debug info and set up the DIContext for it.
294   if (UseDbg) {
295     // A separate DSym file path was specified, parse it as a macho file,
296     // get the sections and supply it to the section name parsing machinery.
297     if (!DSYMFile.empty()) {
298       OwningPtr<MemoryBuffer> Buf;
299       if (error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile, Buf)) {
300         errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
301         return;
302       }
303       DbgObj = ObjectFile::createMachOObjectFile(Buf.take());
304     }
305
306     // Setup the DIContext
307     diContext.reset(DIContext::getDWARFContext(DbgObj));
308   }
309
310   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
311
312     bool SectIsText = false;
313     Sections[SectIdx].isText(SectIsText);
314     if (SectIsText == false)
315       continue;
316
317     StringRef SectName;
318     if (Sections[SectIdx].getName(SectName) ||
319         SectName != "__text")
320       continue; // Skip non-text sections
321
322     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
323
324     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
325     if (SegmentName != "__TEXT")
326       continue;
327
328     StringRef Bytes;
329     Sections[SectIdx].getContents(Bytes);
330     StringRefMemoryObject memoryObject(Bytes);
331     bool symbolTableWorked = false;
332
333     // Parse relocations.
334     std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
335     error_code ec;
336     for (relocation_iterator RI = Sections[SectIdx].begin_relocations(),
337          RE = Sections[SectIdx].end_relocations(); RI != RE; RI.increment(ec)) {
338       uint64_t RelocOffset, SectionAddress;
339       RI->getOffset(RelocOffset);
340       Sections[SectIdx].getAddress(SectionAddress);
341       RelocOffset -= SectionAddress;
342
343       symbol_iterator RelocSym = RI->getSymbol();
344
345       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
346     }
347     array_pod_sort(Relocs.begin(), Relocs.end());
348
349     // Disassemble symbol by symbol.
350     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
351       StringRef SymName;
352       Symbols[SymIdx].getName(SymName);
353
354       SymbolRef::Type ST;
355       Symbols[SymIdx].getType(ST);
356       if (ST != SymbolRef::ST_Function)
357         continue;
358
359       // Make sure the symbol is defined in this section.
360       bool containsSym = false;
361       Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
362       if (!containsSym)
363         continue;
364
365       // Start at the address of the symbol relative to the section's address.
366       uint64_t SectionAddress = 0;
367       uint64_t Start = 0;
368       Sections[SectIdx].getAddress(SectionAddress);
369       Symbols[SymIdx].getAddress(Start);
370       Start -= SectionAddress;
371
372       // Stop disassembling either at the beginning of the next symbol or at
373       // the end of the section.
374       bool containsNextSym = false;
375       uint64_t NextSym = 0;
376       uint64_t NextSymIdx = SymIdx+1;
377       while (Symbols.size() > NextSymIdx) {
378         SymbolRef::Type NextSymType;
379         Symbols[NextSymIdx].getType(NextSymType);
380         if (NextSymType == SymbolRef::ST_Function) {
381           Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
382                                            containsNextSym);
383           Symbols[NextSymIdx].getAddress(NextSym);
384           NextSym -= SectionAddress;
385           break;
386         }
387         ++NextSymIdx;
388       }
389
390       uint64_t SectSize;
391       Sections[SectIdx].getSize(SectSize);
392       uint64_t End = containsNextSym ?  NextSym : SectSize;
393       uint64_t Size;
394
395       symbolTableWorked = true;
396
397       outs() << SymName << ":\n";
398       DILineInfo lastLine;
399       for (uint64_t Index = Start; Index < End; Index += Size) {
400         MCInst Inst;
401
402         uint64_t SectAddress = 0;
403         Sections[SectIdx].getAddress(SectAddress);
404         outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
405
406         // Check the data in code table here to see if this is data not an
407         // instruction to be disassembled.
408         DiceTable Dice;
409         Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
410         dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
411                                               Dice.begin(), Dice.end(),
412                                               compareDiceTableEntries);
413         if (DTI != Dices.end()){
414           uint16_t Length;
415           DTI->second.getLength(Length);
416           DumpBytes(StringRef(Bytes.data() + Index, Length));
417           uint16_t Kind;
418           DTI->second.getKind(Kind);
419           DumpDataInCode(Bytes.data() + Index, Length, Kind);
420           continue;
421         }
422
423         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
424                                    DebugOut, nulls())) {
425           DumpBytes(StringRef(Bytes.data() + Index, Size));
426           IP->printInst(&Inst, outs(), "");
427
428           // Print debug info.
429           if (diContext) {
430             DILineInfo dli =
431               diContext->getLineInfoForAddress(SectAddress + Index);
432             // Print valid line info if it changed.
433             if (dli != lastLine && dli.getLine() != 0)
434               outs() << "\t## " << dli.getFileName() << ':'
435                 << dli.getLine() << ':' << dli.getColumn();
436             lastLine = dli;
437           }
438           outs() << "\n";
439         } else {
440           errs() << "llvm-objdump: warning: invalid instruction encoding\n";
441           if (Size == 0)
442             Size = 1; // skip illegible bytes
443         }
444       }
445     }
446     if (!symbolTableWorked) {
447       // Reading the symbol table didn't work, disassemble the whole section. 
448       uint64_t SectAddress;
449       Sections[SectIdx].getAddress(SectAddress);
450       uint64_t SectSize;
451       Sections[SectIdx].getSize(SectSize);
452       uint64_t InstSize;
453       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
454         MCInst Inst;
455
456         if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
457                                    DebugOut, nulls())) {
458           outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
459           DumpBytes(StringRef(Bytes.data() + Index, InstSize));
460           IP->printInst(&Inst, outs(), "");
461           outs() << "\n";
462         } else {
463           errs() << "llvm-objdump: warning: invalid instruction encoding\n";
464           if (InstSize == 0)
465             InstSize = 1; // skip illegible bytes
466         }
467       }
468     }
469   }
470 }