1 //===- COFF.h - COFF object file implementation -----------------*- 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 // This file declares the COFFObjectFile class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_OBJECT_COFF_H 14 #define LLVM_OBJECT_COFF_H 15 16 #include "llvm/ADT/iterator_range.h" 17 #include "llvm/BinaryFormat/COFF.h" 18 #include "llvm/Object/Binary.h" 19 #include "llvm/Object/CVDebugRecord.h" 20 #include "llvm/Object/Error.h" 21 #include "llvm/Object/ObjectFile.h" 22 #include "llvm/Support/BinaryByteStream.h" 23 #include "llvm/Support/ConvertUTF.h" 24 #include "llvm/Support/Endian.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/TargetParser/SubtargetFeature.h" 27 #include <cassert> 28 #include <cstddef> 29 #include <cstdint> 30 #include <system_error> 31 32 namespace llvm { 33 34 template <typename T> class ArrayRef; 35 36 namespace object { 37 38 class Arm64XRelocRef; 39 class BaseRelocRef; 40 class DelayImportDirectoryEntryRef; 41 class DynamicRelocRef; 42 class ExportDirectoryEntryRef; 43 class ImportDirectoryEntryRef; 44 class ImportedSymbolRef; 45 class ResourceSectionRef; 46 47 using import_directory_iterator = content_iterator<ImportDirectoryEntryRef>; 48 using delay_import_directory_iterator = 49 content_iterator<DelayImportDirectoryEntryRef>; 50 using export_directory_iterator = content_iterator<ExportDirectoryEntryRef>; 51 using imported_symbol_iterator = content_iterator<ImportedSymbolRef>; 52 using base_reloc_iterator = content_iterator<BaseRelocRef>; 53 using dynamic_reloc_iterator = content_iterator<DynamicRelocRef>; 54 using arm64x_reloc_iterator = content_iterator<Arm64XRelocRef>; 55 56 /// The DOS compatible header at the front of all PE/COFF executables. 57 struct dos_header { 58 char Magic[2]; 59 support::ulittle16_t UsedBytesInTheLastPage; 60 support::ulittle16_t FileSizeInPages; 61 support::ulittle16_t NumberOfRelocationItems; 62 support::ulittle16_t HeaderSizeInParagraphs; 63 support::ulittle16_t MinimumExtraParagraphs; 64 support::ulittle16_t MaximumExtraParagraphs; 65 support::ulittle16_t InitialRelativeSS; 66 support::ulittle16_t InitialSP; 67 support::ulittle16_t Checksum; 68 support::ulittle16_t InitialIP; 69 support::ulittle16_t InitialRelativeCS; 70 support::ulittle16_t AddressOfRelocationTable; 71 support::ulittle16_t OverlayNumber; 72 support::ulittle16_t Reserved[4]; 73 support::ulittle16_t OEMid; 74 support::ulittle16_t OEMinfo; 75 support::ulittle16_t Reserved2[10]; 76 support::ulittle32_t AddressOfNewExeHeader; 77 }; 78 79 struct coff_file_header { 80 support::ulittle16_t Machine; 81 support::ulittle16_t NumberOfSections; 82 support::ulittle32_t TimeDateStamp; 83 support::ulittle32_t PointerToSymbolTable; 84 support::ulittle32_t NumberOfSymbols; 85 support::ulittle16_t SizeOfOptionalHeader; 86 support::ulittle16_t Characteristics; 87 88 bool isImportLibrary() const { return NumberOfSections == 0xffff; } 89 }; 90 91 struct coff_bigobj_file_header { 92 support::ulittle16_t Sig1; 93 support::ulittle16_t Sig2; 94 support::ulittle16_t Version; 95 support::ulittle16_t Machine; 96 support::ulittle32_t TimeDateStamp; 97 uint8_t UUID[16]; 98 support::ulittle32_t unused1; 99 support::ulittle32_t unused2; 100 support::ulittle32_t unused3; 101 support::ulittle32_t unused4; 102 support::ulittle32_t NumberOfSections; 103 support::ulittle32_t PointerToSymbolTable; 104 support::ulittle32_t NumberOfSymbols; 105 }; 106 107 /// The 32-bit PE header that follows the COFF header. 108 struct pe32_header { 109 support::ulittle16_t Magic; 110 uint8_t MajorLinkerVersion; 111 uint8_t MinorLinkerVersion; 112 support::ulittle32_t SizeOfCode; 113 support::ulittle32_t SizeOfInitializedData; 114 support::ulittle32_t SizeOfUninitializedData; 115 support::ulittle32_t AddressOfEntryPoint; 116 support::ulittle32_t BaseOfCode; 117 support::ulittle32_t BaseOfData; 118 support::ulittle32_t ImageBase; 119 support::ulittle32_t SectionAlignment; 120 support::ulittle32_t FileAlignment; 121 support::ulittle16_t MajorOperatingSystemVersion; 122 support::ulittle16_t MinorOperatingSystemVersion; 123 support::ulittle16_t MajorImageVersion; 124 support::ulittle16_t MinorImageVersion; 125 support::ulittle16_t MajorSubsystemVersion; 126 support::ulittle16_t MinorSubsystemVersion; 127 support::ulittle32_t Win32VersionValue; 128 support::ulittle32_t SizeOfImage; 129 support::ulittle32_t SizeOfHeaders; 130 support::ulittle32_t CheckSum; 131 support::ulittle16_t Subsystem; 132 // FIXME: This should be DllCharacteristics. 133 support::ulittle16_t DLLCharacteristics; 134 support::ulittle32_t SizeOfStackReserve; 135 support::ulittle32_t SizeOfStackCommit; 136 support::ulittle32_t SizeOfHeapReserve; 137 support::ulittle32_t SizeOfHeapCommit; 138 support::ulittle32_t LoaderFlags; 139 // FIXME: This should be NumberOfRvaAndSizes. 140 support::ulittle32_t NumberOfRvaAndSize; 141 }; 142 143 /// The 64-bit PE header that follows the COFF header. 144 struct pe32plus_header { 145 support::ulittle16_t Magic; 146 uint8_t MajorLinkerVersion; 147 uint8_t MinorLinkerVersion; 148 support::ulittle32_t SizeOfCode; 149 support::ulittle32_t SizeOfInitializedData; 150 support::ulittle32_t SizeOfUninitializedData; 151 support::ulittle32_t AddressOfEntryPoint; 152 support::ulittle32_t BaseOfCode; 153 support::ulittle64_t ImageBase; 154 support::ulittle32_t SectionAlignment; 155 support::ulittle32_t FileAlignment; 156 support::ulittle16_t MajorOperatingSystemVersion; 157 support::ulittle16_t MinorOperatingSystemVersion; 158 support::ulittle16_t MajorImageVersion; 159 support::ulittle16_t MinorImageVersion; 160 support::ulittle16_t MajorSubsystemVersion; 161 support::ulittle16_t MinorSubsystemVersion; 162 support::ulittle32_t Win32VersionValue; 163 support::ulittle32_t SizeOfImage; 164 support::ulittle32_t SizeOfHeaders; 165 support::ulittle32_t CheckSum; 166 support::ulittle16_t Subsystem; 167 support::ulittle16_t DLLCharacteristics; 168 support::ulittle64_t SizeOfStackReserve; 169 support::ulittle64_t SizeOfStackCommit; 170 support::ulittle64_t SizeOfHeapReserve; 171 support::ulittle64_t SizeOfHeapCommit; 172 support::ulittle32_t LoaderFlags; 173 support::ulittle32_t NumberOfRvaAndSize; 174 }; 175 176 struct data_directory { 177 support::ulittle32_t RelativeVirtualAddress; 178 support::ulittle32_t Size; 179 }; 180 181 struct debug_directory { 182 support::ulittle32_t Characteristics; 183 support::ulittle32_t TimeDateStamp; 184 support::ulittle16_t MajorVersion; 185 support::ulittle16_t MinorVersion; 186 support::ulittle32_t Type; 187 support::ulittle32_t SizeOfData; 188 support::ulittle32_t AddressOfRawData; 189 support::ulittle32_t PointerToRawData; 190 }; 191 192 template <typename IntTy> 193 struct import_lookup_table_entry { 194 IntTy Data; 195 196 bool isOrdinal() const { return Data < 0; } 197 198 uint16_t getOrdinal() const { 199 assert(isOrdinal() && "ILT entry is not an ordinal!"); 200 return Data & 0xFFFF; 201 } 202 203 uint32_t getHintNameRVA() const { 204 assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!"); 205 return Data & 0xFFFFFFFF; 206 } 207 }; 208 209 using import_lookup_table_entry32 = 210 import_lookup_table_entry<support::little32_t>; 211 using import_lookup_table_entry64 = 212 import_lookup_table_entry<support::little64_t>; 213 214 struct delay_import_directory_table_entry { 215 // dumpbin reports this field as "Characteristics" instead of "Attributes". 216 support::ulittle32_t Attributes; 217 support::ulittle32_t Name; 218 support::ulittle32_t ModuleHandle; 219 support::ulittle32_t DelayImportAddressTable; 220 support::ulittle32_t DelayImportNameTable; 221 support::ulittle32_t BoundDelayImportTable; 222 support::ulittle32_t UnloadDelayImportTable; 223 support::ulittle32_t TimeStamp; 224 }; 225 226 struct export_directory_table_entry { 227 support::ulittle32_t ExportFlags; 228 support::ulittle32_t TimeDateStamp; 229 support::ulittle16_t MajorVersion; 230 support::ulittle16_t MinorVersion; 231 support::ulittle32_t NameRVA; 232 support::ulittle32_t OrdinalBase; 233 support::ulittle32_t AddressTableEntries; 234 support::ulittle32_t NumberOfNamePointers; 235 support::ulittle32_t ExportAddressTableRVA; 236 support::ulittle32_t NamePointerRVA; 237 support::ulittle32_t OrdinalTableRVA; 238 }; 239 240 union export_address_table_entry { 241 support::ulittle32_t ExportRVA; 242 support::ulittle32_t ForwarderRVA; 243 }; 244 245 using export_name_pointer_table_entry = support::ulittle32_t; 246 using export_ordinal_table_entry = support::ulittle16_t; 247 248 struct StringTableOffset { 249 support::ulittle32_t Zeroes; 250 support::ulittle32_t Offset; 251 }; 252 253 template <typename SectionNumberType> 254 struct coff_symbol { 255 union { 256 char ShortName[COFF::NameSize]; 257 StringTableOffset Offset; 258 } Name; 259 260 support::ulittle32_t Value; 261 SectionNumberType SectionNumber; 262 263 support::ulittle16_t Type; 264 265 uint8_t StorageClass; 266 uint8_t NumberOfAuxSymbols; 267 }; 268 269 using coff_symbol16 = coff_symbol<support::ulittle16_t>; 270 using coff_symbol32 = coff_symbol<support::ulittle32_t>; 271 272 // Contains only common parts of coff_symbol16 and coff_symbol32. 273 struct coff_symbol_generic { 274 union { 275 char ShortName[COFF::NameSize]; 276 StringTableOffset Offset; 277 } Name; 278 support::ulittle32_t Value; 279 }; 280 281 struct coff_aux_section_definition; 282 struct coff_aux_weak_external; 283 284 class COFFSymbolRef { 285 public: 286 COFFSymbolRef() = default; 287 COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {} 288 COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {} 289 290 const void *getRawPtr() const { 291 return CS16 ? static_cast<const void *>(CS16) : CS32; 292 } 293 294 const coff_symbol_generic *getGeneric() const { 295 if (CS16) 296 return reinterpret_cast<const coff_symbol_generic *>(CS16); 297 return reinterpret_cast<const coff_symbol_generic *>(CS32); 298 } 299 300 friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) { 301 return A.getRawPtr() < B.getRawPtr(); 302 } 303 304 bool isBigObj() const { 305 if (CS16) 306 return false; 307 if (CS32) 308 return true; 309 llvm_unreachable("COFFSymbolRef points to nothing!"); 310 } 311 312 const char *getShortName() const { 313 return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName; 314 } 315 316 const StringTableOffset &getStringTableOffset() const { 317 assert(isSet() && "COFFSymbolRef points to nothing!"); 318 return CS16 ? CS16->Name.Offset : CS32->Name.Offset; 319 } 320 321 uint32_t getValue() const { 322 assert(isSet() && "COFFSymbolRef points to nothing!"); 323 return CS16 ? CS16->Value : CS32->Value; 324 } 325 326 int32_t getSectionNumber() const { 327 assert(isSet() && "COFFSymbolRef points to nothing!"); 328 if (CS16) { 329 // Reserved sections are returned as negative numbers. 330 if (CS16->SectionNumber <= COFF::MaxNumberOfSections16) 331 return CS16->SectionNumber; 332 return static_cast<int16_t>(CS16->SectionNumber); 333 } 334 return static_cast<int32_t>(CS32->SectionNumber); 335 } 336 337 uint16_t getType() const { 338 assert(isSet() && "COFFSymbolRef points to nothing!"); 339 return CS16 ? CS16->Type : CS32->Type; 340 } 341 342 uint8_t getStorageClass() const { 343 assert(isSet() && "COFFSymbolRef points to nothing!"); 344 return CS16 ? CS16->StorageClass : CS32->StorageClass; 345 } 346 347 uint8_t getNumberOfAuxSymbols() const { 348 assert(isSet() && "COFFSymbolRef points to nothing!"); 349 return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols; 350 } 351 352 uint8_t getBaseType() const { return getType() & 0x0F; } 353 354 uint8_t getComplexType() const { 355 return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT; 356 } 357 358 template <typename T> const T *getAux() const { 359 return CS16 ? reinterpret_cast<const T *>(CS16 + 1) 360 : reinterpret_cast<const T *>(CS32 + 1); 361 } 362 363 const coff_aux_section_definition *getSectionDefinition() const { 364 if (!getNumberOfAuxSymbols() || 365 getStorageClass() != COFF::IMAGE_SYM_CLASS_STATIC) 366 return nullptr; 367 return getAux<coff_aux_section_definition>(); 368 } 369 370 const coff_aux_weak_external *getWeakExternal() const { 371 if (!getNumberOfAuxSymbols() || 372 getStorageClass() != COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) 373 return nullptr; 374 return getAux<coff_aux_weak_external>(); 375 } 376 377 bool isAbsolute() const { 378 return getSectionNumber() == -1; 379 } 380 381 bool isExternal() const { 382 return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL; 383 } 384 385 bool isCommon() const { 386 return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && 387 getValue() != 0; 388 } 389 390 bool isUndefined() const { 391 return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && 392 getValue() == 0; 393 } 394 395 bool isEmptySectionDeclaration() const { 396 return isSection() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED; 397 } 398 399 bool isWeakExternal() const { 400 return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL; 401 } 402 403 bool isFunctionDefinition() const { 404 return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL && 405 getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION && 406 !COFF::isReservedSectionNumber(getSectionNumber()); 407 } 408 409 bool isFunctionLineInfo() const { 410 return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION; 411 } 412 413 bool isAnyUndefined() const { 414 return isUndefined() || isWeakExternal(); 415 } 416 417 bool isFileRecord() const { 418 return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE; 419 } 420 421 bool isSection() const { 422 return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION; 423 } 424 425 bool isSectionDefinition() const { 426 // C++/CLI creates external ABS symbols for non-const appdomain globals. 427 // These are also followed by an auxiliary section definition. 428 bool isAppdomainGlobal = 429 getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL && 430 getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE; 431 bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC; 432 if (!getNumberOfAuxSymbols()) 433 return false; 434 return isAppdomainGlobal || isOrdinarySection; 435 } 436 437 bool isCLRToken() const { 438 return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN; 439 } 440 441 private: 442 bool isSet() const { return CS16 || CS32; } 443 444 const coff_symbol16 *CS16 = nullptr; 445 const coff_symbol32 *CS32 = nullptr; 446 }; 447 448 struct coff_section { 449 char Name[COFF::NameSize]; 450 support::ulittle32_t VirtualSize; 451 support::ulittle32_t VirtualAddress; 452 support::ulittle32_t SizeOfRawData; 453 support::ulittle32_t PointerToRawData; 454 support::ulittle32_t PointerToRelocations; 455 support::ulittle32_t PointerToLinenumbers; 456 support::ulittle16_t NumberOfRelocations; 457 support::ulittle16_t NumberOfLinenumbers; 458 support::ulittle32_t Characteristics; 459 460 // Returns true if the actual number of relocations is stored in 461 // VirtualAddress field of the first relocation table entry. 462 bool hasExtendedRelocations() const { 463 return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) && 464 NumberOfRelocations == UINT16_MAX; 465 } 466 467 uint32_t getAlignment() const { 468 // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to 469 // IMAGE_SCN_ALIGN_1BYTES. 470 if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD) 471 return 1; 472 473 // Bit [20:24] contains section alignment. 0 means use a default alignment 474 // of 16. 475 uint32_t Shift = (Characteristics >> 20) & 0xF; 476 if (Shift > 0) 477 return 1U << (Shift - 1); 478 return 16; 479 } 480 }; 481 482 struct coff_relocation { 483 support::ulittle32_t VirtualAddress; 484 support::ulittle32_t SymbolTableIndex; 485 support::ulittle16_t Type; 486 }; 487 488 struct coff_aux_function_definition { 489 support::ulittle32_t TagIndex; 490 support::ulittle32_t TotalSize; 491 support::ulittle32_t PointerToLinenumber; 492 support::ulittle32_t PointerToNextFunction; 493 char Unused1[2]; 494 }; 495 496 static_assert(sizeof(coff_aux_function_definition) == 18, 497 "auxiliary entry must be 18 bytes"); 498 499 struct coff_aux_bf_and_ef_symbol { 500 char Unused1[4]; 501 support::ulittle16_t Linenumber; 502 char Unused2[6]; 503 support::ulittle32_t PointerToNextFunction; 504 char Unused3[2]; 505 }; 506 507 static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18, 508 "auxiliary entry must be 18 bytes"); 509 510 struct coff_aux_weak_external { 511 support::ulittle32_t TagIndex; 512 support::ulittle32_t Characteristics; 513 char Unused1[10]; 514 }; 515 516 static_assert(sizeof(coff_aux_weak_external) == 18, 517 "auxiliary entry must be 18 bytes"); 518 519 struct coff_aux_section_definition { 520 support::ulittle32_t Length; 521 support::ulittle16_t NumberOfRelocations; 522 support::ulittle16_t NumberOfLinenumbers; 523 support::ulittle32_t CheckSum; 524 support::ulittle16_t NumberLowPart; 525 uint8_t Selection; 526 uint8_t Unused; 527 support::ulittle16_t NumberHighPart; 528 int32_t getNumber(bool IsBigObj) const { 529 uint32_t Number = static_cast<uint32_t>(NumberLowPart); 530 if (IsBigObj) 531 Number |= static_cast<uint32_t>(NumberHighPart) << 16; 532 return static_cast<int32_t>(Number); 533 } 534 }; 535 536 static_assert(sizeof(coff_aux_section_definition) == 18, 537 "auxiliary entry must be 18 bytes"); 538 539 struct coff_aux_clr_token { 540 uint8_t AuxType; 541 uint8_t Reserved; 542 support::ulittle32_t SymbolTableIndex; 543 char MBZ[12]; 544 }; 545 546 static_assert(sizeof(coff_aux_clr_token) == 18, 547 "auxiliary entry must be 18 bytes"); 548 549 struct coff_import_header { 550 support::ulittle16_t Sig1; 551 support::ulittle16_t Sig2; 552 support::ulittle16_t Version; 553 support::ulittle16_t Machine; 554 support::ulittle32_t TimeDateStamp; 555 support::ulittle32_t SizeOfData; 556 support::ulittle16_t OrdinalHint; 557 support::ulittle16_t TypeInfo; 558 559 int getType() const { return TypeInfo & 0x3; } 560 int getNameType() const { return (TypeInfo >> 2) & 0x7; } 561 }; 562 563 struct coff_import_directory_table_entry { 564 support::ulittle32_t ImportLookupTableRVA; 565 support::ulittle32_t TimeDateStamp; 566 support::ulittle32_t ForwarderChain; 567 support::ulittle32_t NameRVA; 568 support::ulittle32_t ImportAddressTableRVA; 569 570 bool isNull() const { 571 return ImportLookupTableRVA == 0 && TimeDateStamp == 0 && 572 ForwarderChain == 0 && NameRVA == 0 && ImportAddressTableRVA == 0; 573 } 574 }; 575 576 template <typename IntTy> 577 struct coff_tls_directory { 578 IntTy StartAddressOfRawData; 579 IntTy EndAddressOfRawData; 580 IntTy AddressOfIndex; 581 IntTy AddressOfCallBacks; 582 support::ulittle32_t SizeOfZeroFill; 583 support::ulittle32_t Characteristics; 584 585 uint32_t getAlignment() const { 586 // Bit [20:24] contains section alignment. 587 uint32_t Shift = (Characteristics & COFF::IMAGE_SCN_ALIGN_MASK) >> 20; 588 if (Shift > 0) 589 return 1U << (Shift - 1); 590 return 0; 591 } 592 593 void setAlignment(uint32_t Align) { 594 uint32_t AlignBits = 0; 595 if (Align) { 596 assert(llvm::isPowerOf2_32(Align) && "alignment is not a power of 2"); 597 assert(llvm::Log2_32(Align) <= 13 && "alignment requested is too large"); 598 AlignBits = (llvm::Log2_32(Align) + 1) << 20; 599 } 600 Characteristics = 601 (Characteristics & ~COFF::IMAGE_SCN_ALIGN_MASK) | AlignBits; 602 } 603 }; 604 605 using coff_tls_directory32 = coff_tls_directory<support::little32_t>; 606 using coff_tls_directory64 = coff_tls_directory<support::little64_t>; 607 608 enum class frame_type : uint16_t { Fpo = 0, Trap = 1, Tss = 2, NonFpo = 3 }; 609 610 struct coff_load_config_code_integrity { 611 support::ulittle16_t Flags; 612 support::ulittle16_t Catalog; 613 support::ulittle32_t CatalogOffset; 614 support::ulittle32_t Reserved; 615 }; 616 617 /// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32) 618 struct coff_load_configuration32 { 619 support::ulittle32_t Size; 620 support::ulittle32_t TimeDateStamp; 621 support::ulittle16_t MajorVersion; 622 support::ulittle16_t MinorVersion; 623 support::ulittle32_t GlobalFlagsClear; 624 support::ulittle32_t GlobalFlagsSet; 625 support::ulittle32_t CriticalSectionDefaultTimeout; 626 support::ulittle32_t DeCommitFreeBlockThreshold; 627 support::ulittle32_t DeCommitTotalFreeThreshold; 628 support::ulittle32_t LockPrefixTable; 629 support::ulittle32_t MaximumAllocationSize; 630 support::ulittle32_t VirtualMemoryThreshold; 631 support::ulittle32_t ProcessAffinityMask; 632 support::ulittle32_t ProcessHeapFlags; 633 support::ulittle16_t CSDVersion; 634 support::ulittle16_t DependentLoadFlags; 635 support::ulittle32_t EditList; 636 support::ulittle32_t SecurityCookie; 637 support::ulittle32_t SEHandlerTable; 638 support::ulittle32_t SEHandlerCount; 639 640 // Added in MSVC 2015 for /guard:cf. 641 support::ulittle32_t GuardCFCheckFunction; 642 support::ulittle32_t GuardCFCheckDispatch; 643 support::ulittle32_t GuardCFFunctionTable; 644 support::ulittle32_t GuardCFFunctionCount; 645 support::ulittle32_t GuardFlags; // coff_guard_flags 646 647 // Added in MSVC 2017 648 coff_load_config_code_integrity CodeIntegrity; 649 support::ulittle32_t GuardAddressTakenIatEntryTable; 650 support::ulittle32_t GuardAddressTakenIatEntryCount; 651 support::ulittle32_t GuardLongJumpTargetTable; 652 support::ulittle32_t GuardLongJumpTargetCount; 653 support::ulittle32_t DynamicValueRelocTable; 654 support::ulittle32_t CHPEMetadataPointer; 655 support::ulittle32_t GuardRFFailureRoutine; 656 support::ulittle32_t GuardRFFailureRoutineFunctionPointer; 657 support::ulittle32_t DynamicValueRelocTableOffset; 658 support::ulittle16_t DynamicValueRelocTableSection; 659 support::ulittle16_t Reserved2; 660 support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer; 661 support::ulittle32_t HotPatchTableOffset; 662 663 // Added in MSVC 2019 664 support::ulittle32_t Reserved3; 665 support::ulittle32_t EnclaveConfigurationPointer; 666 support::ulittle32_t VolatileMetadataPointer; 667 support::ulittle32_t GuardEHContinuationTable; 668 support::ulittle32_t GuardEHContinuationCount; 669 support::ulittle32_t GuardXFGCheckFunctionPointer; 670 support::ulittle32_t GuardXFGDispatchFunctionPointer; 671 support::ulittle32_t GuardXFGTableDispatchFunctionPointer; 672 support::ulittle32_t CastGuardOsDeterminedFailureMode; 673 }; 674 675 /// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64) 676 struct coff_load_configuration64 { 677 support::ulittle32_t Size; 678 support::ulittle32_t TimeDateStamp; 679 support::ulittle16_t MajorVersion; 680 support::ulittle16_t MinorVersion; 681 support::ulittle32_t GlobalFlagsClear; 682 support::ulittle32_t GlobalFlagsSet; 683 support::ulittle32_t CriticalSectionDefaultTimeout; 684 support::ulittle64_t DeCommitFreeBlockThreshold; 685 support::ulittle64_t DeCommitTotalFreeThreshold; 686 support::ulittle64_t LockPrefixTable; 687 support::ulittle64_t MaximumAllocationSize; 688 support::ulittle64_t VirtualMemoryThreshold; 689 support::ulittle64_t ProcessAffinityMask; 690 support::ulittle32_t ProcessHeapFlags; 691 support::ulittle16_t CSDVersion; 692 support::ulittle16_t DependentLoadFlags; 693 support::ulittle64_t EditList; 694 support::ulittle64_t SecurityCookie; 695 support::ulittle64_t SEHandlerTable; 696 support::ulittle64_t SEHandlerCount; 697 698 // Added in MSVC 2015 for /guard:cf. 699 support::ulittle64_t GuardCFCheckFunction; 700 support::ulittle64_t GuardCFCheckDispatch; 701 support::ulittle64_t GuardCFFunctionTable; 702 support::ulittle64_t GuardCFFunctionCount; 703 support::ulittle32_t GuardFlags; 704 705 // Added in MSVC 2017 706 coff_load_config_code_integrity CodeIntegrity; 707 support::ulittle64_t GuardAddressTakenIatEntryTable; 708 support::ulittle64_t GuardAddressTakenIatEntryCount; 709 support::ulittle64_t GuardLongJumpTargetTable; 710 support::ulittle64_t GuardLongJumpTargetCount; 711 support::ulittle64_t DynamicValueRelocTable; 712 support::ulittle64_t CHPEMetadataPointer; 713 support::ulittle64_t GuardRFFailureRoutine; 714 support::ulittle64_t GuardRFFailureRoutineFunctionPointer; 715 support::ulittle32_t DynamicValueRelocTableOffset; 716 support::ulittle16_t DynamicValueRelocTableSection; 717 support::ulittle16_t Reserved2; 718 support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer; 719 support::ulittle32_t HotPatchTableOffset; 720 721 // Added in MSVC 2019 722 support::ulittle32_t Reserved3; 723 support::ulittle64_t EnclaveConfigurationPointer; 724 support::ulittle64_t VolatileMetadataPointer; 725 support::ulittle64_t GuardEHContinuationTable; 726 support::ulittle64_t GuardEHContinuationCount; 727 support::ulittle64_t GuardXFGCheckFunctionPointer; 728 support::ulittle64_t GuardXFGDispatchFunctionPointer; 729 support::ulittle64_t GuardXFGTableDispatchFunctionPointer; 730 support::ulittle64_t CastGuardOsDeterminedFailureMode; 731 }; 732 733 struct chpe_metadata { 734 support::ulittle32_t Version; 735 support::ulittle32_t CodeMap; 736 support::ulittle32_t CodeMapCount; 737 support::ulittle32_t CodeRangesToEntryPoints; 738 support::ulittle32_t RedirectionMetadata; 739 support::ulittle32_t __os_arm64x_dispatch_call_no_redirect; 740 support::ulittle32_t __os_arm64x_dispatch_ret; 741 support::ulittle32_t __os_arm64x_dispatch_call; 742 support::ulittle32_t __os_arm64x_dispatch_icall; 743 support::ulittle32_t __os_arm64x_dispatch_icall_cfg; 744 support::ulittle32_t AlternateEntryPoint; 745 support::ulittle32_t AuxiliaryIAT; 746 support::ulittle32_t CodeRangesToEntryPointsCount; 747 support::ulittle32_t RedirectionMetadataCount; 748 support::ulittle32_t GetX64InformationFunctionPointer; 749 support::ulittle32_t SetX64InformationFunctionPointer; 750 support::ulittle32_t ExtraRFETable; 751 support::ulittle32_t ExtraRFETableSize; 752 support::ulittle32_t __os_arm64x_dispatch_fptr; 753 support::ulittle32_t AuxiliaryIATCopy; 754 755 // Added in CHPE metadata v2 756 support::ulittle32_t AuxiliaryDelayloadIAT; 757 support::ulittle32_t AuxiliaryDelayloadIATCopy; 758 support::ulittle32_t HybridImageInfoBitfield; 759 }; 760 761 enum chpe_range_type { Arm64 = 0, Arm64EC = 1, Amd64 = 2 }; 762 763 struct chpe_range_entry { 764 support::ulittle32_t StartOffset; 765 support::ulittle32_t Length; 766 767 // The two low bits of StartOffset contain a range type. 768 static constexpr uint32_t TypeMask = 3; 769 770 uint32_t getStart() const { return StartOffset & ~TypeMask; } 771 uint16_t getType() const { return StartOffset & TypeMask; } 772 }; 773 774 struct chpe_code_range_entry { 775 support::ulittle32_t StartRva; 776 support::ulittle32_t EndRva; 777 support::ulittle32_t EntryPoint; 778 }; 779 780 struct chpe_redirection_entry { 781 support::ulittle32_t Source; 782 support::ulittle32_t Destination; 783 }; 784 785 struct coff_runtime_function_x64 { 786 support::ulittle32_t BeginAddress; 787 support::ulittle32_t EndAddress; 788 support::ulittle32_t UnwindInformation; 789 }; 790 791 struct coff_base_reloc_block_header { 792 support::ulittle32_t PageRVA; 793 support::ulittle32_t BlockSize; 794 }; 795 796 struct coff_base_reloc_block_entry { 797 support::ulittle16_t Data; 798 799 int getType() const { return Data >> 12; } 800 int getOffset() const { return Data & ((1 << 12) - 1); } 801 }; 802 803 struct coff_resource_dir_entry { 804 union { 805 support::ulittle32_t NameOffset; 806 support::ulittle32_t ID; 807 uint32_t getNameOffset() const { 808 return maskTrailingOnes<uint32_t>(31) & NameOffset; 809 } 810 // Even though the PE/COFF spec doesn't mention this, the high bit of a name 811 // offset is set. 812 void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); } 813 } Identifier; 814 union { 815 support::ulittle32_t DataEntryOffset; 816 support::ulittle32_t SubdirOffset; 817 818 bool isSubDir() const { return SubdirOffset >> 31; } 819 uint32_t value() const { 820 return maskTrailingOnes<uint32_t>(31) & SubdirOffset; 821 } 822 823 } Offset; 824 }; 825 826 struct coff_resource_data_entry { 827 support::ulittle32_t DataRVA; 828 support::ulittle32_t DataSize; 829 support::ulittle32_t Codepage; 830 support::ulittle32_t Reserved; 831 }; 832 833 struct coff_resource_dir_table { 834 support::ulittle32_t Characteristics; 835 support::ulittle32_t TimeDateStamp; 836 support::ulittle16_t MajorVersion; 837 support::ulittle16_t MinorVersion; 838 support::ulittle16_t NumberOfNameEntries; 839 support::ulittle16_t NumberOfIDEntries; 840 }; 841 842 struct debug_h_header { 843 support::ulittle32_t Magic; 844 support::ulittle16_t Version; 845 support::ulittle16_t HashAlgorithm; 846 }; 847 848 struct coff_dynamic_reloc_table { 849 support::ulittle32_t Version; 850 support::ulittle32_t Size; 851 }; 852 853 struct coff_dynamic_relocation32 { 854 support::ulittle32_t Symbol; 855 support::ulittle32_t BaseRelocSize; 856 }; 857 858 struct coff_dynamic_relocation64 { 859 support::ulittle64_t Symbol; 860 support::ulittle32_t BaseRelocSize; 861 }; 862 863 struct coff_dynamic_relocation32_v2 { 864 support::ulittle32_t HeaderSize; 865 support::ulittle32_t FixupInfoSize; 866 support::ulittle32_t Symbol; 867 support::ulittle32_t SymbolGroup; 868 support::ulittle32_t Flags; 869 }; 870 871 struct coff_dynamic_relocation64_v2 { 872 support::ulittle32_t HeaderSize; 873 support::ulittle32_t FixupInfoSize; 874 support::ulittle64_t Symbol; 875 support::ulittle32_t SymbolGroup; 876 support::ulittle32_t Flags; 877 }; 878 879 class COFFObjectFile : public ObjectFile { 880 private: 881 COFFObjectFile(MemoryBufferRef Object); 882 883 friend class ImportDirectoryEntryRef; 884 friend class ExportDirectoryEntryRef; 885 const coff_file_header *COFFHeader; 886 const coff_bigobj_file_header *COFFBigObjHeader; 887 const pe32_header *PE32Header; 888 const pe32plus_header *PE32PlusHeader; 889 const data_directory *DataDirectory; 890 const coff_section *SectionTable; 891 const coff_symbol16 *SymbolTable16; 892 const coff_symbol32 *SymbolTable32; 893 const char *StringTable; 894 uint32_t StringTableSize; 895 const coff_import_directory_table_entry *ImportDirectory; 896 const delay_import_directory_table_entry *DelayImportDirectory; 897 uint32_t NumberOfDelayImportDirectory; 898 const export_directory_table_entry *ExportDirectory; 899 const coff_base_reloc_block_header *BaseRelocHeader; 900 const coff_base_reloc_block_header *BaseRelocEnd; 901 const debug_directory *DebugDirectoryBegin; 902 const debug_directory *DebugDirectoryEnd; 903 const coff_tls_directory32 *TLSDirectory32; 904 const coff_tls_directory64 *TLSDirectory64; 905 // Either coff_load_configuration32 or coff_load_configuration64. 906 const void *LoadConfig = nullptr; 907 const chpe_metadata *CHPEMetadata = nullptr; 908 const coff_dynamic_reloc_table *DynamicRelocTable = nullptr; 909 910 Expected<StringRef> getString(uint32_t offset) const; 911 912 template <typename coff_symbol_type> 913 const coff_symbol_type *toSymb(DataRefImpl Symb) const; 914 const coff_section *toSec(DataRefImpl Sec) const; 915 const coff_relocation *toRel(DataRefImpl Rel) const; 916 917 // Finish initializing the object and return success or an error. 918 Error initialize(); 919 920 Error initSymbolTablePtr(); 921 Error initImportTablePtr(); 922 Error initDelayImportTablePtr(); 923 Error initExportTablePtr(); 924 Error initBaseRelocPtr(); 925 Error initDebugDirectoryPtr(); 926 Error initTLSDirectoryPtr(); 927 Error initLoadConfigPtr(); 928 Error initDynamicRelocPtr(uint32_t SectionIndex, uint32_t SectionOffset); 929 930 public: 931 static Expected<std::unique_ptr<COFFObjectFile>> 932 create(MemoryBufferRef Object); 933 934 uintptr_t getSymbolTable() const { 935 if (SymbolTable16) 936 return reinterpret_cast<uintptr_t>(SymbolTable16); 937 if (SymbolTable32) 938 return reinterpret_cast<uintptr_t>(SymbolTable32); 939 return uintptr_t(0); 940 } 941 942 uint16_t getMachine() const { 943 if (COFFHeader) { 944 if (CHPEMetadata) { 945 switch (COFFHeader->Machine) { 946 case COFF::IMAGE_FILE_MACHINE_AMD64: 947 return COFF::IMAGE_FILE_MACHINE_ARM64EC; 948 case COFF::IMAGE_FILE_MACHINE_ARM64: 949 return COFF::IMAGE_FILE_MACHINE_ARM64X; 950 } 951 } 952 return COFFHeader->Machine; 953 } 954 if (COFFBigObjHeader) 955 return COFFBigObjHeader->Machine; 956 llvm_unreachable("no COFF header!"); 957 } 958 959 uint16_t getSizeOfOptionalHeader() const { 960 if (COFFHeader) 961 return COFFHeader->isImportLibrary() ? 0 962 : COFFHeader->SizeOfOptionalHeader; 963 // bigobj doesn't have this field. 964 if (COFFBigObjHeader) 965 return 0; 966 llvm_unreachable("no COFF header!"); 967 } 968 969 uint16_t getCharacteristics() const { 970 if (COFFHeader) 971 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics; 972 // bigobj doesn't have characteristics to speak of, 973 // editbin will silently lie to you if you attempt to set any. 974 if (COFFBigObjHeader) 975 return 0; 976 llvm_unreachable("no COFF header!"); 977 } 978 979 uint32_t getTimeDateStamp() const { 980 if (COFFHeader) 981 return COFFHeader->TimeDateStamp; 982 if (COFFBigObjHeader) 983 return COFFBigObjHeader->TimeDateStamp; 984 llvm_unreachable("no COFF header!"); 985 } 986 987 uint32_t getNumberOfSections() const { 988 if (COFFHeader) 989 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections; 990 if (COFFBigObjHeader) 991 return COFFBigObjHeader->NumberOfSections; 992 llvm_unreachable("no COFF header!"); 993 } 994 995 uint32_t getPointerToSymbolTable() const { 996 if (COFFHeader) 997 return COFFHeader->isImportLibrary() ? 0 998 : COFFHeader->PointerToSymbolTable; 999 if (COFFBigObjHeader) 1000 return COFFBigObjHeader->PointerToSymbolTable; 1001 llvm_unreachable("no COFF header!"); 1002 } 1003 1004 uint32_t getRawNumberOfSymbols() const { 1005 if (COFFHeader) 1006 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols; 1007 if (COFFBigObjHeader) 1008 return COFFBigObjHeader->NumberOfSymbols; 1009 llvm_unreachable("no COFF header!"); 1010 } 1011 1012 uint32_t getNumberOfSymbols() const { 1013 if (!SymbolTable16 && !SymbolTable32) 1014 return 0; 1015 return getRawNumberOfSymbols(); 1016 } 1017 1018 uint32_t getStringTableSize() const { return StringTableSize; } 1019 1020 const export_directory_table_entry *getExportTable() const { 1021 return ExportDirectory; 1022 } 1023 1024 const coff_load_configuration32 *getLoadConfig32() const { 1025 assert(!is64()); 1026 return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig); 1027 } 1028 1029 const coff_load_configuration64 *getLoadConfig64() const { 1030 assert(is64()); 1031 return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig); 1032 } 1033 1034 const chpe_metadata *getCHPEMetadata() const { return CHPEMetadata; } 1035 const coff_dynamic_reloc_table *getDynamicRelocTable() const { 1036 return DynamicRelocTable; 1037 } 1038 1039 StringRef getRelocationTypeName(uint16_t Type) const; 1040 1041 protected: 1042 void moveSymbolNext(DataRefImpl &Symb) const override; 1043 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override; 1044 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override; 1045 uint32_t getSymbolAlignment(DataRefImpl Symb) const override; 1046 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override; 1047 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override; 1048 Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override; 1049 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override; 1050 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override; 1051 void moveSectionNext(DataRefImpl &Sec) const override; 1052 Expected<StringRef> getSectionName(DataRefImpl Sec) const override; 1053 uint64_t getSectionAddress(DataRefImpl Sec) const override; 1054 uint64_t getSectionIndex(DataRefImpl Sec) const override; 1055 uint64_t getSectionSize(DataRefImpl Sec) const override; 1056 Expected<ArrayRef<uint8_t>> 1057 getSectionContents(DataRefImpl Sec) const override; 1058 uint64_t getSectionAlignment(DataRefImpl Sec) const override; 1059 bool isSectionCompressed(DataRefImpl Sec) const override; 1060 bool isSectionText(DataRefImpl Sec) const override; 1061 bool isSectionData(DataRefImpl Sec) const override; 1062 bool isSectionBSS(DataRefImpl Sec) const override; 1063 bool isSectionVirtual(DataRefImpl Sec) const override; 1064 bool isDebugSection(DataRefImpl Sec) const override; 1065 relocation_iterator section_rel_begin(DataRefImpl Sec) const override; 1066 relocation_iterator section_rel_end(DataRefImpl Sec) const override; 1067 1068 void moveRelocationNext(DataRefImpl &Rel) const override; 1069 uint64_t getRelocationOffset(DataRefImpl Rel) const override; 1070 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override; 1071 uint64_t getRelocationType(DataRefImpl Rel) const override; 1072 void getRelocationTypeName(DataRefImpl Rel, 1073 SmallVectorImpl<char> &Result) const override; 1074 1075 public: 1076 basic_symbol_iterator symbol_begin() const override; 1077 basic_symbol_iterator symbol_end() const override; 1078 section_iterator section_begin() const override; 1079 section_iterator section_end() const override; 1080 1081 bool is64Bit() const override { return false; } 1082 1083 const coff_section *getCOFFSection(const SectionRef &Section) const; 1084 COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const; 1085 COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const; 1086 const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const; 1087 unsigned getSectionID(SectionRef Sec) const; 1088 unsigned getSymbolSectionID(SymbolRef Sym) const; 1089 1090 uint8_t getBytesInAddress() const override; 1091 StringRef getFileFormatName() const override; 1092 Triple::ArchType getArch() const override; 1093 Expected<uint64_t> getStartAddress() const override; 1094 Expected<SubtargetFeatures> getFeatures() const override { 1095 return SubtargetFeatures(); 1096 } 1097 std::unique_ptr<MemoryBuffer> getHybridObjectView() const; 1098 1099 import_directory_iterator import_directory_begin() const; 1100 import_directory_iterator import_directory_end() const; 1101 delay_import_directory_iterator delay_import_directory_begin() const; 1102 delay_import_directory_iterator delay_import_directory_end() const; 1103 export_directory_iterator export_directory_begin() const; 1104 export_directory_iterator export_directory_end() const; 1105 base_reloc_iterator base_reloc_begin() const; 1106 base_reloc_iterator base_reloc_end() const; 1107 dynamic_reloc_iterator dynamic_reloc_begin() const; 1108 dynamic_reloc_iterator dynamic_reloc_end() const; 1109 const debug_directory *debug_directory_begin() const { 1110 return DebugDirectoryBegin; 1111 } 1112 const debug_directory *debug_directory_end() const { 1113 return DebugDirectoryEnd; 1114 } 1115 1116 iterator_range<import_directory_iterator> import_directories() const; 1117 iterator_range<delay_import_directory_iterator> 1118 delay_import_directories() const; 1119 iterator_range<export_directory_iterator> export_directories() const; 1120 iterator_range<base_reloc_iterator> base_relocs() const; 1121 iterator_range<dynamic_reloc_iterator> dynamic_relocs() const; 1122 iterator_range<const debug_directory *> debug_directories() const { 1123 return make_range(debug_directory_begin(), debug_directory_end()); 1124 } 1125 1126 const coff_tls_directory32 *getTLSDirectory32() const { 1127 return TLSDirectory32; 1128 } 1129 const coff_tls_directory64 *getTLSDirectory64() const { 1130 return TLSDirectory64; 1131 } 1132 1133 const dos_header *getDOSHeader() const { 1134 if (!PE32Header && !PE32PlusHeader) 1135 return nullptr; 1136 return reinterpret_cast<const dos_header *>(base()); 1137 } 1138 1139 const coff_file_header *getCOFFHeader() const { return COFFHeader; } 1140 const coff_bigobj_file_header *getCOFFBigObjHeader() const { 1141 return COFFBigObjHeader; 1142 } 1143 const pe32_header *getPE32Header() const { return PE32Header; } 1144 const pe32plus_header *getPE32PlusHeader() const { return PE32PlusHeader; } 1145 1146 const data_directory *getDataDirectory(uint32_t index) const; 1147 Expected<const coff_section *> getSection(int32_t index) const; 1148 1149 Expected<COFFSymbolRef> getSymbol(uint32_t index) const { 1150 if (index >= getNumberOfSymbols()) 1151 return errorCodeToError(object_error::parse_failed); 1152 if (SymbolTable16) 1153 return COFFSymbolRef(SymbolTable16 + index); 1154 if (SymbolTable32) 1155 return COFFSymbolRef(SymbolTable32 + index); 1156 return errorCodeToError(object_error::parse_failed); 1157 } 1158 1159 template <typename T> 1160 Error getAuxSymbol(uint32_t index, const T *&Res) const { 1161 Expected<COFFSymbolRef> S = getSymbol(index); 1162 if (Error E = S.takeError()) 1163 return E; 1164 Res = reinterpret_cast<const T *>(S->getRawPtr()); 1165 return Error::success(); 1166 } 1167 1168 Expected<StringRef> getSymbolName(COFFSymbolRef Symbol) const; 1169 Expected<StringRef> getSymbolName(const coff_symbol_generic *Symbol) const; 1170 1171 ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const; 1172 1173 uint32_t getSymbolIndex(COFFSymbolRef Symbol) const; 1174 1175 size_t getSymbolTableEntrySize() const { 1176 if (COFFHeader) 1177 return sizeof(coff_symbol16); 1178 if (COFFBigObjHeader) 1179 return sizeof(coff_symbol32); 1180 llvm_unreachable("null symbol table pointer!"); 1181 } 1182 1183 ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const; 1184 1185 Expected<StringRef> getSectionName(const coff_section *Sec) const; 1186 uint64_t getSectionSize(const coff_section *Sec) const; 1187 Error getSectionContents(const coff_section *Sec, 1188 ArrayRef<uint8_t> &Res) const; 1189 1190 uint64_t getImageBase() const; 1191 Error getVaPtr(uint64_t VA, uintptr_t &Res) const; 1192 Error getRvaPtr(uint32_t Rva, uintptr_t &Res, 1193 const char *ErrorContext = nullptr) const; 1194 1195 /// Given an RVA base and size, returns a valid array of bytes or an error 1196 /// code if the RVA and size is not contained completely within a valid 1197 /// section. 1198 Error getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, 1199 ArrayRef<uint8_t> &Contents, 1200 const char *ErrorContext = nullptr) const; 1201 1202 Error getHintName(uint32_t Rva, uint16_t &Hint, 1203 StringRef &Name) const; 1204 1205 /// Get PDB information out of a codeview debug directory entry. 1206 Error getDebugPDBInfo(const debug_directory *DebugDir, 1207 const codeview::DebugInfo *&Info, 1208 StringRef &PDBFileName) const; 1209 1210 /// Get PDB information from an executable. If the information is not present, 1211 /// Info will be set to nullptr and PDBFileName will be empty. An error is 1212 /// returned only on corrupt object files. Convenience accessor that can be 1213 /// used if the debug directory is not already handy. 1214 Error getDebugPDBInfo(const codeview::DebugInfo *&Info, 1215 StringRef &PDBFileName) const; 1216 1217 bool isRelocatableObject() const override; 1218 bool is64() const { return PE32PlusHeader; } 1219 1220 StringRef mapDebugSectionName(StringRef Name) const override; 1221 1222 static bool classof(const Binary *v) { return v->isCOFF(); } 1223 }; 1224 1225 // The iterator for the import directory table. 1226 class ImportDirectoryEntryRef { 1227 public: 1228 ImportDirectoryEntryRef() = default; 1229 ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table, 1230 uint32_t I, const COFFObjectFile *Owner) 1231 : ImportTable(Table), Index(I), OwningObject(Owner) {} 1232 1233 bool operator==(const ImportDirectoryEntryRef &Other) const; 1234 void moveNext(); 1235 1236 imported_symbol_iterator imported_symbol_begin() const; 1237 imported_symbol_iterator imported_symbol_end() const; 1238 iterator_range<imported_symbol_iterator> imported_symbols() const; 1239 1240 imported_symbol_iterator lookup_table_begin() const; 1241 imported_symbol_iterator lookup_table_end() const; 1242 iterator_range<imported_symbol_iterator> lookup_table_symbols() const; 1243 1244 Error getName(StringRef &Result) const; 1245 Error getImportLookupTableRVA(uint32_t &Result) const; 1246 Error getImportAddressTableRVA(uint32_t &Result) const; 1247 1248 Error 1249 getImportTableEntry(const coff_import_directory_table_entry *&Result) const; 1250 1251 private: 1252 const coff_import_directory_table_entry *ImportTable; 1253 uint32_t Index; 1254 const COFFObjectFile *OwningObject = nullptr; 1255 }; 1256 1257 class DelayImportDirectoryEntryRef { 1258 public: 1259 DelayImportDirectoryEntryRef() = default; 1260 DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T, 1261 uint32_t I, const COFFObjectFile *Owner) 1262 : Table(T), Index(I), OwningObject(Owner) {} 1263 1264 bool operator==(const DelayImportDirectoryEntryRef &Other) const; 1265 void moveNext(); 1266 1267 imported_symbol_iterator imported_symbol_begin() const; 1268 imported_symbol_iterator imported_symbol_end() const; 1269 iterator_range<imported_symbol_iterator> imported_symbols() const; 1270 1271 Error getName(StringRef &Result) const; 1272 Error getDelayImportTable( 1273 const delay_import_directory_table_entry *&Result) const; 1274 Error getImportAddress(int AddrIndex, uint64_t &Result) const; 1275 1276 private: 1277 const delay_import_directory_table_entry *Table; 1278 uint32_t Index; 1279 const COFFObjectFile *OwningObject = nullptr; 1280 }; 1281 1282 // The iterator for the export directory table entry. 1283 class ExportDirectoryEntryRef { 1284 public: 1285 ExportDirectoryEntryRef() = default; 1286 ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I, 1287 const COFFObjectFile *Owner) 1288 : ExportTable(Table), Index(I), OwningObject(Owner) {} 1289 1290 bool operator==(const ExportDirectoryEntryRef &Other) const; 1291 void moveNext(); 1292 1293 Error getDllName(StringRef &Result) const; 1294 Error getOrdinalBase(uint32_t &Result) const; 1295 Error getOrdinal(uint32_t &Result) const; 1296 Error getExportRVA(uint32_t &Result) const; 1297 Error getSymbolName(StringRef &Result) const; 1298 1299 Error isForwarder(bool &Result) const; 1300 Error getForwardTo(StringRef &Result) const; 1301 1302 private: 1303 const export_directory_table_entry *ExportTable; 1304 uint32_t Index; 1305 const COFFObjectFile *OwningObject = nullptr; 1306 }; 1307 1308 class ImportedSymbolRef { 1309 public: 1310 ImportedSymbolRef() = default; 1311 ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I, 1312 const COFFObjectFile *Owner) 1313 : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {} 1314 ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I, 1315 const COFFObjectFile *Owner) 1316 : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {} 1317 1318 bool operator==(const ImportedSymbolRef &Other) const; 1319 void moveNext(); 1320 1321 Error getSymbolName(StringRef &Result) const; 1322 Error isOrdinal(bool &Result) const; 1323 Error getOrdinal(uint16_t &Result) const; 1324 Error getHintNameRVA(uint32_t &Result) const; 1325 1326 private: 1327 const import_lookup_table_entry32 *Entry32; 1328 const import_lookup_table_entry64 *Entry64; 1329 uint32_t Index; 1330 const COFFObjectFile *OwningObject = nullptr; 1331 }; 1332 1333 class BaseRelocRef { 1334 public: 1335 BaseRelocRef() = default; 1336 BaseRelocRef(const coff_base_reloc_block_header *Header, 1337 const COFFObjectFile *Owner) 1338 : Header(Header), Index(0) {} 1339 1340 bool operator==(const BaseRelocRef &Other) const; 1341 void moveNext(); 1342 1343 Error getType(uint8_t &Type) const; 1344 Error getRVA(uint32_t &Result) const; 1345 1346 private: 1347 const coff_base_reloc_block_header *Header; 1348 uint32_t Index; 1349 }; 1350 1351 class DynamicRelocRef { 1352 public: 1353 DynamicRelocRef() = default; 1354 DynamicRelocRef(const void *Header, const COFFObjectFile *Owner) 1355 : Obj(Owner), Header(reinterpret_cast<const uint8_t *>(Header)) {} 1356 1357 bool operator==(const DynamicRelocRef &Other) const; 1358 void moveNext(); 1359 uint32_t getType() const; 1360 void getContents(ArrayRef<uint8_t> &Ref) const; 1361 1362 arm64x_reloc_iterator arm64x_reloc_begin() const; 1363 arm64x_reloc_iterator arm64x_reloc_end() const; 1364 iterator_range<arm64x_reloc_iterator> arm64x_relocs() const; 1365 1366 private: 1367 Error validate() const; 1368 1369 const COFFObjectFile *Obj; 1370 const uint8_t *Header; 1371 1372 friend class COFFObjectFile; 1373 }; 1374 1375 class Arm64XRelocRef { 1376 public: 1377 Arm64XRelocRef() = default; 1378 Arm64XRelocRef(const coff_base_reloc_block_header *Header, uint32_t Index = 0) 1379 : Header(Header), Index(Index) {} 1380 1381 bool operator==(const Arm64XRelocRef &Other) const; 1382 void moveNext(); 1383 1384 COFF::Arm64XFixupType getType() const { 1385 return COFF::Arm64XFixupType((getReloc() >> 12) & 3); 1386 } 1387 uint32_t getRVA() const { return Header->PageRVA + (getReloc() & 0xfff); } 1388 uint8_t getSize() const; 1389 uint64_t getValue() const; 1390 1391 private: 1392 const support::ulittle16_t &getReloc(uint32_t Offset = 0) const { 1393 return reinterpret_cast<const support::ulittle16_t *>(Header + 1394 1)[Index + Offset]; 1395 } 1396 1397 uint16_t getArg() const { return getReloc() >> 14; } 1398 uint8_t getEntrySize() const; 1399 Error validate(const COFFObjectFile *Obj) const; 1400 1401 const coff_base_reloc_block_header *Header; 1402 uint32_t Index; 1403 1404 friend class DynamicRelocRef; 1405 }; 1406 1407 class ResourceSectionRef { 1408 public: 1409 ResourceSectionRef() = default; 1410 explicit ResourceSectionRef(StringRef Ref) 1411 : BBS(Ref, llvm::endianness::little) {} 1412 1413 Error load(const COFFObjectFile *O); 1414 Error load(const COFFObjectFile *O, const SectionRef &S); 1415 1416 Expected<ArrayRef<UTF16>> 1417 getEntryNameString(const coff_resource_dir_entry &Entry); 1418 Expected<const coff_resource_dir_table &> 1419 getEntrySubDir(const coff_resource_dir_entry &Entry); 1420 Expected<const coff_resource_data_entry &> 1421 getEntryData(const coff_resource_dir_entry &Entry); 1422 Expected<const coff_resource_dir_table &> getBaseTable(); 1423 Expected<const coff_resource_dir_entry &> 1424 getTableEntry(const coff_resource_dir_table &Table, uint32_t Index); 1425 1426 Expected<StringRef> getContents(const coff_resource_data_entry &Entry); 1427 1428 private: 1429 BinaryByteStream BBS; 1430 1431 SectionRef Section; 1432 const COFFObjectFile *Obj = nullptr; 1433 1434 std::vector<const coff_relocation *> Relocs; 1435 1436 Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset); 1437 Expected<const coff_resource_dir_entry &> 1438 getTableEntryAtOffset(uint32_t Offset); 1439 Expected<const coff_resource_data_entry &> 1440 getDataEntryAtOffset(uint32_t Offset); 1441 Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset); 1442 }; 1443 1444 // Corresponds to `_FPO_DATA` structure in the PE/COFF spec. 1445 struct FpoData { 1446 support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code 1447 support::ulittle32_t Size; // cbProcSize: # bytes in function 1448 support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4 1449 support::ulittle16_t NumParams; // cdwParams: # bytes in params/4 1450 support::ulittle16_t Attributes; 1451 1452 // cbProlog: # bytes in prolog 1453 int getPrologSize() const { return Attributes & 0xF; } 1454 1455 // cbRegs: # regs saved 1456 int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; } 1457 1458 // fHasSEH: true if seh is func 1459 bool hasSEH() const { return (Attributes >> 9) & 1; } 1460 1461 // fUseBP: true if EBP has been allocated 1462 bool useBP() const { return (Attributes >> 10) & 1; } 1463 1464 // cbFrame: frame pointer 1465 frame_type getFP() const { return static_cast<frame_type>(Attributes >> 14); } 1466 }; 1467 1468 class SectionStrippedError 1469 : public ErrorInfo<SectionStrippedError, BinaryError> { 1470 public: 1471 SectionStrippedError() { setErrorCode(object_error::section_stripped); } 1472 }; 1473 1474 } // end namespace object 1475 1476 } // end namespace llvm 1477 1478 #endif // LLVM_OBJECT_COFF_H 1479