1 //===-- COFFDump.cpp - COFF-specific dumper ---------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the COFF-specific dumper for llvm-objdump.
11 /// It outputs the Win64 EH data structures as plain text.
12 /// The encoding of the unwind codes is described in MSDN:
13 /// http://msdn.microsoft.com/en-us/library/ck9asaa9.aspx
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm-objdump.h"
18 #include "llvm/Demangle/Demangle.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/COFFImportFile.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/Win64EH.h"
24 #include "llvm/Support/WithColor.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 using namespace llvm::object;
28 using namespace llvm::Win64EH;
29 
30 namespace llvm {
31 // Returns the name of the unwind code.
32 static StringRef getUnwindCodeTypeName(uint8_t Code) {
33   switch(Code) {
34   default: llvm_unreachable("Invalid unwind code");
35   case UOP_PushNonVol: return "UOP_PushNonVol";
36   case UOP_AllocLarge: return "UOP_AllocLarge";
37   case UOP_AllocSmall: return "UOP_AllocSmall";
38   case UOP_SetFPReg: return "UOP_SetFPReg";
39   case UOP_SaveNonVol: return "UOP_SaveNonVol";
40   case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
41   case UOP_SaveXMM128: return "UOP_SaveXMM128";
42   case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
43   case UOP_PushMachFrame: return "UOP_PushMachFrame";
44   }
45 }
46 
47 // Returns the name of a referenced register.
48 static StringRef getUnwindRegisterName(uint8_t Reg) {
49   switch(Reg) {
50   default: llvm_unreachable("Invalid register");
51   case 0: return "RAX";
52   case 1: return "RCX";
53   case 2: return "RDX";
54   case 3: return "RBX";
55   case 4: return "RSP";
56   case 5: return "RBP";
57   case 6: return "RSI";
58   case 7: return "RDI";
59   case 8: return "R8";
60   case 9: return "R9";
61   case 10: return "R10";
62   case 11: return "R11";
63   case 12: return "R12";
64   case 13: return "R13";
65   case 14: return "R14";
66   case 15: return "R15";
67   }
68 }
69 
70 // Calculates the number of array slots required for the unwind code.
71 static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
72   switch (UnwindCode.getUnwindOp()) {
73   default: llvm_unreachable("Invalid unwind code");
74   case UOP_PushNonVol:
75   case UOP_AllocSmall:
76   case UOP_SetFPReg:
77   case UOP_PushMachFrame:
78     return 1;
79   case UOP_SaveNonVol:
80   case UOP_SaveXMM128:
81     return 2;
82   case UOP_SaveNonVolBig:
83   case UOP_SaveXMM128Big:
84     return 3;
85   case UOP_AllocLarge:
86     return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
87   }
88 }
89 
90 // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
91 // the unwind codes array, this function requires that the correct number of
92 // slots is provided.
93 static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
94   assert(UCs.size() >= getNumUsedSlots(UCs[0]));
95   outs() <<  format("      0x%02x: ", unsigned(UCs[0].u.CodeOffset))
96          << getUnwindCodeTypeName(UCs[0].getUnwindOp());
97   switch (UCs[0].getUnwindOp()) {
98   case UOP_PushNonVol:
99     outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
100     break;
101   case UOP_AllocLarge:
102     if (UCs[0].getOpInfo() == 0) {
103       outs() << " " << UCs[1].FrameOffset;
104     } else {
105       outs() << " " << UCs[1].FrameOffset
106                        + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
107     }
108     break;
109   case UOP_AllocSmall:
110     outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
111     break;
112   case UOP_SetFPReg:
113     outs() << " ";
114     break;
115   case UOP_SaveNonVol:
116     outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
117            << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
118     break;
119   case UOP_SaveNonVolBig:
120     outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
121            << format(" [0x%08x]", UCs[1].FrameOffset
122                     + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
123     break;
124   case UOP_SaveXMM128:
125     outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
126            << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
127     break;
128   case UOP_SaveXMM128Big:
129     outs() << " XMM" << UCs[0].getOpInfo()
130            << format(" [0x%08x]", UCs[1].FrameOffset
131                            + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
132     break;
133   case UOP_PushMachFrame:
134     outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
135            << " error code";
136     break;
137   }
138   outs() << "\n";
139 }
140 
141 static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
142   for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
143     unsigned UsedSlots = getNumUsedSlots(*I);
144     if (UsedSlots > UCs.size()) {
145       outs() << "Unwind data corrupted: Encountered unwind op "
146              << getUnwindCodeTypeName((*I).getUnwindOp())
147              << " which requires " << UsedSlots
148              << " slots, but only " << UCs.size()
149              << " remaining in buffer";
150       return ;
151     }
152     printUnwindCode(makeArrayRef(I, E));
153     I += UsedSlots;
154   }
155 }
156 
157 // Given a symbol sym this functions returns the address and section of it.
158 static Error resolveSectionAndAddress(const COFFObjectFile *Obj,
159                                       const SymbolRef &Sym,
160                                       const coff_section *&ResolvedSection,
161                                       uint64_t &ResolvedAddr) {
162   Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
163   if (!ResolvedAddrOrErr)
164     return ResolvedAddrOrErr.takeError();
165   ResolvedAddr = *ResolvedAddrOrErr;
166   Expected<section_iterator> Iter = Sym.getSection();
167   if (!Iter)
168     return Iter.takeError();
169   ResolvedSection = Obj->getCOFFSection(**Iter);
170   return Error::success();
171 }
172 
173 // Given a vector of relocations for a section and an offset into this section
174 // the function returns the symbol used for the relocation at the offset.
175 static Error resolveSymbol(const std::vector<RelocationRef> &Rels,
176                                      uint64_t Offset, SymbolRef &Sym) {
177   for (auto &R : Rels) {
178     uint64_t Ofs = R.getOffset();
179     if (Ofs == Offset) {
180       Sym = *R.getSymbol();
181       return Error::success();
182     }
183   }
184   return make_error<BinaryError>();
185 }
186 
187 // Given a vector of relocations for a section and an offset into this section
188 // the function resolves the symbol used for the relocation at the offset and
189 // returns the section content and the address inside the content pointed to
190 // by the symbol.
191 static Error
192 getSectionContents(const COFFObjectFile *Obj,
193                    const std::vector<RelocationRef> &Rels, uint64_t Offset,
194                    ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
195   SymbolRef Sym;
196   if (Error E = resolveSymbol(Rels, Offset, Sym))
197     return E;
198   const coff_section *Section;
199   if (Error E = resolveSectionAndAddress(Obj, Sym, Section, Addr))
200     return E;
201   return Obj->getSectionContents(Section, Contents);
202 }
203 
204 // Given a vector of relocations for a section and an offset into this section
205 // the function returns the name of the symbol used for the relocation at the
206 // offset.
207 static Error resolveSymbolName(const std::vector<RelocationRef> &Rels,
208                                uint64_t Offset, StringRef &Name) {
209   SymbolRef Sym;
210   if (Error EC = resolveSymbol(Rels, Offset, Sym))
211     return EC;
212   Expected<StringRef> NameOrErr = Sym.getName();
213   if (!NameOrErr)
214     return NameOrErr.takeError();
215   Name = *NameOrErr;
216   return Error::success();
217 }
218 
219 static void printCOFFSymbolAddress(raw_ostream &Out,
220                                    const std::vector<RelocationRef> &Rels,
221                                    uint64_t Offset, uint32_t Disp) {
222   StringRef Sym;
223   if (!resolveSymbolName(Rels, Offset, Sym)) {
224     Out << Sym;
225     if (Disp > 0)
226       Out << format(" + 0x%04x", Disp);
227   } else {
228     Out << format("0x%04x", Disp);
229   }
230 }
231 
232 static void
233 printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
234   if (Count == 0)
235     return;
236 
237   uint32_t ImageBase = Obj->getPE32Header()->ImageBase;
238   uintptr_t IntPtr = 0;
239   error(Obj->getVaPtr(TableVA, IntPtr));
240   const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
241   outs() << "SEH Table:";
242   for (int I = 0; I < Count; ++I)
243     outs() << format(" 0x%x", P[I] + ImageBase);
244   outs() << "\n\n";
245 }
246 
247 template <typename T>
248 static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
249   size_t FormatWidth = sizeof(T) * 2;
250   outs() << "TLS directory:"
251          << "\n  StartAddressOfRawData: "
252          << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
253          << "\n  EndAddressOfRawData: "
254          << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
255          << "\n  AddressOfIndex: "
256          << format_hex(TLSDir->AddressOfIndex, FormatWidth)
257          << "\n  AddressOfCallBacks: "
258          << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
259          << "\n  SizeOfZeroFill: "
260          << TLSDir->SizeOfZeroFill
261          << "\n  Characteristics: "
262          << TLSDir->Characteristics
263          << "\n  Alignment: "
264          << TLSDir->getAlignment()
265          << "\n\n";
266 }
267 
268 static void printTLSDirectory(const COFFObjectFile *Obj) {
269   const pe32_header *PE32Header = Obj->getPE32Header();
270   const pe32plus_header *PE32PlusHeader = Obj->getPE32PlusHeader();
271 
272   // Skip if it's not executable.
273   if (!PE32Header && !PE32PlusHeader)
274     return;
275 
276   const data_directory *DataDir;
277   error(Obj->getDataDirectory(COFF::TLS_TABLE, DataDir));
278   uintptr_t IntPtr = 0;
279   if (DataDir->RelativeVirtualAddress == 0)
280     return;
281   error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
282 
283   if (PE32Header) {
284     auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
285     printTLSDirectoryT(TLSDir);
286   } else {
287     auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
288     printTLSDirectoryT(TLSDir);
289   }
290 
291   outs() << "\n";
292 }
293 
294 static void printLoadConfiguration(const COFFObjectFile *Obj) {
295   // Skip if it's not executable.
296   if (!Obj->getPE32Header())
297     return;
298 
299   // Currently only x86 is supported
300   if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
301     return;
302 
303   const data_directory *DataDir;
304   error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
305   uintptr_t IntPtr = 0;
306   if (DataDir->RelativeVirtualAddress == 0)
307     return;
308   error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
309 
310   auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
311   outs() << "Load configuration:"
312          << "\n  Timestamp: " << LoadConf->TimeDateStamp
313          << "\n  Major Version: " << LoadConf->MajorVersion
314          << "\n  Minor Version: " << LoadConf->MinorVersion
315          << "\n  GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
316          << "\n  GlobalFlags Set: " << LoadConf->GlobalFlagsSet
317          << "\n  Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
318          << "\n  Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
319          << "\n  Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
320          << "\n  Lock Prefix Table: " << LoadConf->LockPrefixTable
321          << "\n  Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
322          << "\n  Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
323          << "\n  Process Affinity Mask: " << LoadConf->ProcessAffinityMask
324          << "\n  Process Heap Flags: " << LoadConf->ProcessHeapFlags
325          << "\n  CSD Version: " << LoadConf->CSDVersion
326          << "\n  Security Cookie: " << LoadConf->SecurityCookie
327          << "\n  SEH Table: " << LoadConf->SEHandlerTable
328          << "\n  SEH Count: " << LoadConf->SEHandlerCount
329          << "\n\n";
330   printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
331   outs() << "\n";
332 }
333 
334 // Prints import tables. The import table is a table containing the list of
335 // DLL name and symbol names which will be linked by the loader.
336 static void printImportTables(const COFFObjectFile *Obj) {
337   import_directory_iterator I = Obj->import_directory_begin();
338   import_directory_iterator E = Obj->import_directory_end();
339   if (I == E)
340     return;
341   outs() << "The Import Tables:\n";
342   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
343     const coff_import_directory_table_entry *Dir;
344     StringRef Name;
345     if (DirRef.getImportTableEntry(Dir)) return;
346     if (DirRef.getName(Name)) return;
347 
348     outs() << format("  lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
349                      static_cast<uint32_t>(Dir->ImportLookupTableRVA),
350                      static_cast<uint32_t>(Dir->TimeDateStamp),
351                      static_cast<uint32_t>(Dir->ForwarderChain),
352                      static_cast<uint32_t>(Dir->NameRVA),
353                      static_cast<uint32_t>(Dir->ImportAddressTableRVA));
354     outs() << "    DLL Name: " << Name << "\n";
355     outs() << "    Hint/Ord  Name\n";
356     for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
357       bool IsOrdinal;
358       if (Entry.isOrdinal(IsOrdinal))
359         return;
360       if (IsOrdinal) {
361         uint16_t Ordinal;
362         if (Entry.getOrdinal(Ordinal))
363           return;
364         outs() << format("      % 6d\n", Ordinal);
365         continue;
366       }
367       uint32_t HintNameRVA;
368       if (Entry.getHintNameRVA(HintNameRVA))
369         return;
370       uint16_t Hint;
371       StringRef Name;
372       if (Obj->getHintName(HintNameRVA, Hint, Name))
373         return;
374       outs() << format("      % 6d  ", Hint) << Name << "\n";
375     }
376     outs() << "\n";
377   }
378 }
379 
380 // Prints export tables. The export table is a table containing the list of
381 // exported symbol from the DLL.
382 static void printExportTable(const COFFObjectFile *Obj) {
383   outs() << "Export Table:\n";
384   export_directory_iterator I = Obj->export_directory_begin();
385   export_directory_iterator E = Obj->export_directory_end();
386   if (I == E)
387     return;
388   StringRef DllName;
389   uint32_t OrdinalBase;
390   if (I->getDllName(DllName))
391     return;
392   if (I->getOrdinalBase(OrdinalBase))
393     return;
394   outs() << " DLL name: " << DllName << "\n";
395   outs() << " Ordinal base: " << OrdinalBase << "\n";
396   outs() << " Ordinal      RVA  Name\n";
397   for (; I != E; I = ++I) {
398     uint32_t Ordinal;
399     if (I->getOrdinal(Ordinal))
400       return;
401     uint32_t RVA;
402     if (I->getExportRVA(RVA))
403       return;
404     bool IsForwarder;
405     if (I->isForwarder(IsForwarder))
406       return;
407 
408     if (IsForwarder) {
409       // Export table entries can be used to re-export symbols that
410       // this COFF file is imported from some DLLs. This is rare.
411       // In most cases IsForwarder is false.
412       outs() << format("    % 4d         ", Ordinal);
413     } else {
414       outs() << format("    % 4d %# 8x", Ordinal, RVA);
415     }
416 
417     StringRef Name;
418     if (I->getSymbolName(Name))
419       continue;
420     if (!Name.empty())
421       outs() << "  " << Name;
422     if (IsForwarder) {
423       StringRef S;
424       if (I->getForwardTo(S))
425         return;
426       outs() << " (forwarded to " << S << ")";
427     }
428     outs() << "\n";
429   }
430 }
431 
432 // Given the COFF object file, this function returns the relocations for .pdata
433 // and the pointer to "runtime function" structs.
434 static bool getPDataSection(const COFFObjectFile *Obj,
435                             std::vector<RelocationRef> &Rels,
436                             const RuntimeFunction *&RFStart, int &NumRFs) {
437   for (const SectionRef &Section : Obj->sections()) {
438     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
439     if (Name != ".pdata")
440       continue;
441 
442     const coff_section *Pdata = Obj->getCOFFSection(Section);
443     for (const RelocationRef &Reloc : Section.relocations())
444       Rels.push_back(Reloc);
445 
446     // Sort relocations by address.
447     llvm::sort(Rels, isRelocAddressLess);
448 
449     ArrayRef<uint8_t> Contents;
450     error(Obj->getSectionContents(Pdata, Contents));
451     if (Contents.empty())
452       continue;
453 
454     RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
455     NumRFs = Contents.size() / sizeof(RuntimeFunction);
456     return true;
457   }
458   return false;
459 }
460 
461 Error getCOFFRelocationValueString(const COFFObjectFile *Obj,
462                                          const RelocationRef &Rel,
463                                          SmallVectorImpl<char> &Result) {
464   symbol_iterator SymI = Rel.getSymbol();
465   Expected<StringRef> SymNameOrErr = SymI->getName();
466   if (!SymNameOrErr)
467     return SymNameOrErr.takeError();
468   StringRef SymName = *SymNameOrErr;
469   Result.append(SymName.begin(), SymName.end());
470   return Error::success();
471 }
472 
473 static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
474   // The casts to int are required in order to output the value as number.
475   // Without the casts the value would be interpreted as char data (which
476   // results in garbage output).
477   outs() << "    Version: " << static_cast<int>(UI->getVersion()) << "\n";
478   outs() << "    Flags: " << static_cast<int>(UI->getFlags());
479   if (UI->getFlags()) {
480     if (UI->getFlags() & UNW_ExceptionHandler)
481       outs() << " UNW_ExceptionHandler";
482     if (UI->getFlags() & UNW_TerminateHandler)
483       outs() << " UNW_TerminateHandler";
484     if (UI->getFlags() & UNW_ChainInfo)
485       outs() << " UNW_ChainInfo";
486   }
487   outs() << "\n";
488   outs() << "    Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
489   outs() << "    Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
490   // Maybe this should move to output of UOP_SetFPReg?
491   if (UI->getFrameRegister()) {
492     outs() << "    Frame register: "
493            << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
494     outs() << "    Frame offset: " << 16 * UI->getFrameOffset() << "\n";
495   } else {
496     outs() << "    No frame pointer used\n";
497   }
498   if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
499     // FIXME: Output exception handler data
500   } else if (UI->getFlags() & UNW_ChainInfo) {
501     // FIXME: Output chained unwind info
502   }
503 
504   if (UI->NumCodes)
505     outs() << "    Unwind Codes:\n";
506 
507   printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
508 
509   outs() << "\n";
510   outs().flush();
511 }
512 
513 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
514 /// pointing to an executable file.
515 static void printRuntimeFunction(const COFFObjectFile *Obj,
516                                  const RuntimeFunction &RF) {
517   if (!RF.StartAddress)
518     return;
519   outs() << "Function Table:\n"
520          << format("  Start Address: 0x%04x\n",
521                    static_cast<uint32_t>(RF.StartAddress))
522          << format("  End Address: 0x%04x\n",
523                    static_cast<uint32_t>(RF.EndAddress))
524          << format("  Unwind Info Address: 0x%04x\n",
525                    static_cast<uint32_t>(RF.UnwindInfoOffset));
526   uintptr_t addr;
527   if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
528     return;
529   printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
530 }
531 
532 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
533 /// pointing to an object file. Unlike executable, fields in RuntimeFunction
534 /// struct are filled with zeros, but instead there are relocations pointing to
535 /// them so that the linker will fill targets' RVAs to the fields at link
536 /// time. This function interprets the relocations to find the data to be used
537 /// in the resulting executable.
538 static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
539                                      const RuntimeFunction &RF,
540                                      uint64_t SectionOffset,
541                                      const std::vector<RelocationRef> &Rels) {
542   outs() << "Function Table:\n";
543   outs() << "  Start Address: ";
544   printCOFFSymbolAddress(outs(), Rels,
545                          SectionOffset +
546                              /*offsetof(RuntimeFunction, StartAddress)*/ 0,
547                          RF.StartAddress);
548   outs() << "\n";
549 
550   outs() << "  End Address: ";
551   printCOFFSymbolAddress(outs(), Rels,
552                          SectionOffset +
553                              /*offsetof(RuntimeFunction, EndAddress)*/ 4,
554                          RF.EndAddress);
555   outs() << "\n";
556 
557   outs() << "  Unwind Info Address: ";
558   printCOFFSymbolAddress(outs(), Rels,
559                          SectionOffset +
560                              /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
561                          RF.UnwindInfoOffset);
562   outs() << "\n";
563 
564   ArrayRef<uint8_t> XContents;
565   uint64_t UnwindInfoOffset = 0;
566   error(getSectionContents(
567           Obj, Rels, SectionOffset +
568                          /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
569           XContents, UnwindInfoOffset));
570   if (XContents.empty())
571     return;
572 
573   UnwindInfoOffset += RF.UnwindInfoOffset;
574   if (UnwindInfoOffset > XContents.size())
575     return;
576 
577   auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
578                                                            UnwindInfoOffset);
579   printWin64EHUnwindInfo(UI);
580 }
581 
582 void printCOFFUnwindInfo(const COFFObjectFile *Obj) {
583   if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
584     WithColor::error(errs(), "llvm-objdump")
585         << "unsupported image machine type "
586            "(currently only AMD64 is supported).\n";
587     return;
588   }
589 
590   std::vector<RelocationRef> Rels;
591   const RuntimeFunction *RFStart;
592   int NumRFs;
593   if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
594     return;
595   ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
596 
597   bool IsExecutable = Rels.empty();
598   if (IsExecutable) {
599     for (const RuntimeFunction &RF : RFs)
600       printRuntimeFunction(Obj, RF);
601     return;
602   }
603 
604   for (const RuntimeFunction &RF : RFs) {
605     uint64_t SectionOffset =
606         std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
607     printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
608   }
609 }
610 
611 void printCOFFFileHeader(const object::ObjectFile *Obj) {
612   const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
613   printTLSDirectory(file);
614   printLoadConfiguration(file);
615   printImportTables(file);
616   printExportTable(file);
617 }
618 
619 void printCOFFSymbolTable(const object::COFFImportFile *i) {
620   unsigned Index = 0;
621   bool IsCode = i->getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
622 
623   for (const object::BasicSymbolRef &Sym : i->symbols()) {
624     std::string Name;
625     raw_string_ostream NS(Name);
626 
627     cantFail(Sym.printName(NS));
628     NS.flush();
629 
630     outs() << "[" << format("%2d", Index) << "]"
631            << "(sec " << format("%2d", 0) << ")"
632            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
633            << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
634            << "(scl " << format("%3x", 0) << ") "
635            << "(nx " << 0 << ") "
636            << "0x" << format("%08x", 0) << " " << Name << '\n';
637 
638     ++Index;
639   }
640 }
641 
642 void printCOFFSymbolTable(const COFFObjectFile *coff) {
643   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
644     Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
645     StringRef Name;
646     error(Symbol.takeError());
647     error(coff->getSymbolName(*Symbol, Name));
648 
649     outs() << "[" << format("%2d", SI) << "]"
650            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
651            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
652            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
653            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
654            << ") "
655            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
656            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
657            << Name;
658     if (Demangle && Name.startswith("?")) {
659       char *DemangledSymbol = nullptr;
660       size_t Size = 0;
661       int Status = -1;
662       DemangledSymbol =
663           microsoftDemangle(Name.data(), DemangledSymbol, &Size, &Status);
664 
665       if (Status == 0 && DemangledSymbol) {
666         outs() << " (" << StringRef(DemangledSymbol) << ")";
667         std::free(DemangledSymbol);
668       } else {
669         outs() << " (invalid mangled name)";
670       }
671     }
672     outs() << "\n";
673 
674     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
675       if (Symbol->isSectionDefinition()) {
676         const coff_aux_section_definition *asd;
677         error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
678 
679         int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
680 
681         outs() << "AUX "
682                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
683                          , unsigned(asd->Length)
684                          , unsigned(asd->NumberOfRelocations)
685                          , unsigned(asd->NumberOfLinenumbers)
686                          , unsigned(asd->CheckSum))
687                << format("assoc %d comdat %d\n"
688                          , unsigned(AuxNumber)
689                          , unsigned(asd->Selection));
690       } else if (Symbol->isFileRecord()) {
691         const char *FileName;
692         error(coff->getAuxSymbol<char>(SI + 1, FileName));
693 
694         StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
695                                      coff->getSymbolTableEntrySize());
696         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
697 
698         SI = SI + Symbol->getNumberOfAuxSymbols();
699         break;
700       } else if (Symbol->isWeakExternal()) {
701         const coff_aux_weak_external *awe;
702         error(coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe));
703 
704         outs() << "AUX " << format("indx %d srch %d\n",
705                                    static_cast<uint32_t>(awe->TagIndex),
706                                    static_cast<uint32_t>(awe->Characteristics));
707       } else {
708         outs() << "AUX Unknown\n";
709       }
710     }
711   }
712 }
713 } // namespace llvm
714