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