1 //===- COFFObjectFile.cpp - COFF object file implementation ---------------===// 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 #include "llvm/ADT/ArrayRef.h" 14 #include "llvm/ADT/StringRef.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/ADT/iterator_range.h" 18 #include "llvm/BinaryFormat/COFF.h" 19 #include "llvm/Object/Binary.h" 20 #include "llvm/Object/COFF.h" 21 #include "llvm/Object/Error.h" 22 #include "llvm/Object/ObjectFile.h" 23 #include "llvm/Support/BinaryStreamReader.h" 24 #include "llvm/Support/Endian.h" 25 #include "llvm/Support/Error.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/MathExtras.h" 28 #include "llvm/Support/MemoryBuffer.h" 29 #include <algorithm> 30 #include <cassert> 31 #include <cstddef> 32 #include <cstdint> 33 #include <cstring> 34 #include <limits> 35 #include <memory> 36 #include <system_error> 37 38 using namespace llvm; 39 using namespace object; 40 41 using support::ulittle16_t; 42 using support::ulittle32_t; 43 using support::ulittle64_t; 44 using support::little16_t; 45 46 // Returns false if size is greater than the buffer size. And sets ec. 47 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) { 48 if (M.getBufferSize() < Size) { 49 EC = object_error::unexpected_eof; 50 return false; 51 } 52 return true; 53 } 54 55 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. 56 // Returns unexpected_eof if error. 57 template <typename T> 58 static std::error_code getObject(const T *&Obj, MemoryBufferRef M, 59 const void *Ptr, 60 const uint64_t Size = sizeof(T)) { 61 uintptr_t Addr = uintptr_t(Ptr); 62 if (std::error_code EC = Binary::checkOffset(M, Addr, Size)) 63 return EC; 64 Obj = reinterpret_cast<const T *>(Addr); 65 return std::error_code(); 66 } 67 68 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without 69 // prefixed slashes. 70 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) { 71 assert(Str.size() <= 6 && "String too long, possible overflow."); 72 if (Str.size() > 6) 73 return true; 74 75 uint64_t Value = 0; 76 while (!Str.empty()) { 77 unsigned CharVal; 78 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25 79 CharVal = Str[0] - 'A'; 80 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51 81 CharVal = Str[0] - 'a' + 26; 82 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61 83 CharVal = Str[0] - '0' + 52; 84 else if (Str[0] == '+') // 62 85 CharVal = 62; 86 else if (Str[0] == '/') // 63 87 CharVal = 63; 88 else 89 return true; 90 91 Value = (Value * 64) + CharVal; 92 Str = Str.substr(1); 93 } 94 95 if (Value > std::numeric_limits<uint32_t>::max()) 96 return true; 97 98 Result = static_cast<uint32_t>(Value); 99 return false; 100 } 101 102 template <typename coff_symbol_type> 103 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const { 104 const coff_symbol_type *Addr = 105 reinterpret_cast<const coff_symbol_type *>(Ref.p); 106 107 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr))); 108 #ifndef NDEBUG 109 // Verify that the symbol points to a valid entry in the symbol table. 110 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base()); 111 112 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && 113 "Symbol did not point to the beginning of a symbol"); 114 #endif 115 116 return Addr; 117 } 118 119 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { 120 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); 121 122 #ifndef NDEBUG 123 // Verify that the section points to a valid entry in the section table. 124 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections())) 125 report_fatal_error("Section was outside of section table."); 126 127 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable); 128 assert(Offset % sizeof(coff_section) == 0 && 129 "Section did not point to the beginning of a section"); 130 #endif 131 132 return Addr; 133 } 134 135 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const { 136 auto End = reinterpret_cast<uintptr_t>(StringTable); 137 if (SymbolTable16) { 138 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref); 139 Symb += 1 + Symb->NumberOfAuxSymbols; 140 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End); 141 } else if (SymbolTable32) { 142 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref); 143 Symb += 1 + Symb->NumberOfAuxSymbols; 144 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End); 145 } else { 146 llvm_unreachable("no symbol table pointer!"); 147 } 148 } 149 150 Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const { 151 return getSymbolName(getCOFFSymbol(Ref)); 152 } 153 154 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const { 155 return getCOFFSymbol(Ref).getValue(); 156 } 157 158 uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const { 159 // MSVC/link.exe seems to align symbols to the next-power-of-2 160 // up to 32 bytes. 161 COFFSymbolRef Symb = getCOFFSymbol(Ref); 162 return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue())); 163 } 164 165 Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const { 166 uint64_t Result = cantFail(getSymbolValue(Ref)); 167 COFFSymbolRef Symb = getCOFFSymbol(Ref); 168 int32_t SectionNumber = Symb.getSectionNumber(); 169 170 if (Symb.isAnyUndefined() || Symb.isCommon() || 171 COFF::isReservedSectionNumber(SectionNumber)) 172 return Result; 173 174 Expected<const coff_section *> Section = getSection(SectionNumber); 175 if (!Section) 176 return Section.takeError(); 177 Result += (*Section)->VirtualAddress; 178 179 // The section VirtualAddress does not include ImageBase, and we want to 180 // return virtual addresses. 181 Result += getImageBase(); 182 183 return Result; 184 } 185 186 Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const { 187 COFFSymbolRef Symb = getCOFFSymbol(Ref); 188 int32_t SectionNumber = Symb.getSectionNumber(); 189 190 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) 191 return SymbolRef::ST_Function; 192 if (Symb.isAnyUndefined()) 193 return SymbolRef::ST_Unknown; 194 if (Symb.isCommon()) 195 return SymbolRef::ST_Data; 196 if (Symb.isFileRecord()) 197 return SymbolRef::ST_File; 198 199 // TODO: perhaps we need a new symbol type ST_Section. 200 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition()) 201 return SymbolRef::ST_Debug; 202 203 if (!COFF::isReservedSectionNumber(SectionNumber)) 204 return SymbolRef::ST_Data; 205 206 return SymbolRef::ST_Other; 207 } 208 209 Expected<uint32_t> COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const { 210 COFFSymbolRef Symb = getCOFFSymbol(Ref); 211 uint32_t Result = SymbolRef::SF_None; 212 213 if (Symb.isExternal() || Symb.isWeakExternal()) 214 Result |= SymbolRef::SF_Global; 215 216 if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) { 217 Result |= SymbolRef::SF_Weak; 218 if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS) 219 Result |= SymbolRef::SF_Undefined; 220 } 221 222 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE) 223 Result |= SymbolRef::SF_Absolute; 224 225 if (Symb.isFileRecord()) 226 Result |= SymbolRef::SF_FormatSpecific; 227 228 if (Symb.isSectionDefinition()) 229 Result |= SymbolRef::SF_FormatSpecific; 230 231 if (Symb.isCommon()) 232 Result |= SymbolRef::SF_Common; 233 234 if (Symb.isUndefined()) 235 Result |= SymbolRef::SF_Undefined; 236 237 return Result; 238 } 239 240 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const { 241 COFFSymbolRef Symb = getCOFFSymbol(Ref); 242 return Symb.getValue(); 243 } 244 245 Expected<section_iterator> 246 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const { 247 COFFSymbolRef Symb = getCOFFSymbol(Ref); 248 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) 249 return section_end(); 250 Expected<const coff_section *> Sec = getSection(Symb.getSectionNumber()); 251 if (!Sec) 252 return Sec.takeError(); 253 DataRefImpl Ret; 254 Ret.p = reinterpret_cast<uintptr_t>(*Sec); 255 return section_iterator(SectionRef(Ret, this)); 256 } 257 258 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const { 259 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl()); 260 return Symb.getSectionNumber(); 261 } 262 263 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const { 264 const coff_section *Sec = toSec(Ref); 265 Sec += 1; 266 Ref.p = reinterpret_cast<uintptr_t>(Sec); 267 } 268 269 Expected<StringRef> COFFObjectFile::getSectionName(DataRefImpl Ref) const { 270 const coff_section *Sec = toSec(Ref); 271 return getSectionName(Sec); 272 } 273 274 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const { 275 const coff_section *Sec = toSec(Ref); 276 uint64_t Result = Sec->VirtualAddress; 277 278 // The section VirtualAddress does not include ImageBase, and we want to 279 // return virtual addresses. 280 Result += getImageBase(); 281 return Result; 282 } 283 284 uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const { 285 return toSec(Sec) - SectionTable; 286 } 287 288 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const { 289 return getSectionSize(toSec(Ref)); 290 } 291 292 Expected<ArrayRef<uint8_t>> 293 COFFObjectFile::getSectionContents(DataRefImpl Ref) const { 294 const coff_section *Sec = toSec(Ref); 295 ArrayRef<uint8_t> Res; 296 if (Error E = getSectionContents(Sec, Res)) 297 return std::move(E); 298 return Res; 299 } 300 301 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const { 302 const coff_section *Sec = toSec(Ref); 303 return Sec->getAlignment(); 304 } 305 306 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const { 307 return false; 308 } 309 310 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const { 311 const coff_section *Sec = toSec(Ref); 312 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE; 313 } 314 315 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const { 316 const coff_section *Sec = toSec(Ref); 317 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; 318 } 319 320 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const { 321 const coff_section *Sec = toSec(Ref); 322 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 323 COFF::IMAGE_SCN_MEM_READ | 324 COFF::IMAGE_SCN_MEM_WRITE; 325 return (Sec->Characteristics & BssFlags) == BssFlags; 326 } 327 328 // The .debug sections are the only debug sections for COFF 329 // (\see MCObjectFileInfo.cpp). 330 bool COFFObjectFile::isDebugSection(StringRef SectionName) const { 331 return SectionName.startswith(".debug"); 332 } 333 334 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const { 335 uintptr_t Offset = 336 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable); 337 assert((Offset % sizeof(coff_section)) == 0); 338 return (Offset / sizeof(coff_section)) + 1; 339 } 340 341 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const { 342 const coff_section *Sec = toSec(Ref); 343 // In COFF, a virtual section won't have any in-file 344 // content, so the file pointer to the content will be zero. 345 return Sec->PointerToRawData == 0; 346 } 347 348 static uint32_t getNumberOfRelocations(const coff_section *Sec, 349 MemoryBufferRef M, const uint8_t *base) { 350 // The field for the number of relocations in COFF section table is only 351 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to 352 // NumberOfRelocations field, and the actual relocation count is stored in the 353 // VirtualAddress field in the first relocation entry. 354 if (Sec->hasExtendedRelocations()) { 355 const coff_relocation *FirstReloc; 356 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>( 357 base + Sec->PointerToRelocations))) 358 return 0; 359 // -1 to exclude this first relocation entry. 360 return FirstReloc->VirtualAddress - 1; 361 } 362 return Sec->NumberOfRelocations; 363 } 364 365 static const coff_relocation * 366 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) { 367 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base); 368 if (!NumRelocs) 369 return nullptr; 370 auto begin = reinterpret_cast<const coff_relocation *>( 371 Base + Sec->PointerToRelocations); 372 if (Sec->hasExtendedRelocations()) { 373 // Skip the first relocation entry repurposed to store the number of 374 // relocations. 375 begin++; 376 } 377 if (Binary::checkOffset(M, uintptr_t(begin), 378 sizeof(coff_relocation) * NumRelocs)) 379 return nullptr; 380 return begin; 381 } 382 383 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { 384 const coff_section *Sec = toSec(Ref); 385 const coff_relocation *begin = getFirstReloc(Sec, Data, base()); 386 if (begin && Sec->VirtualAddress != 0) 387 report_fatal_error("Sections with relocations should have an address of 0"); 388 DataRefImpl Ret; 389 Ret.p = reinterpret_cast<uintptr_t>(begin); 390 return relocation_iterator(RelocationRef(Ret, this)); 391 } 392 393 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { 394 const coff_section *Sec = toSec(Ref); 395 const coff_relocation *I = getFirstReloc(Sec, Data, base()); 396 if (I) 397 I += getNumberOfRelocations(Sec, Data, base()); 398 DataRefImpl Ret; 399 Ret.p = reinterpret_cast<uintptr_t>(I); 400 return relocation_iterator(RelocationRef(Ret, this)); 401 } 402 403 // Initialize the pointer to the symbol table. 404 std::error_code COFFObjectFile::initSymbolTablePtr() { 405 if (COFFHeader) 406 if (std::error_code EC = getObject( 407 SymbolTable16, Data, base() + getPointerToSymbolTable(), 408 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize())) 409 return EC; 410 411 if (COFFBigObjHeader) 412 if (std::error_code EC = getObject( 413 SymbolTable32, Data, base() + getPointerToSymbolTable(), 414 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize())) 415 return EC; 416 417 // Find string table. The first four byte of the string table contains the 418 // total size of the string table, including the size field itself. If the 419 // string table is empty, the value of the first four byte would be 4. 420 uint32_t StringTableOffset = getPointerToSymbolTable() + 421 getNumberOfSymbols() * getSymbolTableEntrySize(); 422 const uint8_t *StringTableAddr = base() + StringTableOffset; 423 const ulittle32_t *StringTableSizePtr; 424 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr)) 425 return EC; 426 StringTableSize = *StringTableSizePtr; 427 if (std::error_code EC = 428 getObject(StringTable, Data, StringTableAddr, StringTableSize)) 429 return EC; 430 431 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some 432 // tools like cvtres write a size of 0 for an empty table instead of 4. 433 if (StringTableSize < 4) 434 StringTableSize = 4; 435 436 // Check that the string table is null terminated if has any in it. 437 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0) 438 return object_error::parse_failed; 439 return std::error_code(); 440 } 441 442 uint64_t COFFObjectFile::getImageBase() const { 443 if (PE32Header) 444 return PE32Header->ImageBase; 445 else if (PE32PlusHeader) 446 return PE32PlusHeader->ImageBase; 447 // This actually comes up in practice. 448 return 0; 449 } 450 451 // Returns the file offset for the given VA. 452 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const { 453 uint64_t ImageBase = getImageBase(); 454 uint64_t Rva = Addr - ImageBase; 455 assert(Rva <= UINT32_MAX); 456 return getRvaPtr((uint32_t)Rva, Res); 457 } 458 459 // Returns the file offset for the given RVA. 460 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const { 461 for (const SectionRef &S : sections()) { 462 const coff_section *Section = getCOFFSection(S); 463 uint32_t SectionStart = Section->VirtualAddress; 464 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize; 465 if (SectionStart <= Addr && Addr < SectionEnd) { 466 uint32_t Offset = Addr - SectionStart; 467 Res = uintptr_t(base()) + Section->PointerToRawData + Offset; 468 return std::error_code(); 469 } 470 } 471 return object_error::parse_failed; 472 } 473 474 std::error_code 475 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, 476 ArrayRef<uint8_t> &Contents) const { 477 for (const SectionRef &S : sections()) { 478 const coff_section *Section = getCOFFSection(S); 479 uint32_t SectionStart = Section->VirtualAddress; 480 // Check if this RVA is within the section bounds. Be careful about integer 481 // overflow. 482 uint32_t OffsetIntoSection = RVA - SectionStart; 483 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize && 484 Size <= Section->VirtualSize - OffsetIntoSection) { 485 uintptr_t Begin = 486 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection; 487 Contents = 488 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size); 489 return std::error_code(); 490 } 491 } 492 return object_error::parse_failed; 493 } 494 495 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name 496 // table entry. 497 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint, 498 StringRef &Name) const { 499 uintptr_t IntPtr = 0; 500 if (std::error_code EC = getRvaPtr(Rva, IntPtr)) 501 return EC; 502 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); 503 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); 504 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); 505 return std::error_code(); 506 } 507 508 std::error_code 509 COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir, 510 const codeview::DebugInfo *&PDBInfo, 511 StringRef &PDBFileName) const { 512 ArrayRef<uint8_t> InfoBytes; 513 if (std::error_code EC = getRvaAndSizeAsBytes( 514 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes)) 515 return EC; 516 if (InfoBytes.size() < sizeof(*PDBInfo) + 1) 517 return object_error::parse_failed; 518 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data()); 519 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo)); 520 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()), 521 InfoBytes.size()); 522 // Truncate the name at the first null byte. Ignore any padding. 523 PDBFileName = PDBFileName.split('\0').first; 524 return std::error_code(); 525 } 526 527 std::error_code 528 COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo, 529 StringRef &PDBFileName) const { 530 for (const debug_directory &D : debug_directories()) 531 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) 532 return getDebugPDBInfo(&D, PDBInfo, PDBFileName); 533 // If we get here, there is no PDB info to return. 534 PDBInfo = nullptr; 535 PDBFileName = StringRef(); 536 return std::error_code(); 537 } 538 539 // Find the import table. 540 std::error_code COFFObjectFile::initImportTablePtr() { 541 // First, we get the RVA of the import table. If the file lacks a pointer to 542 // the import table, do nothing. 543 const data_directory *DataEntry; 544 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry)) 545 return std::error_code(); 546 547 // Do nothing if the pointer to import table is NULL. 548 if (DataEntry->RelativeVirtualAddress == 0) 549 return std::error_code(); 550 551 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; 552 553 // Find the section that contains the RVA. This is needed because the RVA is 554 // the import table's memory address which is different from its file offset. 555 uintptr_t IntPtr = 0; 556 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr)) 557 return EC; 558 if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size)) 559 return EC; 560 ImportDirectory = reinterpret_cast< 561 const coff_import_directory_table_entry *>(IntPtr); 562 return std::error_code(); 563 } 564 565 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory. 566 std::error_code COFFObjectFile::initDelayImportTablePtr() { 567 const data_directory *DataEntry; 568 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry)) 569 return std::error_code(); 570 if (DataEntry->RelativeVirtualAddress == 0) 571 return std::error_code(); 572 573 uint32_t RVA = DataEntry->RelativeVirtualAddress; 574 NumberOfDelayImportDirectory = DataEntry->Size / 575 sizeof(delay_import_directory_table_entry) - 1; 576 577 uintptr_t IntPtr = 0; 578 if (std::error_code EC = getRvaPtr(RVA, IntPtr)) 579 return EC; 580 DelayImportDirectory = reinterpret_cast< 581 const delay_import_directory_table_entry *>(IntPtr); 582 return std::error_code(); 583 } 584 585 // Find the export table. 586 std::error_code COFFObjectFile::initExportTablePtr() { 587 // First, we get the RVA of the export table. If the file lacks a pointer to 588 // the export table, do nothing. 589 const data_directory *DataEntry; 590 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) 591 return std::error_code(); 592 593 // Do nothing if the pointer to export table is NULL. 594 if (DataEntry->RelativeVirtualAddress == 0) 595 return std::error_code(); 596 597 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; 598 uintptr_t IntPtr = 0; 599 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr)) 600 return EC; 601 ExportDirectory = 602 reinterpret_cast<const export_directory_table_entry *>(IntPtr); 603 return std::error_code(); 604 } 605 606 std::error_code COFFObjectFile::initBaseRelocPtr() { 607 const data_directory *DataEntry; 608 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry)) 609 return std::error_code(); 610 if (DataEntry->RelativeVirtualAddress == 0) 611 return std::error_code(); 612 613 uintptr_t IntPtr = 0; 614 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr)) 615 return EC; 616 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>( 617 IntPtr); 618 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>( 619 IntPtr + DataEntry->Size); 620 // FIXME: Verify the section containing BaseRelocHeader has at least 621 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress. 622 return std::error_code(); 623 } 624 625 std::error_code COFFObjectFile::initDebugDirectoryPtr() { 626 // Get the RVA of the debug directory. Do nothing if it does not exist. 627 const data_directory *DataEntry; 628 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry)) 629 return std::error_code(); 630 631 // Do nothing if the RVA is NULL. 632 if (DataEntry->RelativeVirtualAddress == 0) 633 return std::error_code(); 634 635 // Check that the size is a multiple of the entry size. 636 if (DataEntry->Size % sizeof(debug_directory) != 0) 637 return object_error::parse_failed; 638 639 uintptr_t IntPtr = 0; 640 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr)) 641 return EC; 642 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr); 643 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>( 644 IntPtr + DataEntry->Size); 645 // FIXME: Verify the section containing DebugDirectoryBegin has at least 646 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress. 647 return std::error_code(); 648 } 649 650 std::error_code COFFObjectFile::initLoadConfigPtr() { 651 // Get the RVA of the debug directory. Do nothing if it does not exist. 652 const data_directory *DataEntry; 653 if (getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataEntry)) 654 return std::error_code(); 655 656 // Do nothing if the RVA is NULL. 657 if (DataEntry->RelativeVirtualAddress == 0) 658 return std::error_code(); 659 uintptr_t IntPtr = 0; 660 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr)) 661 return EC; 662 663 LoadConfig = (const void *)IntPtr; 664 return std::error_code(); 665 } 666 667 Expected<std::unique_ptr<COFFObjectFile>> 668 COFFObjectFile::create(MemoryBufferRef Object) { 669 std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object))); 670 if (Error E = Obj->initialize()) 671 return std::move(E); 672 return std::move(Obj); 673 } 674 675 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object) 676 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr), 677 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr), 678 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr), 679 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0), 680 ImportDirectory(nullptr), DelayImportDirectory(nullptr), 681 NumberOfDelayImportDirectory(0), ExportDirectory(nullptr), 682 BaseRelocHeader(nullptr), BaseRelocEnd(nullptr), 683 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {} 684 685 Error COFFObjectFile::initialize() { 686 // Check that we at least have enough room for a header. 687 std::error_code EC; 688 if (!checkSize(Data, EC, sizeof(coff_file_header))) 689 return errorCodeToError(EC); 690 691 // The current location in the file where we are looking at. 692 uint64_t CurPtr = 0; 693 694 // PE header is optional and is present only in executables. If it exists, 695 // it is placed right after COFF header. 696 bool HasPEHeader = false; 697 698 // Check if this is a PE/COFF file. 699 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) { 700 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte 701 // PE signature to find 'normal' COFF header. 702 const auto *DH = reinterpret_cast<const dos_header *>(base()); 703 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') { 704 CurPtr = DH->AddressOfNewExeHeader; 705 // Check the PE magic bytes. ("PE\0\0") 706 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) { 707 return errorCodeToError(object_error::parse_failed); 708 } 709 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes. 710 HasPEHeader = true; 711 } 712 } 713 714 if ((EC = getObject(COFFHeader, Data, base() + CurPtr))) 715 return errorCodeToError(EC); 716 717 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF 718 // import libraries share a common prefix but bigobj is more restrictive. 719 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN && 720 COFFHeader->NumberOfSections == uint16_t(0xffff) && 721 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) { 722 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr))) 723 return errorCodeToError(EC); 724 725 // Verify that we are dealing with bigobj. 726 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion && 727 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic, 728 sizeof(COFF::BigObjMagic)) == 0) { 729 COFFHeader = nullptr; 730 CurPtr += sizeof(coff_bigobj_file_header); 731 } else { 732 // It's not a bigobj. 733 COFFBigObjHeader = nullptr; 734 } 735 } 736 if (COFFHeader) { 737 // The prior checkSize call may have failed. This isn't a hard error 738 // because we were just trying to sniff out bigobj. 739 EC = std::error_code(); 740 CurPtr += sizeof(coff_file_header); 741 742 if (COFFHeader->isImportLibrary()) 743 return errorCodeToError(EC); 744 } 745 746 if (HasPEHeader) { 747 const pe32_header *Header; 748 if ((EC = getObject(Header, Data, base() + CurPtr))) 749 return errorCodeToError(EC); 750 751 const uint8_t *DataDirAddr; 752 uint64_t DataDirSize; 753 if (Header->Magic == COFF::PE32Header::PE32) { 754 PE32Header = Header; 755 DataDirAddr = base() + CurPtr + sizeof(pe32_header); 756 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize; 757 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) { 758 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header); 759 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header); 760 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize; 761 } else { 762 // It's neither PE32 nor PE32+. 763 return errorCodeToError(object_error::parse_failed); 764 } 765 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))) 766 return errorCodeToError(EC); 767 } 768 769 if (COFFHeader) 770 CurPtr += COFFHeader->SizeOfOptionalHeader; 771 772 if ((EC = getObject(SectionTable, Data, base() + CurPtr, 773 (uint64_t)getNumberOfSections() * sizeof(coff_section)))) 774 return errorCodeToError(EC); 775 776 // Initialize the pointer to the symbol table. 777 if (getPointerToSymbolTable() != 0) { 778 if ((EC = initSymbolTablePtr())) { 779 SymbolTable16 = nullptr; 780 SymbolTable32 = nullptr; 781 StringTable = nullptr; 782 StringTableSize = 0; 783 } 784 } else { 785 // We had better not have any symbols if we don't have a symbol table. 786 if (getNumberOfSymbols() != 0) { 787 return errorCodeToError(object_error::parse_failed); 788 } 789 } 790 791 // Initialize the pointer to the beginning of the import table. 792 if ((EC = initImportTablePtr())) 793 return errorCodeToError(EC); 794 if ((EC = initDelayImportTablePtr())) 795 return errorCodeToError(EC); 796 797 // Initialize the pointer to the export table. 798 if ((EC = initExportTablePtr())) 799 return errorCodeToError(EC); 800 801 // Initialize the pointer to the base relocation table. 802 if ((EC = initBaseRelocPtr())) 803 return errorCodeToError(EC); 804 805 // Initialize the pointer to the export table. 806 if ((EC = initDebugDirectoryPtr())) 807 return errorCodeToError(EC); 808 809 if ((EC = initLoadConfigPtr())) 810 return errorCodeToError(EC); 811 812 return Error::success(); 813 } 814 815 basic_symbol_iterator COFFObjectFile::symbol_begin() const { 816 DataRefImpl Ret; 817 Ret.p = getSymbolTable(); 818 return basic_symbol_iterator(SymbolRef(Ret, this)); 819 } 820 821 basic_symbol_iterator COFFObjectFile::symbol_end() const { 822 // The symbol table ends where the string table begins. 823 DataRefImpl Ret; 824 Ret.p = reinterpret_cast<uintptr_t>(StringTable); 825 return basic_symbol_iterator(SymbolRef(Ret, this)); 826 } 827 828 import_directory_iterator COFFObjectFile::import_directory_begin() const { 829 if (!ImportDirectory) 830 return import_directory_end(); 831 if (ImportDirectory->isNull()) 832 return import_directory_end(); 833 return import_directory_iterator( 834 ImportDirectoryEntryRef(ImportDirectory, 0, this)); 835 } 836 837 import_directory_iterator COFFObjectFile::import_directory_end() const { 838 return import_directory_iterator( 839 ImportDirectoryEntryRef(nullptr, -1, this)); 840 } 841 842 delay_import_directory_iterator 843 COFFObjectFile::delay_import_directory_begin() const { 844 return delay_import_directory_iterator( 845 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this)); 846 } 847 848 delay_import_directory_iterator 849 COFFObjectFile::delay_import_directory_end() const { 850 return delay_import_directory_iterator( 851 DelayImportDirectoryEntryRef( 852 DelayImportDirectory, NumberOfDelayImportDirectory, this)); 853 } 854 855 export_directory_iterator COFFObjectFile::export_directory_begin() const { 856 return export_directory_iterator( 857 ExportDirectoryEntryRef(ExportDirectory, 0, this)); 858 } 859 860 export_directory_iterator COFFObjectFile::export_directory_end() const { 861 if (!ExportDirectory) 862 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this)); 863 ExportDirectoryEntryRef Ref(ExportDirectory, 864 ExportDirectory->AddressTableEntries, this); 865 return export_directory_iterator(Ref); 866 } 867 868 section_iterator COFFObjectFile::section_begin() const { 869 DataRefImpl Ret; 870 Ret.p = reinterpret_cast<uintptr_t>(SectionTable); 871 return section_iterator(SectionRef(Ret, this)); 872 } 873 874 section_iterator COFFObjectFile::section_end() const { 875 DataRefImpl Ret; 876 int NumSections = 877 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections(); 878 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections); 879 return section_iterator(SectionRef(Ret, this)); 880 } 881 882 base_reloc_iterator COFFObjectFile::base_reloc_begin() const { 883 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this)); 884 } 885 886 base_reloc_iterator COFFObjectFile::base_reloc_end() const { 887 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this)); 888 } 889 890 uint8_t COFFObjectFile::getBytesInAddress() const { 891 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4; 892 } 893 894 StringRef COFFObjectFile::getFileFormatName() const { 895 switch(getMachine()) { 896 case COFF::IMAGE_FILE_MACHINE_I386: 897 return "COFF-i386"; 898 case COFF::IMAGE_FILE_MACHINE_AMD64: 899 return "COFF-x86-64"; 900 case COFF::IMAGE_FILE_MACHINE_ARMNT: 901 return "COFF-ARM"; 902 case COFF::IMAGE_FILE_MACHINE_ARM64: 903 return "COFF-ARM64"; 904 default: 905 return "COFF-<unknown arch>"; 906 } 907 } 908 909 Triple::ArchType COFFObjectFile::getArch() const { 910 switch (getMachine()) { 911 case COFF::IMAGE_FILE_MACHINE_I386: 912 return Triple::x86; 913 case COFF::IMAGE_FILE_MACHINE_AMD64: 914 return Triple::x86_64; 915 case COFF::IMAGE_FILE_MACHINE_ARMNT: 916 return Triple::thumb; 917 case COFF::IMAGE_FILE_MACHINE_ARM64: 918 return Triple::aarch64; 919 default: 920 return Triple::UnknownArch; 921 } 922 } 923 924 Expected<uint64_t> COFFObjectFile::getStartAddress() const { 925 if (PE32Header) 926 return PE32Header->AddressOfEntryPoint; 927 return 0; 928 } 929 930 iterator_range<import_directory_iterator> 931 COFFObjectFile::import_directories() const { 932 return make_range(import_directory_begin(), import_directory_end()); 933 } 934 935 iterator_range<delay_import_directory_iterator> 936 COFFObjectFile::delay_import_directories() const { 937 return make_range(delay_import_directory_begin(), 938 delay_import_directory_end()); 939 } 940 941 iterator_range<export_directory_iterator> 942 COFFObjectFile::export_directories() const { 943 return make_range(export_directory_begin(), export_directory_end()); 944 } 945 946 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const { 947 return make_range(base_reloc_begin(), base_reloc_end()); 948 } 949 950 std::error_code 951 COFFObjectFile::getDataDirectory(uint32_t Index, 952 const data_directory *&Res) const { 953 // Error if there's no data directory or the index is out of range. 954 if (!DataDirectory) { 955 Res = nullptr; 956 return object_error::parse_failed; 957 } 958 assert(PE32Header || PE32PlusHeader); 959 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize 960 : PE32PlusHeader->NumberOfRvaAndSize; 961 if (Index >= NumEnt) { 962 Res = nullptr; 963 return object_error::parse_failed; 964 } 965 Res = &DataDirectory[Index]; 966 return std::error_code(); 967 } 968 969 Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const { 970 // Perhaps getting the section of a reserved section index should be an error, 971 // but callers rely on this to return null. 972 if (COFF::isReservedSectionNumber(Index)) 973 return (const coff_section *)nullptr; 974 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) { 975 // We already verified the section table data, so no need to check again. 976 return SectionTable + (Index - 1); 977 } 978 return errorCodeToError(object_error::parse_failed); 979 } 980 981 Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const { 982 if (StringTableSize <= 4) 983 // Tried to get a string from an empty string table. 984 return errorCodeToError(object_error::parse_failed); 985 if (Offset >= StringTableSize) 986 return errorCodeToError(object_error::unexpected_eof); 987 return StringRef(StringTable + Offset); 988 } 989 990 Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const { 991 return getSymbolName(Symbol.getGeneric()); 992 } 993 994 Expected<StringRef> 995 COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const { 996 // Check for string table entry. First 4 bytes are 0. 997 if (Symbol->Name.Offset.Zeroes == 0) 998 return getString(Symbol->Name.Offset.Offset); 999 1000 // Null terminated, let ::strlen figure out the length. 1001 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0) 1002 return StringRef(Symbol->Name.ShortName); 1003 1004 // Not null terminated, use all 8 bytes. 1005 return StringRef(Symbol->Name.ShortName, COFF::NameSize); 1006 } 1007 1008 ArrayRef<uint8_t> 1009 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const { 1010 const uint8_t *Aux = nullptr; 1011 1012 size_t SymbolSize = getSymbolTableEntrySize(); 1013 if (Symbol.getNumberOfAuxSymbols() > 0) { 1014 // AUX data comes immediately after the symbol in COFF 1015 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize; 1016 #ifndef NDEBUG 1017 // Verify that the Aux symbol points to a valid entry in the symbol table. 1018 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); 1019 if (Offset < getPointerToSymbolTable() || 1020 Offset >= 1021 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize)) 1022 report_fatal_error("Aux Symbol data was outside of symbol table."); 1023 1024 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 && 1025 "Aux Symbol data did not point to the beginning of a symbol"); 1026 #endif 1027 } 1028 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize); 1029 } 1030 1031 uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const { 1032 uintptr_t Offset = 1033 reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable(); 1034 assert(Offset % getSymbolTableEntrySize() == 0 && 1035 "Symbol did not point to the beginning of a symbol"); 1036 size_t Index = Offset / getSymbolTableEntrySize(); 1037 assert(Index < getNumberOfSymbols()); 1038 return Index; 1039 } 1040 1041 Expected<StringRef> 1042 COFFObjectFile::getSectionName(const coff_section *Sec) const { 1043 StringRef Name; 1044 if (Sec->Name[COFF::NameSize - 1] == 0) 1045 // Null terminated, let ::strlen figure out the length. 1046 Name = Sec->Name; 1047 else 1048 // Not null terminated, use all 8 bytes. 1049 Name = StringRef(Sec->Name, COFF::NameSize); 1050 1051 // Check for string table entry. First byte is '/'. 1052 if (Name.startswith("/")) { 1053 uint32_t Offset; 1054 if (Name.startswith("//")) { 1055 if (decodeBase64StringEntry(Name.substr(2), Offset)) 1056 return createStringError(object_error::parse_failed, 1057 "invalid section name"); 1058 } else { 1059 if (Name.substr(1).getAsInteger(10, Offset)) 1060 return createStringError(object_error::parse_failed, 1061 "invalid section name"); 1062 } 1063 return getString(Offset); 1064 } 1065 1066 return Name; 1067 } 1068 1069 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const { 1070 // SizeOfRawData and VirtualSize change what they represent depending on 1071 // whether or not we have an executable image. 1072 // 1073 // For object files, SizeOfRawData contains the size of section's data; 1074 // VirtualSize should be zero but isn't due to buggy COFF writers. 1075 // 1076 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the 1077 // actual section size is in VirtualSize. It is possible for VirtualSize to 1078 // be greater than SizeOfRawData; the contents past that point should be 1079 // considered to be zero. 1080 if (getDOSHeader()) 1081 return std::min(Sec->VirtualSize, Sec->SizeOfRawData); 1082 return Sec->SizeOfRawData; 1083 } 1084 1085 Error COFFObjectFile::getSectionContents(const coff_section *Sec, 1086 ArrayRef<uint8_t> &Res) const { 1087 // In COFF, a virtual section won't have any in-file 1088 // content, so the file pointer to the content will be zero. 1089 if (Sec->PointerToRawData == 0) 1090 return Error::success(); 1091 // The only thing that we need to verify is that the contents is contained 1092 // within the file bounds. We don't need to make sure it doesn't cover other 1093 // data, as there's nothing that says that is not allowed. 1094 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData; 1095 uint32_t SectionSize = getSectionSize(Sec); 1096 if (checkOffset(Data, ConStart, SectionSize)) 1097 return make_error<BinaryError>(); 1098 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize); 1099 return Error::success(); 1100 } 1101 1102 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { 1103 return reinterpret_cast<const coff_relocation*>(Rel.p); 1104 } 1105 1106 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { 1107 Rel.p = reinterpret_cast<uintptr_t>( 1108 reinterpret_cast<const coff_relocation*>(Rel.p) + 1); 1109 } 1110 1111 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const { 1112 const coff_relocation *R = toRel(Rel); 1113 return R->VirtualAddress; 1114 } 1115 1116 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 1117 const coff_relocation *R = toRel(Rel); 1118 DataRefImpl Ref; 1119 if (R->SymbolTableIndex >= getNumberOfSymbols()) 1120 return symbol_end(); 1121 if (SymbolTable16) 1122 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex); 1123 else if (SymbolTable32) 1124 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex); 1125 else 1126 llvm_unreachable("no symbol table pointer!"); 1127 return symbol_iterator(SymbolRef(Ref, this)); 1128 } 1129 1130 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const { 1131 const coff_relocation* R = toRel(Rel); 1132 return R->Type; 1133 } 1134 1135 const coff_section * 1136 COFFObjectFile::getCOFFSection(const SectionRef &Section) const { 1137 return toSec(Section.getRawDataRefImpl()); 1138 } 1139 1140 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const { 1141 if (SymbolTable16) 1142 return toSymb<coff_symbol16>(Ref); 1143 if (SymbolTable32) 1144 return toSymb<coff_symbol32>(Ref); 1145 llvm_unreachable("no symbol table pointer!"); 1146 } 1147 1148 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const { 1149 return getCOFFSymbol(Symbol.getRawDataRefImpl()); 1150 } 1151 1152 const coff_relocation * 1153 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const { 1154 return toRel(Reloc.getRawDataRefImpl()); 1155 } 1156 1157 ArrayRef<coff_relocation> 1158 COFFObjectFile::getRelocations(const coff_section *Sec) const { 1159 return {getFirstReloc(Sec, Data, base()), 1160 getNumberOfRelocations(Sec, Data, base())}; 1161 } 1162 1163 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \ 1164 case COFF::reloc_type: \ 1165 return #reloc_type; 1166 1167 StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const { 1168 switch (getMachine()) { 1169 case COFF::IMAGE_FILE_MACHINE_AMD64: 1170 switch (Type) { 1171 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); 1172 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); 1173 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); 1174 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); 1175 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); 1176 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); 1177 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); 1178 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); 1179 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); 1180 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); 1181 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); 1182 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); 1183 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); 1184 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); 1185 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); 1186 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); 1187 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); 1188 default: 1189 return "Unknown"; 1190 } 1191 break; 1192 case COFF::IMAGE_FILE_MACHINE_ARMNT: 1193 switch (Type) { 1194 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE); 1195 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32); 1196 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB); 1197 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24); 1198 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11); 1199 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN); 1200 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24); 1201 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11); 1202 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32); 1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION); 1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL); 1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A); 1206 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T); 1207 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T); 1208 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T); 1209 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T); 1210 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR); 1211 default: 1212 return "Unknown"; 1213 } 1214 break; 1215 case COFF::IMAGE_FILE_MACHINE_ARM64: 1216 switch (Type) { 1217 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE); 1218 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32); 1219 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB); 1220 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26); 1221 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21); 1222 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21); 1223 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A); 1224 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L); 1225 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL); 1226 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A); 1227 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A); 1228 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L); 1229 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN); 1230 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION); 1231 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64); 1232 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19); 1233 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14); 1234 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32); 1235 default: 1236 return "Unknown"; 1237 } 1238 break; 1239 case COFF::IMAGE_FILE_MACHINE_I386: 1240 switch (Type) { 1241 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); 1242 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); 1243 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); 1244 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); 1245 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); 1246 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); 1247 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); 1248 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); 1249 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); 1250 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); 1251 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); 1252 default: 1253 return "Unknown"; 1254 } 1255 break; 1256 default: 1257 return "Unknown"; 1258 } 1259 } 1260 1261 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME 1262 1263 void COFFObjectFile::getRelocationTypeName( 1264 DataRefImpl Rel, SmallVectorImpl<char> &Result) const { 1265 const coff_relocation *Reloc = toRel(Rel); 1266 StringRef Res = getRelocationTypeName(Reloc->Type); 1267 Result.append(Res.begin(), Res.end()); 1268 } 1269 1270 bool COFFObjectFile::isRelocatableObject() const { 1271 return !DataDirectory; 1272 } 1273 1274 StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const { 1275 return StringSwitch<StringRef>(Name) 1276 .Case("eh_fram", "eh_frame") 1277 .Default(Name); 1278 } 1279 1280 bool ImportDirectoryEntryRef:: 1281 operator==(const ImportDirectoryEntryRef &Other) const { 1282 return ImportTable == Other.ImportTable && Index == Other.Index; 1283 } 1284 1285 void ImportDirectoryEntryRef::moveNext() { 1286 ++Index; 1287 if (ImportTable[Index].isNull()) { 1288 Index = -1; 1289 ImportTable = nullptr; 1290 } 1291 } 1292 1293 std::error_code ImportDirectoryEntryRef::getImportTableEntry( 1294 const coff_import_directory_table_entry *&Result) const { 1295 return getObject(Result, OwningObject->Data, ImportTable + Index); 1296 } 1297 1298 static imported_symbol_iterator 1299 makeImportedSymbolIterator(const COFFObjectFile *Object, 1300 uintptr_t Ptr, int Index) { 1301 if (Object->getBytesInAddress() == 4) { 1302 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr); 1303 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1304 } 1305 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr); 1306 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1307 } 1308 1309 static imported_symbol_iterator 1310 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) { 1311 uintptr_t IntPtr = 0; 1312 Object->getRvaPtr(RVA, IntPtr); 1313 return makeImportedSymbolIterator(Object, IntPtr, 0); 1314 } 1315 1316 static imported_symbol_iterator 1317 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) { 1318 uintptr_t IntPtr = 0; 1319 Object->getRvaPtr(RVA, IntPtr); 1320 // Forward the pointer to the last entry which is null. 1321 int Index = 0; 1322 if (Object->getBytesInAddress() == 4) { 1323 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr); 1324 while (*Entry++) 1325 ++Index; 1326 } else { 1327 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr); 1328 while (*Entry++) 1329 ++Index; 1330 } 1331 return makeImportedSymbolIterator(Object, IntPtr, Index); 1332 } 1333 1334 imported_symbol_iterator 1335 ImportDirectoryEntryRef::imported_symbol_begin() const { 1336 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA, 1337 OwningObject); 1338 } 1339 1340 imported_symbol_iterator 1341 ImportDirectoryEntryRef::imported_symbol_end() const { 1342 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA, 1343 OwningObject); 1344 } 1345 1346 iterator_range<imported_symbol_iterator> 1347 ImportDirectoryEntryRef::imported_symbols() const { 1348 return make_range(imported_symbol_begin(), imported_symbol_end()); 1349 } 1350 1351 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const { 1352 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA, 1353 OwningObject); 1354 } 1355 1356 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const { 1357 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA, 1358 OwningObject); 1359 } 1360 1361 iterator_range<imported_symbol_iterator> 1362 ImportDirectoryEntryRef::lookup_table_symbols() const { 1363 return make_range(lookup_table_begin(), lookup_table_end()); 1364 } 1365 1366 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const { 1367 uintptr_t IntPtr = 0; 1368 if (std::error_code EC = 1369 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr)) 1370 return EC; 1371 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1372 return std::error_code(); 1373 } 1374 1375 std::error_code 1376 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const { 1377 Result = ImportTable[Index].ImportLookupTableRVA; 1378 return std::error_code(); 1379 } 1380 1381 std::error_code 1382 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const { 1383 Result = ImportTable[Index].ImportAddressTableRVA; 1384 return std::error_code(); 1385 } 1386 1387 bool DelayImportDirectoryEntryRef:: 1388 operator==(const DelayImportDirectoryEntryRef &Other) const { 1389 return Table == Other.Table && Index == Other.Index; 1390 } 1391 1392 void DelayImportDirectoryEntryRef::moveNext() { 1393 ++Index; 1394 } 1395 1396 imported_symbol_iterator 1397 DelayImportDirectoryEntryRef::imported_symbol_begin() const { 1398 return importedSymbolBegin(Table[Index].DelayImportNameTable, 1399 OwningObject); 1400 } 1401 1402 imported_symbol_iterator 1403 DelayImportDirectoryEntryRef::imported_symbol_end() const { 1404 return importedSymbolEnd(Table[Index].DelayImportNameTable, 1405 OwningObject); 1406 } 1407 1408 iterator_range<imported_symbol_iterator> 1409 DelayImportDirectoryEntryRef::imported_symbols() const { 1410 return make_range(imported_symbol_begin(), imported_symbol_end()); 1411 } 1412 1413 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const { 1414 uintptr_t IntPtr = 0; 1415 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr)) 1416 return EC; 1417 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1418 return std::error_code(); 1419 } 1420 1421 std::error_code DelayImportDirectoryEntryRef:: 1422 getDelayImportTable(const delay_import_directory_table_entry *&Result) const { 1423 Result = &Table[Index]; 1424 return std::error_code(); 1425 } 1426 1427 std::error_code DelayImportDirectoryEntryRef:: 1428 getImportAddress(int AddrIndex, uint64_t &Result) const { 1429 uint32_t RVA = Table[Index].DelayImportAddressTable + 1430 AddrIndex * (OwningObject->is64() ? 8 : 4); 1431 uintptr_t IntPtr = 0; 1432 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1433 return EC; 1434 if (OwningObject->is64()) 1435 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr); 1436 else 1437 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr); 1438 return std::error_code(); 1439 } 1440 1441 bool ExportDirectoryEntryRef:: 1442 operator==(const ExportDirectoryEntryRef &Other) const { 1443 return ExportTable == Other.ExportTable && Index == Other.Index; 1444 } 1445 1446 void ExportDirectoryEntryRef::moveNext() { 1447 ++Index; 1448 } 1449 1450 // Returns the name of the current export symbol. If the symbol is exported only 1451 // by ordinal, the empty string is set as a result. 1452 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const { 1453 uintptr_t IntPtr = 0; 1454 if (std::error_code EC = 1455 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr)) 1456 return EC; 1457 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1458 return std::error_code(); 1459 } 1460 1461 // Returns the starting ordinal number. 1462 std::error_code 1463 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { 1464 Result = ExportTable->OrdinalBase; 1465 return std::error_code(); 1466 } 1467 1468 // Returns the export ordinal of the current export symbol. 1469 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { 1470 Result = ExportTable->OrdinalBase + Index; 1471 return std::error_code(); 1472 } 1473 1474 // Returns the address of the current export symbol. 1475 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { 1476 uintptr_t IntPtr = 0; 1477 if (std::error_code EC = 1478 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr)) 1479 return EC; 1480 const export_address_table_entry *entry = 1481 reinterpret_cast<const export_address_table_entry *>(IntPtr); 1482 Result = entry[Index].ExportRVA; 1483 return std::error_code(); 1484 } 1485 1486 // Returns the name of the current export symbol. If the symbol is exported only 1487 // by ordinal, the empty string is set as a result. 1488 std::error_code 1489 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { 1490 uintptr_t IntPtr = 0; 1491 if (std::error_code EC = 1492 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr)) 1493 return EC; 1494 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); 1495 1496 uint32_t NumEntries = ExportTable->NumberOfNamePointers; 1497 int Offset = 0; 1498 for (const ulittle16_t *I = Start, *E = Start + NumEntries; 1499 I < E; ++I, ++Offset) { 1500 if (*I != Index) 1501 continue; 1502 if (std::error_code EC = 1503 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr)) 1504 return EC; 1505 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); 1506 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr)) 1507 return EC; 1508 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1509 return std::error_code(); 1510 } 1511 Result = ""; 1512 return std::error_code(); 1513 } 1514 1515 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const { 1516 const data_directory *DataEntry; 1517 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) 1518 return EC; 1519 uint32_t RVA; 1520 if (auto EC = getExportRVA(RVA)) 1521 return EC; 1522 uint32_t Begin = DataEntry->RelativeVirtualAddress; 1523 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size; 1524 Result = (Begin <= RVA && RVA < End); 1525 return std::error_code(); 1526 } 1527 1528 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const { 1529 uint32_t RVA; 1530 if (auto EC = getExportRVA(RVA)) 1531 return EC; 1532 uintptr_t IntPtr = 0; 1533 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1534 return EC; 1535 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1536 return std::error_code(); 1537 } 1538 1539 bool ImportedSymbolRef:: 1540 operator==(const ImportedSymbolRef &Other) const { 1541 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64 1542 && Index == Other.Index; 1543 } 1544 1545 void ImportedSymbolRef::moveNext() { 1546 ++Index; 1547 } 1548 1549 std::error_code 1550 ImportedSymbolRef::getSymbolName(StringRef &Result) const { 1551 uint32_t RVA; 1552 if (Entry32) { 1553 // If a symbol is imported only by ordinal, it has no name. 1554 if (Entry32[Index].isOrdinal()) 1555 return std::error_code(); 1556 RVA = Entry32[Index].getHintNameRVA(); 1557 } else { 1558 if (Entry64[Index].isOrdinal()) 1559 return std::error_code(); 1560 RVA = Entry64[Index].getHintNameRVA(); 1561 } 1562 uintptr_t IntPtr = 0; 1563 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1564 return EC; 1565 // +2 because the first two bytes is hint. 1566 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2)); 1567 return std::error_code(); 1568 } 1569 1570 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const { 1571 if (Entry32) 1572 Result = Entry32[Index].isOrdinal(); 1573 else 1574 Result = Entry64[Index].isOrdinal(); 1575 return std::error_code(); 1576 } 1577 1578 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const { 1579 if (Entry32) 1580 Result = Entry32[Index].getHintNameRVA(); 1581 else 1582 Result = Entry64[Index].getHintNameRVA(); 1583 return std::error_code(); 1584 } 1585 1586 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const { 1587 uint32_t RVA; 1588 if (Entry32) { 1589 if (Entry32[Index].isOrdinal()) { 1590 Result = Entry32[Index].getOrdinal(); 1591 return std::error_code(); 1592 } 1593 RVA = Entry32[Index].getHintNameRVA(); 1594 } else { 1595 if (Entry64[Index].isOrdinal()) { 1596 Result = Entry64[Index].getOrdinal(); 1597 return std::error_code(); 1598 } 1599 RVA = Entry64[Index].getHintNameRVA(); 1600 } 1601 uintptr_t IntPtr = 0; 1602 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1603 return EC; 1604 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr); 1605 return std::error_code(); 1606 } 1607 1608 Expected<std::unique_ptr<COFFObjectFile>> 1609 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) { 1610 return COFFObjectFile::create(Object); 1611 } 1612 1613 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const { 1614 return Header == Other.Header && Index == Other.Index; 1615 } 1616 1617 void BaseRelocRef::moveNext() { 1618 // Header->BlockSize is the size of the current block, including the 1619 // size of the header itself. 1620 uint32_t Size = sizeof(*Header) + 1621 sizeof(coff_base_reloc_block_entry) * (Index + 1); 1622 if (Size == Header->BlockSize) { 1623 // .reloc contains a list of base relocation blocks. Each block 1624 // consists of the header followed by entries. The header contains 1625 // how many entories will follow. When we reach the end of the 1626 // current block, proceed to the next block. 1627 Header = reinterpret_cast<const coff_base_reloc_block_header *>( 1628 reinterpret_cast<const uint8_t *>(Header) + Size); 1629 Index = 0; 1630 } else { 1631 ++Index; 1632 } 1633 } 1634 1635 std::error_code BaseRelocRef::getType(uint8_t &Type) const { 1636 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1); 1637 Type = Entry[Index].getType(); 1638 return std::error_code(); 1639 } 1640 1641 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const { 1642 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1); 1643 Result = Header->PageRVA + Entry[Index].getOffset(); 1644 return std::error_code(); 1645 } 1646 1647 #define RETURN_IF_ERROR(Expr) \ 1648 do { \ 1649 Error E = (Expr); \ 1650 if (E) \ 1651 return std::move(E); \ 1652 } while (0) 1653 1654 Expected<ArrayRef<UTF16>> 1655 ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) { 1656 BinaryStreamReader Reader = BinaryStreamReader(BBS); 1657 Reader.setOffset(Offset); 1658 uint16_t Length; 1659 RETURN_IF_ERROR(Reader.readInteger(Length)); 1660 ArrayRef<UTF16> RawDirString; 1661 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length)); 1662 return RawDirString; 1663 } 1664 1665 Expected<ArrayRef<UTF16>> 1666 ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) { 1667 return getDirStringAtOffset(Entry.Identifier.getNameOffset()); 1668 } 1669 1670 Expected<const coff_resource_dir_table &> 1671 ResourceSectionRef::getTableAtOffset(uint32_t Offset) { 1672 const coff_resource_dir_table *Table = nullptr; 1673 1674 BinaryStreamReader Reader(BBS); 1675 Reader.setOffset(Offset); 1676 RETURN_IF_ERROR(Reader.readObject(Table)); 1677 assert(Table != nullptr); 1678 return *Table; 1679 } 1680 1681 Expected<const coff_resource_dir_entry &> 1682 ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) { 1683 const coff_resource_dir_entry *Entry = nullptr; 1684 1685 BinaryStreamReader Reader(BBS); 1686 Reader.setOffset(Offset); 1687 RETURN_IF_ERROR(Reader.readObject(Entry)); 1688 assert(Entry != nullptr); 1689 return *Entry; 1690 } 1691 1692 Expected<const coff_resource_data_entry &> 1693 ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) { 1694 const coff_resource_data_entry *Entry = nullptr; 1695 1696 BinaryStreamReader Reader(BBS); 1697 Reader.setOffset(Offset); 1698 RETURN_IF_ERROR(Reader.readObject(Entry)); 1699 assert(Entry != nullptr); 1700 return *Entry; 1701 } 1702 1703 Expected<const coff_resource_dir_table &> 1704 ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) { 1705 assert(Entry.Offset.isSubDir()); 1706 return getTableAtOffset(Entry.Offset.value()); 1707 } 1708 1709 Expected<const coff_resource_data_entry &> 1710 ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) { 1711 assert(!Entry.Offset.isSubDir()); 1712 return getDataEntryAtOffset(Entry.Offset.value()); 1713 } 1714 1715 Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() { 1716 return getTableAtOffset(0); 1717 } 1718 1719 Expected<const coff_resource_dir_entry &> 1720 ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table, 1721 uint32_t Index) { 1722 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries)) 1723 return createStringError(object_error::parse_failed, "index out of range"); 1724 const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table); 1725 ptrdiff_t TableOffset = TablePtr - BBS.data().data(); 1726 return getTableEntryAtOffset(TableOffset + sizeof(Table) + 1727 Index * sizeof(coff_resource_dir_entry)); 1728 } 1729 1730 Error ResourceSectionRef::load(const COFFObjectFile *O) { 1731 for (const SectionRef &S : O->sections()) { 1732 Expected<StringRef> Name = S.getName(); 1733 if (!Name) 1734 return Name.takeError(); 1735 1736 if (*Name == ".rsrc" || *Name == ".rsrc$01") 1737 return load(O, S); 1738 } 1739 return createStringError(object_error::parse_failed, 1740 "no resource section found"); 1741 } 1742 1743 Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) { 1744 Obj = O; 1745 Section = S; 1746 Expected<StringRef> Contents = Section.getContents(); 1747 if (!Contents) 1748 return Contents.takeError(); 1749 BBS = BinaryByteStream(*Contents, support::little); 1750 const coff_section *COFFSect = Obj->getCOFFSection(Section); 1751 ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect); 1752 Relocs.reserve(OrigRelocs.size()); 1753 for (const coff_relocation &R : OrigRelocs) 1754 Relocs.push_back(&R); 1755 std::sort(Relocs.begin(), Relocs.end(), 1756 [](const coff_relocation *A, const coff_relocation *B) { 1757 return A->VirtualAddress < B->VirtualAddress; 1758 }); 1759 return Error::success(); 1760 } 1761 1762 Expected<StringRef> 1763 ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) { 1764 if (!Obj) 1765 return createStringError(object_error::parse_failed, "no object provided"); 1766 1767 // Find a potential relocation at the DataRVA field (first member of 1768 // the coff_resource_data_entry struct). 1769 const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry); 1770 ptrdiff_t EntryOffset = EntryPtr - BBS.data().data(); 1771 coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0), 1772 ulittle16_t(0)}; 1773 auto RelocsForOffset = 1774 std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget, 1775 [](const coff_relocation *A, const coff_relocation *B) { 1776 return A->VirtualAddress < B->VirtualAddress; 1777 }); 1778 1779 if (RelocsForOffset.first != RelocsForOffset.second) { 1780 // We found a relocation with the right offset. Check that it does have 1781 // the expected type. 1782 const coff_relocation &R = **RelocsForOffset.first; 1783 uint16_t RVAReloc; 1784 switch (Obj->getMachine()) { 1785 case COFF::IMAGE_FILE_MACHINE_I386: 1786 RVAReloc = COFF::IMAGE_REL_I386_DIR32NB; 1787 break; 1788 case COFF::IMAGE_FILE_MACHINE_AMD64: 1789 RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB; 1790 break; 1791 case COFF::IMAGE_FILE_MACHINE_ARMNT: 1792 RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB; 1793 break; 1794 case COFF::IMAGE_FILE_MACHINE_ARM64: 1795 RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB; 1796 break; 1797 default: 1798 return createStringError(object_error::parse_failed, 1799 "unsupported architecture"); 1800 } 1801 if (R.Type != RVAReloc) 1802 return createStringError(object_error::parse_failed, 1803 "unexpected relocation type"); 1804 // Get the relocation's symbol 1805 Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex); 1806 if (!Sym) 1807 return Sym.takeError(); 1808 // And the symbol's section 1809 Expected<const coff_section *> Section = 1810 Obj->getSection(Sym->getSectionNumber()); 1811 if (!Section) 1812 return Section.takeError(); 1813 // Add the initial value of DataRVA to the symbol's offset to find the 1814 // data it points at. 1815 uint64_t Offset = Entry.DataRVA + Sym->getValue(); 1816 ArrayRef<uint8_t> Contents; 1817 if (Error E = Obj->getSectionContents(*Section, Contents)) 1818 return std::move(E); 1819 if (Offset + Entry.DataSize > Contents.size()) 1820 return createStringError(object_error::parse_failed, 1821 "data outside of section"); 1822 // Return a reference to the data inside the section. 1823 return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset, 1824 Entry.DataSize); 1825 } else { 1826 // Relocatable objects need a relocation for the DataRVA field. 1827 if (Obj->isRelocatableObject()) 1828 return createStringError(object_error::parse_failed, 1829 "no relocation found for DataRVA"); 1830 1831 // Locate the section that contains the address that DataRVA points at. 1832 uint64_t VA = Entry.DataRVA + Obj->getImageBase(); 1833 for (const SectionRef &S : Obj->sections()) { 1834 if (VA >= S.getAddress() && 1835 VA + Entry.DataSize <= S.getAddress() + S.getSize()) { 1836 uint64_t Offset = VA - S.getAddress(); 1837 Expected<StringRef> Contents = S.getContents(); 1838 if (!Contents) 1839 return Contents.takeError(); 1840 return Contents->slice(Offset, Offset + Entry.DataSize); 1841 } 1842 } 1843 return createStringError(object_error::parse_failed, 1844 "address not found in image"); 1845 } 1846 } 1847