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