1 //===-- COFFDumper.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-readobj.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMWinEHPrinter.h"
15 #include "ObjDumper.h"
16 #include "StackMapPrinter.h"
17 #include "Win64EHDumper.h"
18 #include "llvm-readobj.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/BinaryFormat/COFF.h"
23 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
24 #include "llvm/DebugInfo/CodeView/CodeView.h"
25 #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
26 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
27 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
28 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
29 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
30 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
31 #include "llvm/DebugInfo/CodeView/Line.h"
32 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
33 #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
34 #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
35 #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
36 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
37 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
38 #include "llvm/DebugInfo/CodeView/TypeHashing.h"
39 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
40 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
41 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
42 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
43 #include "llvm/Object/COFF.h"
44 #include "llvm/Object/ObjectFile.h"
45 #include "llvm/Object/WindowsResource.h"
46 #include "llvm/Support/BinaryStreamReader.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/FormatVariadic.h"
51 #include "llvm/Support/LEB128.h"
52 #include "llvm/Support/ScopedPrinter.h"
53 #include "llvm/Support/Win64EH.h"
54 #include "llvm/Support/raw_ostream.h"
55 
56 using namespace llvm;
57 using namespace llvm::object;
58 using namespace llvm::codeview;
59 using namespace llvm::support;
60 using namespace llvm::Win64EH;
61 
62 namespace {
63 
64 struct LoadConfigTables {
65   uint64_t SEHTableVA = 0;
66   uint64_t SEHTableCount = 0;
67   uint32_t GuardFlags = 0;
68   uint64_t GuardFidTableVA = 0;
69   uint64_t GuardFidTableCount = 0;
70   uint64_t GuardLJmpTableVA = 0;
71   uint64_t GuardLJmpTableCount = 0;
72 };
73 
74 class COFFDumper : public ObjDumper {
75 public:
76   friend class COFFObjectDumpDelegate;
COFFDumper(const llvm::object::COFFObjectFile * Obj,ScopedPrinter & Writer)77   COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
78       : ObjDumper(Writer), Obj(Obj), Writer(Writer), Types(100) {}
79 
80   void printFileHeaders() override;
81   void printSectionHeaders() override;
82   void printRelocations() override;
83   void printUnwindInfo() override;
84 
85   void printNeededLibraries() override;
86 
87   void printCOFFImports() override;
88   void printCOFFExports() override;
89   void printCOFFDirectives() override;
90   void printCOFFBaseReloc() override;
91   void printCOFFDebugDirectory() override;
92   void printCOFFTLSDirectory() override;
93   void printCOFFResources() override;
94   void printCOFFLoadConfig() override;
95   void printCodeViewDebugInfo() override;
96   void mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
97                           llvm::codeview::MergingTypeTableBuilder &CVTypes,
98                           llvm::codeview::GlobalTypeTableBuilder &GlobalCVIDs,
99                           llvm::codeview::GlobalTypeTableBuilder &GlobalCVTypes,
100                           bool GHash) override;
101   void printStackMap() const override;
102   void printAddrsig() override;
103   void printCGProfile() override;
104 
105 private:
106   StringRef getSymbolName(uint32_t Index);
107   void printSymbols() override;
108   void printDynamicSymbols() override;
109   void printSymbol(const SymbolRef &Sym);
110   void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
111                        uint64_t Bias = 0);
112   void printDataDirectory(uint32_t Index, const std::string &FieldName);
113 
114   void printDOSHeader(const dos_header *DH);
115   template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
116   void printBaseOfDataField(const pe32_header *Hdr);
117   void printBaseOfDataField(const pe32plus_header *Hdr);
118   template <typename T>
119   void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
120   template <typename IntTy>
121   void printCOFFTLSDirectory(const coff_tls_directory<IntTy> *TlsTable);
122   typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
123   void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
124                      PrintExtraCB PrintExtra = 0);
125 
126   void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
127   void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
128   StringRef getTypeName(TypeIndex Ty);
129   StringRef getFileNameForFileOffset(uint32_t FileOffset);
130   void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
printTypeIndex(StringRef FieldName,TypeIndex TI)131   void printTypeIndex(StringRef FieldName, TypeIndex TI) {
132     // Forward to CVTypeDumper for simplicity.
133     codeview::printTypeIndex(Writer, FieldName, TI, Types);
134   }
135 
136   void printCodeViewSymbolsSubsection(StringRef Subsection,
137                                       const SectionRef &Section,
138                                       StringRef SectionContents);
139 
140   void printCodeViewFileChecksums(StringRef Subsection);
141 
142   void printCodeViewInlineeLines(StringRef Subsection);
143 
144   void printRelocatedField(StringRef Label, const coff_section *Sec,
145                            uint32_t RelocOffset, uint32_t Offset,
146                            StringRef *RelocSym = nullptr);
147 
148   uint32_t countTotalTableEntries(ResourceSectionRef RSF,
149                                   const coff_resource_dir_table &Table,
150                                   StringRef Level);
151 
152   void printResourceDirectoryTable(ResourceSectionRef RSF,
153                                    const coff_resource_dir_table &Table,
154                                    StringRef Level);
155 
156   void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
157                                   StringRef SectionContents, StringRef Block);
158 
159   /// Given a .debug$S section, find the string table and file checksum table.
160   void initializeFileAndStringTables(BinaryStreamReader &Reader);
161 
162   void cacheRelocations();
163 
164   std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
165                                 SymbolRef &Sym);
166   std::error_code resolveSymbolName(const coff_section *Section,
167                                     uint64_t Offset, StringRef &Name);
168   std::error_code resolveSymbolName(const coff_section *Section,
169                                     StringRef SectionContents,
170                                     const void *RelocPtr, StringRef &Name);
171   void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
172   void printDelayImportedSymbols(
173       const DelayImportDirectoryEntryRef &I,
174       iterator_range<imported_symbol_iterator> Range);
175 
176   typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
177 
178   const llvm::object::COFFObjectFile *Obj;
179   bool RelocCached = false;
180   RelocMapTy RelocMap;
181 
182   DebugChecksumsSubsectionRef CVFileChecksumTable;
183 
184   DebugStringTableSubsectionRef CVStringTable;
185 
186   /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
187   /// first, but if we don't see one, just assume an X64 CPU type. It is common.
188   CPUType CompilationCPUType = CPUType::X64;
189 
190   ScopedPrinter &Writer;
191   BinaryByteStream TypeContents;
192   LazyRandomTypeCollection Types;
193 };
194 
195 class COFFObjectDumpDelegate : public SymbolDumpDelegate {
196 public:
COFFObjectDumpDelegate(COFFDumper & CD,const SectionRef & SR,const COFFObjectFile * Obj,StringRef SectionContents)197   COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
198                          const COFFObjectFile *Obj, StringRef SectionContents)
199       : CD(CD), SR(SR), SectionContents(SectionContents) {
200     Sec = Obj->getCOFFSection(SR);
201   }
202 
getRecordOffset(BinaryStreamReader Reader)203   uint32_t getRecordOffset(BinaryStreamReader Reader) override {
204     ArrayRef<uint8_t> Data;
205     if (auto EC = Reader.readLongestContiguousChunk(Data)) {
206       llvm::consumeError(std::move(EC));
207       return 0;
208     }
209     return Data.data() - SectionContents.bytes_begin();
210   }
211 
printRelocatedField(StringRef Label,uint32_t RelocOffset,uint32_t Offset,StringRef * RelocSym)212   void printRelocatedField(StringRef Label, uint32_t RelocOffset,
213                            uint32_t Offset, StringRef *RelocSym) override {
214     CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
215   }
216 
printBinaryBlockWithRelocs(StringRef Label,ArrayRef<uint8_t> Block)217   void printBinaryBlockWithRelocs(StringRef Label,
218                                   ArrayRef<uint8_t> Block) override {
219     StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
220                      Block.size());
221     if (opts::CodeViewSubsectionBytes)
222       CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
223   }
224 
getFileNameForFileOffset(uint32_t FileOffset)225   StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
226     return CD.getFileNameForFileOffset(FileOffset);
227   }
228 
getStringTable()229   DebugStringTableSubsectionRef getStringTable() override {
230     return CD.CVStringTable;
231   }
232 
233 private:
234   COFFDumper &CD;
235   const SectionRef &SR;
236   const coff_section *Sec;
237   StringRef SectionContents;
238 };
239 
240 } // end namespace
241 
242 namespace llvm {
243 
createCOFFDumper(const object::COFFObjectFile & Obj,ScopedPrinter & Writer)244 std::unique_ptr<ObjDumper> createCOFFDumper(const object::COFFObjectFile &Obj,
245                                             ScopedPrinter &Writer) {
246   return std::make_unique<COFFDumper>(&Obj, Writer);
247 }
248 
249 } // namespace llvm
250 
251 // Given a section and an offset into this section the function returns the
252 // symbol used for the relocation at the offset.
resolveSymbol(const coff_section * Section,uint64_t Offset,SymbolRef & Sym)253 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
254                                           uint64_t Offset, SymbolRef &Sym) {
255   cacheRelocations();
256   const auto &Relocations = RelocMap[Section];
257   auto SymI = Obj->symbol_end();
258   for (const auto &Relocation : Relocations) {
259     uint64_t RelocationOffset = Relocation.getOffset();
260 
261     if (RelocationOffset == Offset) {
262       SymI = Relocation.getSymbol();
263       break;
264     }
265   }
266   if (SymI == Obj->symbol_end())
267     return inconvertibleErrorCode();
268   Sym = *SymI;
269   return std::error_code();
270 }
271 
272 // Given a section and an offset into this section the function returns the name
273 // of the symbol used for the relocation at the offset.
resolveSymbolName(const coff_section * Section,uint64_t Offset,StringRef & Name)274 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
275                                               uint64_t Offset,
276                                               StringRef &Name) {
277   SymbolRef Symbol;
278   if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
279     return EC;
280   Expected<StringRef> NameOrErr = Symbol.getName();
281   if (!NameOrErr)
282     return errorToErrorCode(NameOrErr.takeError());
283   Name = *NameOrErr;
284   return std::error_code();
285 }
286 
287 // Helper for when you have a pointer to real data and you want to know about
288 // relocations against it.
resolveSymbolName(const coff_section * Section,StringRef SectionContents,const void * RelocPtr,StringRef & Name)289 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
290                                               StringRef SectionContents,
291                                               const void *RelocPtr,
292                                               StringRef &Name) {
293   assert(SectionContents.data() < RelocPtr &&
294          RelocPtr < SectionContents.data() + SectionContents.size() &&
295          "pointer to relocated object is not in section");
296   uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
297                               SectionContents.data());
298   return resolveSymbolName(Section, Offset, Name);
299 }
300 
printRelocatedField(StringRef Label,const coff_section * Sec,uint32_t RelocOffset,uint32_t Offset,StringRef * RelocSym)301 void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
302                                      uint32_t RelocOffset, uint32_t Offset,
303                                      StringRef *RelocSym) {
304   StringRef SymStorage;
305   StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
306   if (!resolveSymbolName(Sec, RelocOffset, Symbol))
307     W.printSymbolOffset(Label, Symbol, Offset);
308   else
309     W.printHex(Label, RelocOffset);
310 }
311 
printBinaryBlockWithRelocs(StringRef Label,const SectionRef & Sec,StringRef SectionContents,StringRef Block)312 void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
313                                             const SectionRef &Sec,
314                                             StringRef SectionContents,
315                                             StringRef Block) {
316   W.printBinaryBlock(Label, Block);
317 
318   assert(SectionContents.begin() < Block.begin() &&
319          SectionContents.end() >= Block.end() &&
320          "Block is not contained in SectionContents");
321   uint64_t OffsetStart = Block.data() - SectionContents.data();
322   uint64_t OffsetEnd = OffsetStart + Block.size();
323 
324   W.flush();
325   cacheRelocations();
326   ListScope D(W, "BlockRelocations");
327   const coff_section *Section = Obj->getCOFFSection(Sec);
328   const auto &Relocations = RelocMap[Section];
329   for (const auto &Relocation : Relocations) {
330     uint64_t RelocationOffset = Relocation.getOffset();
331     if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
332       printRelocation(Sec, Relocation, OffsetStart);
333   }
334 }
335 
336 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
337   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN  ),
338   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33     ),
339   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64    ),
340   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM      ),
341   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64    ),
342   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT    ),
343   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC      ),
344   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386     ),
345   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64     ),
346   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R     ),
347   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16   ),
348   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU  ),
349   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
350   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC  ),
351   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
352   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000    ),
353   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3      ),
354   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP   ),
355   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4      ),
356   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5      ),
357   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB    ),
358   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
359 };
360 
361 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
362   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED        ),
363   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE       ),
364   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED     ),
365   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED    ),
366   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM     ),
367   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE    ),
368   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO      ),
369   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE          ),
370   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED         ),
371   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
372   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP      ),
373   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM                 ),
374   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL                    ),
375   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY         ),
376   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI      )
377 };
378 
379 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
380   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN                ),
381   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE                 ),
382   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI            ),
383   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI            ),
384   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI              ),
385   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI         ),
386   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION        ),
387   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
388   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER     ),
389   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM                ),
390   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX                   ),
391 };
392 
393 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
394   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA      ),
395   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE         ),
396   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY      ),
397   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT            ),
398   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION         ),
399   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH               ),
400   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND              ),
401   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER         ),
402   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER           ),
403   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF             ),
404   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
405 };
406 
407 static const EnumEntry<COFF::ExtendedDLLCharacteristics>
408     PEExtendedDLLCharacteristics[] = {
409         LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT),
410 };
411 
412 static const EnumEntry<COFF::SectionCharacteristics>
413 ImageSectionCharacteristics[] = {
414   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD           ),
415   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD           ),
416   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE              ),
417   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA  ),
418   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
419   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER             ),
420   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO              ),
421   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE            ),
422   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT            ),
423   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL                 ),
424   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE         ),
425   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT             ),
426   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED            ),
427   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD           ),
428   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES          ),
429   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES          ),
430   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES          ),
431   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES          ),
432   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES         ),
433   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES         ),
434   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES         ),
435   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES        ),
436   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES        ),
437   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES        ),
438   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES       ),
439   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES       ),
440   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES       ),
441   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES       ),
442   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL       ),
443   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE       ),
444   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED        ),
445   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED         ),
446   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED            ),
447   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE           ),
448   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ              ),
449   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE             )
450 };
451 
452 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
453   { "Null"  , COFF::IMAGE_SYM_TYPE_NULL   },
454   { "Void"  , COFF::IMAGE_SYM_TYPE_VOID   },
455   { "Char"  , COFF::IMAGE_SYM_TYPE_CHAR   },
456   { "Short" , COFF::IMAGE_SYM_TYPE_SHORT  },
457   { "Int"   , COFF::IMAGE_SYM_TYPE_INT    },
458   { "Long"  , COFF::IMAGE_SYM_TYPE_LONG   },
459   { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT  },
460   { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
461   { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
462   { "Union" , COFF::IMAGE_SYM_TYPE_UNION  },
463   { "Enum"  , COFF::IMAGE_SYM_TYPE_ENUM   },
464   { "MOE"   , COFF::IMAGE_SYM_TYPE_MOE    },
465   { "Byte"  , COFF::IMAGE_SYM_TYPE_BYTE   },
466   { "Word"  , COFF::IMAGE_SYM_TYPE_WORD   },
467   { "UInt"  , COFF::IMAGE_SYM_TYPE_UINT   },
468   { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD  }
469 };
470 
471 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
472   { "Null"    , COFF::IMAGE_SYM_DTYPE_NULL     },
473   { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER  },
474   { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
475   { "Array"   , COFF::IMAGE_SYM_DTYPE_ARRAY    }
476 };
477 
478 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
479   { "EndOfFunction"  , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION  },
480   { "Null"           , COFF::IMAGE_SYM_CLASS_NULL             },
481   { "Automatic"      , COFF::IMAGE_SYM_CLASS_AUTOMATIC        },
482   { "External"       , COFF::IMAGE_SYM_CLASS_EXTERNAL         },
483   { "Static"         , COFF::IMAGE_SYM_CLASS_STATIC           },
484   { "Register"       , COFF::IMAGE_SYM_CLASS_REGISTER         },
485   { "ExternalDef"    , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF     },
486   { "Label"          , COFF::IMAGE_SYM_CLASS_LABEL            },
487   { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL  },
488   { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
489   { "Argument"       , COFF::IMAGE_SYM_CLASS_ARGUMENT         },
490   { "StructTag"      , COFF::IMAGE_SYM_CLASS_STRUCT_TAG       },
491   { "MemberOfUnion"  , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION  },
492   { "UnionTag"       , COFF::IMAGE_SYM_CLASS_UNION_TAG        },
493   { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION  },
494   { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
495   { "EnumTag"        , COFF::IMAGE_SYM_CLASS_ENUM_TAG         },
496   { "MemberOfEnum"   , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM   },
497   { "RegisterParam"  , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM   },
498   { "BitField"       , COFF::IMAGE_SYM_CLASS_BIT_FIELD        },
499   { "Block"          , COFF::IMAGE_SYM_CLASS_BLOCK            },
500   { "Function"       , COFF::IMAGE_SYM_CLASS_FUNCTION         },
501   { "EndOfStruct"    , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT    },
502   { "File"           , COFF::IMAGE_SYM_CLASS_FILE             },
503   { "Section"        , COFF::IMAGE_SYM_CLASS_SECTION          },
504   { "WeakExternal"   , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL    },
505   { "CLRToken"       , COFF::IMAGE_SYM_CLASS_CLR_TOKEN        }
506 };
507 
508 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
509   { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
510   { "Any"         , COFF::IMAGE_COMDAT_SELECT_ANY          },
511   { "SameSize"    , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE    },
512   { "ExactMatch"  , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH  },
513   { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE  },
514   { "Largest"     , COFF::IMAGE_COMDAT_SELECT_LARGEST      },
515   { "Newest"      , COFF::IMAGE_COMDAT_SELECT_NEWEST       }
516 };
517 
518 static const EnumEntry<COFF::DebugType> ImageDebugType[] = {
519     {"Unknown", COFF::IMAGE_DEBUG_TYPE_UNKNOWN},
520     {"COFF", COFF::IMAGE_DEBUG_TYPE_COFF},
521     {"CodeView", COFF::IMAGE_DEBUG_TYPE_CODEVIEW},
522     {"FPO", COFF::IMAGE_DEBUG_TYPE_FPO},
523     {"Misc", COFF::IMAGE_DEBUG_TYPE_MISC},
524     {"Exception", COFF::IMAGE_DEBUG_TYPE_EXCEPTION},
525     {"Fixup", COFF::IMAGE_DEBUG_TYPE_FIXUP},
526     {"OmapToSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC},
527     {"OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC},
528     {"Borland", COFF::IMAGE_DEBUG_TYPE_BORLAND},
529     {"Reserved10", COFF::IMAGE_DEBUG_TYPE_RESERVED10},
530     {"CLSID", COFF::IMAGE_DEBUG_TYPE_CLSID},
531     {"VCFeature", COFF::IMAGE_DEBUG_TYPE_VC_FEATURE},
532     {"POGO", COFF::IMAGE_DEBUG_TYPE_POGO},
533     {"ILTCG", COFF::IMAGE_DEBUG_TYPE_ILTCG},
534     {"MPX", COFF::IMAGE_DEBUG_TYPE_MPX},
535     {"Repro", COFF::IMAGE_DEBUG_TYPE_REPRO},
536     {"ExtendedDLLCharacteristics",
537      COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS},
538 };
539 
540 static const EnumEntry<COFF::WeakExternalCharacteristics>
541 WeakExternalCharacteristics[] = {
542   { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
543   { "Library"  , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY   },
544   { "Alias"    , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS     }
545 };
546 
547 static const EnumEntry<uint32_t> SubSectionTypes[] = {
548     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
549     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
550     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
551     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
552     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
553     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
554     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
555     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
556     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
557     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
558     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
559     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
560     LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
561 };
562 
563 static const EnumEntry<uint32_t> FrameDataFlags[] = {
564     LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
565     LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
566     LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
567 };
568 
569 static const EnumEntry<uint8_t> FileChecksumKindNames[] = {
570   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
571   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
572   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
573   LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
574 };
575 
576 template <typename T>
getSymbolAuxData(const COFFObjectFile * Obj,COFFSymbolRef Symbol,uint8_t AuxSymbolIdx,const T * & Aux)577 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
578                                         COFFSymbolRef Symbol,
579                                         uint8_t AuxSymbolIdx, const T *&Aux) {
580   ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
581   AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
582   Aux = reinterpret_cast<const T*>(AuxData.data());
583   return std::error_code();
584 }
585 
cacheRelocations()586 void COFFDumper::cacheRelocations() {
587   if (RelocCached)
588     return;
589   RelocCached = true;
590 
591   for (const SectionRef &S : Obj->sections()) {
592     const coff_section *Section = Obj->getCOFFSection(S);
593 
594     for (const RelocationRef &Reloc : S.relocations())
595       RelocMap[Section].push_back(Reloc);
596 
597     // Sort relocations by address.
598     llvm::sort(RelocMap[Section], [](RelocationRef L, RelocationRef R) {
599       return L.getOffset() < R.getOffset();
600     });
601   }
602 }
603 
printDataDirectory(uint32_t Index,const std::string & FieldName)604 void COFFDumper::printDataDirectory(uint32_t Index,
605                                     const std::string &FieldName) {
606   const data_directory *Data = Obj->getDataDirectory(Index);
607   if (!Data)
608     return;
609   W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
610   W.printHex(FieldName + "Size", Data->Size);
611 }
612 
printFileHeaders()613 void COFFDumper::printFileHeaders() {
614   time_t TDS = Obj->getTimeDateStamp();
615   char FormattedTime[20] = { };
616   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
617 
618   {
619     DictScope D(W, "ImageFileHeader");
620     W.printEnum  ("Machine", Obj->getMachine(),
621                     makeArrayRef(ImageFileMachineType));
622     W.printNumber("SectionCount", Obj->getNumberOfSections());
623     W.printHex   ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
624     W.printHex   ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
625     W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
626     W.printNumber("StringTableSize", Obj->getStringTableSize());
627     W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
628     W.printFlags ("Characteristics", Obj->getCharacteristics(),
629                     makeArrayRef(ImageFileCharacteristics));
630   }
631 
632   // Print PE header. This header does not exist if this is an object file and
633   // not an executable.
634   if (const pe32_header *PEHeader = Obj->getPE32Header())
635     printPEHeader<pe32_header>(PEHeader);
636 
637   if (const pe32plus_header *PEPlusHeader = Obj->getPE32PlusHeader())
638     printPEHeader<pe32plus_header>(PEPlusHeader);
639 
640   if (const dos_header *DH = Obj->getDOSHeader())
641     printDOSHeader(DH);
642 }
643 
printDOSHeader(const dos_header * DH)644 void COFFDumper::printDOSHeader(const dos_header *DH) {
645   DictScope D(W, "DOSHeader");
646   W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
647   W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
648   W.printNumber("FileSizeInPages", DH->FileSizeInPages);
649   W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
650   W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
651   W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
652   W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
653   W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
654   W.printNumber("InitialSP", DH->InitialSP);
655   W.printNumber("Checksum", DH->Checksum);
656   W.printNumber("InitialIP", DH->InitialIP);
657   W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
658   W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
659   W.printNumber("OverlayNumber", DH->OverlayNumber);
660   W.printNumber("OEMid", DH->OEMid);
661   W.printNumber("OEMinfo", DH->OEMinfo);
662   W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
663 }
664 
665 template <class PEHeader>
printPEHeader(const PEHeader * Hdr)666 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
667   DictScope D(W, "ImageOptionalHeader");
668   W.printHex   ("Magic", Hdr->Magic);
669   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
670   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
671   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
672   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
673   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
674   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
675   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
676   printBaseOfDataField(Hdr);
677   W.printHex   ("ImageBase", Hdr->ImageBase);
678   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
679   W.printNumber("FileAlignment", Hdr->FileAlignment);
680   W.printNumber("MajorOperatingSystemVersion",
681                 Hdr->MajorOperatingSystemVersion);
682   W.printNumber("MinorOperatingSystemVersion",
683                 Hdr->MinorOperatingSystemVersion);
684   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
685   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
686   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
687   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
688   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
689   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
690   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
691   W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
692                 makeArrayRef(PEDLLCharacteristics));
693   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
694   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
695   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
696   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
697   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
698 
699   if (Hdr->NumberOfRvaAndSize > 0) {
700     DictScope D(W, "DataDirectory");
701     static const char * const directory[] = {
702       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
703       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
704       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
705       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
706     };
707 
708     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
709       printDataDirectory(i, directory[i]);
710   }
711 }
712 
printCOFFDebugDirectory()713 void COFFDumper::printCOFFDebugDirectory() {
714   ListScope LS(W, "DebugDirectory");
715   for (const debug_directory &D : Obj->debug_directories()) {
716     char FormattedTime[20] = {};
717     time_t TDS = D.TimeDateStamp;
718     strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
719     DictScope S(W, "DebugEntry");
720     W.printHex("Characteristics", D.Characteristics);
721     W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
722     W.printHex("MajorVersion", D.MajorVersion);
723     W.printHex("MinorVersion", D.MinorVersion);
724     W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
725     W.printHex("SizeOfData", D.SizeOfData);
726     W.printHex("AddressOfRawData", D.AddressOfRawData);
727     W.printHex("PointerToRawData", D.PointerToRawData);
728     // Ideally, if D.AddressOfRawData == 0, we should try to load the payload
729     // using D.PointerToRawData instead.
730     if (D.AddressOfRawData == 0)
731       continue;
732     if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
733       const codeview::DebugInfo *DebugInfo;
734       StringRef PDBFileName;
735       if (Error E = Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName))
736         reportError(std::move(E), Obj->getFileName());
737 
738       DictScope PDBScope(W, "PDBInfo");
739       W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
740       if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
741         W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
742         W.printNumber("PDBAge", DebugInfo->PDB70.Age);
743         W.printString("PDBFileName", PDBFileName);
744       }
745     } else if (D.SizeOfData != 0) {
746       // FIXME: Data visualization for IMAGE_DEBUG_TYPE_VC_FEATURE and
747       // IMAGE_DEBUG_TYPE_POGO?
748       ArrayRef<uint8_t> RawData;
749       if (Error E = Obj->getRvaAndSizeAsBytes(D.AddressOfRawData,
750                                                          D.SizeOfData, RawData))
751         reportError(std::move(E), Obj->getFileName());
752       if (D.Type == COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS) {
753         // FIXME right now the only possible value would fit in 8 bits,
754         // but that might change in the future
755         uint16_t Characteristics = RawData[0];
756         W.printFlags("ExtendedCharacteristics", Characteristics,
757                      makeArrayRef(PEExtendedDLLCharacteristics));
758       }
759       W.printBinaryBlock("RawData", RawData);
760     }
761   }
762 }
763 
printRVATable(uint64_t TableVA,uint64_t Count,uint64_t EntrySize,PrintExtraCB PrintExtra)764 void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
765                                uint64_t EntrySize, PrintExtraCB PrintExtra) {
766   uintptr_t TableStart, TableEnd;
767   if (Error E = Obj->getVaPtr(TableVA, TableStart))
768     reportError(std::move(E), Obj->getFileName());
769   if (Error E =
770           Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd))
771     reportError(std::move(E), Obj->getFileName());
772   TableEnd++;
773   for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
774     uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
775     raw_ostream &OS = W.startLine();
776     OS << W.hex(Obj->getImageBase() + RVA);
777     if (PrintExtra)
778       PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
779     OS << '\n';
780   }
781 }
782 
printCOFFLoadConfig()783 void COFFDumper::printCOFFLoadConfig() {
784   LoadConfigTables Tables;
785   if (Obj->is64())
786     printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
787   else
788     printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
789 
790   if (Tables.SEHTableVA) {
791     ListScope LS(W, "SEHTable");
792     printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
793   }
794 
795   if (Tables.GuardFidTableVA) {
796     ListScope LS(W, "GuardFidTable");
797     if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags)) {
798       auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
799         uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
800         if (Flags)
801           OS << " flags " << utohexstr(Flags);
802       };
803       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
804                     PrintGuardFlags);
805     } else {
806       printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
807     }
808   }
809 
810   if (Tables.GuardLJmpTableVA) {
811     ListScope LS(W, "GuardLJmpTable");
812     printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount, 4);
813   }
814 }
815 
816 template <typename T>
printCOFFLoadConfig(const T * Conf,LoadConfigTables & Tables)817 void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
818   if (!Conf)
819     return;
820 
821   ListScope LS(W, "LoadConfig");
822   char FormattedTime[20] = {};
823   time_t TDS = Conf->TimeDateStamp;
824   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
825   W.printHex("Size", Conf->Size);
826 
827   // Print everything before SecurityCookie. The vast majority of images today
828   // have all these fields.
829   if (Conf->Size < offsetof(T, SEHandlerTable))
830     return;
831   W.printHex("TimeDateStamp", FormattedTime, TDS);
832   W.printHex("MajorVersion", Conf->MajorVersion);
833   W.printHex("MinorVersion", Conf->MinorVersion);
834   W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
835   W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
836   W.printHex("CriticalSectionDefaultTimeout",
837              Conf->CriticalSectionDefaultTimeout);
838   W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
839   W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
840   W.printHex("LockPrefixTable", Conf->LockPrefixTable);
841   W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
842   W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
843   W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
844   W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
845   W.printHex("CSDVersion", Conf->CSDVersion);
846   W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
847   W.printHex("EditList", Conf->EditList);
848   W.printHex("SecurityCookie", Conf->SecurityCookie);
849 
850   // Print the safe SEH table if present.
851   if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
852     return;
853   W.printHex("SEHandlerTable", Conf->SEHandlerTable);
854   W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
855 
856   Tables.SEHTableVA = Conf->SEHandlerTable;
857   Tables.SEHTableCount = Conf->SEHandlerCount;
858 
859   // Print everything before CodeIntegrity. (2015)
860   if (Conf->Size < offsetof(T, CodeIntegrity))
861     return;
862   W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
863   W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
864   W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
865   W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
866   W.printHex("GuardFlags", Conf->GuardFlags);
867 
868   Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
869   Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
870   Tables.GuardFlags = Conf->GuardFlags;
871 
872   // Print the rest. (2017)
873   if (Conf->Size < sizeof(T))
874     return;
875   W.printHex("GuardAddressTakenIatEntryTable",
876              Conf->GuardAddressTakenIatEntryTable);
877   W.printNumber("GuardAddressTakenIatEntryCount",
878                 Conf->GuardAddressTakenIatEntryCount);
879   W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
880   W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
881   W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
882   W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
883   W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
884   W.printHex("GuardRFFailureRoutineFunctionPointer",
885              Conf->GuardRFFailureRoutineFunctionPointer);
886   W.printHex("DynamicValueRelocTableOffset",
887              Conf->DynamicValueRelocTableOffset);
888   W.printNumber("DynamicValueRelocTableSection",
889                 Conf->DynamicValueRelocTableSection);
890   W.printHex("GuardRFVerifyStackPointerFunctionPointer",
891              Conf->GuardRFVerifyStackPointerFunctionPointer);
892   W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
893 
894   Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
895   Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
896 }
897 
printBaseOfDataField(const pe32_header * Hdr)898 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
899   W.printHex("BaseOfData", Hdr->BaseOfData);
900 }
901 
printBaseOfDataField(const pe32plus_header *)902 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
903 
printCodeViewDebugInfo()904 void COFFDumper::printCodeViewDebugInfo() {
905   // Print types first to build CVUDTNames, then print symbols.
906   for (const SectionRef &S : Obj->sections()) {
907     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
908     // .debug$T is a standard CodeView type section, while .debug$P is the same
909     // format but used for MSVC precompiled header object files.
910     if (SectionName == ".debug$T" || SectionName == ".debug$P")
911       printCodeViewTypeSection(SectionName, S);
912   }
913   for (const SectionRef &S : Obj->sections()) {
914     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
915     if (SectionName == ".debug$S")
916       printCodeViewSymbolSection(SectionName, S);
917   }
918 }
919 
initializeFileAndStringTables(BinaryStreamReader & Reader)920 void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
921   while (Reader.bytesRemaining() > 0 &&
922          (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
923     // The section consists of a number of subsection in the following format:
924     // |SubSectionType|SubSectionSize|Contents...|
925     uint32_t SubType, SubSectionSize;
926 
927     if (Error E = Reader.readInteger(SubType))
928       reportError(std::move(E), Obj->getFileName());
929     if (Error E = Reader.readInteger(SubSectionSize))
930       reportError(std::move(E), Obj->getFileName());
931 
932     StringRef Contents;
933     if (Error E = Reader.readFixedString(Contents, SubSectionSize))
934       reportError(std::move(E), Obj->getFileName());
935 
936     BinaryStreamRef ST(Contents, support::little);
937     switch (DebugSubsectionKind(SubType)) {
938     case DebugSubsectionKind::FileChecksums:
939       if (Error E = CVFileChecksumTable.initialize(ST))
940         reportError(std::move(E), Obj->getFileName());
941       break;
942     case DebugSubsectionKind::StringTable:
943       if (Error E = CVStringTable.initialize(ST))
944         reportError(std::move(E), Obj->getFileName());
945       break;
946     default:
947       break;
948     }
949 
950     uint32_t PaddedSize = alignTo(SubSectionSize, 4);
951     if (Error E = Reader.skip(PaddedSize - SubSectionSize))
952       reportError(std::move(E), Obj->getFileName());
953   }
954 }
955 
printCodeViewSymbolSection(StringRef SectionName,const SectionRef & Section)956 void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
957                                             const SectionRef &Section) {
958   StringRef SectionContents =
959       unwrapOrError(Obj->getFileName(), Section.getContents());
960   StringRef Data = SectionContents;
961 
962   SmallVector<StringRef, 10> FunctionNames;
963   StringMap<StringRef> FunctionLineTables;
964 
965   ListScope D(W, "CodeViewDebugInfo");
966   // Print the section to allow correlation with printSectionHeaders.
967   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
968 
969   uint32_t Magic;
970   if (Error E = consume(Data, Magic))
971     reportError(std::move(E), Obj->getFileName());
972 
973   W.printHex("Magic", Magic);
974   if (Magic != COFF::DEBUG_SECTION_MAGIC)
975     reportError(errorCodeToError(object_error::parse_failed),
976                 Obj->getFileName());
977 
978   BinaryStreamReader FSReader(Data, support::little);
979   initializeFileAndStringTables(FSReader);
980 
981   // TODO: Convert this over to using ModuleSubstreamVisitor.
982   while (!Data.empty()) {
983     // The section consists of a number of subsection in the following format:
984     // |SubSectionType|SubSectionSize|Contents...|
985     uint32_t SubType, SubSectionSize;
986     if (Error E = consume(Data, SubType))
987       reportError(std::move(E), Obj->getFileName());
988     if (Error E = consume(Data, SubSectionSize))
989       reportError(std::move(E), Obj->getFileName());
990 
991     ListScope S(W, "Subsection");
992     // Dump the subsection as normal even if the ignore bit is set.
993     if (SubType & SubsectionIgnoreFlag) {
994       W.printHex("IgnoredSubsectionKind", SubType);
995       SubType &= ~SubsectionIgnoreFlag;
996     }
997     W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
998     W.printHex("SubSectionSize", SubSectionSize);
999 
1000     // Get the contents of the subsection.
1001     if (SubSectionSize > Data.size())
1002       return reportError(errorCodeToError(object_error::parse_failed),
1003                          Obj->getFileName());
1004     StringRef Contents = Data.substr(0, SubSectionSize);
1005 
1006     // Add SubSectionSize to the current offset and align that offset to find
1007     // the next subsection.
1008     size_t SectionOffset = Data.data() - SectionContents.data();
1009     size_t NextOffset = SectionOffset + SubSectionSize;
1010     NextOffset = alignTo(NextOffset, 4);
1011     if (NextOffset > SectionContents.size())
1012       return reportError(errorCodeToError(object_error::parse_failed),
1013                          Obj->getFileName());
1014     Data = SectionContents.drop_front(NextOffset);
1015 
1016     // Optionally print the subsection bytes in case our parsing gets confused
1017     // later.
1018     if (opts::CodeViewSubsectionBytes)
1019       printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
1020                                  Contents);
1021 
1022     switch (DebugSubsectionKind(SubType)) {
1023     case DebugSubsectionKind::Symbols:
1024       printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
1025       break;
1026 
1027     case DebugSubsectionKind::InlineeLines:
1028       printCodeViewInlineeLines(Contents);
1029       break;
1030 
1031     case DebugSubsectionKind::FileChecksums:
1032       printCodeViewFileChecksums(Contents);
1033       break;
1034 
1035     case DebugSubsectionKind::Lines: {
1036       // Holds a PC to file:line table.  Some data to parse this subsection is
1037       // stored in the other subsections, so just check sanity and store the
1038       // pointers for deferred processing.
1039 
1040       if (SubSectionSize < 12) {
1041         // There should be at least three words to store two function
1042         // relocations and size of the code.
1043         reportError(errorCodeToError(object_error::parse_failed),
1044                     Obj->getFileName());
1045         return;
1046       }
1047 
1048       StringRef LinkageName;
1049       if (std::error_code EC = resolveSymbolName(Obj->getCOFFSection(Section),
1050                                                  SectionOffset, LinkageName))
1051         reportError(errorCodeToError(EC), Obj->getFileName());
1052 
1053       W.printString("LinkageName", LinkageName);
1054       if (FunctionLineTables.count(LinkageName) != 0) {
1055         // Saw debug info for this function already?
1056         reportError(errorCodeToError(object_error::parse_failed),
1057                     Obj->getFileName());
1058         return;
1059       }
1060 
1061       FunctionLineTables[LinkageName] = Contents;
1062       FunctionNames.push_back(LinkageName);
1063       break;
1064     }
1065     case DebugSubsectionKind::FrameData: {
1066       // First four bytes is a relocation against the function.
1067       BinaryStreamReader SR(Contents, llvm::support::little);
1068 
1069       DebugFrameDataSubsectionRef FrameData;
1070       if (Error E = FrameData.initialize(SR))
1071         reportError(std::move(E), Obj->getFileName());
1072 
1073       StringRef LinkageName;
1074       if (std::error_code EC =
1075               resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
1076                                 FrameData.getRelocPtr(), LinkageName))
1077         reportError(errorCodeToError(EC), Obj->getFileName());
1078       W.printString("LinkageName", LinkageName);
1079 
1080       // To find the active frame description, search this array for the
1081       // smallest PC range that includes the current PC.
1082       for (const auto &FD : FrameData) {
1083         StringRef FrameFunc = unwrapOrError(
1084             Obj->getFileName(), CVStringTable.getString(FD.FrameFunc));
1085 
1086         DictScope S(W, "FrameData");
1087         W.printHex("RvaStart", FD.RvaStart);
1088         W.printHex("CodeSize", FD.CodeSize);
1089         W.printHex("LocalSize", FD.LocalSize);
1090         W.printHex("ParamsSize", FD.ParamsSize);
1091         W.printHex("MaxStackSize", FD.MaxStackSize);
1092         W.printHex("PrologSize", FD.PrologSize);
1093         W.printHex("SavedRegsSize", FD.SavedRegsSize);
1094         W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
1095 
1096         // The FrameFunc string is a small RPN program. It can be broken up into
1097         // statements that end in the '=' operator, which assigns the value on
1098         // the top of the stack to the previously pushed variable. Variables can
1099         // be temporary values ($T0) or physical registers ($esp). Print each
1100         // assignment on its own line to make these programs easier to read.
1101         {
1102           ListScope FFS(W, "FrameFunc");
1103           while (!FrameFunc.empty()) {
1104             size_t EqOrEnd = FrameFunc.find('=');
1105             if (EqOrEnd == StringRef::npos)
1106               EqOrEnd = FrameFunc.size();
1107             else
1108               ++EqOrEnd;
1109             StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
1110             W.printString(Stmt);
1111             FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
1112           }
1113         }
1114       }
1115       break;
1116     }
1117 
1118     // Do nothing for unrecognized subsections.
1119     default:
1120       break;
1121     }
1122     W.flush();
1123   }
1124 
1125   // Dump the line tables now that we've read all the subsections and know all
1126   // the required information.
1127   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
1128     StringRef Name = FunctionNames[I];
1129     ListScope S(W, "FunctionLineTable");
1130     W.printString("LinkageName", Name);
1131 
1132     BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
1133 
1134     DebugLinesSubsectionRef LineInfo;
1135     if (Error E = LineInfo.initialize(Reader))
1136       reportError(std::move(E), Obj->getFileName());
1137 
1138     W.printHex("Flags", LineInfo.header()->Flags);
1139     W.printHex("CodeSize", LineInfo.header()->CodeSize);
1140     for (const auto &Entry : LineInfo) {
1141 
1142       ListScope S(W, "FilenameSegment");
1143       printFileNameForOffset("Filename", Entry.NameIndex);
1144       uint32_t ColumnIndex = 0;
1145       for (const auto &Line : Entry.LineNumbers) {
1146         if (Line.Offset >= LineInfo.header()->CodeSize) {
1147           reportError(errorCodeToError(object_error::parse_failed),
1148                       Obj->getFileName());
1149           return;
1150         }
1151 
1152         std::string PC = std::string(formatv("+{0:X}", uint32_t(Line.Offset)));
1153         ListScope PCScope(W, PC);
1154         codeview::LineInfo LI(Line.Flags);
1155 
1156         if (LI.isAlwaysStepInto())
1157           W.printString("StepInto", StringRef("Always"));
1158         else if (LI.isNeverStepInto())
1159           W.printString("StepInto", StringRef("Never"));
1160         else
1161           W.printNumber("LineNumberStart", LI.getStartLine());
1162         W.printNumber("LineNumberEndDelta", LI.getLineDelta());
1163         W.printBoolean("IsStatement", LI.isStatement());
1164         if (LineInfo.hasColumnInfo()) {
1165           W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
1166           W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
1167           ++ColumnIndex;
1168         }
1169       }
1170     }
1171   }
1172 }
1173 
printCodeViewSymbolsSubsection(StringRef Subsection,const SectionRef & Section,StringRef SectionContents)1174 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
1175                                                 const SectionRef &Section,
1176                                                 StringRef SectionContents) {
1177   ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
1178                                Subsection.bytes_end());
1179   auto CODD = std::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
1180                                                         SectionContents);
1181   CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
1182                       CompilationCPUType, opts::CodeViewSubsectionBytes);
1183   CVSymbolArray Symbols;
1184   BinaryStreamReader Reader(BinaryData, llvm::support::little);
1185   if (Error E = Reader.readArray(Symbols, Reader.getLength())) {
1186     W.flush();
1187     reportError(std::move(E), Obj->getFileName());
1188   }
1189 
1190   if (Error E = CVSD.dump(Symbols)) {
1191     W.flush();
1192     reportError(std::move(E), Obj->getFileName());
1193   }
1194   CompilationCPUType = CVSD.getCompilationCPUType();
1195   W.flush();
1196 }
1197 
printCodeViewFileChecksums(StringRef Subsection)1198 void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
1199   BinaryStreamRef Stream(Subsection, llvm::support::little);
1200   DebugChecksumsSubsectionRef Checksums;
1201   if (Error E = Checksums.initialize(Stream))
1202     reportError(std::move(E), Obj->getFileName());
1203 
1204   for (auto &FC : Checksums) {
1205     DictScope S(W, "FileChecksum");
1206 
1207     StringRef Filename = unwrapOrError(
1208         Obj->getFileName(), CVStringTable.getString(FC.FileNameOffset));
1209     W.printHex("Filename", Filename, FC.FileNameOffset);
1210     W.printHex("ChecksumSize", FC.Checksum.size());
1211     W.printEnum("ChecksumKind", uint8_t(FC.Kind),
1212                 makeArrayRef(FileChecksumKindNames));
1213 
1214     W.printBinary("ChecksumBytes", FC.Checksum);
1215   }
1216 }
1217 
printCodeViewInlineeLines(StringRef Subsection)1218 void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
1219   BinaryStreamReader SR(Subsection, llvm::support::little);
1220   DebugInlineeLinesSubsectionRef Lines;
1221   if (Error E = Lines.initialize(SR))
1222     reportError(std::move(E), Obj->getFileName());
1223 
1224   for (auto &Line : Lines) {
1225     DictScope S(W, "InlineeSourceLine");
1226     printTypeIndex("Inlinee", Line.Header->Inlinee);
1227     printFileNameForOffset("FileID", Line.Header->FileID);
1228     W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
1229 
1230     if (Lines.hasExtraFiles()) {
1231       W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
1232       ListScope ExtraFiles(W, "ExtraFiles");
1233       for (const auto &FID : Line.ExtraFiles) {
1234         printFileNameForOffset("FileID", FID);
1235       }
1236     }
1237   }
1238 }
1239 
getFileNameForFileOffset(uint32_t FileOffset)1240 StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
1241   // The file checksum subsection should precede all references to it.
1242   if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
1243     reportError(errorCodeToError(object_error::parse_failed),
1244                 Obj->getFileName());
1245 
1246   auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
1247 
1248   // Check if the file checksum table offset is valid.
1249   if (Iter == CVFileChecksumTable.end())
1250     reportError(errorCodeToError(object_error::parse_failed),
1251                 Obj->getFileName());
1252 
1253   return unwrapOrError(Obj->getFileName(),
1254                        CVStringTable.getString(Iter->FileNameOffset));
1255 }
1256 
printFileNameForOffset(StringRef Label,uint32_t FileOffset)1257 void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
1258   W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
1259 }
1260 
mergeCodeViewTypes(MergingTypeTableBuilder & CVIDs,MergingTypeTableBuilder & CVTypes,GlobalTypeTableBuilder & GlobalCVIDs,GlobalTypeTableBuilder & GlobalCVTypes,bool GHash)1261 void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
1262                                     MergingTypeTableBuilder &CVTypes,
1263                                     GlobalTypeTableBuilder &GlobalCVIDs,
1264                                     GlobalTypeTableBuilder &GlobalCVTypes,
1265                                     bool GHash) {
1266   for (const SectionRef &S : Obj->sections()) {
1267     StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
1268     if (SectionName == ".debug$T") {
1269       StringRef Data = unwrapOrError(Obj->getFileName(), S.getContents());
1270       uint32_t Magic;
1271       if (Error E = consume(Data, Magic))
1272         reportError(std::move(E), Obj->getFileName());
1273 
1274       if (Magic != 4)
1275         reportError(errorCodeToError(object_error::parse_failed),
1276                     Obj->getFileName());
1277 
1278       CVTypeArray Types;
1279       BinaryStreamReader Reader(Data, llvm::support::little);
1280       if (auto EC = Reader.readArray(Types, Reader.getLength())) {
1281         consumeError(std::move(EC));
1282         W.flush();
1283         reportError(errorCodeToError(object_error::parse_failed),
1284                     Obj->getFileName());
1285       }
1286       SmallVector<TypeIndex, 128> SourceToDest;
1287       Optional<uint32_t> PCHSignature;
1288       if (GHash) {
1289         std::vector<GloballyHashedType> Hashes =
1290             GloballyHashedType::hashTypes(Types);
1291         if (Error E =
1292                 mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
1293                                       Types, Hashes, PCHSignature))
1294           return reportError(std::move(E), Obj->getFileName());
1295       } else {
1296         if (Error E = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
1297                                             PCHSignature))
1298           return reportError(std::move(E), Obj->getFileName());
1299       }
1300     }
1301   }
1302 }
1303 
printCodeViewTypeSection(StringRef SectionName,const SectionRef & Section)1304 void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
1305                                           const SectionRef &Section) {
1306   ListScope D(W, "CodeViewTypes");
1307   W.printNumber("Section", SectionName, Obj->getSectionID(Section));
1308 
1309   StringRef Data = unwrapOrError(Obj->getFileName(), Section.getContents());
1310   if (opts::CodeViewSubsectionBytes)
1311     W.printBinaryBlock("Data", Data);
1312 
1313   uint32_t Magic;
1314   if (Error E = consume(Data, Magic))
1315     reportError(std::move(E), Obj->getFileName());
1316 
1317   W.printHex("Magic", Magic);
1318   if (Magic != COFF::DEBUG_SECTION_MAGIC)
1319     reportError(errorCodeToError(object_error::parse_failed),
1320                 Obj->getFileName());
1321 
1322   Types.reset(Data, 100);
1323 
1324   TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
1325   if (Error E = codeview::visitTypeStream(Types, TDV))
1326     reportError(std::move(E), Obj->getFileName());
1327 
1328   W.flush();
1329 }
1330 
printSectionHeaders()1331 void COFFDumper::printSectionHeaders() {
1332   ListScope SectionsD(W, "Sections");
1333   int SectionNumber = 0;
1334   for (const SectionRef &Sec : Obj->sections()) {
1335     ++SectionNumber;
1336     const coff_section *Section = Obj->getCOFFSection(Sec);
1337 
1338     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
1339 
1340     DictScope D(W, "Section");
1341     W.printNumber("Number", SectionNumber);
1342     W.printBinary("Name", Name, Section->Name);
1343     W.printHex   ("VirtualSize", Section->VirtualSize);
1344     W.printHex   ("VirtualAddress", Section->VirtualAddress);
1345     W.printNumber("RawDataSize", Section->SizeOfRawData);
1346     W.printHex   ("PointerToRawData", Section->PointerToRawData);
1347     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
1348     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
1349     W.printNumber("RelocationCount", Section->NumberOfRelocations);
1350     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
1351     W.printFlags ("Characteristics", Section->Characteristics,
1352                     makeArrayRef(ImageSectionCharacteristics),
1353                     COFF::SectionCharacteristics(0x00F00000));
1354 
1355     if (opts::SectionRelocations) {
1356       ListScope D(W, "Relocations");
1357       for (const RelocationRef &Reloc : Sec.relocations())
1358         printRelocation(Sec, Reloc);
1359     }
1360 
1361     if (opts::SectionSymbols) {
1362       ListScope D(W, "Symbols");
1363       for (const SymbolRef &Symbol : Obj->symbols()) {
1364         if (!Sec.containsSymbol(Symbol))
1365           continue;
1366 
1367         printSymbol(Symbol);
1368       }
1369     }
1370 
1371     if (opts::SectionData &&
1372         !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1373       StringRef Data = unwrapOrError(Obj->getFileName(), Sec.getContents());
1374       W.printBinaryBlock("SectionData", Data);
1375     }
1376   }
1377 }
1378 
printRelocations()1379 void COFFDumper::printRelocations() {
1380   ListScope D(W, "Relocations");
1381 
1382   int SectionNumber = 0;
1383   for (const SectionRef &Section : Obj->sections()) {
1384     ++SectionNumber;
1385     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1386 
1387     bool PrintedGroup = false;
1388     for (const RelocationRef &Reloc : Section.relocations()) {
1389       if (!PrintedGroup) {
1390         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
1391         W.indent();
1392         PrintedGroup = true;
1393       }
1394 
1395       printRelocation(Section, Reloc);
1396     }
1397 
1398     if (PrintedGroup) {
1399       W.unindent();
1400       W.startLine() << "}\n";
1401     }
1402   }
1403 }
1404 
printRelocation(const SectionRef & Section,const RelocationRef & Reloc,uint64_t Bias)1405 void COFFDumper::printRelocation(const SectionRef &Section,
1406                                  const RelocationRef &Reloc, uint64_t Bias) {
1407   uint64_t Offset = Reloc.getOffset() - Bias;
1408   uint64_t RelocType = Reloc.getType();
1409   SmallString<32> RelocName;
1410   StringRef SymbolName;
1411   Reloc.getTypeName(RelocName);
1412   symbol_iterator Symbol = Reloc.getSymbol();
1413   int64_t SymbolIndex = -1;
1414   if (Symbol != Obj->symbol_end()) {
1415     Expected<StringRef> SymbolNameOrErr = Symbol->getName();
1416     if (!SymbolNameOrErr)
1417       reportError(SymbolNameOrErr.takeError(), Obj->getFileName());
1418 
1419     SymbolName = *SymbolNameOrErr;
1420     SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
1421   }
1422 
1423   if (opts::ExpandRelocs) {
1424     DictScope Group(W, "Relocation");
1425     W.printHex("Offset", Offset);
1426     W.printNumber("Type", RelocName, RelocType);
1427     W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
1428     W.printNumber("SymbolIndex", SymbolIndex);
1429   } else {
1430     raw_ostream& OS = W.startLine();
1431     OS << W.hex(Offset)
1432        << " " << RelocName
1433        << " " << (SymbolName.empty() ? "-" : SymbolName)
1434        << " (" << SymbolIndex << ")"
1435        << "\n";
1436   }
1437 }
1438 
printSymbols()1439 void COFFDumper::printSymbols() {
1440   ListScope Group(W, "Symbols");
1441 
1442   for (const SymbolRef &Symbol : Obj->symbols())
1443     printSymbol(Symbol);
1444 }
1445 
printDynamicSymbols()1446 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
1447 
1448 static Expected<StringRef>
getSectionName(const llvm::object::COFFObjectFile * Obj,int32_t SectionNumber,const coff_section * Section)1449 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
1450                const coff_section *Section) {
1451   if (Section)
1452     return Obj->getSectionName(Section);
1453   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
1454     return StringRef("IMAGE_SYM_DEBUG");
1455   if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
1456     return StringRef("IMAGE_SYM_ABSOLUTE");
1457   if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
1458     return StringRef("IMAGE_SYM_UNDEFINED");
1459   return StringRef("");
1460 }
1461 
printSymbol(const SymbolRef & Sym)1462 void COFFDumper::printSymbol(const SymbolRef &Sym) {
1463   DictScope D(W, "Symbol");
1464 
1465   COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
1466   Expected<const coff_section *> SecOrErr =
1467       Obj->getSection(Symbol.getSectionNumber());
1468   if (!SecOrErr) {
1469     W.startLine() << "Invalid section number: " << Symbol.getSectionNumber()
1470                   << "\n";
1471     W.flush();
1472     consumeError(SecOrErr.takeError());
1473     return;
1474   }
1475   const coff_section *Section = *SecOrErr;
1476 
1477   StringRef SymbolName;
1478   if (Expected<StringRef> SymNameOrErr = Obj->getSymbolName(Symbol))
1479     SymbolName = *SymNameOrErr;
1480 
1481   StringRef SectionName;
1482   if (Expected<StringRef> SecNameOrErr =
1483           getSectionName(Obj, Symbol.getSectionNumber(), Section))
1484     SectionName = *SecNameOrErr;
1485 
1486   W.printString("Name", SymbolName);
1487   W.printNumber("Value", Symbol.getValue());
1488   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
1489   W.printEnum  ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
1490   W.printEnum  ("ComplexType", Symbol.getComplexType(),
1491                                                    makeArrayRef(ImageSymDType));
1492   W.printEnum  ("StorageClass", Symbol.getStorageClass(),
1493                                                    makeArrayRef(ImageSymClass));
1494   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
1495 
1496   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
1497     if (Symbol.isFunctionDefinition()) {
1498       const coff_aux_function_definition *Aux;
1499       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1500         reportError(errorCodeToError(EC), Obj->getFileName());
1501 
1502       DictScope AS(W, "AuxFunctionDef");
1503       W.printNumber("TagIndex", Aux->TagIndex);
1504       W.printNumber("TotalSize", Aux->TotalSize);
1505       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
1506       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
1507 
1508     } else if (Symbol.isAnyUndefined()) {
1509       const coff_aux_weak_external *Aux;
1510       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1511         reportError(errorCodeToError(EC), Obj->getFileName());
1512 
1513       DictScope AS(W, "AuxWeakExternal");
1514       W.printNumber("Linked", getSymbolName(Aux->TagIndex), Aux->TagIndex);
1515       W.printEnum  ("Search", Aux->Characteristics,
1516                     makeArrayRef(WeakExternalCharacteristics));
1517 
1518     } else if (Symbol.isFileRecord()) {
1519       const char *FileName;
1520       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, FileName))
1521         reportError(errorCodeToError(EC), Obj->getFileName());
1522       DictScope AS(W, "AuxFileRecord");
1523 
1524       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
1525                                    Obj->getSymbolTableEntrySize());
1526       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
1527       break;
1528     } else if (Symbol.isSectionDefinition()) {
1529       const coff_aux_section_definition *Aux;
1530       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1531         reportError(errorCodeToError(EC), Obj->getFileName());
1532 
1533       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
1534 
1535       DictScope AS(W, "AuxSectionDef");
1536       W.printNumber("Length", Aux->Length);
1537       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
1538       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
1539       W.printHex("Checksum", Aux->CheckSum);
1540       W.printNumber("Number", AuxNumber);
1541       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
1542 
1543       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
1544           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
1545         Expected<const coff_section *> Assoc = Obj->getSection(AuxNumber);
1546         if (!Assoc)
1547           reportError(Assoc.takeError(), Obj->getFileName());
1548         Expected<StringRef> AssocName = getSectionName(Obj, AuxNumber, *Assoc);
1549         if (!AssocName)
1550           reportError(AssocName.takeError(), Obj->getFileName());
1551 
1552         W.printNumber("AssocSection", *AssocName, AuxNumber);
1553       }
1554     } else if (Symbol.isCLRToken()) {
1555       const coff_aux_clr_token *Aux;
1556       if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
1557         reportError(errorCodeToError(EC), Obj->getFileName());
1558 
1559       DictScope AS(W, "AuxCLRToken");
1560       W.printNumber("AuxType", Aux->AuxType);
1561       W.printNumber("Reserved", Aux->Reserved);
1562       W.printNumber("SymbolTableIndex", getSymbolName(Aux->SymbolTableIndex),
1563                     Aux->SymbolTableIndex);
1564 
1565     } else {
1566       W.startLine() << "<unhandled auxiliary record>\n";
1567     }
1568   }
1569 }
1570 
printUnwindInfo()1571 void COFFDumper::printUnwindInfo() {
1572   ListScope D(W, "UnwindInformation");
1573   switch (Obj->getMachine()) {
1574   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1575     Win64EH::Dumper Dumper(W);
1576     Win64EH::Dumper::SymbolResolver
1577     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1578                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1579       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1580       return Dumper->resolveSymbol(Section, Offset, Symbol);
1581     };
1582     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1583     Dumper.printData(Ctx);
1584     break;
1585   }
1586   case COFF::IMAGE_FILE_MACHINE_ARM64:
1587   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1588     ARM::WinEH::Decoder Decoder(W, Obj->getMachine() ==
1589                                        COFF::IMAGE_FILE_MACHINE_ARM64);
1590     // TODO Propagate the error.
1591     consumeError(Decoder.dumpProcedureData(*Obj));
1592     break;
1593   }
1594   default:
1595     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1596                 makeArrayRef(ImageFileMachineType));
1597     break;
1598   }
1599 }
1600 
printNeededLibraries()1601 void COFFDumper::printNeededLibraries() {
1602   ListScope D(W, "NeededLibraries");
1603 
1604   using LibsTy = std::vector<StringRef>;
1605   LibsTy Libs;
1606 
1607   for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
1608     StringRef Name;
1609     if (!DirRef.getName(Name))
1610       Libs.push_back(Name);
1611   }
1612 
1613   llvm::stable_sort(Libs);
1614 
1615   for (const auto &L : Libs) {
1616     W.startLine() << L << "\n";
1617   }
1618 }
1619 
printImportedSymbols(iterator_range<imported_symbol_iterator> Range)1620 void COFFDumper::printImportedSymbols(
1621     iterator_range<imported_symbol_iterator> Range) {
1622   for (const ImportedSymbolRef &I : Range) {
1623     StringRef Sym;
1624     if (Error E = I.getSymbolName(Sym))
1625       reportError(std::move(E), Obj->getFileName());
1626     uint16_t Ordinal;
1627     if (Error E = I.getOrdinal(Ordinal))
1628       reportError(std::move(E), Obj->getFileName());
1629     W.printNumber("Symbol", Sym, Ordinal);
1630   }
1631 }
1632 
printDelayImportedSymbols(const DelayImportDirectoryEntryRef & I,iterator_range<imported_symbol_iterator> Range)1633 void COFFDumper::printDelayImportedSymbols(
1634     const DelayImportDirectoryEntryRef &I,
1635     iterator_range<imported_symbol_iterator> Range) {
1636   int Index = 0;
1637   for (const ImportedSymbolRef &S : Range) {
1638     DictScope Import(W, "Import");
1639     StringRef Sym;
1640     if (Error E = S.getSymbolName(Sym))
1641       reportError(std::move(E), Obj->getFileName());
1642 
1643     uint16_t Ordinal;
1644     if (Error E = S.getOrdinal(Ordinal))
1645       reportError(std::move(E), Obj->getFileName());
1646     W.printNumber("Symbol", Sym, Ordinal);
1647 
1648     uint64_t Addr;
1649     if (Error E = I.getImportAddress(Index++, Addr))
1650       reportError(std::move(E), Obj->getFileName());
1651     W.printHex("Address", Addr);
1652   }
1653 }
1654 
printCOFFImports()1655 void COFFDumper::printCOFFImports() {
1656   // Regular imports
1657   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1658     DictScope Import(W, "Import");
1659     StringRef Name;
1660     if (Error E = I.getName(Name))
1661       reportError(std::move(E), Obj->getFileName());
1662     W.printString("Name", Name);
1663     uint32_t ILTAddr;
1664     if (Error E = I.getImportLookupTableRVA(ILTAddr))
1665       reportError(std::move(E), Obj->getFileName());
1666     W.printHex("ImportLookupTableRVA", ILTAddr);
1667     uint32_t IATAddr;
1668     if (Error E = I.getImportAddressTableRVA(IATAddr))
1669       reportError(std::move(E), Obj->getFileName());
1670     W.printHex("ImportAddressTableRVA", IATAddr);
1671     // The import lookup table can be missing with certain older linkers, so
1672     // fall back to the import address table in that case.
1673     if (ILTAddr)
1674       printImportedSymbols(I.lookup_table_symbols());
1675     else
1676       printImportedSymbols(I.imported_symbols());
1677   }
1678 
1679   // Delay imports
1680   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1681     DictScope Import(W, "DelayImport");
1682     StringRef Name;
1683     if (Error E = I.getName(Name))
1684       reportError(std::move(E), Obj->getFileName());
1685     W.printString("Name", Name);
1686     const delay_import_directory_table_entry *Table;
1687     if (Error E = I.getDelayImportTable(Table))
1688       reportError(std::move(E), Obj->getFileName());
1689     W.printHex("Attributes", Table->Attributes);
1690     W.printHex("ModuleHandle", Table->ModuleHandle);
1691     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1692     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1693     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1694     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1695     printDelayImportedSymbols(I, I.imported_symbols());
1696   }
1697 }
1698 
printCOFFExports()1699 void COFFDumper::printCOFFExports() {
1700   for (const ExportDirectoryEntryRef &Exp : Obj->export_directories()) {
1701     DictScope Export(W, "Export");
1702 
1703     StringRef Name;
1704     uint32_t Ordinal, RVA;
1705 
1706     if (Error E = Exp.getSymbolName(Name))
1707       reportError(std::move(E), Obj->getFileName());
1708     if (Error E = Exp.getOrdinal(Ordinal))
1709       reportError(std::move(E), Obj->getFileName());
1710     if (Error E = Exp.getExportRVA(RVA))
1711       reportError(std::move(E), Obj->getFileName());
1712 
1713     W.printNumber("Ordinal", Ordinal);
1714     W.printString("Name", Name);
1715     W.printHex("RVA", RVA);
1716   }
1717 }
1718 
printCOFFDirectives()1719 void COFFDumper::printCOFFDirectives() {
1720   for (const SectionRef &Section : Obj->sections()) {
1721     StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
1722     if (Name != ".drectve")
1723       continue;
1724 
1725     StringRef Contents =
1726         unwrapOrError(Obj->getFileName(), Section.getContents());
1727     W.printString("Directive(s)", Contents);
1728   }
1729 }
1730 
getBaseRelocTypeName(uint8_t Type)1731 static std::string getBaseRelocTypeName(uint8_t Type) {
1732   switch (Type) {
1733   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1734   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1735   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1736   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1737   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1738   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1739   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1740   default: return "unknown (" + llvm::utostr(Type) + ")";
1741   }
1742 }
1743 
printCOFFBaseReloc()1744 void COFFDumper::printCOFFBaseReloc() {
1745   ListScope D(W, "BaseReloc");
1746   for (const BaseRelocRef &I : Obj->base_relocs()) {
1747     uint8_t Type;
1748     uint32_t RVA;
1749     if (Error E = I.getRVA(RVA))
1750       reportError(std::move(E), Obj->getFileName());
1751     if (Error E = I.getType(Type))
1752       reportError(std::move(E), Obj->getFileName());
1753     DictScope Import(W, "Entry");
1754     W.printString("Type", getBaseRelocTypeName(Type));
1755     W.printHex("Address", RVA);
1756   }
1757 }
1758 
printCOFFResources()1759 void COFFDumper::printCOFFResources() {
1760   ListScope ResourcesD(W, "Resources");
1761   for (const SectionRef &S : Obj->sections()) {
1762     StringRef Name = unwrapOrError(Obj->getFileName(), S.getName());
1763     if (!Name.startswith(".rsrc"))
1764       continue;
1765 
1766     StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
1767 
1768     if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
1769       ResourceSectionRef RSF;
1770       Error E = RSF.load(Obj, S);
1771       if (E)
1772         reportError(std::move(E), Obj->getFileName());
1773       auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
1774       W.printNumber("Total Number of Resources",
1775                     countTotalTableEntries(RSF, BaseTable, "Type"));
1776       W.printHex("Base Table Address",
1777                  Obj->getCOFFSection(S)->PointerToRawData);
1778       W.startLine() << "\n";
1779       printResourceDirectoryTable(RSF, BaseTable, "Type");
1780     }
1781     if (opts::SectionData)
1782       W.printBinaryBlock(Name.str() + " Data", Ref);
1783   }
1784 }
1785 
1786 uint32_t
countTotalTableEntries(ResourceSectionRef RSF,const coff_resource_dir_table & Table,StringRef Level)1787 COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
1788                                    const coff_resource_dir_table &Table,
1789                                    StringRef Level) {
1790   uint32_t TotalEntries = 0;
1791   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1792        i++) {
1793     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1794     if (Entry.Offset.isSubDir()) {
1795       StringRef NextLevel;
1796       if (Level == "Name")
1797         NextLevel = "Language";
1798       else
1799         NextLevel = "Name";
1800       auto &NextTable =
1801           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1802       TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
1803     } else {
1804       TotalEntries += 1;
1805     }
1806   }
1807   return TotalEntries;
1808 }
1809 
printResourceDirectoryTable(ResourceSectionRef RSF,const coff_resource_dir_table & Table,StringRef Level)1810 void COFFDumper::printResourceDirectoryTable(
1811     ResourceSectionRef RSF, const coff_resource_dir_table &Table,
1812     StringRef Level) {
1813 
1814   W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
1815   W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
1816 
1817   // Iterate through level in resource directory tree.
1818   for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
1819        i++) {
1820     auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
1821     StringRef Name;
1822     SmallString<20> IDStr;
1823     raw_svector_ostream OS(IDStr);
1824     if (i < Table.NumberOfNameEntries) {
1825       ArrayRef<UTF16> RawEntryNameString =
1826           unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
1827       std::vector<UTF16> EndianCorrectedNameString;
1828       if (llvm::sys::IsBigEndianHost) {
1829         EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
1830         std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
1831                   EndianCorrectedNameString.begin() + 1);
1832         EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
1833         RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
1834       }
1835       std::string EntryNameString;
1836       if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
1837         reportError(errorCodeToError(object_error::parse_failed),
1838                     Obj->getFileName());
1839       OS << ": ";
1840       OS << EntryNameString;
1841     } else {
1842       if (Level == "Type") {
1843         OS << ": ";
1844         printResourceTypeName(Entry.Identifier.ID, OS);
1845       } else {
1846         OS << ": (ID " << Entry.Identifier.ID << ")";
1847       }
1848     }
1849     Name = StringRef(IDStr);
1850     ListScope ResourceType(W, Level.str() + Name.str());
1851     if (Entry.Offset.isSubDir()) {
1852       W.printHex("Table Offset", Entry.Offset.value());
1853       StringRef NextLevel;
1854       if (Level == "Name")
1855         NextLevel = "Language";
1856       else
1857         NextLevel = "Name";
1858       auto &NextTable =
1859           unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
1860       printResourceDirectoryTable(RSF, NextTable, NextLevel);
1861     } else {
1862       W.printHex("Entry Offset", Entry.Offset.value());
1863       char FormattedTime[20] = {};
1864       time_t TDS = time_t(Table.TimeDateStamp);
1865       strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
1866       W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
1867       W.printNumber("Major Version", Table.MajorVersion);
1868       W.printNumber("Minor Version", Table.MinorVersion);
1869       W.printNumber("Characteristics", Table.Characteristics);
1870       ListScope DataScope(W, "Data");
1871       auto &DataEntry =
1872           unwrapOrError(Obj->getFileName(), RSF.getEntryData(Entry));
1873       W.printHex("DataRVA", DataEntry.DataRVA);
1874       W.printNumber("DataSize", DataEntry.DataSize);
1875       W.printNumber("Codepage", DataEntry.Codepage);
1876       W.printNumber("Reserved", DataEntry.Reserved);
1877       StringRef Contents =
1878           unwrapOrError(Obj->getFileName(), RSF.getContents(DataEntry));
1879       W.printBinaryBlock("Data", Contents);
1880     }
1881   }
1882 }
1883 
printStackMap() const1884 void COFFDumper::printStackMap() const {
1885   SectionRef StackMapSection;
1886   for (auto Sec : Obj->sections()) {
1887     StringRef Name;
1888     if (Expected<StringRef> NameOrErr = Sec.getName())
1889       Name = *NameOrErr;
1890     else
1891       consumeError(NameOrErr.takeError());
1892 
1893     if (Name == ".llvm_stackmaps") {
1894       StackMapSection = Sec;
1895       break;
1896     }
1897   }
1898 
1899   if (StackMapSection == SectionRef())
1900     return;
1901 
1902   StringRef StackMapContents =
1903       unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
1904   ArrayRef<uint8_t> StackMapContentsArray =
1905       arrayRefFromStringRef(StackMapContents);
1906 
1907   if (Obj->isLittleEndian())
1908     prettyPrintStackMap(
1909         W, StackMapParser<support::little>(StackMapContentsArray));
1910   else
1911     prettyPrintStackMap(
1912         W, StackMapParser<support::big>(StackMapContentsArray));
1913 }
1914 
printAddrsig()1915 void COFFDumper::printAddrsig() {
1916   SectionRef AddrsigSection;
1917   for (auto Sec : Obj->sections()) {
1918     StringRef Name;
1919     if (Expected<StringRef> NameOrErr = Sec.getName())
1920       Name = *NameOrErr;
1921     else
1922       consumeError(NameOrErr.takeError());
1923 
1924     if (Name == ".llvm_addrsig") {
1925       AddrsigSection = Sec;
1926       break;
1927     }
1928   }
1929 
1930   if (AddrsigSection == SectionRef())
1931     return;
1932 
1933   StringRef AddrsigContents =
1934       unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
1935   ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
1936                                          AddrsigContents.size());
1937 
1938   ListScope L(W, "Addrsig");
1939   const uint8_t *Cur = AddrsigContents.bytes_begin();
1940   const uint8_t *End = AddrsigContents.bytes_end();
1941   while (Cur != End) {
1942     unsigned Size;
1943     const char *Err;
1944     uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
1945     if (Err)
1946       reportError(createError(Err), Obj->getFileName());
1947 
1948     W.printNumber("Sym", getSymbolName(SymIndex), SymIndex);
1949     Cur += Size;
1950   }
1951 }
1952 
printCGProfile()1953 void COFFDumper::printCGProfile() {
1954   SectionRef CGProfileSection;
1955   for (SectionRef Sec : Obj->sections()) {
1956     StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
1957     if (Name == ".llvm.call-graph-profile") {
1958       CGProfileSection = Sec;
1959       break;
1960     }
1961   }
1962 
1963   if (CGProfileSection == SectionRef())
1964     return;
1965 
1966   StringRef CGProfileContents =
1967       unwrapOrError(Obj->getFileName(), CGProfileSection.getContents());
1968   BinaryStreamReader Reader(CGProfileContents, llvm::support::little);
1969 
1970   ListScope L(W, "CGProfile");
1971   while (!Reader.empty()) {
1972     uint32_t FromIndex, ToIndex;
1973     uint64_t Count;
1974     if (Error Err = Reader.readInteger(FromIndex))
1975       reportError(std::move(Err), Obj->getFileName());
1976     if (Error Err = Reader.readInteger(ToIndex))
1977       reportError(std::move(Err), Obj->getFileName());
1978     if (Error Err = Reader.readInteger(Count))
1979       reportError(std::move(Err), Obj->getFileName());
1980 
1981     DictScope D(W, "CGProfileEntry");
1982     W.printNumber("From", getSymbolName(FromIndex), FromIndex);
1983     W.printNumber("To", getSymbolName(ToIndex), ToIndex);
1984     W.printNumber("Weight", Count);
1985   }
1986 }
1987 
getSymbolName(uint32_t Index)1988 StringRef COFFDumper::getSymbolName(uint32_t Index) {
1989   Expected<COFFSymbolRef> Sym = Obj->getSymbol(Index);
1990   if (!Sym)
1991     reportError(Sym.takeError(), Obj->getFileName());
1992 
1993   Expected<StringRef> SymName = Obj->getSymbolName(*Sym);
1994   if (!SymName)
1995     reportError(SymName.takeError(), Obj->getFileName());
1996 
1997   return *SymName;
1998 }
1999 
dumpCodeViewMergedTypes(ScopedPrinter & Writer,ArrayRef<ArrayRef<uint8_t>> IpiRecords,ArrayRef<ArrayRef<uint8_t>> TpiRecords)2000 void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
2001                                    ArrayRef<ArrayRef<uint8_t>> IpiRecords,
2002                                    ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
2003   TypeTableCollection TpiTypes(TpiRecords);
2004   {
2005     ListScope S(Writer, "MergedTypeStream");
2006     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2007     if (Error Err = codeview::visitTypeStream(TpiTypes, TDV))
2008       reportError(std::move(Err), "<?>");
2009     Writer.flush();
2010   }
2011 
2012   // Flatten the id stream and print it next. The ID stream refers to names from
2013   // the type stream.
2014   TypeTableCollection IpiTypes(IpiRecords);
2015   {
2016     ListScope S(Writer, "MergedIDStream");
2017     TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
2018     TDV.setIpiTypes(IpiTypes);
2019     if (Error Err = codeview::visitTypeStream(IpiTypes, TDV))
2020       reportError(std::move(Err), "<?>");
2021     Writer.flush();
2022   }
2023 }
2024 
printCOFFTLSDirectory()2025 void COFFDumper::printCOFFTLSDirectory() {
2026   if (Obj->is64())
2027     printCOFFTLSDirectory(Obj->getTLSDirectory64());
2028   else
2029     printCOFFTLSDirectory(Obj->getTLSDirectory32());
2030 }
2031 
2032 template <typename IntTy>
printCOFFTLSDirectory(const coff_tls_directory<IntTy> * TlsTable)2033 void COFFDumper::printCOFFTLSDirectory(
2034     const coff_tls_directory<IntTy> *TlsTable) {
2035   DictScope D(W, "TLSDirectory");
2036   if (!TlsTable)
2037     return;
2038 
2039   W.printHex("StartAddressOfRawData", TlsTable->StartAddressOfRawData);
2040   W.printHex("EndAddressOfRawData", TlsTable->EndAddressOfRawData);
2041   W.printHex("AddressOfIndex", TlsTable->AddressOfIndex);
2042   W.printHex("AddressOfCallBacks", TlsTable->AddressOfCallBacks);
2043   W.printHex("SizeOfZeroFill", TlsTable->SizeOfZeroFill);
2044   W.printFlags("Characteristics", TlsTable->Characteristics,
2045                makeArrayRef(ImageSectionCharacteristics),
2046                COFF::SectionCharacteristics(COFF::IMAGE_SCN_ALIGN_MASK));
2047 }
2048