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