Remove all uses of 'using std::error_code' from headers.
[oota-llvm.git] / tools / llvm-objdump / COFFDump.cpp
1 //===-- COFFDump.cpp - COFF-specific dumper ---------------------*- C++ -*-===//
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 /// \file
11 /// \brief This file implements the COFF-specific dumper for llvm-objdump.
12 /// It outputs the Win64 EH data structures as plain text.
13 /// The encoding of the unwind codes is described in MSDN:
14 /// http://msdn.microsoft.com/en-us/library/ck9asaa9.aspx
15 ///
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm-objdump.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/Win64EH.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <cstring>
27 #include <system_error>
28
29 using namespace llvm;
30 using namespace object;
31 using namespace llvm::Win64EH;
32 using std::error_code;
33
34 // Returns the name of the unwind code.
35 static StringRef getUnwindCodeTypeName(uint8_t Code) {
36   switch(Code) {
37   default: llvm_unreachable("Invalid unwind code");
38   case UOP_PushNonVol: return "UOP_PushNonVol";
39   case UOP_AllocLarge: return "UOP_AllocLarge";
40   case UOP_AllocSmall: return "UOP_AllocSmall";
41   case UOP_SetFPReg: return "UOP_SetFPReg";
42   case UOP_SaveNonVol: return "UOP_SaveNonVol";
43   case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
44   case UOP_SaveXMM128: return "UOP_SaveXMM128";
45   case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
46   case UOP_PushMachFrame: return "UOP_PushMachFrame";
47   }
48 }
49
50 // Returns the name of a referenced register.
51 static StringRef getUnwindRegisterName(uint8_t Reg) {
52   switch(Reg) {
53   default: llvm_unreachable("Invalid register");
54   case 0: return "RAX";
55   case 1: return "RCX";
56   case 2: return "RDX";
57   case 3: return "RBX";
58   case 4: return "RSP";
59   case 5: return "RBP";
60   case 6: return "RSI";
61   case 7: return "RDI";
62   case 8: return "R8";
63   case 9: return "R9";
64   case 10: return "R10";
65   case 11: return "R11";
66   case 12: return "R12";
67   case 13: return "R13";
68   case 14: return "R14";
69   case 15: return "R15";
70   }
71 }
72
73 // Calculates the number of array slots required for the unwind code.
74 static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
75   switch (UnwindCode.getUnwindOp()) {
76   default: llvm_unreachable("Invalid unwind code");
77   case UOP_PushNonVol:
78   case UOP_AllocSmall:
79   case UOP_SetFPReg:
80   case UOP_PushMachFrame:
81     return 1;
82   case UOP_SaveNonVol:
83   case UOP_SaveXMM128:
84     return 2;
85   case UOP_SaveNonVolBig:
86   case UOP_SaveXMM128Big:
87     return 3;
88   case UOP_AllocLarge:
89     return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
90   }
91 }
92
93 // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
94 // the unwind codes array, this function requires that the correct number of
95 // slots is provided.
96 static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
97   assert(UCs.size() >= getNumUsedSlots(UCs[0]));
98   outs() <<  format("      0x%02x: ", unsigned(UCs[0].u.CodeOffset))
99          << getUnwindCodeTypeName(UCs[0].getUnwindOp());
100   switch (UCs[0].getUnwindOp()) {
101   case UOP_PushNonVol:
102     outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
103     break;
104   case UOP_AllocLarge:
105     if (UCs[0].getOpInfo() == 0) {
106       outs() << " " << UCs[1].FrameOffset;
107     } else {
108       outs() << " " << UCs[1].FrameOffset
109                        + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
110     }
111     break;
112   case UOP_AllocSmall:
113     outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
114     break;
115   case UOP_SetFPReg:
116     outs() << " ";
117     break;
118   case UOP_SaveNonVol:
119     outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
120            << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
121     break;
122   case UOP_SaveNonVolBig:
123     outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
124            << format(" [0x%08x]", UCs[1].FrameOffset
125                     + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
126     break;
127   case UOP_SaveXMM128:
128     outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
129            << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
130     break;
131   case UOP_SaveXMM128Big:
132     outs() << " XMM" << UCs[0].getOpInfo()
133            << format(" [0x%08x]", UCs[1].FrameOffset
134                            + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
135     break;
136   case UOP_PushMachFrame:
137     outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
138            << " error code";
139     break;
140   }
141   outs() << "\n";
142 }
143
144 static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
145   for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
146     unsigned UsedSlots = getNumUsedSlots(*I);
147     if (UsedSlots > UCs.size()) {
148       outs() << "Unwind data corrupted: Encountered unwind op "
149              << getUnwindCodeTypeName((*I).getUnwindOp())
150              << " which requires " << UsedSlots
151              << " slots, but only " << UCs.size()
152              << " remaining in buffer";
153       return ;
154     }
155     printUnwindCode(ArrayRef<UnwindCode>(I, E));
156     I += UsedSlots;
157   }
158 }
159
160 // Given a symbol sym this functions returns the address and section of it.
161 static error_code resolveSectionAndAddress(const COFFObjectFile *Obj,
162                                            const SymbolRef &Sym,
163                                            const coff_section *&ResolvedSection,
164                                            uint64_t &ResolvedAddr) {
165   if (error_code EC = Sym.getAddress(ResolvedAddr))
166     return EC;
167   section_iterator iter(Obj->section_begin());
168   if (error_code EC = Sym.getSection(iter))
169     return EC;
170   ResolvedSection = Obj->getCOFFSection(*iter);
171   return object_error::success;
172 }
173
174 // Given a vector of relocations for a section and an offset into this section
175 // the function returns the symbol used for the relocation at the offset.
176 static error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
177                                 uint64_t Offset, SymbolRef &Sym) {
178   for (std::vector<RelocationRef>::const_iterator I = Rels.begin(),
179                                                   E = Rels.end();
180                                                   I != E; ++I) {
181     uint64_t Ofs;
182     if (error_code EC = I->getOffset(Ofs))
183       return EC;
184     if (Ofs == Offset) {
185       Sym = *I->getSymbol();
186       return object_error::success;
187     }
188   }
189   return object_error::parse_failed;
190 }
191
192 // Given a vector of relocations for a section and an offset into this section
193 // the function resolves the symbol used for the relocation at the offset and
194 // returns the section content and the address inside the content pointed to
195 // by the symbol.
196 static error_code getSectionContents(const COFFObjectFile *Obj,
197                                      const std::vector<RelocationRef> &Rels,
198                                      uint64_t Offset,
199                                      ArrayRef<uint8_t> &Contents,
200                                      uint64_t &Addr) {
201   SymbolRef Sym;
202   if (error_code EC = resolveSymbol(Rels, Offset, Sym))
203     return EC;
204   const coff_section *Section;
205   if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
206     return EC;
207   if (error_code EC = Obj->getSectionContents(Section, Contents))
208     return EC;
209   return object_error::success;
210 }
211
212 // Given a vector of relocations for a section and an offset into this section
213 // the function returns the name of the symbol used for the relocation at the
214 // offset.
215 static error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
216                                     uint64_t Offset, StringRef &Name) {
217   SymbolRef Sym;
218   if (error_code EC = resolveSymbol(Rels, Offset, Sym))
219     return EC;
220   if (error_code EC = Sym.getName(Name))
221     return EC;
222   return object_error::success;
223 }
224
225 static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
226                                    const std::vector<RelocationRef> &Rels,
227                                    uint64_t Offset, uint32_t Disp) {
228   StringRef Sym;
229   if (!resolveSymbolName(Rels, Offset, Sym)) {
230     Out << Sym;
231     if (Disp > 0)
232       Out << format(" + 0x%04x", Disp);
233   } else {
234     Out << format("0x%04x", Disp);
235   }
236 }
237
238 static void
239 printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
240   if (Count == 0)
241     return;
242
243   const pe32_header *PE32Header;
244   if (error(Obj->getPE32Header(PE32Header)))
245     return;
246   uint32_t ImageBase = PE32Header->ImageBase;
247   uintptr_t IntPtr = 0;
248   if (error(Obj->getVaPtr(TableVA, IntPtr)))
249     return;
250   const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
251   outs() << "SEH Table:";
252   for (int I = 0; I < Count; ++I)
253     outs() << format(" 0x%x", P[I] + ImageBase);
254   outs() << "\n\n";
255 }
256
257 static void printLoadConfiguration(const COFFObjectFile *Obj) {
258   // Skip if it's not executable.
259   const pe32_header *PE32Header;
260   if (error(Obj->getPE32Header(PE32Header)))
261     return;
262   if (!PE32Header)
263     return;
264
265   const coff_file_header *Header;
266   if (error(Obj->getCOFFHeader(Header)))
267     return;
268   // Currently only x86 is supported
269   if (Header->Machine != COFF::IMAGE_FILE_MACHINE_I386)
270     return;
271
272   const data_directory *DataDir;
273   if (error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir)))
274     return;
275   uintptr_t IntPtr = 0;
276   if (DataDir->RelativeVirtualAddress == 0)
277     return;
278   if (error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr)))
279     return;
280
281   auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
282   outs() << "Load configuration:"
283          << "\n  Timestamp: " << LoadConf->TimeDateStamp
284          << "\n  Major Version: " << LoadConf->MajorVersion
285          << "\n  Minor Version: " << LoadConf->MinorVersion
286          << "\n  GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
287          << "\n  GlobalFlags Set: " << LoadConf->GlobalFlagsSet
288          << "\n  Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
289          << "\n  Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
290          << "\n  Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
291          << "\n  Lock Prefix Table: " << LoadConf->LockPrefixTable
292          << "\n  Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
293          << "\n  Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
294          << "\n  Process Affinity Mask: " << LoadConf->ProcessAffinityMask
295          << "\n  Process Heap Flags: " << LoadConf->ProcessHeapFlags
296          << "\n  CSD Version: " << LoadConf->CSDVersion
297          << "\n  Security Cookie: " << LoadConf->SecurityCookie
298          << "\n  SEH Table: " << LoadConf->SEHandlerTable
299          << "\n  SEH Count: " << LoadConf->SEHandlerCount
300          << "\n\n";
301   printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
302   outs() << "\n";
303 }
304
305 // Prints import tables. The import table is a table containing the list of
306 // DLL name and symbol names which will be linked by the loader.
307 static void printImportTables(const COFFObjectFile *Obj) {
308   import_directory_iterator I = Obj->import_directory_begin();
309   import_directory_iterator E = Obj->import_directory_end();
310   if (I == E)
311     return;
312   outs() << "The Import Tables:\n";
313   for (; I != E; I = ++I) {
314     const import_directory_table_entry *Dir;
315     StringRef Name;
316     if (I->getImportTableEntry(Dir)) return;
317     if (I->getName(Name)) return;
318
319     outs() << format("  lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
320                      static_cast<uint32_t>(Dir->ImportLookupTableRVA),
321                      static_cast<uint32_t>(Dir->TimeDateStamp),
322                      static_cast<uint32_t>(Dir->ForwarderChain),
323                      static_cast<uint32_t>(Dir->NameRVA),
324                      static_cast<uint32_t>(Dir->ImportAddressTableRVA));
325     outs() << "    DLL Name: " << Name << "\n";
326     outs() << "    Hint/Ord  Name\n";
327     const import_lookup_table_entry32 *entry;
328     if (I->getImportLookupEntry(entry))
329       return;
330     for (; entry->data; ++entry) {
331       if (entry->isOrdinal()) {
332         outs() << format("      % 6d\n", entry->getOrdinal());
333         continue;
334       }
335       uint16_t Hint;
336       StringRef Name;
337       if (Obj->getHintName(entry->getHintNameRVA(), Hint, Name))
338         return;
339       outs() << format("      % 6d  ", Hint) << Name << "\n";
340     }
341     outs() << "\n";
342   }
343 }
344
345 // Prints export tables. The export table is a table containing the list of
346 // exported symbol from the DLL.
347 static void printExportTable(const COFFObjectFile *Obj) {
348   outs() << "Export Table:\n";
349   export_directory_iterator I = Obj->export_directory_begin();
350   export_directory_iterator E = Obj->export_directory_end();
351   if (I == E)
352     return;
353   StringRef DllName;
354   uint32_t OrdinalBase;
355   if (I->getDllName(DllName))
356     return;
357   if (I->getOrdinalBase(OrdinalBase))
358     return;
359   outs() << " DLL name: " << DllName << "\n";
360   outs() << " Ordinal base: " << OrdinalBase << "\n";
361   outs() << " Ordinal      RVA  Name\n";
362   for (; I != E; I = ++I) {
363     uint32_t Ordinal;
364     if (I->getOrdinal(Ordinal))
365       return;
366     uint32_t RVA;
367     if (I->getExportRVA(RVA))
368       return;
369     outs() << format("    % 4d %# 8x", Ordinal, RVA);
370
371     StringRef Name;
372     if (I->getSymbolName(Name))
373       continue;
374     if (!Name.empty())
375       outs() << "  " << Name;
376     outs() << "\n";
377   }
378 }
379
380 // Given the COFF object file, this function returns the relocations for .pdata
381 // and the pointer to "runtime function" structs.
382 static bool getPDataSection(const COFFObjectFile *Obj,
383                             std::vector<RelocationRef> &Rels,
384                             const RuntimeFunction *&RFStart, int &NumRFs) {
385   for (const SectionRef &Section : Obj->sections()) {
386     StringRef Name;
387     if (error(Section.getName(Name)))
388       continue;
389     if (Name != ".pdata")
390       continue;
391
392     const coff_section *Pdata = Obj->getCOFFSection(Section);
393     for (const RelocationRef &Reloc : Section.relocations())
394       Rels.push_back(Reloc);
395
396     // Sort relocations by address.
397     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
398
399     ArrayRef<uint8_t> Contents;
400     if (error(Obj->getSectionContents(Pdata, Contents)))
401       continue;
402     if (Contents.empty())
403       continue;
404
405     RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
406     NumRFs = Contents.size() / sizeof(RuntimeFunction);
407     return true;
408   }
409   return false;
410 }
411
412 static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
413   // The casts to int are required in order to output the value as number.
414   // Without the casts the value would be interpreted as char data (which
415   // results in garbage output).
416   outs() << "    Version: " << static_cast<int>(UI->getVersion()) << "\n";
417   outs() << "    Flags: " << static_cast<int>(UI->getFlags());
418   if (UI->getFlags()) {
419     if (UI->getFlags() & UNW_ExceptionHandler)
420       outs() << " UNW_ExceptionHandler";
421     if (UI->getFlags() & UNW_TerminateHandler)
422       outs() << " UNW_TerminateHandler";
423     if (UI->getFlags() & UNW_ChainInfo)
424       outs() << " UNW_ChainInfo";
425   }
426   outs() << "\n";
427   outs() << "    Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
428   outs() << "    Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
429   // Maybe this should move to output of UOP_SetFPReg?
430   if (UI->getFrameRegister()) {
431     outs() << "    Frame register: "
432            << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
433     outs() << "    Frame offset: " << 16 * UI->getFrameOffset() << "\n";
434   } else {
435     outs() << "    No frame pointer used\n";
436   }
437   if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
438     // FIXME: Output exception handler data
439   } else if (UI->getFlags() & UNW_ChainInfo) {
440     // FIXME: Output chained unwind info
441   }
442
443   if (UI->NumCodes)
444     outs() << "    Unwind Codes:\n";
445
446   printAllUnwindCodes(ArrayRef<UnwindCode>(&UI->UnwindCodes[0], UI->NumCodes));
447
448   outs() << "\n";
449   outs().flush();
450 }
451
452 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
453 /// pointing to an executable file.
454 static void printRuntimeFunction(const COFFObjectFile *Obj,
455                                  const RuntimeFunction &RF) {
456   if (!RF.StartAddress)
457     return;
458   outs() << "Function Table:\n"
459          << format("  Start Address: 0x%04x\n",
460                    static_cast<uint32_t>(RF.StartAddress))
461          << format("  End Address: 0x%04x\n",
462                    static_cast<uint32_t>(RF.EndAddress))
463          << format("  Unwind Info Address: 0x%04x\n",
464                    static_cast<uint32_t>(RF.UnwindInfoOffset));
465   uintptr_t addr;
466   if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
467     return;
468   printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
469 }
470
471 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
472 /// pointing to an object file. Unlike executable, fields in RuntimeFunction
473 /// struct are filled with zeros, but instead there are relocations pointing to
474 /// them so that the linker will fill targets' RVAs to the fields at link
475 /// time. This function interprets the relocations to find the data to be used
476 /// in the resulting executable.
477 static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
478                                      const RuntimeFunction &RF,
479                                      uint64_t SectionOffset,
480                                      const std::vector<RelocationRef> &Rels) {
481   outs() << "Function Table:\n";
482   outs() << "  Start Address: ";
483   printCOFFSymbolAddress(outs(), Rels,
484                          SectionOffset +
485                              /*offsetof(RuntimeFunction, StartAddress)*/ 0,
486                          RF.StartAddress);
487   outs() << "\n";
488
489   outs() << "  End Address: ";
490   printCOFFSymbolAddress(outs(), Rels,
491                          SectionOffset +
492                              /*offsetof(RuntimeFunction, EndAddress)*/ 4,
493                          RF.EndAddress);
494   outs() << "\n";
495
496   outs() << "  Unwind Info Address: ";
497   printCOFFSymbolAddress(outs(), Rels,
498                          SectionOffset +
499                              /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
500                          RF.UnwindInfoOffset);
501   outs() << "\n";
502
503   ArrayRef<uint8_t> XContents;
504   uint64_t UnwindInfoOffset = 0;
505   if (error(getSectionContents(
506           Obj, Rels, SectionOffset +
507                          /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
508           XContents, UnwindInfoOffset)))
509     return;
510   if (XContents.empty())
511     return;
512
513   UnwindInfoOffset += RF.UnwindInfoOffset;
514   if (UnwindInfoOffset > XContents.size())
515     return;
516
517   auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
518                                                            UnwindInfoOffset);
519   printWin64EHUnwindInfo(UI);
520 }
521
522 void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
523   const coff_file_header *Header;
524   if (error(Obj->getCOFFHeader(Header)))
525     return;
526
527   if (Header->Machine != COFF::IMAGE_FILE_MACHINE_AMD64) {
528     errs() << "Unsupported image machine type "
529               "(currently only AMD64 is supported).\n";
530     return;
531   }
532
533   std::vector<RelocationRef> Rels;
534   const RuntimeFunction *RFStart;
535   int NumRFs;
536   if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
537     return;
538   ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
539
540   bool IsExecutable = Rels.empty();
541   if (IsExecutable) {
542     for (const RuntimeFunction &RF : RFs)
543       printRuntimeFunction(Obj, RF);
544     return;
545   }
546
547   for (const RuntimeFunction &RF : RFs) {
548     uint64_t SectionOffset =
549         std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
550     printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
551   }
552 }
553
554 void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
555   const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
556   printLoadConfiguration(file);
557   printImportTables(file);
558   printExportTable(file);
559 }