llvm-readobj: Fix an unused variable after r241764
[oota-llvm.git] / tools / llvm-readobj / COFFDumper.cpp
1 //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements the COFF-specific dumper for llvm-readobj.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm-readobj.h"
16 #include "ARMWinEHPrinter.h"
17 #include "Error.h"
18 #include "ObjDumper.h"
19 #include "StackMapPrinter.h"
20 #include "StreamWriter.h"
21 #include "Win64EHDumper.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Object/COFF.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Support/COFF.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/DataExtractor.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/Win64EH.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cstring>
37 #include <system_error>
38 #include <time.h>
39
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::Win64EH;
43
44 namespace {
45
46 class COFFDumper : public ObjDumper {
47 public:
48   COFFDumper(const llvm::object::COFFObjectFile *Obj, StreamWriter& Writer)
49     : ObjDumper(Writer)
50     , Obj(Obj) {
51   }
52
53   void printFileHeaders() override;
54   void printSections() override;
55   void printRelocations() override;
56   void printSymbols() override;
57   void printDynamicSymbols() override;
58   void printUnwindInfo() override;
59   void printCOFFImports() override;
60   void printCOFFExports() override;
61   void printCOFFDirectives() override;
62   void printCOFFBaseReloc() override;
63   void printStackMap() const override;
64 private:
65   void printSymbol(const SymbolRef &Sym);
66   void printRelocation(const SectionRef &Section, const RelocationRef &Reloc);
67   void printDataDirectory(uint32_t Index, const std::string &FieldName);
68
69   void printDOSHeader(const dos_header *DH);
70   template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
71   void printBaseOfDataField(const pe32_header *Hdr);
72   void printBaseOfDataField(const pe32plus_header *Hdr);
73
74   void printCodeViewDebugInfo(const SectionRef &Section);
75
76   void printCodeViewSymbolsSubsection(StringRef Subsection,
77                                       const SectionRef &Section,
78                                       uint32_t Offset);
79
80   void cacheRelocations();
81
82   std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
83                                 SymbolRef &Sym);
84   std::error_code resolveSymbolName(const coff_section *Section,
85                                     uint64_t Offset, StringRef &Name);
86   void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
87   void printDelayImportedSymbols(
88       const DelayImportDirectoryEntryRef &I,
89       iterator_range<imported_symbol_iterator> Range);
90
91   typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
92
93   const llvm::object::COFFObjectFile *Obj;
94   bool RelocCached = false;
95   RelocMapTy RelocMap;
96   StringRef CVFileIndexToStringOffsetTable;
97   StringRef CVStringTable;
98 };
99
100 } // namespace
101
102
103 namespace llvm {
104
105 std::error_code createCOFFDumper(const object::ObjectFile *Obj,
106                                  StreamWriter &Writer,
107                                  std::unique_ptr<ObjDumper> &Result) {
108   const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Obj);
109   if (!COFFObj)
110     return readobj_error::unsupported_obj_file_format;
111
112   Result.reset(new COFFDumper(COFFObj, Writer));
113   return readobj_error::success;
114 }
115
116 } // namespace llvm
117
118 // Given a a section and an offset into this section the function returns the
119 // symbol used for the relocation at the offset.
120 std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
121                                           uint64_t Offset, SymbolRef &Sym) {
122   cacheRelocations();
123   const auto &Relocations = RelocMap[Section];
124   for (const auto &Relocation : Relocations) {
125     uint64_t RelocationOffset = Relocation.getOffset();
126
127     if (RelocationOffset == Offset) {
128       Sym = *Relocation.getSymbol();
129       return readobj_error::success;
130     }
131   }
132   return readobj_error::unknown_symbol;
133 }
134
135 // Given a section and an offset into this section the function returns the name
136 // of the symbol used for the relocation at the offset.
137 std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
138                                               uint64_t Offset,
139                                               StringRef &Name) {
140   SymbolRef Symbol;
141   if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
142     return EC;
143   ErrorOr<StringRef> NameOrErr = Symbol.getName();
144   if (std::error_code EC = NameOrErr.getError())
145     return EC;
146   Name = *NameOrErr;
147   return std::error_code();
148 }
149
150 static const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
151   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN  ),
152   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33     ),
153   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64    ),
154   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM      ),
155   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT    ),
156   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC      ),
157   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386     ),
158   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64     ),
159   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R     ),
160   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16   ),
161   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU  ),
162   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
163   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC  ),
164   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
165   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000    ),
166   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3      ),
167   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP   ),
168   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4      ),
169   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5      ),
170   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB    ),
171   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
172 };
173
174 static const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
175   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED        ),
176   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE       ),
177   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED     ),
178   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED    ),
179   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM     ),
180   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE    ),
181   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO      ),
182   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE          ),
183   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED         ),
184   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
185   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP      ),
186   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM                 ),
187   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL                    ),
188   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY         ),
189   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI      )
190 };
191
192 static const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
193   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN                ),
194   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE                 ),
195   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI            ),
196   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI            ),
197   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI              ),
198   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI         ),
199   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION        ),
200   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
201   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER     ),
202   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM                ),
203   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX                   ),
204 };
205
206 static const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
207   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA      ),
208   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE         ),
209   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY      ),
210   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT            ),
211   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION         ),
212   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH               ),
213   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND              ),
214   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER         ),
215   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER           ),
216   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF             ),
217   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
218 };
219
220 static const EnumEntry<COFF::SectionCharacteristics>
221 ImageSectionCharacteristics[] = {
222   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD           ),
223   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE              ),
224   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA  ),
225   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
226   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER             ),
227   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO              ),
228   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE            ),
229   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT            ),
230   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL                 ),
231   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE         ),
232   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT             ),
233   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED            ),
234   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD           ),
235   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES          ),
236   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES          ),
237   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES          ),
238   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES          ),
239   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES         ),
240   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES         ),
241   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES         ),
242   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES        ),
243   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES        ),
244   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES        ),
245   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES       ),
246   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES       ),
247   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES       ),
248   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES       ),
249   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL       ),
250   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE       ),
251   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED        ),
252   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED         ),
253   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED            ),
254   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE           ),
255   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ              ),
256   LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE             )
257 };
258
259 static const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
260   { "Null"  , COFF::IMAGE_SYM_TYPE_NULL   },
261   { "Void"  , COFF::IMAGE_SYM_TYPE_VOID   },
262   { "Char"  , COFF::IMAGE_SYM_TYPE_CHAR   },
263   { "Short" , COFF::IMAGE_SYM_TYPE_SHORT  },
264   { "Int"   , COFF::IMAGE_SYM_TYPE_INT    },
265   { "Long"  , COFF::IMAGE_SYM_TYPE_LONG   },
266   { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT  },
267   { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
268   { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
269   { "Union" , COFF::IMAGE_SYM_TYPE_UNION  },
270   { "Enum"  , COFF::IMAGE_SYM_TYPE_ENUM   },
271   { "MOE"   , COFF::IMAGE_SYM_TYPE_MOE    },
272   { "Byte"  , COFF::IMAGE_SYM_TYPE_BYTE   },
273   { "Word"  , COFF::IMAGE_SYM_TYPE_WORD   },
274   { "UInt"  , COFF::IMAGE_SYM_TYPE_UINT   },
275   { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD  }
276 };
277
278 static const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
279   { "Null"    , COFF::IMAGE_SYM_DTYPE_NULL     },
280   { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER  },
281   { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
282   { "Array"   , COFF::IMAGE_SYM_DTYPE_ARRAY    }
283 };
284
285 static const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
286   { "EndOfFunction"  , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION  },
287   { "Null"           , COFF::IMAGE_SYM_CLASS_NULL             },
288   { "Automatic"      , COFF::IMAGE_SYM_CLASS_AUTOMATIC        },
289   { "External"       , COFF::IMAGE_SYM_CLASS_EXTERNAL         },
290   { "Static"         , COFF::IMAGE_SYM_CLASS_STATIC           },
291   { "Register"       , COFF::IMAGE_SYM_CLASS_REGISTER         },
292   { "ExternalDef"    , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF     },
293   { "Label"          , COFF::IMAGE_SYM_CLASS_LABEL            },
294   { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL  },
295   { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
296   { "Argument"       , COFF::IMAGE_SYM_CLASS_ARGUMENT         },
297   { "StructTag"      , COFF::IMAGE_SYM_CLASS_STRUCT_TAG       },
298   { "MemberOfUnion"  , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION  },
299   { "UnionTag"       , COFF::IMAGE_SYM_CLASS_UNION_TAG        },
300   { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION  },
301   { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
302   { "EnumTag"        , COFF::IMAGE_SYM_CLASS_ENUM_TAG         },
303   { "MemberOfEnum"   , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM   },
304   { "RegisterParam"  , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM   },
305   { "BitField"       , COFF::IMAGE_SYM_CLASS_BIT_FIELD        },
306   { "Block"          , COFF::IMAGE_SYM_CLASS_BLOCK            },
307   { "Function"       , COFF::IMAGE_SYM_CLASS_FUNCTION         },
308   { "EndOfStruct"    , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT    },
309   { "File"           , COFF::IMAGE_SYM_CLASS_FILE             },
310   { "Section"        , COFF::IMAGE_SYM_CLASS_SECTION          },
311   { "WeakExternal"   , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL    },
312   { "CLRToken"       , COFF::IMAGE_SYM_CLASS_CLR_TOKEN        }
313 };
314
315 static const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
316   { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
317   { "Any"         , COFF::IMAGE_COMDAT_SELECT_ANY          },
318   { "SameSize"    , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE    },
319   { "ExactMatch"  , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH  },
320   { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE  },
321   { "Largest"     , COFF::IMAGE_COMDAT_SELECT_LARGEST      },
322   { "Newest"      , COFF::IMAGE_COMDAT_SELECT_NEWEST       }
323 };
324
325 static const EnumEntry<COFF::WeakExternalCharacteristics>
326 WeakExternalCharacteristics[] = {
327   { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
328   { "Library"  , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY   },
329   { "Alias"    , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS     }
330 };
331
332 template <typename T>
333 static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
334                                         COFFSymbolRef Symbol,
335                                         uint8_t AuxSymbolIdx, const T *&Aux) {
336   ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
337   AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
338   Aux = reinterpret_cast<const T*>(AuxData.data());
339   return readobj_error::success;
340 }
341
342 void COFFDumper::cacheRelocations() {
343   if (RelocCached)
344     return;
345   RelocCached = true;
346
347   for (const SectionRef &S : Obj->sections()) {
348     const coff_section *Section = Obj->getCOFFSection(S);
349
350     for (const RelocationRef &Reloc : S.relocations())
351       RelocMap[Section].push_back(Reloc);
352
353     // Sort relocations by address.
354     std::sort(RelocMap[Section].begin(), RelocMap[Section].end(),
355               relocAddressLess);
356   }
357 }
358
359 void COFFDumper::printDataDirectory(uint32_t Index, const std::string &FieldName) {
360   const data_directory *Data;
361   if (Obj->getDataDirectory(Index, Data))
362     return;
363   W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
364   W.printHex(FieldName + "Size", Data->Size);
365 }
366
367 void COFFDumper::printFileHeaders() {
368   time_t TDS = Obj->getTimeDateStamp();
369   char FormattedTime[20] = { };
370   strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
371
372   {
373     DictScope D(W, "ImageFileHeader");
374     W.printEnum  ("Machine", Obj->getMachine(),
375                     makeArrayRef(ImageFileMachineType));
376     W.printNumber("SectionCount", Obj->getNumberOfSections());
377     W.printHex   ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
378     W.printHex   ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
379     W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
380     W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
381     W.printFlags ("Characteristics", Obj->getCharacteristics(),
382                     makeArrayRef(ImageFileCharacteristics));
383   }
384
385   // Print PE header. This header does not exist if this is an object file and
386   // not an executable.
387   const pe32_header *PEHeader = nullptr;
388   if (error(Obj->getPE32Header(PEHeader)))
389     return;
390   if (PEHeader)
391     printPEHeader<pe32_header>(PEHeader);
392
393   const pe32plus_header *PEPlusHeader = nullptr;
394   if (error(Obj->getPE32PlusHeader(PEPlusHeader)))
395     return;
396   if (PEPlusHeader)
397     printPEHeader<pe32plus_header>(PEPlusHeader);
398
399   if (const dos_header *DH = Obj->getDOSHeader())
400     printDOSHeader(DH);
401 }
402
403 void COFFDumper::printDOSHeader(const dos_header *DH) {
404   DictScope D(W, "DOSHeader");
405   W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
406   W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
407   W.printNumber("FileSizeInPages", DH->FileSizeInPages);
408   W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
409   W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
410   W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
411   W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
412   W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
413   W.printNumber("InitialSP", DH->InitialSP);
414   W.printNumber("Checksum", DH->Checksum);
415   W.printNumber("InitialIP", DH->InitialIP);
416   W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
417   W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
418   W.printNumber("OverlayNumber", DH->OverlayNumber);
419   W.printNumber("OEMid", DH->OEMid);
420   W.printNumber("OEMinfo", DH->OEMinfo);
421   W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
422 }
423
424 template <class PEHeader>
425 void COFFDumper::printPEHeader(const PEHeader *Hdr) {
426   DictScope D(W, "ImageOptionalHeader");
427   W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
428   W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
429   W.printNumber("SizeOfCode", Hdr->SizeOfCode);
430   W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
431   W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
432   W.printHex   ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
433   W.printHex   ("BaseOfCode", Hdr->BaseOfCode);
434   printBaseOfDataField(Hdr);
435   W.printHex   ("ImageBase", Hdr->ImageBase);
436   W.printNumber("SectionAlignment", Hdr->SectionAlignment);
437   W.printNumber("FileAlignment", Hdr->FileAlignment);
438   W.printNumber("MajorOperatingSystemVersion",
439                 Hdr->MajorOperatingSystemVersion);
440   W.printNumber("MinorOperatingSystemVersion",
441                 Hdr->MinorOperatingSystemVersion);
442   W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
443   W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
444   W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
445   W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
446   W.printNumber("SizeOfImage", Hdr->SizeOfImage);
447   W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
448   W.printEnum  ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
449   W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
450                 makeArrayRef(PEDLLCharacteristics));
451   W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
452   W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
453   W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
454   W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
455   W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
456
457   if (Hdr->NumberOfRvaAndSize > 0) {
458     DictScope D(W, "DataDirectory");
459     static const char * const directory[] = {
460       "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
461       "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
462       "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
463       "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
464     };
465
466     for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i) {
467       printDataDirectory(i, directory[i]);
468     }
469   }
470 }
471
472 void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
473   W.printHex("BaseOfData", Hdr->BaseOfData);
474 }
475
476 void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
477
478 void COFFDumper::printCodeViewDebugInfo(const SectionRef &Section) {
479   StringRef Data;
480   if (error(Section.getContents(Data)))
481     return;
482
483   SmallVector<StringRef, 10> FunctionNames;
484   StringMap<StringRef> FunctionLineTables;
485
486   ListScope D(W, "CodeViewDebugInfo");
487   {
488     // FIXME: Add more offset correctness checks.
489     DataExtractor DE(Data, true, 4);
490     uint32_t Offset = 0,
491              Magic = DE.getU32(&Offset);
492     W.printHex("Magic", Magic);
493     if (Magic != COFF::DEBUG_SECTION_MAGIC) {
494       error(object_error::parse_failed);
495       return;
496     }
497
498     bool Finished = false;
499     while (DE.isValidOffset(Offset) && !Finished) {
500       // The section consists of a number of subsection in the following format:
501       // |Type|PayloadSize|Payload...|
502       uint32_t SubSectionType = DE.getU32(&Offset),
503                PayloadSize = DE.getU32(&Offset);
504       ListScope S(W, "Subsection");
505       W.printHex("Type", SubSectionType);
506       W.printHex("PayloadSize", PayloadSize);
507       if (PayloadSize > Data.size() - Offset) {
508         error(object_error::parse_failed);
509         return;
510       }
511
512       StringRef Contents = Data.substr(Offset, PayloadSize);
513       if (opts::CodeViewSubsectionBytes) {
514         // Print the raw contents to simplify debugging if anything goes wrong
515         // afterwards.
516         W.printBinaryBlock("Contents", Contents);
517       }
518
519       switch (SubSectionType) {
520       case COFF::DEBUG_SYMBOL_SUBSECTION:
521         if (opts::SectionSymbols)
522           printCodeViewSymbolsSubsection(Contents, Section, Offset);
523         break;
524       case COFF::DEBUG_LINE_TABLE_SUBSECTION: {
525         // Holds a PC to file:line table.  Some data to parse this subsection is
526         // stored in the other subsections, so just check sanity and store the
527         // pointers for deferred processing.
528
529         if (PayloadSize < 12) {
530           // There should be at least three words to store two function
531           // relocations and size of the code.
532           error(object_error::parse_failed);
533           return;
534         }
535
536         StringRef FunctionName;
537         if (error(resolveSymbolName(Obj->getCOFFSection(Section), Offset,
538                                     FunctionName)))
539           return;
540         W.printString("FunctionName", FunctionName);
541         if (FunctionLineTables.count(FunctionName) != 0) {
542           // Saw debug info for this function already?
543           error(object_error::parse_failed);
544           return;
545         }
546
547         FunctionLineTables[FunctionName] = Contents;
548         FunctionNames.push_back(FunctionName);
549         break;
550       }
551       case COFF::DEBUG_STRING_TABLE_SUBSECTION:
552         if (PayloadSize == 0 || CVStringTable.data() != nullptr ||
553             Contents.back() != '\0') {
554           // Empty or duplicate or non-null-terminated subsection.
555           error(object_error::parse_failed);
556           return;
557         }
558         CVStringTable = Contents;
559         break;
560       case COFF::DEBUG_INDEX_SUBSECTION:
561         // Holds the translation table from file indices
562         // to offsets in the string table.
563
564         if (PayloadSize == 0 ||
565             CVFileIndexToStringOffsetTable.data() != nullptr) {
566           // Empty or duplicate subsection.
567           error(object_error::parse_failed);
568           return;
569         }
570         CVFileIndexToStringOffsetTable = Contents;
571         break;
572       }
573       Offset += PayloadSize;
574
575       // Align the reading pointer by 4.
576       Offset += (-Offset) % 4;
577     }
578   }
579
580   // Dump the line tables now that we've read all the subsections and know all
581   // the required information.
582   for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
583     StringRef Name = FunctionNames[I];
584     ListScope S(W, "FunctionLineTable");
585     W.printString("FunctionName", Name);
586
587     DataExtractor DE(FunctionLineTables[Name], true, 4);
588     uint32_t Offset = 6;  // Skip relocations.
589     uint16_t Flags = DE.getU16(&Offset);
590     W.printHex("Flags", Flags);
591     bool HasColumnInformation =
592         Flags & COFF::DEBUG_LINE_TABLES_HAVE_COLUMN_RECORDS;
593     uint32_t FunctionSize = DE.getU32(&Offset);
594     W.printHex("CodeSize", FunctionSize);
595     while (DE.isValidOffset(Offset)) {
596       // For each range of lines with the same filename, we have a segment
597       // in the line table.  The filename string is accessed using double
598       // indirection to the string table subsection using the index subsection.
599       uint32_t OffsetInIndex = DE.getU32(&Offset),
600                SegmentLength = DE.getU32(&Offset);
601       Offset += sizeof(uint32_t); // Skip FullSegmentSize
602
603       uint32_t FilenameOffset;
604       {
605         DataExtractor SDE(CVFileIndexToStringOffsetTable, true, 4);
606         uint32_t OffsetInSDE = OffsetInIndex;
607         if (!SDE.isValidOffset(OffsetInSDE)) {
608           error(object_error::parse_failed);
609           return;
610         }
611         FilenameOffset = SDE.getU32(&OffsetInSDE);
612       }
613
614       if (FilenameOffset == 0 || FilenameOffset + 1 >= CVStringTable.size() ||
615           CVStringTable.data()[FilenameOffset - 1] != '\0') {
616         // Each string in an F3 subsection should be preceded by a null
617         // character.
618         error(object_error::parse_failed);
619         return;
620       }
621
622       StringRef Filename(CVStringTable.data() + FilenameOffset);
623       ListScope S(W, "FilenameSegment");
624       W.printString("Filename", Filename);
625       for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
626            ++J) {
627         // Then go the (PC, LineNumber) pairs.  The line number is stored in the
628         // least significant 31 bits of the respective word in the table.
629         uint32_t PC = DE.getU32(&Offset),
630                  LineNumber = DE.getU32(&Offset) & 0x7fffffff;
631         if (PC >= FunctionSize) {
632           error(object_error::parse_failed);
633           return;
634         }
635         char Buffer[32];
636         format("+0x%X", PC).snprint(Buffer, 32);
637         W.printNumber(Buffer, LineNumber);
638       }
639       if (HasColumnInformation) {
640         for (unsigned J = 0; J != SegmentLength && DE.isValidOffset(Offset);
641              ++J) {
642           uint16_t ColStart = DE.getU16(&Offset);
643           W.printNumber("ColStart", ColStart);
644           uint16_t ColEnd = DE.getU16(&Offset);
645           W.printNumber("ColEnd", ColEnd);
646         }
647       }
648     }
649   }
650 }
651
652 void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
653                                                 const SectionRef &Section,
654                                                 uint32_t OffsetInSection) {
655   if (Subsection.size() == 0) {
656     error(object_error::parse_failed);
657     return;
658   }
659   DataExtractor DE(Subsection, true, 4);
660   uint32_t Offset = 0;
661
662   // Function-level subsections have "procedure start" and "procedure end"
663   // commands that should come in pairs and surround relevant info.
664   bool InFunctionScope = false;
665   while (DE.isValidOffset(Offset)) {
666     // Read subsection segments one by one.
667     uint16_t Size = DE.getU16(&Offset);
668     // The section size includes the size of the type identifier.
669     if (Size < 2 || !DE.isValidOffsetForDataOfSize(Offset, Size)) {
670       error(object_error::parse_failed);
671       return;
672     }
673     Size -= 2;
674     uint16_t Type = DE.getU16(&Offset);
675     switch (Type) {
676     case COFF::DEBUG_SYMBOL_TYPE_PROC_START: {
677       DictScope S(W, "ProcStart");
678       if (InFunctionScope || Size < 36) {
679         error(object_error::parse_failed);
680         return;
681       }
682       InFunctionScope = true;
683
684       // We're currently interested in a limited subset of fields in this
685       // segment, just ignore the rest of the fields for now.
686       uint8_t Unused[12];
687       DE.getU8(&Offset, Unused, 12);
688       uint32_t CodeSize = DE.getU32(&Offset);
689       DE.getU8(&Offset, Unused, 12);
690       StringRef SectionName;
691       if (error(resolveSymbolName(Obj->getCOFFSection(Section),
692                                   OffsetInSection + Offset, SectionName)))
693         return;
694       Offset += 4;
695       DE.getU8(&Offset, Unused, 3);
696       StringRef DisplayName = DE.getCStr(&Offset);
697       if (!DE.isValidOffset(Offset)) {
698         error(object_error::parse_failed);
699         return;
700       }
701       W.printString("DisplayName", DisplayName);
702       W.printString("Section", SectionName);
703       W.printHex("CodeSize", CodeSize);
704
705       break;
706     }
707     case COFF::DEBUG_SYMBOL_TYPE_PROC_END: {
708       W.startLine() << "ProcEnd\n";
709       if (!InFunctionScope || Size > 0) {
710         error(object_error::parse_failed);
711         return;
712       }
713       InFunctionScope = false;
714       break;
715     }
716     default: {
717       if (opts::CodeViewSubsectionBytes) {
718         ListScope S(W, "Record");
719         W.printHex("Size", Size);
720         W.printHex("Type", Type);
721
722         StringRef Contents = DE.getData().substr(Offset, Size);
723         W.printBinaryBlock("Contents", Contents);
724       }
725
726       Offset += Size;
727       break;
728     }
729     }
730   }
731
732   if (InFunctionScope)
733     error(object_error::parse_failed);
734 }
735
736 void COFFDumper::printSections() {
737   ListScope SectionsD(W, "Sections");
738   int SectionNumber = 0;
739   for (const SectionRef &Sec : Obj->sections()) {
740     ++SectionNumber;
741     const coff_section *Section = Obj->getCOFFSection(Sec);
742
743     StringRef Name;
744     if (error(Sec.getName(Name)))
745       Name = "";
746
747     DictScope D(W, "Section");
748     W.printNumber("Number", SectionNumber);
749     W.printBinary("Name", Name, Section->Name);
750     W.printHex   ("VirtualSize", Section->VirtualSize);
751     W.printHex   ("VirtualAddress", Section->VirtualAddress);
752     W.printNumber("RawDataSize", Section->SizeOfRawData);
753     W.printHex   ("PointerToRawData", Section->PointerToRawData);
754     W.printHex   ("PointerToRelocations", Section->PointerToRelocations);
755     W.printHex   ("PointerToLineNumbers", Section->PointerToLinenumbers);
756     W.printNumber("RelocationCount", Section->NumberOfRelocations);
757     W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
758     W.printFlags ("Characteristics", Section->Characteristics,
759                     makeArrayRef(ImageSectionCharacteristics),
760                     COFF::SectionCharacteristics(0x00F00000));
761
762     if (opts::SectionRelocations) {
763       ListScope D(W, "Relocations");
764       for (const RelocationRef &Reloc : Sec.relocations())
765         printRelocation(Sec, Reloc);
766     }
767
768     if (opts::SectionSymbols) {
769       ListScope D(W, "Symbols");
770       for (const SymbolRef &Symbol : Obj->symbols()) {
771         if (!Sec.containsSymbol(Symbol))
772           continue;
773
774         printSymbol(Symbol);
775       }
776     }
777
778     if (Name == ".debug$S" && opts::CodeView)
779       printCodeViewDebugInfo(Sec);
780
781     if (opts::SectionData &&
782         !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
783       StringRef Data;
784       if (error(Sec.getContents(Data)))
785         break;
786
787       W.printBinaryBlock("SectionData", Data);
788     }
789   }
790 }
791
792 void COFFDumper::printRelocations() {
793   ListScope D(W, "Relocations");
794
795   int SectionNumber = 0;
796   for (const SectionRef &Section : Obj->sections()) {
797     ++SectionNumber;
798     StringRef Name;
799     if (error(Section.getName(Name)))
800       continue;
801
802     bool PrintedGroup = false;
803     for (const RelocationRef &Reloc : Section.relocations()) {
804       if (!PrintedGroup) {
805         W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
806         W.indent();
807         PrintedGroup = true;
808       }
809
810       printRelocation(Section, Reloc);
811     }
812
813     if (PrintedGroup) {
814       W.unindent();
815       W.startLine() << "}\n";
816     }
817   }
818 }
819
820 void COFFDumper::printRelocation(const SectionRef &Section,
821                                  const RelocationRef &Reloc) {
822   uint64_t Offset = Reloc.getOffset();
823   uint64_t RelocType = Reloc.getType();
824   SmallString<32> RelocName;
825   StringRef SymbolName;
826   Reloc.getTypeName(RelocName);
827   symbol_iterator Symbol = Reloc.getSymbol();
828   if (Symbol != Obj->symbol_end()) {
829     ErrorOr<StringRef> SymbolNameOrErr = Symbol->getName();
830     if (error(SymbolNameOrErr.getError()))
831       return;
832     SymbolName = *SymbolNameOrErr;
833   }
834
835   if (opts::ExpandRelocs) {
836     DictScope Group(W, "Relocation");
837     W.printHex("Offset", Offset);
838     W.printNumber("Type", RelocName, RelocType);
839     W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
840   } else {
841     raw_ostream& OS = W.startLine();
842     OS << W.hex(Offset)
843        << " " << RelocName
844        << " " << (SymbolName.empty() ? "-" : SymbolName)
845        << "\n";
846   }
847 }
848
849 void COFFDumper::printSymbols() {
850   ListScope Group(W, "Symbols");
851
852   for (const SymbolRef &Symbol : Obj->symbols())
853     printSymbol(Symbol);
854 }
855
856 void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
857
858 static ErrorOr<StringRef>
859 getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
860                const coff_section *Section) {
861   if (Section) {
862     StringRef SectionName;
863     if (std::error_code EC = Obj->getSectionName(Section, SectionName))
864       return EC;
865     return SectionName;
866   }
867   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
868     return StringRef("IMAGE_SYM_DEBUG");
869   if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
870     return StringRef("IMAGE_SYM_ABSOLUTE");
871   if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
872     return StringRef("IMAGE_SYM_UNDEFINED");
873   return StringRef("");
874 }
875
876 void COFFDumper::printSymbol(const SymbolRef &Sym) {
877   DictScope D(W, "Symbol");
878
879   COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
880   const coff_section *Section;
881   if (std::error_code EC = Obj->getSection(Symbol.getSectionNumber(), Section)) {
882     W.startLine() << "Invalid section number: " << EC.message() << "\n";
883     W.flush();
884     return;
885   }
886
887   StringRef SymbolName;
888   if (Obj->getSymbolName(Symbol, SymbolName))
889     SymbolName = "";
890
891   StringRef SectionName = "";
892   ErrorOr<StringRef> Res =
893       getSectionName(Obj, Symbol.getSectionNumber(), Section);
894   if (Res)
895     SectionName = *Res;
896
897   W.printString("Name", SymbolName);
898   W.printNumber("Value", Symbol.getValue());
899   W.printNumber("Section", SectionName, Symbol.getSectionNumber());
900   W.printEnum  ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
901   W.printEnum  ("ComplexType", Symbol.getComplexType(),
902                                                    makeArrayRef(ImageSymDType));
903   W.printEnum  ("StorageClass", Symbol.getStorageClass(),
904                                                    makeArrayRef(ImageSymClass));
905   W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
906
907   for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
908     if (Symbol.isFunctionDefinition()) {
909       const coff_aux_function_definition *Aux;
910       if (error(getSymbolAuxData(Obj, Symbol, I, Aux)))
911         break;
912
913       DictScope AS(W, "AuxFunctionDef");
914       W.printNumber("TagIndex", Aux->TagIndex);
915       W.printNumber("TotalSize", Aux->TotalSize);
916       W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
917       W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
918
919     } else if (Symbol.isAnyUndefined()) {
920       const coff_aux_weak_external *Aux;
921       if (error(getSymbolAuxData(Obj, Symbol, I, Aux)))
922         break;
923
924       ErrorOr<COFFSymbolRef> Linked = Obj->getSymbol(Aux->TagIndex);
925       StringRef LinkedName;
926       std::error_code EC = Linked.getError();
927       if (EC || (EC = Obj->getSymbolName(*Linked, LinkedName))) {
928         LinkedName = "";
929         error(EC);
930       }
931
932       DictScope AS(W, "AuxWeakExternal");
933       W.printNumber("Linked", LinkedName, Aux->TagIndex);
934       W.printEnum  ("Search", Aux->Characteristics,
935                     makeArrayRef(WeakExternalCharacteristics));
936
937     } else if (Symbol.isFileRecord()) {
938       const char *FileName;
939       if (error(getSymbolAuxData(Obj, Symbol, I, FileName)))
940         break;
941
942       DictScope AS(W, "AuxFileRecord");
943
944       StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
945                                    Obj->getSymbolTableEntrySize());
946       W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
947       break;
948     } else if (Symbol.isSectionDefinition()) {
949       const coff_aux_section_definition *Aux;
950       if (error(getSymbolAuxData(Obj, Symbol, I, Aux)))
951         break;
952
953       int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
954
955       DictScope AS(W, "AuxSectionDef");
956       W.printNumber("Length", Aux->Length);
957       W.printNumber("RelocationCount", Aux->NumberOfRelocations);
958       W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
959       W.printHex("Checksum", Aux->CheckSum);
960       W.printNumber("Number", AuxNumber);
961       W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
962
963       if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
964           && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
965         const coff_section *Assoc;
966         StringRef AssocName = "";
967         std::error_code EC = Obj->getSection(AuxNumber, Assoc);
968         ErrorOr<StringRef> Res = getSectionName(Obj, AuxNumber, Assoc);
969         if (Res)
970           AssocName = *Res;
971         if (!EC)
972           EC = Res.getError();
973         if (EC) {
974           AssocName = "";
975           error(EC);
976         }
977
978         W.printNumber("AssocSection", AssocName, AuxNumber);
979       }
980     } else if (Symbol.isCLRToken()) {
981       const coff_aux_clr_token *Aux;
982       if (error(getSymbolAuxData(Obj, Symbol, I, Aux)))
983         break;
984
985       ErrorOr<COFFSymbolRef> ReferredSym =
986           Obj->getSymbol(Aux->SymbolTableIndex);
987       StringRef ReferredName;
988       std::error_code EC = ReferredSym.getError();
989       if (EC || (EC = Obj->getSymbolName(*ReferredSym, ReferredName))) {
990         ReferredName = "";
991         error(EC);
992       }
993
994       DictScope AS(W, "AuxCLRToken");
995       W.printNumber("AuxType", Aux->AuxType);
996       W.printNumber("Reserved", Aux->Reserved);
997       W.printNumber("SymbolTableIndex", ReferredName, Aux->SymbolTableIndex);
998
999     } else {
1000       W.startLine() << "<unhandled auxiliary record>\n";
1001     }
1002   }
1003 }
1004
1005 void COFFDumper::printUnwindInfo() {
1006   ListScope D(W, "UnwindInformation");
1007   switch (Obj->getMachine()) {
1008   case COFF::IMAGE_FILE_MACHINE_AMD64: {
1009     Win64EH::Dumper Dumper(W);
1010     Win64EH::Dumper::SymbolResolver
1011     Resolver = [](const object::coff_section *Section, uint64_t Offset,
1012                   SymbolRef &Symbol, void *user_data) -> std::error_code {
1013       COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
1014       return Dumper->resolveSymbol(Section, Offset, Symbol);
1015     };
1016     Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
1017     Dumper.printData(Ctx);
1018     break;
1019   }
1020   case COFF::IMAGE_FILE_MACHINE_ARMNT: {
1021     ARM::WinEH::Decoder Decoder(W);
1022     Decoder.dumpProcedureData(*Obj);
1023     break;
1024   }
1025   default:
1026     W.printEnum("unsupported Image Machine", Obj->getMachine(),
1027                 makeArrayRef(ImageFileMachineType));
1028     break;
1029   }
1030 }
1031
1032 void COFFDumper::printImportedSymbols(
1033     iterator_range<imported_symbol_iterator> Range) {
1034   for (const ImportedSymbolRef &I : Range) {
1035     StringRef Sym;
1036     if (error(I.getSymbolName(Sym))) return;
1037     uint16_t Ordinal;
1038     if (error(I.getOrdinal(Ordinal))) return;
1039     W.printNumber("Symbol", Sym, Ordinal);
1040   }
1041 }
1042
1043 void COFFDumper::printDelayImportedSymbols(
1044     const DelayImportDirectoryEntryRef &I,
1045     iterator_range<imported_symbol_iterator> Range) {
1046   int Index = 0;
1047   for (const ImportedSymbolRef &S : Range) {
1048     DictScope Import(W, "Import");
1049     StringRef Sym;
1050     if (error(S.getSymbolName(Sym))) return;
1051     uint16_t Ordinal;
1052     if (error(S.getOrdinal(Ordinal))) return;
1053     W.printNumber("Symbol", Sym, Ordinal);
1054     uint64_t Addr;
1055     if (error(I.getImportAddress(Index++, Addr))) return;
1056     W.printHex("Address", Addr);
1057   }
1058 }
1059
1060 void COFFDumper::printCOFFImports() {
1061   // Regular imports
1062   for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
1063     DictScope Import(W, "Import");
1064     StringRef Name;
1065     if (error(I.getName(Name))) return;
1066     W.printString("Name", Name);
1067     uint32_t Addr;
1068     if (error(I.getImportLookupTableRVA(Addr))) return;
1069     W.printHex("ImportLookupTableRVA", Addr);
1070     if (error(I.getImportAddressTableRVA(Addr))) return;
1071     W.printHex("ImportAddressTableRVA", Addr);
1072     printImportedSymbols(I.imported_symbols());
1073   }
1074
1075   // Delay imports
1076   for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
1077     DictScope Import(W, "DelayImport");
1078     StringRef Name;
1079     if (error(I.getName(Name))) return;
1080     W.printString("Name", Name);
1081     const delay_import_directory_table_entry *Table;
1082     if (error(I.getDelayImportTable(Table))) return;
1083     W.printHex("Attributes", Table->Attributes);
1084     W.printHex("ModuleHandle", Table->ModuleHandle);
1085     W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
1086     W.printHex("ImportNameTable", Table->DelayImportNameTable);
1087     W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
1088     W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
1089     printDelayImportedSymbols(I, I.imported_symbols());
1090   }
1091 }
1092
1093 void COFFDumper::printCOFFExports() {
1094   for (const ExportDirectoryEntryRef &E : Obj->export_directories()) {
1095     DictScope Export(W, "Export");
1096
1097     StringRef Name;
1098     uint32_t Ordinal, RVA;
1099
1100     if (error(E.getSymbolName(Name)))
1101       continue;
1102     if (error(E.getOrdinal(Ordinal)))
1103       continue;
1104     if (error(E.getExportRVA(RVA)))
1105       continue;
1106
1107     W.printNumber("Ordinal", Ordinal);
1108     W.printString("Name", Name);
1109     W.printHex("RVA", RVA);
1110   }
1111 }
1112
1113 void COFFDumper::printCOFFDirectives() {
1114   for (const SectionRef &Section : Obj->sections()) {
1115     StringRef Contents;
1116     StringRef Name;
1117
1118     if (error(Section.getName(Name)))
1119       continue;
1120     if (Name != ".drectve")
1121       continue;
1122
1123     if (error(Section.getContents(Contents)))
1124       return;
1125
1126     W.printString("Directive(s)", Contents);
1127   }
1128 }
1129
1130 static StringRef getBaseRelocTypeName(uint8_t Type) {
1131   switch (Type) {
1132   case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
1133   case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
1134   case COFF::IMAGE_REL_BASED_LOW: return "LOW";
1135   case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
1136   case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
1137   case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
1138   case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
1139   default: return "unknown (" + llvm::utostr(Type) + ")";
1140   }
1141 }
1142
1143 void COFFDumper::printCOFFBaseReloc() {
1144   ListScope D(W, "BaseReloc");
1145   for (const BaseRelocRef &I : Obj->base_relocs()) {
1146     uint8_t Type;
1147     uint32_t RVA;
1148     if (error(I.getRVA(RVA)))
1149       continue;
1150     if (error(I.getType(Type)))
1151       continue;
1152     DictScope Import(W, "Entry");
1153     W.printString("Type", getBaseRelocTypeName(Type));
1154     W.printHex("Address", RVA);
1155   }
1156 }
1157
1158 void COFFDumper::printStackMap() const {
1159   object::SectionRef StackMapSection;
1160   for (auto Sec : Obj->sections()) {
1161     StringRef Name;
1162     Sec.getName(Name);
1163     if (Name == ".llvm_stackmaps") {
1164       StackMapSection = Sec;
1165       break;
1166     }
1167   }
1168
1169   if (StackMapSection == object::SectionRef())
1170     return;
1171
1172   StringRef StackMapContents;
1173   StackMapSection.getContents(StackMapContents);
1174   ArrayRef<uint8_t> StackMapContentsArray(
1175       reinterpret_cast<const uint8_t*>(StackMapContents.data()),
1176       StackMapContents.size());
1177
1178   if (Obj->isLittleEndian())
1179     prettyPrintStackMap(
1180                       llvm::outs(),
1181                       StackMapV1Parser<support::little>(StackMapContentsArray));
1182   else
1183     prettyPrintStackMap(llvm::outs(),
1184                         StackMapV1Parser<support::big>(StackMapContentsArray));
1185 }