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