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