OSDN Git Service

[llvm-objdump] Dump inline relocations if the relocated section is specified with...
[android-x86/external-llvm.git] / tools / llvm-objdump / COFFDump.cpp
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   const pe32_header *PE32Header;
238   error(Obj->getPE32Header(PE32Header));
239   uint32_t ImageBase = PE32Header->ImageBase;
240   uintptr_t IntPtr = 0;
241   error(Obj->getVaPtr(TableVA, IntPtr));
242   const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
243   outs() << "SEH Table:";
244   for (int I = 0; I < Count; ++I)
245     outs() << format(" 0x%x", P[I] + ImageBase);
246   outs() << "\n\n";
247 }
248
249 template <typename T>
250 static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
251   size_t FormatWidth = sizeof(T) * 2;
252   outs() << "TLS directory:"
253          << "\n  StartAddressOfRawData: "
254          << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
255          << "\n  EndAddressOfRawData: "
256          << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
257          << "\n  AddressOfIndex: "
258          << format_hex(TLSDir->AddressOfIndex, FormatWidth)
259          << "\n  AddressOfCallBacks: "
260          << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
261          << "\n  SizeOfZeroFill: "
262          << TLSDir->SizeOfZeroFill
263          << "\n  Characteristics: "
264          << TLSDir->Characteristics
265          << "\n  Alignment: "
266          << TLSDir->getAlignment()
267          << "\n\n";
268 }
269
270 static void printTLSDirectory(const COFFObjectFile *Obj) {
271   const pe32_header *PE32Header;
272   error(Obj->getPE32Header(PE32Header));
273
274   const pe32plus_header *PE32PlusHeader;
275   error(Obj->getPE32PlusHeader(PE32PlusHeader));
276
277   // Skip if it's not executable.
278   if (!PE32Header && !PE32PlusHeader)
279     return;
280
281   const data_directory *DataDir;
282   error(Obj->getDataDirectory(COFF::TLS_TABLE, DataDir));
283   uintptr_t IntPtr = 0;
284   if (DataDir->RelativeVirtualAddress == 0)
285     return;
286   error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
287
288   if (PE32Header) {
289     auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
290     printTLSDirectoryT(TLSDir);
291   } else {
292     auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
293     printTLSDirectoryT(TLSDir);
294   }
295
296   outs() << "\n";
297 }
298
299 static void printLoadConfiguration(const COFFObjectFile *Obj) {
300   // Skip if it's not executable.
301   const pe32_header *PE32Header;
302   error(Obj->getPE32Header(PE32Header));
303   if (!PE32Header)
304     return;
305
306   // Currently only x86 is supported
307   if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
308     return;
309
310   const data_directory *DataDir;
311   error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
312   uintptr_t IntPtr = 0;
313   if (DataDir->RelativeVirtualAddress == 0)
314     return;
315   error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
316
317   auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
318   outs() << "Load configuration:"
319          << "\n  Timestamp: " << LoadConf->TimeDateStamp
320          << "\n  Major Version: " << LoadConf->MajorVersion
321          << "\n  Minor Version: " << LoadConf->MinorVersion
322          << "\n  GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
323          << "\n  GlobalFlags Set: " << LoadConf->GlobalFlagsSet
324          << "\n  Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
325          << "\n  Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
326          << "\n  Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
327          << "\n  Lock Prefix Table: " << LoadConf->LockPrefixTable
328          << "\n  Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
329          << "\n  Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
330          << "\n  Process Affinity Mask: " << LoadConf->ProcessAffinityMask
331          << "\n  Process Heap Flags: " << LoadConf->ProcessHeapFlags
332          << "\n  CSD Version: " << LoadConf->CSDVersion
333          << "\n  Security Cookie: " << LoadConf->SecurityCookie
334          << "\n  SEH Table: " << LoadConf->SEHandlerTable
335          << "\n  SEH Count: " << LoadConf->SEHandlerCount
336          << "\n\n";
337   printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
338   outs() << "\n";
339 }
340
341 // Prints import tables. The import table is a table containing the list of
342 // DLL name and symbol names which will be linked by the loader.
343 static void printImportTables(const COFFObjectFile *Obj) {
344   import_directory_iterator I = Obj->import_directory_begin();
345   import_directory_iterator E = Obj->import_directory_end();
346   if (I == E)
347     return;
348   outs() << "The Import Tables:\n";
349   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
350     const coff_import_directory_table_entry *Dir;
351     StringRef Name;
352     if (DirRef.getImportTableEntry(Dir)) return;
353     if (DirRef.getName(Name)) return;
354
355     outs() << format("  lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
356                      static_cast<uint32_t>(Dir->ImportLookupTableRVA),
357                      static_cast<uint32_t>(Dir->TimeDateStamp),
358                      static_cast<uint32_t>(Dir->ForwarderChain),
359                      static_cast<uint32_t>(Dir->NameRVA),
360                      static_cast<uint32_t>(Dir->ImportAddressTableRVA));
361     outs() << "    DLL Name: " << Name << "\n";
362     outs() << "    Hint/Ord  Name\n";
363     for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
364       bool IsOrdinal;
365       if (Entry.isOrdinal(IsOrdinal))
366         return;
367       if (IsOrdinal) {
368         uint16_t Ordinal;
369         if (Entry.getOrdinal(Ordinal))
370           return;
371         outs() << format("      % 6d\n", Ordinal);
372         continue;
373       }
374       uint32_t HintNameRVA;
375       if (Entry.getHintNameRVA(HintNameRVA))
376         return;
377       uint16_t Hint;
378       StringRef Name;
379       if (Obj->getHintName(HintNameRVA, Hint, Name))
380         return;
381       outs() << format("      % 6d  ", Hint) << Name << "\n";
382     }
383     outs() << "\n";
384   }
385 }
386
387 // Prints export tables. The export table is a table containing the list of
388 // exported symbol from the DLL.
389 static void printExportTable(const COFFObjectFile *Obj) {
390   outs() << "Export Table:\n";
391   export_directory_iterator I = Obj->export_directory_begin();
392   export_directory_iterator E = Obj->export_directory_end();
393   if (I == E)
394     return;
395   StringRef DllName;
396   uint32_t OrdinalBase;
397   if (I->getDllName(DllName))
398     return;
399   if (I->getOrdinalBase(OrdinalBase))
400     return;
401   outs() << " DLL name: " << DllName << "\n";
402   outs() << " Ordinal base: " << OrdinalBase << "\n";
403   outs() << " Ordinal      RVA  Name\n";
404   for (; I != E; I = ++I) {
405     uint32_t Ordinal;
406     if (I->getOrdinal(Ordinal))
407       return;
408     uint32_t RVA;
409     if (I->getExportRVA(RVA))
410       return;
411     bool IsForwarder;
412     if (I->isForwarder(IsForwarder))
413       return;
414
415     if (IsForwarder) {
416       // Export table entries can be used to re-export symbols that
417       // this COFF file is imported from some DLLs. This is rare.
418       // In most cases IsForwarder is false.
419       outs() << format("    % 4d         ", Ordinal);
420     } else {
421       outs() << format("    % 4d %# 8x", Ordinal, RVA);
422     }
423
424     StringRef Name;
425     if (I->getSymbolName(Name))
426       continue;
427     if (!Name.empty())
428       outs() << "  " << Name;
429     if (IsForwarder) {
430       StringRef S;
431       if (I->getForwardTo(S))
432         return;
433       outs() << " (forwarded to " << S << ")";
434     }
435     outs() << "\n";
436   }
437 }
438
439 // Given the COFF object file, this function returns the relocations for .pdata
440 // and the pointer to "runtime function" structs.
441 static bool getPDataSection(const COFFObjectFile *Obj,
442                             std::vector<RelocationRef> &Rels,
443                             const RuntimeFunction *&RFStart, int &NumRFs) {
444   for (const SectionRef &Section : Obj->sections()) {
445     StringRef Name;
446     error(Section.getName(Name));
447     if (Name != ".pdata")
448       continue;
449
450     const coff_section *Pdata = Obj->getCOFFSection(Section);
451     for (const RelocationRef &Reloc : Section.relocations())
452       Rels.push_back(Reloc);
453
454     // Sort relocations by address.
455     llvm::sort(Rels, isRelocAddressLess);
456
457     ArrayRef<uint8_t> Contents;
458     error(Obj->getSectionContents(Pdata, Contents));
459     if (Contents.empty())
460       continue;
461
462     RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
463     NumRFs = Contents.size() / sizeof(RuntimeFunction);
464     return true;
465   }
466   return false;
467 }
468
469 Error getCOFFRelocationValueString(const COFFObjectFile *Obj,
470                                          const RelocationRef &Rel,
471                                          SmallVectorImpl<char> &Result) {
472   symbol_iterator SymI = Rel.getSymbol();
473   Expected<StringRef> SymNameOrErr = SymI->getName();
474   if (!SymNameOrErr)
475     return SymNameOrErr.takeError();
476   StringRef SymName = *SymNameOrErr;
477   Result.append(SymName.begin(), SymName.end());
478   return Error::success();
479 }
480
481 static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
482   // The casts to int are required in order to output the value as number.
483   // Without the casts the value would be interpreted as char data (which
484   // results in garbage output).
485   outs() << "    Version: " << static_cast<int>(UI->getVersion()) << "\n";
486   outs() << "    Flags: " << static_cast<int>(UI->getFlags());
487   if (UI->getFlags()) {
488     if (UI->getFlags() & UNW_ExceptionHandler)
489       outs() << " UNW_ExceptionHandler";
490     if (UI->getFlags() & UNW_TerminateHandler)
491       outs() << " UNW_TerminateHandler";
492     if (UI->getFlags() & UNW_ChainInfo)
493       outs() << " UNW_ChainInfo";
494   }
495   outs() << "\n";
496   outs() << "    Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
497   outs() << "    Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
498   // Maybe this should move to output of UOP_SetFPReg?
499   if (UI->getFrameRegister()) {
500     outs() << "    Frame register: "
501            << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
502     outs() << "    Frame offset: " << 16 * UI->getFrameOffset() << "\n";
503   } else {
504     outs() << "    No frame pointer used\n";
505   }
506   if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
507     // FIXME: Output exception handler data
508   } else if (UI->getFlags() & UNW_ChainInfo) {
509     // FIXME: Output chained unwind info
510   }
511
512   if (UI->NumCodes)
513     outs() << "    Unwind Codes:\n";
514
515   printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
516
517   outs() << "\n";
518   outs().flush();
519 }
520
521 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
522 /// pointing to an executable file.
523 static void printRuntimeFunction(const COFFObjectFile *Obj,
524                                  const RuntimeFunction &RF) {
525   if (!RF.StartAddress)
526     return;
527   outs() << "Function Table:\n"
528          << format("  Start Address: 0x%04x\n",
529                    static_cast<uint32_t>(RF.StartAddress))
530          << format("  End Address: 0x%04x\n",
531                    static_cast<uint32_t>(RF.EndAddress))
532          << format("  Unwind Info Address: 0x%04x\n",
533                    static_cast<uint32_t>(RF.UnwindInfoOffset));
534   uintptr_t addr;
535   if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
536     return;
537   printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
538 }
539
540 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
541 /// pointing to an object file. Unlike executable, fields in RuntimeFunction
542 /// struct are filled with zeros, but instead there are relocations pointing to
543 /// them so that the linker will fill targets' RVAs to the fields at link
544 /// time. This function interprets the relocations to find the data to be used
545 /// in the resulting executable.
546 static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
547                                      const RuntimeFunction &RF,
548                                      uint64_t SectionOffset,
549                                      const std::vector<RelocationRef> &Rels) {
550   outs() << "Function Table:\n";
551   outs() << "  Start Address: ";
552   printCOFFSymbolAddress(outs(), Rels,
553                          SectionOffset +
554                              /*offsetof(RuntimeFunction, StartAddress)*/ 0,
555                          RF.StartAddress);
556   outs() << "\n";
557
558   outs() << "  End Address: ";
559   printCOFFSymbolAddress(outs(), Rels,
560                          SectionOffset +
561                              /*offsetof(RuntimeFunction, EndAddress)*/ 4,
562                          RF.EndAddress);
563   outs() << "\n";
564
565   outs() << "  Unwind Info Address: ";
566   printCOFFSymbolAddress(outs(), Rels,
567                          SectionOffset +
568                              /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
569                          RF.UnwindInfoOffset);
570   outs() << "\n";
571
572   ArrayRef<uint8_t> XContents;
573   uint64_t UnwindInfoOffset = 0;
574   error(getSectionContents(
575           Obj, Rels, SectionOffset +
576                          /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
577           XContents, UnwindInfoOffset));
578   if (XContents.empty())
579     return;
580
581   UnwindInfoOffset += RF.UnwindInfoOffset;
582   if (UnwindInfoOffset > XContents.size())
583     return;
584
585   auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
586                                                            UnwindInfoOffset);
587   printWin64EHUnwindInfo(UI);
588 }
589
590 void printCOFFUnwindInfo(const COFFObjectFile *Obj) {
591   if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
592     WithColor::error(errs(), "llvm-objdump")
593         << "unsupported image machine type "
594            "(currently only AMD64 is supported).\n";
595     return;
596   }
597
598   std::vector<RelocationRef> Rels;
599   const RuntimeFunction *RFStart;
600   int NumRFs;
601   if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
602     return;
603   ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
604
605   bool IsExecutable = Rels.empty();
606   if (IsExecutable) {
607     for (const RuntimeFunction &RF : RFs)
608       printRuntimeFunction(Obj, RF);
609     return;
610   }
611
612   for (const RuntimeFunction &RF : RFs) {
613     uint64_t SectionOffset =
614         std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
615     printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
616   }
617 }
618
619 void printCOFFFileHeader(const object::ObjectFile *Obj) {
620   const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
621   printTLSDirectory(file);
622   printLoadConfiguration(file);
623   printImportTables(file);
624   printExportTable(file);
625 }
626
627 void printCOFFSymbolTable(const object::COFFImportFile *i) {
628   unsigned Index = 0;
629   bool IsCode = i->getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
630
631   for (const object::BasicSymbolRef &Sym : i->symbols()) {
632     std::string Name;
633     raw_string_ostream NS(Name);
634
635     cantFail(Sym.printName(NS));
636     NS.flush();
637
638     outs() << "[" << format("%2d", Index) << "]"
639            << "(sec " << format("%2d", 0) << ")"
640            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
641            << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
642            << "(scl " << format("%3x", 0) << ") "
643            << "(nx " << 0 << ") "
644            << "0x" << format("%08x", 0) << " " << Name << '\n';
645
646     ++Index;
647   }
648 }
649
650 void printCOFFSymbolTable(const COFFObjectFile *coff) {
651   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
652     Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
653     StringRef Name;
654     error(Symbol.takeError());
655     error(coff->getSymbolName(*Symbol, Name));
656
657     outs() << "[" << format("%2d", SI) << "]"
658            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
659            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
660            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
661            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
662            << ") "
663            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
664            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
665            << Name;
666     if (Demangle && Name.startswith("?")) {
667       char *DemangledSymbol = nullptr;
668       size_t Size = 0;
669       int Status = -1;
670       DemangledSymbol =
671           microsoftDemangle(Name.data(), DemangledSymbol, &Size, &Status);
672
673       if (Status == 0 && DemangledSymbol) {
674         outs() << " (" << StringRef(DemangledSymbol) << ")";
675         std::free(DemangledSymbol);
676       } else {
677         outs() << " (invalid mangled name)";
678       }
679     }
680     outs() << "\n";
681
682     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
683       if (Symbol->isSectionDefinition()) {
684         const coff_aux_section_definition *asd;
685         error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
686
687         int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
688
689         outs() << "AUX "
690                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
691                          , unsigned(asd->Length)
692                          , unsigned(asd->NumberOfRelocations)
693                          , unsigned(asd->NumberOfLinenumbers)
694                          , unsigned(asd->CheckSum))
695                << format("assoc %d comdat %d\n"
696                          , unsigned(AuxNumber)
697                          , unsigned(asd->Selection));
698       } else if (Symbol->isFileRecord()) {
699         const char *FileName;
700         error(coff->getAuxSymbol<char>(SI + 1, FileName));
701
702         StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
703                                      coff->getSymbolTableEntrySize());
704         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
705
706         SI = SI + Symbol->getNumberOfAuxSymbols();
707         break;
708       } else if (Symbol->isWeakExternal()) {
709         const coff_aux_weak_external *awe;
710         error(coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe));
711
712         outs() << "AUX " << format("indx %d srch %d\n",
713                                    static_cast<uint32_t>(awe->TagIndex),
714                                    static_cast<uint32_t>(awe->Characteristics));
715       } else {
716         outs() << "AUX Unknown\n";
717       }
718     }
719   }
720 }
721 } // namespace llvm