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