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