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/iterator_range.h" 17 #include "llvm/Object/Binary.h" 18 #include "llvm/Object/COFF.h" 19 #include "llvm/Object/Error.h" 20 #include "llvm/Object/ObjectFile.h" 21 #include "llvm/Object/WindowsMachineFlag.h" 22 #include "llvm/Support/BinaryStreamReader.h" 23 #include "llvm/Support/Endian.h" 24 #include "llvm/Support/Error.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Support/MemoryBufferRef.h" 28 #include <algorithm> 29 #include <cassert> 30 #include <cinttypes> 31 #include <cstddef> 32 #include <cstring> 33 #include <limits> 34 #include <memory> 35 #include <system_error> 36 37 using namespace llvm; 38 using namespace object; 39 40 using support::ulittle16_t; 41 using support::ulittle32_t; 42 using support::ulittle64_t; 43 using support::little16_t; 44 45 // Returns false if size is greater than the buffer size. And sets ec. 46 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) { 47 if (M.getBufferSize() < Size) { 48 EC = object_error::unexpected_eof; 49 return false; 50 } 51 return true; 52 } 53 54 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. 55 // Returns unexpected_eof if error. 56 template <typename T> 57 static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr, 58 const uint64_t Size = sizeof(T)) { 59 uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr); 60 if (Error E = Binary::checkOffset(M, Addr, Size)) 61 return E; 62 Obj = reinterpret_cast<const T *>(Addr); 63 return Error::success(); 64 } 65 66 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without 67 // prefixed slashes. 68 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) { 69 assert(Str.size() <= 6 && "String too long, possible overflow."); 70 if (Str.size() > 6) 71 return true; 72 73 uint64_t Value = 0; 74 while (!Str.empty()) { 75 unsigned CharVal; 76 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25 77 CharVal = Str[0] - 'A'; 78 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51 79 CharVal = Str[0] - 'a' + 26; 80 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61 81 CharVal = Str[0] - '0' + 52; 82 else if (Str[0] == '+') // 62 83 CharVal = 62; 84 else if (Str[0] == '/') // 63 85 CharVal = 63; 86 else 87 return true; 88 89 Value = (Value * 64) + CharVal; 90 Str = Str.substr(1); 91 } 92 93 if (Value > std::numeric_limits<uint32_t>::max()) 94 return true; 95 96 Result = static_cast<uint32_t>(Value); 97 return false; 98 } 99 100 template <typename coff_symbol_type> 101 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const { 102 const coff_symbol_type *Addr = 103 reinterpret_cast<const coff_symbol_type *>(Ref.p); 104 105 assert(!checkOffset(Data, reinterpret_cast<uintptr_t>(Addr), sizeof(*Addr))); 106 #ifndef NDEBUG 107 // Verify that the symbol points to a valid entry in the symbol table. 108 uintptr_t Offset = 109 reinterpret_cast<uintptr_t>(Addr) - reinterpret_cast<uintptr_t>(base()); 110 111 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && 112 "Symbol did not point to the beginning of a symbol"); 113 #endif 114 115 return Addr; 116 } 117 118 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { 119 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); 120 121 #ifndef NDEBUG 122 // Verify that the section points to a valid entry in the section table. 123 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections())) 124 report_fatal_error("Section was outside of section table."); 125 126 uintptr_t Offset = reinterpret_cast<uintptr_t>(Addr) - 127 reinterpret_cast<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 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(DataRefImpl Ref) const { 331 Expected<StringRef> SectionNameOrErr = getSectionName(Ref); 332 if (!SectionNameOrErr) { 333 // TODO: Report the error message properly. 334 consumeError(SectionNameOrErr.takeError()); 335 return false; 336 } 337 StringRef SectionName = SectionNameOrErr.get(); 338 return SectionName.starts_with(".debug"); 339 } 340 341 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const { 342 uintptr_t Offset = 343 Sec.getRawDataRefImpl().p - reinterpret_cast<uintptr_t>(SectionTable); 344 assert((Offset % sizeof(coff_section)) == 0); 345 return (Offset / sizeof(coff_section)) + 1; 346 } 347 348 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const { 349 const coff_section *Sec = toSec(Ref); 350 // In COFF, a virtual section won't have any in-file 351 // content, so the file pointer to the content will be zero. 352 return Sec->PointerToRawData == 0; 353 } 354 355 static uint32_t getNumberOfRelocations(const coff_section *Sec, 356 MemoryBufferRef M, const uint8_t *base) { 357 // The field for the number of relocations in COFF section table is only 358 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to 359 // NumberOfRelocations field, and the actual relocation count is stored in the 360 // VirtualAddress field in the first relocation entry. 361 if (Sec->hasExtendedRelocations()) { 362 const coff_relocation *FirstReloc; 363 if (Error E = getObject(FirstReloc, M, 364 reinterpret_cast<const coff_relocation *>( 365 base + Sec->PointerToRelocations))) { 366 consumeError(std::move(E)); 367 return 0; 368 } 369 // -1 to exclude this first relocation entry. 370 return FirstReloc->VirtualAddress - 1; 371 } 372 return Sec->NumberOfRelocations; 373 } 374 375 static const coff_relocation * 376 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) { 377 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base); 378 if (!NumRelocs) 379 return nullptr; 380 auto begin = reinterpret_cast<const coff_relocation *>( 381 Base + Sec->PointerToRelocations); 382 if (Sec->hasExtendedRelocations()) { 383 // Skip the first relocation entry repurposed to store the number of 384 // relocations. 385 begin++; 386 } 387 if (auto E = Binary::checkOffset(M, reinterpret_cast<uintptr_t>(begin), 388 sizeof(coff_relocation) * NumRelocs)) { 389 consumeError(std::move(E)); 390 return nullptr; 391 } 392 return begin; 393 } 394 395 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { 396 const coff_section *Sec = toSec(Ref); 397 const coff_relocation *begin = getFirstReloc(Sec, Data, base()); 398 if (begin && Sec->VirtualAddress != 0) 399 report_fatal_error("Sections with relocations should have an address of 0"); 400 DataRefImpl Ret; 401 Ret.p = reinterpret_cast<uintptr_t>(begin); 402 return relocation_iterator(RelocationRef(Ret, this)); 403 } 404 405 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { 406 const coff_section *Sec = toSec(Ref); 407 const coff_relocation *I = getFirstReloc(Sec, Data, base()); 408 if (I) 409 I += getNumberOfRelocations(Sec, Data, base()); 410 DataRefImpl Ret; 411 Ret.p = reinterpret_cast<uintptr_t>(I); 412 return relocation_iterator(RelocationRef(Ret, this)); 413 } 414 415 // Initialize the pointer to the symbol table. 416 Error COFFObjectFile::initSymbolTablePtr() { 417 if (COFFHeader) 418 if (Error E = getObject( 419 SymbolTable16, Data, base() + getPointerToSymbolTable(), 420 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize())) 421 return E; 422 423 if (COFFBigObjHeader) 424 if (Error E = getObject( 425 SymbolTable32, Data, base() + getPointerToSymbolTable(), 426 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize())) 427 return E; 428 429 // Find string table. The first four byte of the string table contains the 430 // total size of the string table, including the size field itself. If the 431 // string table is empty, the value of the first four byte would be 4. 432 uint32_t StringTableOffset = getPointerToSymbolTable() + 433 getNumberOfSymbols() * getSymbolTableEntrySize(); 434 const uint8_t *StringTableAddr = base() + StringTableOffset; 435 const ulittle32_t *StringTableSizePtr; 436 if (Error E = getObject(StringTableSizePtr, Data, StringTableAddr)) 437 return E; 438 StringTableSize = *StringTableSizePtr; 439 if (Error E = getObject(StringTable, Data, StringTableAddr, StringTableSize)) 440 return E; 441 442 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some 443 // tools like cvtres write a size of 0 for an empty table instead of 4. 444 if (StringTableSize < 4) 445 StringTableSize = 4; 446 447 // Check that the string table is null terminated if has any in it. 448 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0) 449 return createStringError(object_error::parse_failed, 450 "string table missing null terminator"); 451 return Error::success(); 452 } 453 454 uint64_t COFFObjectFile::getImageBase() const { 455 if (PE32Header) 456 return PE32Header->ImageBase; 457 else if (PE32PlusHeader) 458 return PE32PlusHeader->ImageBase; 459 // This actually comes up in practice. 460 return 0; 461 } 462 463 // Returns the file offset for the given VA. 464 Error COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const { 465 uint64_t ImageBase = getImageBase(); 466 uint64_t Rva = Addr - ImageBase; 467 assert(Rva <= UINT32_MAX); 468 return getRvaPtr((uint32_t)Rva, Res); 469 } 470 471 // Returns the file offset for the given RVA. 472 Error COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res, 473 const char *ErrorContext) const { 474 for (const SectionRef &S : sections()) { 475 const coff_section *Section = getCOFFSection(S); 476 uint32_t SectionStart = Section->VirtualAddress; 477 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize; 478 if (SectionStart <= Addr && Addr < SectionEnd) { 479 // A table/directory entry can be pointing to somewhere in a stripped 480 // section, in an object that went through `objcopy --only-keep-debug`. 481 // In this case we don't want to cause the parsing of the object file to 482 // fail, otherwise it will be impossible to use this object as debug info 483 // in LLDB. Return SectionStrippedError here so that 484 // COFFObjectFile::initialize can ignore the error. 485 // Somewhat common binaries may have RVAs pointing outside of the 486 // provided raw data. Instead of rejecting the binaries, just 487 // treat the section as stripped for these purposes. 488 if (Section->SizeOfRawData < Section->VirtualSize && 489 Addr >= SectionStart + Section->SizeOfRawData) { 490 return make_error<SectionStrippedError>(); 491 } 492 uint32_t Offset = Addr - SectionStart; 493 Res = reinterpret_cast<uintptr_t>(base()) + Section->PointerToRawData + 494 Offset; 495 return Error::success(); 496 } 497 } 498 if (ErrorContext) 499 return createStringError(object_error::parse_failed, 500 "RVA 0x%" PRIx32 " for %s not found", Addr, 501 ErrorContext); 502 return createStringError(object_error::parse_failed, 503 "RVA 0x%" PRIx32 " not found", Addr); 504 } 505 506 Error COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, 507 ArrayRef<uint8_t> &Contents, 508 const char *ErrorContext) const { 509 for (const SectionRef &S : sections()) { 510 const coff_section *Section = getCOFFSection(S); 511 uint32_t SectionStart = Section->VirtualAddress; 512 // Check if this RVA is within the section bounds. Be careful about integer 513 // overflow. 514 uint32_t OffsetIntoSection = RVA - SectionStart; 515 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize && 516 Size <= Section->VirtualSize - OffsetIntoSection) { 517 uintptr_t Begin = reinterpret_cast<uintptr_t>(base()) + 518 Section->PointerToRawData + OffsetIntoSection; 519 Contents = 520 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size); 521 return Error::success(); 522 } 523 } 524 if (ErrorContext) 525 return createStringError(object_error::parse_failed, 526 "RVA 0x%" PRIx32 " for %s not found", RVA, 527 ErrorContext); 528 return createStringError(object_error::parse_failed, 529 "RVA 0x%" PRIx32 " not found", RVA); 530 } 531 532 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name 533 // table entry. 534 Error COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint, 535 StringRef &Name) const { 536 uintptr_t IntPtr = 0; 537 if (Error E = getRvaPtr(Rva, IntPtr)) 538 return E; 539 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); 540 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); 541 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); 542 return Error::success(); 543 } 544 545 Error COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir, 546 const codeview::DebugInfo *&PDBInfo, 547 StringRef &PDBFileName) const { 548 ArrayRef<uint8_t> InfoBytes; 549 if (Error E = 550 getRvaAndSizeAsBytes(DebugDir->AddressOfRawData, DebugDir->SizeOfData, 551 InfoBytes, "PDB info")) 552 return E; 553 if (InfoBytes.size() < sizeof(*PDBInfo) + 1) 554 return createStringError(object_error::parse_failed, "PDB info too small"); 555 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data()); 556 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo)); 557 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()), 558 InfoBytes.size()); 559 // Truncate the name at the first null byte. Ignore any padding. 560 PDBFileName = PDBFileName.split('\0').first; 561 return Error::success(); 562 } 563 564 Error COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo, 565 StringRef &PDBFileName) const { 566 for (const debug_directory &D : debug_directories()) 567 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) 568 return getDebugPDBInfo(&D, PDBInfo, PDBFileName); 569 // If we get here, there is no PDB info to return. 570 PDBInfo = nullptr; 571 PDBFileName = StringRef(); 572 return Error::success(); 573 } 574 575 // Find the import table. 576 Error COFFObjectFile::initImportTablePtr() { 577 // First, we get the RVA of the import table. If the file lacks a pointer to 578 // the import table, do nothing. 579 const data_directory *DataEntry = getDataDirectory(COFF::IMPORT_TABLE); 580 if (!DataEntry) 581 return Error::success(); 582 583 // Do nothing if the pointer to import table is NULL. 584 if (DataEntry->RelativeVirtualAddress == 0) 585 return Error::success(); 586 587 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; 588 589 // Find the section that contains the RVA. This is needed because the RVA is 590 // the import table's memory address which is different from its file offset. 591 uintptr_t IntPtr = 0; 592 if (Error E = getRvaPtr(ImportTableRva, IntPtr, "import table")) 593 return E; 594 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 595 return E; 596 ImportDirectory = reinterpret_cast< 597 const coff_import_directory_table_entry *>(IntPtr); 598 return Error::success(); 599 } 600 601 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory. 602 Error COFFObjectFile::initDelayImportTablePtr() { 603 const data_directory *DataEntry = 604 getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR); 605 if (!DataEntry) 606 return Error::success(); 607 if (DataEntry->RelativeVirtualAddress == 0) 608 return Error::success(); 609 610 uint32_t RVA = DataEntry->RelativeVirtualAddress; 611 NumberOfDelayImportDirectory = DataEntry->Size / 612 sizeof(delay_import_directory_table_entry) - 1; 613 614 uintptr_t IntPtr = 0; 615 if (Error E = getRvaPtr(RVA, IntPtr, "delay import table")) 616 return E; 617 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 618 return E; 619 620 DelayImportDirectory = reinterpret_cast< 621 const delay_import_directory_table_entry *>(IntPtr); 622 return Error::success(); 623 } 624 625 // Find the export table. 626 Error COFFObjectFile::initExportTablePtr() { 627 // First, we get the RVA of the export table. If the file lacks a pointer to 628 // the export table, do nothing. 629 const data_directory *DataEntry = getDataDirectory(COFF::EXPORT_TABLE); 630 if (!DataEntry) 631 return Error::success(); 632 633 // Do nothing if the pointer to export table is NULL. 634 if (DataEntry->RelativeVirtualAddress == 0) 635 return Error::success(); 636 637 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; 638 uintptr_t IntPtr = 0; 639 if (Error E = getRvaPtr(ExportTableRva, IntPtr, "export table")) 640 return E; 641 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 642 return E; 643 644 ExportDirectory = 645 reinterpret_cast<const export_directory_table_entry *>(IntPtr); 646 return Error::success(); 647 } 648 649 Error COFFObjectFile::initBaseRelocPtr() { 650 const data_directory *DataEntry = 651 getDataDirectory(COFF::BASE_RELOCATION_TABLE); 652 if (!DataEntry) 653 return Error::success(); 654 if (DataEntry->RelativeVirtualAddress == 0) 655 return Error::success(); 656 657 uintptr_t IntPtr = 0; 658 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr, 659 "base reloc table")) 660 return E; 661 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 662 return E; 663 664 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>( 665 IntPtr); 666 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>( 667 IntPtr + DataEntry->Size); 668 // FIXME: Verify the section containing BaseRelocHeader has at least 669 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress. 670 return Error::success(); 671 } 672 673 Error COFFObjectFile::initDebugDirectoryPtr() { 674 // Get the RVA of the debug directory. Do nothing if it does not exist. 675 const data_directory *DataEntry = getDataDirectory(COFF::DEBUG_DIRECTORY); 676 if (!DataEntry) 677 return Error::success(); 678 679 // Do nothing if the RVA is NULL. 680 if (DataEntry->RelativeVirtualAddress == 0) 681 return Error::success(); 682 683 // Check that the size is a multiple of the entry size. 684 if (DataEntry->Size % sizeof(debug_directory) != 0) 685 return createStringError(object_error::parse_failed, 686 "debug directory has uneven size"); 687 688 uintptr_t IntPtr = 0; 689 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr, 690 "debug directory")) 691 return E; 692 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 693 return E; 694 695 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr); 696 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>( 697 IntPtr + DataEntry->Size); 698 // FIXME: Verify the section containing DebugDirectoryBegin has at least 699 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress. 700 return Error::success(); 701 } 702 703 Error COFFObjectFile::initTLSDirectoryPtr() { 704 // Get the RVA of the TLS directory. Do nothing if it does not exist. 705 const data_directory *DataEntry = getDataDirectory(COFF::TLS_TABLE); 706 if (!DataEntry) 707 return Error::success(); 708 709 // Do nothing if the RVA is NULL. 710 if (DataEntry->RelativeVirtualAddress == 0) 711 return Error::success(); 712 713 uint64_t DirSize = 714 is64() ? sizeof(coff_tls_directory64) : sizeof(coff_tls_directory32); 715 716 // Check that the size is correct. 717 if (DataEntry->Size != DirSize) 718 return createStringError( 719 object_error::parse_failed, 720 "TLS Directory size (%u) is not the expected size (%" PRIu64 ").", 721 static_cast<uint32_t>(DataEntry->Size), DirSize); 722 723 uintptr_t IntPtr = 0; 724 if (Error E = 725 getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr, "TLS directory")) 726 return E; 727 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 728 return E; 729 730 if (is64()) 731 TLSDirectory64 = reinterpret_cast<const coff_tls_directory64 *>(IntPtr); 732 else 733 TLSDirectory32 = reinterpret_cast<const coff_tls_directory32 *>(IntPtr); 734 735 return Error::success(); 736 } 737 738 Error COFFObjectFile::initLoadConfigPtr() { 739 // Get the RVA of the debug directory. Do nothing if it does not exist. 740 const data_directory *DataEntry = getDataDirectory(COFF::LOAD_CONFIG_TABLE); 741 if (!DataEntry) 742 return Error::success(); 743 744 // Do nothing if the RVA is NULL. 745 if (DataEntry->RelativeVirtualAddress == 0) 746 return Error::success(); 747 uintptr_t IntPtr = 0; 748 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr, 749 "load config table")) 750 return E; 751 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size)) 752 return E; 753 754 LoadConfig = (const void *)IntPtr; 755 756 if (is64()) { 757 auto Config = getLoadConfig64(); 758 if (Config->Size >= 759 offsetof(coff_load_configuration64, CHPEMetadataPointer) + 760 sizeof(Config->CHPEMetadataPointer) && 761 Config->CHPEMetadataPointer) { 762 uint64_t ChpeOff = Config->CHPEMetadataPointer; 763 if (Error E = 764 getRvaPtr(ChpeOff - getImageBase(), IntPtr, "CHPE metadata")) 765 return E; 766 if (Error E = checkOffset(Data, IntPtr, sizeof(*CHPEMetadata))) 767 return E; 768 769 CHPEMetadata = reinterpret_cast<const chpe_metadata *>(IntPtr); 770 771 // Validate CHPE metadata 772 if (CHPEMetadata->CodeMapCount) { 773 if (Error E = getRvaPtr(CHPEMetadata->CodeMap, IntPtr, "CHPE code map")) 774 return E; 775 if (Error E = checkOffset(Data, IntPtr, 776 CHPEMetadata->CodeMapCount * 777 sizeof(chpe_range_entry))) 778 return E; 779 } 780 781 if (CHPEMetadata->CodeRangesToEntryPointsCount) { 782 if (Error E = getRvaPtr(CHPEMetadata->CodeRangesToEntryPoints, IntPtr, 783 "CHPE entry point ranges")) 784 return E; 785 if (Error E = checkOffset(Data, IntPtr, 786 CHPEMetadata->CodeRangesToEntryPointsCount * 787 sizeof(chpe_code_range_entry))) 788 return E; 789 } 790 791 if (CHPEMetadata->RedirectionMetadataCount) { 792 if (Error E = getRvaPtr(CHPEMetadata->RedirectionMetadata, IntPtr, 793 "CHPE redirection metadata")) 794 return E; 795 if (Error E = checkOffset(Data, IntPtr, 796 CHPEMetadata->RedirectionMetadataCount * 797 sizeof(chpe_redirection_entry))) 798 return E; 799 } 800 } 801 802 if (Config->Size >= 803 offsetof(coff_load_configuration64, DynamicValueRelocTableSection) + 804 sizeof(Config->DynamicValueRelocTableSection)) 805 if (Error E = initDynamicRelocPtr(Config->DynamicValueRelocTableSection, 806 Config->DynamicValueRelocTableOffset)) 807 return E; 808 } else { 809 auto Config = getLoadConfig32(); 810 if (Config->Size >= 811 offsetof(coff_load_configuration32, DynamicValueRelocTableSection) + 812 sizeof(Config->DynamicValueRelocTableSection)) { 813 if (Error E = initDynamicRelocPtr(Config->DynamicValueRelocTableSection, 814 Config->DynamicValueRelocTableOffset)) 815 return E; 816 } 817 } 818 return Error::success(); 819 } 820 821 Error COFFObjectFile::initDynamicRelocPtr(uint32_t SectionIndex, 822 uint32_t SectionOffset) { 823 Expected<const coff_section *> Section = getSection(SectionIndex); 824 if (!Section) 825 return Section.takeError(); 826 if (!*Section) 827 return Error::success(); 828 829 // Interpret and validate dynamic relocations. 830 ArrayRef<uint8_t> Contents; 831 if (Error E = getSectionContents(*Section, Contents)) 832 return E; 833 834 Contents = Contents.drop_front(SectionOffset); 835 if (Contents.size() < sizeof(coff_dynamic_reloc_table)) 836 return createStringError(object_error::parse_failed, 837 "Too large DynamicValueRelocTableOffset (" + 838 Twine(SectionOffset) + ")"); 839 840 DynamicRelocTable = 841 reinterpret_cast<const coff_dynamic_reloc_table *>(Contents.data()); 842 843 if (DynamicRelocTable->Version != 1 && DynamicRelocTable->Version != 2) 844 return createStringError(object_error::parse_failed, 845 "Unsupported dynamic relocations table version (" + 846 Twine(DynamicRelocTable->Version) + ")"); 847 if (DynamicRelocTable->Size > Contents.size() - sizeof(*DynamicRelocTable)) 848 return createStringError(object_error::parse_failed, 849 "Indvalid dynamic relocations directory size (" + 850 Twine(DynamicRelocTable->Size) + ")"); 851 852 for (auto DynReloc : dynamic_relocs()) { 853 if (Error e = DynReloc.validate()) 854 return e; 855 } 856 857 return Error::success(); 858 } 859 860 Expected<std::unique_ptr<COFFObjectFile>> 861 COFFObjectFile::create(MemoryBufferRef Object) { 862 std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object))); 863 if (Error E = Obj->initialize()) 864 return E; 865 return std::move(Obj); 866 } 867 868 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object) 869 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr), 870 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr), 871 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr), 872 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0), 873 ImportDirectory(nullptr), DelayImportDirectory(nullptr), 874 NumberOfDelayImportDirectory(0), ExportDirectory(nullptr), 875 BaseRelocHeader(nullptr), BaseRelocEnd(nullptr), 876 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr), 877 TLSDirectory32(nullptr), TLSDirectory64(nullptr) {} 878 879 static Error ignoreStrippedErrors(Error E) { 880 if (E.isA<SectionStrippedError>()) { 881 consumeError(std::move(E)); 882 return Error::success(); 883 } 884 return E; 885 } 886 887 Error COFFObjectFile::initialize() { 888 // Check that we at least have enough room for a header. 889 std::error_code EC; 890 if (!checkSize(Data, EC, sizeof(coff_file_header))) 891 return errorCodeToError(EC); 892 893 // The current location in the file where we are looking at. 894 uint64_t CurPtr = 0; 895 896 // PE header is optional and is present only in executables. If it exists, 897 // it is placed right after COFF header. 898 bool HasPEHeader = false; 899 900 // Check if this is a PE/COFF file. 901 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) { 902 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte 903 // PE signature to find 'normal' COFF header. 904 const auto *DH = reinterpret_cast<const dos_header *>(base()); 905 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') { 906 CurPtr = DH->AddressOfNewExeHeader; 907 // Check the PE magic bytes. ("PE\0\0") 908 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) { 909 return createStringError(object_error::parse_failed, 910 "incorrect PE magic"); 911 } 912 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes. 913 HasPEHeader = true; 914 } 915 } 916 917 if (Error E = getObject(COFFHeader, Data, base() + CurPtr)) 918 return E; 919 920 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF 921 // import libraries share a common prefix but bigobj is more restrictive. 922 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN && 923 COFFHeader->NumberOfSections == uint16_t(0xffff) && 924 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) { 925 if (Error E = getObject(COFFBigObjHeader, Data, base() + CurPtr)) 926 return E; 927 928 // Verify that we are dealing with bigobj. 929 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion && 930 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic, 931 sizeof(COFF::BigObjMagic)) == 0) { 932 COFFHeader = nullptr; 933 CurPtr += sizeof(coff_bigobj_file_header); 934 } else { 935 // It's not a bigobj. 936 COFFBigObjHeader = nullptr; 937 } 938 } 939 if (COFFHeader) { 940 // The prior checkSize call may have failed. This isn't a hard error 941 // because we were just trying to sniff out bigobj. 942 EC = std::error_code(); 943 CurPtr += sizeof(coff_file_header); 944 945 if (COFFHeader->isImportLibrary()) 946 return errorCodeToError(EC); 947 } 948 949 if (HasPEHeader) { 950 const pe32_header *Header; 951 if (Error E = getObject(Header, Data, base() + CurPtr)) 952 return E; 953 954 const uint8_t *DataDirAddr; 955 uint64_t DataDirSize; 956 if (Header->Magic == COFF::PE32Header::PE32) { 957 PE32Header = Header; 958 DataDirAddr = base() + CurPtr + sizeof(pe32_header); 959 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize; 960 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) { 961 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header); 962 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header); 963 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize; 964 } else { 965 // It's neither PE32 nor PE32+. 966 return createStringError(object_error::parse_failed, 967 "incorrect PE magic"); 968 } 969 if (Error E = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)) 970 return E; 971 } 972 973 if (COFFHeader) 974 CurPtr += COFFHeader->SizeOfOptionalHeader; 975 976 assert(COFFHeader || COFFBigObjHeader); 977 978 if (Error E = 979 getObject(SectionTable, Data, base() + CurPtr, 980 (uint64_t)getNumberOfSections() * sizeof(coff_section))) 981 return E; 982 983 // Initialize the pointer to the symbol table. 984 if (getPointerToSymbolTable() != 0) { 985 if (Error E = initSymbolTablePtr()) { 986 // Recover from errors reading the symbol table. 987 consumeError(std::move(E)); 988 SymbolTable16 = nullptr; 989 SymbolTable32 = nullptr; 990 StringTable = nullptr; 991 StringTableSize = 0; 992 } 993 } else { 994 // We had better not have any symbols if we don't have a symbol table. 995 if (getNumberOfSymbols() != 0) { 996 return createStringError(object_error::parse_failed, 997 "symbol table missing"); 998 } 999 } 1000 1001 // Initialize the pointer to the beginning of the import table. 1002 if (Error E = ignoreStrippedErrors(initImportTablePtr())) 1003 return E; 1004 if (Error E = ignoreStrippedErrors(initDelayImportTablePtr())) 1005 return E; 1006 1007 // Initialize the pointer to the export table. 1008 if (Error E = ignoreStrippedErrors(initExportTablePtr())) 1009 return E; 1010 1011 // Initialize the pointer to the base relocation table. 1012 if (Error E = ignoreStrippedErrors(initBaseRelocPtr())) 1013 return E; 1014 1015 // Initialize the pointer to the debug directory. 1016 if (Error E = ignoreStrippedErrors(initDebugDirectoryPtr())) 1017 return E; 1018 1019 // Initialize the pointer to the TLS directory. 1020 if (Error E = ignoreStrippedErrors(initTLSDirectoryPtr())) 1021 return E; 1022 1023 if (Error E = ignoreStrippedErrors(initLoadConfigPtr())) 1024 return E; 1025 1026 return Error::success(); 1027 } 1028 1029 basic_symbol_iterator COFFObjectFile::symbol_begin() const { 1030 DataRefImpl Ret; 1031 Ret.p = getSymbolTable(); 1032 return basic_symbol_iterator(SymbolRef(Ret, this)); 1033 } 1034 1035 basic_symbol_iterator COFFObjectFile::symbol_end() const { 1036 // The symbol table ends where the string table begins. 1037 DataRefImpl Ret; 1038 Ret.p = reinterpret_cast<uintptr_t>(StringTable); 1039 return basic_symbol_iterator(SymbolRef(Ret, this)); 1040 } 1041 1042 import_directory_iterator COFFObjectFile::import_directory_begin() const { 1043 if (!ImportDirectory) 1044 return import_directory_end(); 1045 if (ImportDirectory->isNull()) 1046 return import_directory_end(); 1047 return import_directory_iterator( 1048 ImportDirectoryEntryRef(ImportDirectory, 0, this)); 1049 } 1050 1051 import_directory_iterator COFFObjectFile::import_directory_end() const { 1052 return import_directory_iterator( 1053 ImportDirectoryEntryRef(nullptr, -1, this)); 1054 } 1055 1056 delay_import_directory_iterator 1057 COFFObjectFile::delay_import_directory_begin() const { 1058 return delay_import_directory_iterator( 1059 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this)); 1060 } 1061 1062 delay_import_directory_iterator 1063 COFFObjectFile::delay_import_directory_end() const { 1064 return delay_import_directory_iterator( 1065 DelayImportDirectoryEntryRef( 1066 DelayImportDirectory, NumberOfDelayImportDirectory, this)); 1067 } 1068 1069 export_directory_iterator COFFObjectFile::export_directory_begin() const { 1070 return export_directory_iterator( 1071 ExportDirectoryEntryRef(ExportDirectory, 0, this)); 1072 } 1073 1074 export_directory_iterator COFFObjectFile::export_directory_end() const { 1075 if (!ExportDirectory) 1076 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this)); 1077 ExportDirectoryEntryRef Ref(ExportDirectory, 1078 ExportDirectory->AddressTableEntries, this); 1079 return export_directory_iterator(Ref); 1080 } 1081 1082 section_iterator COFFObjectFile::section_begin() const { 1083 DataRefImpl Ret; 1084 Ret.p = reinterpret_cast<uintptr_t>(SectionTable); 1085 return section_iterator(SectionRef(Ret, this)); 1086 } 1087 1088 section_iterator COFFObjectFile::section_end() const { 1089 DataRefImpl Ret; 1090 int NumSections = 1091 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections(); 1092 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections); 1093 return section_iterator(SectionRef(Ret, this)); 1094 } 1095 1096 base_reloc_iterator COFFObjectFile::base_reloc_begin() const { 1097 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this)); 1098 } 1099 1100 base_reloc_iterator COFFObjectFile::base_reloc_end() const { 1101 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this)); 1102 } 1103 1104 dynamic_reloc_iterator COFFObjectFile::dynamic_reloc_begin() const { 1105 const void *Header = DynamicRelocTable ? DynamicRelocTable + 1 : nullptr; 1106 return dynamic_reloc_iterator(DynamicRelocRef(Header, this)); 1107 } 1108 1109 dynamic_reloc_iterator COFFObjectFile::dynamic_reloc_end() const { 1110 const void *Header = nullptr; 1111 if (DynamicRelocTable) 1112 Header = reinterpret_cast<const uint8_t *>(DynamicRelocTable + 1) + 1113 DynamicRelocTable->Size; 1114 return dynamic_reloc_iterator(DynamicRelocRef(Header, this)); 1115 } 1116 1117 uint8_t COFFObjectFile::getBytesInAddress() const { 1118 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4; 1119 } 1120 1121 StringRef COFFObjectFile::getFileFormatName() const { 1122 switch(getMachine()) { 1123 case COFF::IMAGE_FILE_MACHINE_I386: 1124 return "COFF-i386"; 1125 case COFF::IMAGE_FILE_MACHINE_AMD64: 1126 return "COFF-x86-64"; 1127 case COFF::IMAGE_FILE_MACHINE_ARMNT: 1128 return "COFF-ARM"; 1129 case COFF::IMAGE_FILE_MACHINE_ARM64: 1130 return "COFF-ARM64"; 1131 case COFF::IMAGE_FILE_MACHINE_ARM64EC: 1132 return "COFF-ARM64EC"; 1133 case COFF::IMAGE_FILE_MACHINE_ARM64X: 1134 return "COFF-ARM64X"; 1135 default: 1136 return "COFF-<unknown arch>"; 1137 } 1138 } 1139 1140 Triple::ArchType COFFObjectFile::getArch() const { 1141 return getMachineArchType(getMachine()); 1142 } 1143 1144 Expected<uint64_t> COFFObjectFile::getStartAddress() const { 1145 if (PE32Header) 1146 return PE32Header->AddressOfEntryPoint; 1147 return 0; 1148 } 1149 1150 iterator_range<import_directory_iterator> 1151 COFFObjectFile::import_directories() const { 1152 return make_range(import_directory_begin(), import_directory_end()); 1153 } 1154 1155 iterator_range<delay_import_directory_iterator> 1156 COFFObjectFile::delay_import_directories() const { 1157 return make_range(delay_import_directory_begin(), 1158 delay_import_directory_end()); 1159 } 1160 1161 iterator_range<export_directory_iterator> 1162 COFFObjectFile::export_directories() const { 1163 return make_range(export_directory_begin(), export_directory_end()); 1164 } 1165 1166 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const { 1167 return make_range(base_reloc_begin(), base_reloc_end()); 1168 } 1169 1170 iterator_range<dynamic_reloc_iterator> COFFObjectFile::dynamic_relocs() const { 1171 return make_range(dynamic_reloc_begin(), dynamic_reloc_end()); 1172 } 1173 1174 const data_directory *COFFObjectFile::getDataDirectory(uint32_t Index) const { 1175 if (!DataDirectory) 1176 return nullptr; 1177 assert(PE32Header || PE32PlusHeader); 1178 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize 1179 : PE32PlusHeader->NumberOfRvaAndSize; 1180 if (Index >= NumEnt) 1181 return nullptr; 1182 return &DataDirectory[Index]; 1183 } 1184 1185 Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const { 1186 // Perhaps getting the section of a reserved section index should be an error, 1187 // but callers rely on this to return null. 1188 if (COFF::isReservedSectionNumber(Index)) 1189 return (const coff_section *)nullptr; 1190 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) { 1191 // We already verified the section table data, so no need to check again. 1192 return SectionTable + (Index - 1); 1193 } 1194 return createStringError(object_error::parse_failed, 1195 "section index out of bounds"); 1196 } 1197 1198 Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const { 1199 if (StringTableSize <= 4) 1200 // Tried to get a string from an empty string table. 1201 return createStringError(object_error::parse_failed, "string table empty"); 1202 if (Offset >= StringTableSize) 1203 return errorCodeToError(object_error::unexpected_eof); 1204 return StringRef(StringTable + Offset); 1205 } 1206 1207 Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const { 1208 return getSymbolName(Symbol.getGeneric()); 1209 } 1210 1211 Expected<StringRef> 1212 COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const { 1213 // Check for string table entry. First 4 bytes are 0. 1214 if (Symbol->Name.Offset.Zeroes == 0) 1215 return getString(Symbol->Name.Offset.Offset); 1216 1217 // Null terminated, let ::strlen figure out the length. 1218 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0) 1219 return StringRef(Symbol->Name.ShortName); 1220 1221 // Not null terminated, use all 8 bytes. 1222 return StringRef(Symbol->Name.ShortName, COFF::NameSize); 1223 } 1224 1225 ArrayRef<uint8_t> 1226 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const { 1227 const uint8_t *Aux = nullptr; 1228 1229 size_t SymbolSize = getSymbolTableEntrySize(); 1230 if (Symbol.getNumberOfAuxSymbols() > 0) { 1231 // AUX data comes immediately after the symbol in COFF 1232 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize; 1233 #ifndef NDEBUG 1234 // Verify that the Aux symbol points to a valid entry in the symbol table. 1235 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); 1236 if (Offset < getPointerToSymbolTable() || 1237 Offset >= 1238 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize)) 1239 report_fatal_error("Aux Symbol data was outside of symbol table."); 1240 1241 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 && 1242 "Aux Symbol data did not point to the beginning of a symbol"); 1243 #endif 1244 } 1245 return ArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize); 1246 } 1247 1248 uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const { 1249 uintptr_t Offset = 1250 reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable(); 1251 assert(Offset % getSymbolTableEntrySize() == 0 && 1252 "Symbol did not point to the beginning of a symbol"); 1253 size_t Index = Offset / getSymbolTableEntrySize(); 1254 assert(Index < getNumberOfSymbols()); 1255 return Index; 1256 } 1257 1258 Expected<StringRef> 1259 COFFObjectFile::getSectionName(const coff_section *Sec) const { 1260 StringRef Name = StringRef(Sec->Name, COFF::NameSize).split('\0').first; 1261 1262 // Check for string table entry. First byte is '/'. 1263 if (Name.starts_with("/")) { 1264 uint32_t Offset; 1265 if (Name.starts_with("//")) { 1266 if (decodeBase64StringEntry(Name.substr(2), Offset)) 1267 return createStringError(object_error::parse_failed, 1268 "invalid section name"); 1269 } else { 1270 if (Name.substr(1).getAsInteger(10, Offset)) 1271 return createStringError(object_error::parse_failed, 1272 "invalid section name"); 1273 } 1274 return getString(Offset); 1275 } 1276 1277 return Name; 1278 } 1279 1280 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const { 1281 // SizeOfRawData and VirtualSize change what they represent depending on 1282 // whether or not we have an executable image. 1283 // 1284 // For object files, SizeOfRawData contains the size of section's data; 1285 // VirtualSize should be zero but isn't due to buggy COFF writers. 1286 // 1287 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the 1288 // actual section size is in VirtualSize. It is possible for VirtualSize to 1289 // be greater than SizeOfRawData; the contents past that point should be 1290 // considered to be zero. 1291 if (getDOSHeader()) 1292 return std::min(Sec->VirtualSize, Sec->SizeOfRawData); 1293 return Sec->SizeOfRawData; 1294 } 1295 1296 Error COFFObjectFile::getSectionContents(const coff_section *Sec, 1297 ArrayRef<uint8_t> &Res) const { 1298 // In COFF, a virtual section won't have any in-file 1299 // content, so the file pointer to the content will be zero. 1300 if (Sec->PointerToRawData == 0) 1301 return Error::success(); 1302 // The only thing that we need to verify is that the contents is contained 1303 // within the file bounds. We don't need to make sure it doesn't cover other 1304 // data, as there's nothing that says that is not allowed. 1305 uintptr_t ConStart = 1306 reinterpret_cast<uintptr_t>(base()) + Sec->PointerToRawData; 1307 uint32_t SectionSize = getSectionSize(Sec); 1308 if (Error E = checkOffset(Data, ConStart, SectionSize)) 1309 return E; 1310 Res = ArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize); 1311 return Error::success(); 1312 } 1313 1314 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { 1315 return reinterpret_cast<const coff_relocation*>(Rel.p); 1316 } 1317 1318 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { 1319 Rel.p = reinterpret_cast<uintptr_t>( 1320 reinterpret_cast<const coff_relocation*>(Rel.p) + 1); 1321 } 1322 1323 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const { 1324 const coff_relocation *R = toRel(Rel); 1325 return R->VirtualAddress; 1326 } 1327 1328 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 1329 const coff_relocation *R = toRel(Rel); 1330 DataRefImpl Ref; 1331 if (R->SymbolTableIndex >= getNumberOfSymbols()) 1332 return symbol_end(); 1333 if (SymbolTable16) 1334 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex); 1335 else if (SymbolTable32) 1336 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex); 1337 else 1338 llvm_unreachable("no symbol table pointer!"); 1339 return symbol_iterator(SymbolRef(Ref, this)); 1340 } 1341 1342 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const { 1343 const coff_relocation* R = toRel(Rel); 1344 return R->Type; 1345 } 1346 1347 const coff_section * 1348 COFFObjectFile::getCOFFSection(const SectionRef &Section) const { 1349 return toSec(Section.getRawDataRefImpl()); 1350 } 1351 1352 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const { 1353 if (SymbolTable16) 1354 return toSymb<coff_symbol16>(Ref); 1355 if (SymbolTable32) 1356 return toSymb<coff_symbol32>(Ref); 1357 llvm_unreachable("no symbol table pointer!"); 1358 } 1359 1360 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const { 1361 return getCOFFSymbol(Symbol.getRawDataRefImpl()); 1362 } 1363 1364 const coff_relocation * 1365 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const { 1366 return toRel(Reloc.getRawDataRefImpl()); 1367 } 1368 1369 ArrayRef<coff_relocation> 1370 COFFObjectFile::getRelocations(const coff_section *Sec) const { 1371 return {getFirstReloc(Sec, Data, base()), 1372 getNumberOfRelocations(Sec, Data, base())}; 1373 } 1374 1375 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \ 1376 case COFF::reloc_type: \ 1377 return #reloc_type; 1378 1379 StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const { 1380 switch (getArch()) { 1381 case Triple::x86_64: 1382 switch (Type) { 1383 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); 1384 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); 1385 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); 1386 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); 1387 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); 1388 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); 1389 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); 1390 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); 1391 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); 1392 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); 1393 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); 1394 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); 1395 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); 1396 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); 1397 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); 1398 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); 1399 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); 1400 default: 1401 return "Unknown"; 1402 } 1403 break; 1404 case Triple::thumb: 1405 switch (Type) { 1406 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE); 1407 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32); 1408 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB); 1409 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24); 1410 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11); 1411 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN); 1412 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24); 1413 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11); 1414 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32); 1415 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION); 1416 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL); 1417 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A); 1418 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T); 1419 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T); 1420 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T); 1421 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T); 1422 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR); 1423 default: 1424 return "Unknown"; 1425 } 1426 break; 1427 case Triple::aarch64: 1428 switch (Type) { 1429 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE); 1430 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32); 1431 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB); 1432 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26); 1433 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21); 1434 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21); 1435 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A); 1436 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L); 1437 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL); 1438 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A); 1439 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A); 1440 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L); 1441 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN); 1442 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION); 1443 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64); 1444 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19); 1445 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14); 1446 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32); 1447 default: 1448 return "Unknown"; 1449 } 1450 break; 1451 case Triple::x86: 1452 switch (Type) { 1453 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); 1454 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); 1455 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); 1456 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); 1457 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); 1458 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); 1459 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); 1460 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); 1461 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); 1462 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); 1463 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); 1464 default: 1465 return "Unknown"; 1466 } 1467 break; 1468 case Triple::mipsel: 1469 switch (Type) { 1470 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_ABSOLUTE); 1471 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFHALF); 1472 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFWORD); 1473 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_JMPADDR); 1474 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFHI); 1475 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFLO); 1476 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_GPREL); 1477 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_LITERAL); 1478 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECTION); 1479 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECREL); 1480 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECRELLO); 1481 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECRELHI); 1482 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_JMPADDR16); 1483 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFWORDNB); 1484 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_PAIR); 1485 default: 1486 return "Unknown"; 1487 } 1488 break; 1489 default: 1490 return "Unknown"; 1491 } 1492 } 1493 1494 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME 1495 1496 void COFFObjectFile::getRelocationTypeName( 1497 DataRefImpl Rel, SmallVectorImpl<char> &Result) const { 1498 const coff_relocation *Reloc = toRel(Rel); 1499 StringRef Res = getRelocationTypeName(Reloc->Type); 1500 Result.append(Res.begin(), Res.end()); 1501 } 1502 1503 bool COFFObjectFile::isRelocatableObject() const { 1504 return !DataDirectory; 1505 } 1506 1507 StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const { 1508 return StringSwitch<StringRef>(Name) 1509 .Case("eh_fram", "eh_frame") 1510 .Default(Name); 1511 } 1512 1513 std::unique_ptr<MemoryBuffer> COFFObjectFile::getHybridObjectView() const { 1514 if (getMachine() != COFF::IMAGE_FILE_MACHINE_ARM64X) 1515 return nullptr; 1516 1517 std::unique_ptr<WritableMemoryBuffer> HybridView; 1518 1519 for (auto DynReloc : dynamic_relocs()) { 1520 if (DynReloc.getType() != COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X) 1521 continue; 1522 1523 for (auto reloc : DynReloc.arm64x_relocs()) { 1524 if (!HybridView) { 1525 HybridView = 1526 WritableMemoryBuffer::getNewUninitMemBuffer(Data.getBufferSize()); 1527 memcpy(HybridView->getBufferStart(), Data.getBufferStart(), 1528 Data.getBufferSize()); 1529 } 1530 1531 uint32_t RVA = reloc.getRVA(); 1532 void *Ptr; 1533 uintptr_t IntPtr; 1534 if (RVA & ~0xfff) { 1535 cantFail(getRvaPtr(RVA, IntPtr)); 1536 Ptr = HybridView->getBufferStart() + IntPtr - 1537 reinterpret_cast<uintptr_t>(base()); 1538 } else { 1539 // PE header relocation. 1540 Ptr = HybridView->getBufferStart() + RVA; 1541 } 1542 1543 switch (reloc.getType()) { 1544 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL: 1545 memset(Ptr, 0, reloc.getSize()); 1546 break; 1547 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: { 1548 auto Value = static_cast<ulittle64_t>(reloc.getValue()); 1549 memcpy(Ptr, &Value, reloc.getSize()); 1550 break; 1551 } 1552 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA: 1553 *reinterpret_cast<ulittle32_t *>(Ptr) += reloc.getValue(); 1554 break; 1555 } 1556 } 1557 } 1558 return HybridView; 1559 } 1560 1561 bool ImportDirectoryEntryRef:: 1562 operator==(const ImportDirectoryEntryRef &Other) const { 1563 return ImportTable == Other.ImportTable && Index == Other.Index; 1564 } 1565 1566 void ImportDirectoryEntryRef::moveNext() { 1567 ++Index; 1568 if (ImportTable[Index].isNull()) { 1569 Index = -1; 1570 ImportTable = nullptr; 1571 } 1572 } 1573 1574 Error ImportDirectoryEntryRef::getImportTableEntry( 1575 const coff_import_directory_table_entry *&Result) const { 1576 return getObject(Result, OwningObject->Data, ImportTable + Index); 1577 } 1578 1579 static imported_symbol_iterator 1580 makeImportedSymbolIterator(const COFFObjectFile *Object, 1581 uintptr_t Ptr, int Index) { 1582 if (Object->getBytesInAddress() == 4) { 1583 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr); 1584 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1585 } 1586 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr); 1587 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1588 } 1589 1590 static imported_symbol_iterator 1591 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) { 1592 uintptr_t IntPtr = 0; 1593 // FIXME: Handle errors. 1594 cantFail(Object->getRvaPtr(RVA, IntPtr)); 1595 return makeImportedSymbolIterator(Object, IntPtr, 0); 1596 } 1597 1598 static imported_symbol_iterator 1599 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) { 1600 uintptr_t IntPtr = 0; 1601 // FIXME: Handle errors. 1602 cantFail(Object->getRvaPtr(RVA, IntPtr)); 1603 // Forward the pointer to the last entry which is null. 1604 int Index = 0; 1605 if (Object->getBytesInAddress() == 4) { 1606 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr); 1607 while (*Entry++) 1608 ++Index; 1609 } else { 1610 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr); 1611 while (*Entry++) 1612 ++Index; 1613 } 1614 return makeImportedSymbolIterator(Object, IntPtr, Index); 1615 } 1616 1617 imported_symbol_iterator 1618 ImportDirectoryEntryRef::imported_symbol_begin() const { 1619 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA, 1620 OwningObject); 1621 } 1622 1623 imported_symbol_iterator 1624 ImportDirectoryEntryRef::imported_symbol_end() const { 1625 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA, 1626 OwningObject); 1627 } 1628 1629 iterator_range<imported_symbol_iterator> 1630 ImportDirectoryEntryRef::imported_symbols() const { 1631 return make_range(imported_symbol_begin(), imported_symbol_end()); 1632 } 1633 1634 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const { 1635 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA, 1636 OwningObject); 1637 } 1638 1639 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const { 1640 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA, 1641 OwningObject); 1642 } 1643 1644 iterator_range<imported_symbol_iterator> 1645 ImportDirectoryEntryRef::lookup_table_symbols() const { 1646 return make_range(lookup_table_begin(), lookup_table_end()); 1647 } 1648 1649 Error ImportDirectoryEntryRef::getName(StringRef &Result) const { 1650 uintptr_t IntPtr = 0; 1651 if (Error E = OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr, 1652 "import directory name")) 1653 return E; 1654 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1655 return Error::success(); 1656 } 1657 1658 Error 1659 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const { 1660 Result = ImportTable[Index].ImportLookupTableRVA; 1661 return Error::success(); 1662 } 1663 1664 Error ImportDirectoryEntryRef::getImportAddressTableRVA( 1665 uint32_t &Result) const { 1666 Result = ImportTable[Index].ImportAddressTableRVA; 1667 return Error::success(); 1668 } 1669 1670 bool DelayImportDirectoryEntryRef:: 1671 operator==(const DelayImportDirectoryEntryRef &Other) const { 1672 return Table == Other.Table && Index == Other.Index; 1673 } 1674 1675 void DelayImportDirectoryEntryRef::moveNext() { 1676 ++Index; 1677 } 1678 1679 imported_symbol_iterator 1680 DelayImportDirectoryEntryRef::imported_symbol_begin() const { 1681 return importedSymbolBegin(Table[Index].DelayImportNameTable, 1682 OwningObject); 1683 } 1684 1685 imported_symbol_iterator 1686 DelayImportDirectoryEntryRef::imported_symbol_end() const { 1687 return importedSymbolEnd(Table[Index].DelayImportNameTable, 1688 OwningObject); 1689 } 1690 1691 iterator_range<imported_symbol_iterator> 1692 DelayImportDirectoryEntryRef::imported_symbols() const { 1693 return make_range(imported_symbol_begin(), imported_symbol_end()); 1694 } 1695 1696 Error DelayImportDirectoryEntryRef::getName(StringRef &Result) const { 1697 uintptr_t IntPtr = 0; 1698 if (Error E = OwningObject->getRvaPtr(Table[Index].Name, IntPtr, 1699 "delay import directory name")) 1700 return E; 1701 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1702 return Error::success(); 1703 } 1704 1705 Error DelayImportDirectoryEntryRef::getDelayImportTable( 1706 const delay_import_directory_table_entry *&Result) const { 1707 Result = &Table[Index]; 1708 return Error::success(); 1709 } 1710 1711 Error DelayImportDirectoryEntryRef::getImportAddress(int AddrIndex, 1712 uint64_t &Result) const { 1713 uint32_t RVA = Table[Index].DelayImportAddressTable + 1714 AddrIndex * (OwningObject->is64() ? 8 : 4); 1715 uintptr_t IntPtr = 0; 1716 if (Error E = OwningObject->getRvaPtr(RVA, IntPtr, "import address")) 1717 return E; 1718 if (OwningObject->is64()) 1719 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr); 1720 else 1721 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr); 1722 return Error::success(); 1723 } 1724 1725 bool ExportDirectoryEntryRef:: 1726 operator==(const ExportDirectoryEntryRef &Other) const { 1727 return ExportTable == Other.ExportTable && Index == Other.Index; 1728 } 1729 1730 void ExportDirectoryEntryRef::moveNext() { 1731 ++Index; 1732 } 1733 1734 // Returns the name of the current export symbol. If the symbol is exported only 1735 // by ordinal, the empty string is set as a result. 1736 Error ExportDirectoryEntryRef::getDllName(StringRef &Result) const { 1737 uintptr_t IntPtr = 0; 1738 if (Error E = 1739 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr, "dll name")) 1740 return E; 1741 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1742 return Error::success(); 1743 } 1744 1745 // Returns the starting ordinal number. 1746 Error ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { 1747 Result = ExportTable->OrdinalBase; 1748 return Error::success(); 1749 } 1750 1751 // Returns the export ordinal of the current export symbol. 1752 Error ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { 1753 Result = ExportTable->OrdinalBase + Index; 1754 return Error::success(); 1755 } 1756 1757 // Returns the address of the current export symbol. 1758 Error ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { 1759 uintptr_t IntPtr = 0; 1760 if (Error EC = OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, 1761 IntPtr, "export address")) 1762 return EC; 1763 const export_address_table_entry *entry = 1764 reinterpret_cast<const export_address_table_entry *>(IntPtr); 1765 Result = entry[Index].ExportRVA; 1766 return Error::success(); 1767 } 1768 1769 // Returns the name of the current export symbol. If the symbol is exported only 1770 // by ordinal, the empty string is set as a result. 1771 Error 1772 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { 1773 uintptr_t IntPtr = 0; 1774 if (Error EC = OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr, 1775 "export ordinal table")) 1776 return EC; 1777 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); 1778 1779 uint32_t NumEntries = ExportTable->NumberOfNamePointers; 1780 int Offset = 0; 1781 for (const ulittle16_t *I = Start, *E = Start + NumEntries; 1782 I < E; ++I, ++Offset) { 1783 if (*I != Index) 1784 continue; 1785 if (Error EC = OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr, 1786 "export table entry")) 1787 return EC; 1788 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); 1789 if (Error EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr, 1790 "export symbol name")) 1791 return EC; 1792 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1793 return Error::success(); 1794 } 1795 Result = ""; 1796 return Error::success(); 1797 } 1798 1799 Error ExportDirectoryEntryRef::isForwarder(bool &Result) const { 1800 const data_directory *DataEntry = 1801 OwningObject->getDataDirectory(COFF::EXPORT_TABLE); 1802 if (!DataEntry) 1803 return createStringError(object_error::parse_failed, 1804 "export table missing"); 1805 uint32_t RVA; 1806 if (auto EC = getExportRVA(RVA)) 1807 return EC; 1808 uint32_t Begin = DataEntry->RelativeVirtualAddress; 1809 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size; 1810 Result = (Begin <= RVA && RVA < End); 1811 return Error::success(); 1812 } 1813 1814 Error ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const { 1815 uint32_t RVA; 1816 if (auto EC = getExportRVA(RVA)) 1817 return EC; 1818 uintptr_t IntPtr = 0; 1819 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr, "export forward target")) 1820 return EC; 1821 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1822 return Error::success(); 1823 } 1824 1825 bool ImportedSymbolRef:: 1826 operator==(const ImportedSymbolRef &Other) const { 1827 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64 1828 && Index == Other.Index; 1829 } 1830 1831 void ImportedSymbolRef::moveNext() { 1832 ++Index; 1833 } 1834 1835 Error ImportedSymbolRef::getSymbolName(StringRef &Result) const { 1836 uint32_t RVA; 1837 if (Entry32) { 1838 // If a symbol is imported only by ordinal, it has no name. 1839 if (Entry32[Index].isOrdinal()) 1840 return Error::success(); 1841 RVA = Entry32[Index].getHintNameRVA(); 1842 } else { 1843 if (Entry64[Index].isOrdinal()) 1844 return Error::success(); 1845 RVA = Entry64[Index].getHintNameRVA(); 1846 } 1847 uintptr_t IntPtr = 0; 1848 if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr, "import symbol name")) 1849 return EC; 1850 // +2 because the first two bytes is hint. 1851 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2)); 1852 return Error::success(); 1853 } 1854 1855 Error ImportedSymbolRef::isOrdinal(bool &Result) const { 1856 if (Entry32) 1857 Result = Entry32[Index].isOrdinal(); 1858 else 1859 Result = Entry64[Index].isOrdinal(); 1860 return Error::success(); 1861 } 1862 1863 Error ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const { 1864 if (Entry32) 1865 Result = Entry32[Index].getHintNameRVA(); 1866 else 1867 Result = Entry64[Index].getHintNameRVA(); 1868 return Error::success(); 1869 } 1870 1871 Error ImportedSymbolRef::getOrdinal(uint16_t &Result) const { 1872 uint32_t RVA; 1873 if (Entry32) { 1874 if (Entry32[Index].isOrdinal()) { 1875 Result = Entry32[Index].getOrdinal(); 1876 return Error::success(); 1877 } 1878 RVA = Entry32[Index].getHintNameRVA(); 1879 } else { 1880 if (Entry64[Index].isOrdinal()) { 1881 Result = Entry64[Index].getOrdinal(); 1882 return Error::success(); 1883 } 1884 RVA = Entry64[Index].getHintNameRVA(); 1885 } 1886 uintptr_t IntPtr = 0; 1887 if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr, "import symbol ordinal")) 1888 return EC; 1889 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr); 1890 return Error::success(); 1891 } 1892 1893 Expected<std::unique_ptr<COFFObjectFile>> 1894 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) { 1895 return COFFObjectFile::create(Object); 1896 } 1897 1898 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const { 1899 return Header == Other.Header && Index == Other.Index; 1900 } 1901 1902 void BaseRelocRef::moveNext() { 1903 // Header->BlockSize is the size of the current block, including the 1904 // size of the header itself. 1905 uint32_t Size = sizeof(*Header) + 1906 sizeof(coff_base_reloc_block_entry) * (Index + 1); 1907 if (Size == Header->BlockSize) { 1908 // .reloc contains a list of base relocation blocks. Each block 1909 // consists of the header followed by entries. The header contains 1910 // how many entories will follow. When we reach the end of the 1911 // current block, proceed to the next block. 1912 Header = reinterpret_cast<const coff_base_reloc_block_header *>( 1913 reinterpret_cast<const uint8_t *>(Header) + Size); 1914 Index = 0; 1915 } else { 1916 ++Index; 1917 } 1918 } 1919 1920 Error BaseRelocRef::getType(uint8_t &Type) const { 1921 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1); 1922 Type = Entry[Index].getType(); 1923 return Error::success(); 1924 } 1925 1926 Error BaseRelocRef::getRVA(uint32_t &Result) const { 1927 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1); 1928 Result = Header->PageRVA + Entry[Index].getOffset(); 1929 return Error::success(); 1930 } 1931 1932 bool DynamicRelocRef::operator==(const DynamicRelocRef &Other) const { 1933 return Header == Other.Header; 1934 } 1935 1936 void DynamicRelocRef::moveNext() { 1937 switch (Obj->getDynamicRelocTable()->Version) { 1938 case 1: 1939 if (Obj->is64()) { 1940 auto H = reinterpret_cast<const coff_dynamic_relocation64 *>(Header); 1941 Header += sizeof(*H) + H->BaseRelocSize; 1942 } else { 1943 auto H = reinterpret_cast<const coff_dynamic_relocation32 *>(Header); 1944 Header += sizeof(*H) + H->BaseRelocSize; 1945 } 1946 break; 1947 case 2: 1948 if (Obj->is64()) { 1949 auto H = reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header); 1950 Header += H->HeaderSize + H->FixupInfoSize; 1951 } else { 1952 auto H = reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header); 1953 Header += H->HeaderSize + H->FixupInfoSize; 1954 } 1955 break; 1956 } 1957 } 1958 1959 uint32_t DynamicRelocRef::getType() const { 1960 switch (Obj->getDynamicRelocTable()->Version) { 1961 case 1: 1962 if (Obj->is64()) { 1963 auto H = reinterpret_cast<const coff_dynamic_relocation64 *>(Header); 1964 return H->Symbol; 1965 } else { 1966 auto H = reinterpret_cast<const coff_dynamic_relocation32 *>(Header); 1967 return H->Symbol; 1968 } 1969 break; 1970 case 2: 1971 if (Obj->is64()) { 1972 auto H = reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header); 1973 return H->Symbol; 1974 } else { 1975 auto H = reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header); 1976 return H->Symbol; 1977 } 1978 break; 1979 default: 1980 llvm_unreachable("invalid version"); 1981 } 1982 } 1983 1984 void DynamicRelocRef::getContents(ArrayRef<uint8_t> &Ref) const { 1985 switch (Obj->getDynamicRelocTable()->Version) { 1986 case 1: 1987 if (Obj->is64()) { 1988 auto H = reinterpret_cast<const coff_dynamic_relocation64 *>(Header); 1989 Ref = ArrayRef(Header + sizeof(*H), H->BaseRelocSize); 1990 } else { 1991 auto H = reinterpret_cast<const coff_dynamic_relocation32 *>(Header); 1992 Ref = ArrayRef(Header + sizeof(*H), H->BaseRelocSize); 1993 } 1994 break; 1995 case 2: 1996 if (Obj->is64()) { 1997 auto H = reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header); 1998 Ref = ArrayRef(Header + H->HeaderSize, H->FixupInfoSize); 1999 } else { 2000 auto H = reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header); 2001 Ref = ArrayRef(Header + H->HeaderSize, H->FixupInfoSize); 2002 } 2003 break; 2004 } 2005 } 2006 2007 Error DynamicRelocRef::validate() const { 2008 const coff_dynamic_reloc_table *Table = Obj->getDynamicRelocTable(); 2009 size_t ContentsSize = 2010 reinterpret_cast<const uint8_t *>(Table + 1) + Table->Size - Header; 2011 size_t HeaderSize; 2012 if (Table->Version == 1) 2013 HeaderSize = Obj->is64() ? sizeof(coff_dynamic_relocation64) 2014 : sizeof(coff_dynamic_relocation32); 2015 else 2016 HeaderSize = Obj->is64() ? sizeof(coff_dynamic_relocation64_v2) 2017 : sizeof(coff_dynamic_relocation32_v2); 2018 if (HeaderSize > ContentsSize) 2019 return createStringError(object_error::parse_failed, 2020 "Unexpected end of dynamic relocations data"); 2021 2022 if (Table->Version == 2) { 2023 size_t Size = 2024 Obj->is64() 2025 ? reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header) 2026 ->HeaderSize 2027 : reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header) 2028 ->HeaderSize; 2029 if (Size < HeaderSize || Size > ContentsSize) 2030 return createStringError(object_error::parse_failed, 2031 "Invalid dynamic relocation header size (" + 2032 Twine(Size) + ")"); 2033 HeaderSize = Size; 2034 } 2035 2036 ArrayRef<uint8_t> Contents; 2037 getContents(Contents); 2038 if (Contents.size() > ContentsSize - HeaderSize) 2039 return createStringError(object_error::parse_failed, 2040 "Too large dynamic relocation size (" + 2041 Twine(Contents.size()) + ")"); 2042 2043 switch (getType()) { 2044 case COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X: 2045 for (auto Reloc : arm64x_relocs()) { 2046 if (Error E = Reloc.validate(Obj)) 2047 return E; 2048 } 2049 break; 2050 } 2051 2052 return Error::success(); 2053 } 2054 2055 arm64x_reloc_iterator DynamicRelocRef::arm64x_reloc_begin() const { 2056 assert(getType() == COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X); 2057 ArrayRef<uint8_t> Content; 2058 getContents(Content); 2059 auto Header = 2060 reinterpret_cast<const coff_base_reloc_block_header *>(Content.begin()); 2061 return arm64x_reloc_iterator(Arm64XRelocRef(Header)); 2062 } 2063 2064 arm64x_reloc_iterator DynamicRelocRef::arm64x_reloc_end() const { 2065 assert(getType() == COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X); 2066 ArrayRef<uint8_t> Content; 2067 getContents(Content); 2068 auto Header = 2069 reinterpret_cast<const coff_base_reloc_block_header *>(Content.end()); 2070 return arm64x_reloc_iterator(Arm64XRelocRef(Header, 0)); 2071 } 2072 2073 iterator_range<arm64x_reloc_iterator> DynamicRelocRef::arm64x_relocs() const { 2074 return make_range(arm64x_reloc_begin(), arm64x_reloc_end()); 2075 } 2076 2077 bool Arm64XRelocRef::operator==(const Arm64XRelocRef &Other) const { 2078 return Header == Other.Header && Index == Other.Index; 2079 } 2080 2081 uint8_t Arm64XRelocRef::getEntrySize() const { 2082 switch (getType()) { 2083 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: 2084 return (1ull << getArg()) / sizeof(uint16_t) + 1; 2085 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA: 2086 return 2; 2087 default: 2088 return 1; 2089 } 2090 } 2091 2092 void Arm64XRelocRef::moveNext() { 2093 Index += getEntrySize(); 2094 if (sizeof(*Header) + Index * sizeof(uint16_t) < Header->BlockSize && 2095 !getReloc()) 2096 ++Index; // Skip padding 2097 if (sizeof(*Header) + Index * sizeof(uint16_t) == Header->BlockSize) { 2098 // The end of the block, move to the next one. 2099 Header = 2100 reinterpret_cast<const coff_base_reloc_block_header *>(&getReloc()); 2101 Index = 0; 2102 } 2103 } 2104 2105 uint8_t Arm64XRelocRef::getSize() const { 2106 switch (getType()) { 2107 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL: 2108 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: 2109 return 1 << getArg(); 2110 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA: 2111 return sizeof(uint32_t); 2112 } 2113 llvm_unreachable("Unknown Arm64XFixupType enum"); 2114 } 2115 2116 uint64_t Arm64XRelocRef::getValue() const { 2117 auto Ptr = reinterpret_cast<const ulittle16_t *>(Header + 1) + Index + 1; 2118 2119 switch (getType()) { 2120 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: { 2121 ulittle64_t Value(0); 2122 memcpy(&Value, Ptr, getSize()); 2123 return Value; 2124 } 2125 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA: { 2126 uint16_t arg = getArg(); 2127 int delta = *Ptr; 2128 2129 if (arg & 1) 2130 delta = -delta; 2131 delta *= (arg & 2) ? 8 : 4; 2132 return delta; 2133 } 2134 default: 2135 return 0; 2136 } 2137 } 2138 2139 Error Arm64XRelocRef::validate(const COFFObjectFile *Obj) const { 2140 if (!Index) { 2141 const coff_dynamic_reloc_table *Table = Obj->getDynamicRelocTable(); 2142 size_t ContentsSize = reinterpret_cast<const uint8_t *>(Table + 1) + 2143 Table->Size - 2144 reinterpret_cast<const uint8_t *>(Header); 2145 if (ContentsSize < sizeof(coff_base_reloc_block_header)) 2146 return createStringError(object_error::parse_failed, 2147 "Unexpected end of ARM64X relocations data"); 2148 if (Header->BlockSize <= sizeof(*Header)) 2149 return createStringError(object_error::parse_failed, 2150 "ARM64X relocations block size (" + 2151 Twine(Header->BlockSize) + ") is too small"); 2152 if (Header->BlockSize % sizeof(uint32_t)) 2153 return createStringError(object_error::parse_failed, 2154 "Unaligned ARM64X relocations block size (" + 2155 Twine(Header->BlockSize) + ")"); 2156 if (Header->BlockSize > ContentsSize) 2157 return createStringError(object_error::parse_failed, 2158 "ARM64X relocations block size (" + 2159 Twine(Header->BlockSize) + ") is too large"); 2160 if (Header->PageRVA & 0xfff) 2161 return createStringError(object_error::parse_failed, 2162 "Unaligned ARM64X relocations page RVA (" + 2163 Twine(Header->PageRVA) + ")"); 2164 } 2165 2166 switch ((getReloc() >> 12) & 3) { 2167 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL: 2168 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA: 2169 break; 2170 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: 2171 if (!getArg()) 2172 return createStringError(object_error::parse_failed, 2173 "Invalid ARM64X relocation value size (0)"); 2174 break; 2175 default: 2176 return createStringError(object_error::parse_failed, 2177 "Invalid relocation type"); 2178 } 2179 2180 uint32_t RelocsSize = 2181 (Header->BlockSize - sizeof(*Header)) / sizeof(uint16_t); 2182 uint16_t EntrySize = getEntrySize(); 2183 if (!getReloc() || 2184 (Index + EntrySize + 1 < RelocsSize && !getReloc(EntrySize))) 2185 return createStringError(object_error::parse_failed, 2186 "Unexpected ARM64X relocations terminator"); 2187 if (Index + EntrySize > RelocsSize) 2188 return createStringError(object_error::parse_failed, 2189 "Unexpected end of ARM64X relocations"); 2190 if (getRVA() % getSize()) 2191 return createStringError(object_error::parse_failed, 2192 "Unaligned ARM64X relocation RVA (" + 2193 Twine(getRVA()) + ")"); 2194 if (Header->PageRVA) { 2195 uintptr_t IntPtr; 2196 return Obj->getRvaPtr(getRVA() + getSize(), IntPtr, "ARM64X reloc"); 2197 } 2198 return Error::success(); 2199 } 2200 2201 #define RETURN_IF_ERROR(Expr) \ 2202 do { \ 2203 Error E = (Expr); \ 2204 if (E) \ 2205 return std::move(E); \ 2206 } while (0) 2207 2208 Expected<ArrayRef<UTF16>> 2209 ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) { 2210 BinaryStreamReader Reader = BinaryStreamReader(BBS); 2211 Reader.setOffset(Offset); 2212 uint16_t Length; 2213 RETURN_IF_ERROR(Reader.readInteger(Length)); 2214 ArrayRef<UTF16> RawDirString; 2215 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length)); 2216 return RawDirString; 2217 } 2218 2219 Expected<ArrayRef<UTF16>> 2220 ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) { 2221 return getDirStringAtOffset(Entry.Identifier.getNameOffset()); 2222 } 2223 2224 Expected<const coff_resource_dir_table &> 2225 ResourceSectionRef::getTableAtOffset(uint32_t Offset) { 2226 const coff_resource_dir_table *Table = nullptr; 2227 2228 BinaryStreamReader Reader(BBS); 2229 Reader.setOffset(Offset); 2230 RETURN_IF_ERROR(Reader.readObject(Table)); 2231 assert(Table != nullptr); 2232 return *Table; 2233 } 2234 2235 Expected<const coff_resource_dir_entry &> 2236 ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) { 2237 const coff_resource_dir_entry *Entry = nullptr; 2238 2239 BinaryStreamReader Reader(BBS); 2240 Reader.setOffset(Offset); 2241 RETURN_IF_ERROR(Reader.readObject(Entry)); 2242 assert(Entry != nullptr); 2243 return *Entry; 2244 } 2245 2246 Expected<const coff_resource_data_entry &> 2247 ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) { 2248 const coff_resource_data_entry *Entry = nullptr; 2249 2250 BinaryStreamReader Reader(BBS); 2251 Reader.setOffset(Offset); 2252 RETURN_IF_ERROR(Reader.readObject(Entry)); 2253 assert(Entry != nullptr); 2254 return *Entry; 2255 } 2256 2257 Expected<const coff_resource_dir_table &> 2258 ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) { 2259 assert(Entry.Offset.isSubDir()); 2260 return getTableAtOffset(Entry.Offset.value()); 2261 } 2262 2263 Expected<const coff_resource_data_entry &> 2264 ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) { 2265 assert(!Entry.Offset.isSubDir()); 2266 return getDataEntryAtOffset(Entry.Offset.value()); 2267 } 2268 2269 Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() { 2270 return getTableAtOffset(0); 2271 } 2272 2273 Expected<const coff_resource_dir_entry &> 2274 ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table, 2275 uint32_t Index) { 2276 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries)) 2277 return createStringError(object_error::parse_failed, "index out of range"); 2278 const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table); 2279 ptrdiff_t TableOffset = TablePtr - BBS.data().data(); 2280 return getTableEntryAtOffset(TableOffset + sizeof(Table) + 2281 Index * sizeof(coff_resource_dir_entry)); 2282 } 2283 2284 Error ResourceSectionRef::load(const COFFObjectFile *O) { 2285 for (const SectionRef &S : O->sections()) { 2286 Expected<StringRef> Name = S.getName(); 2287 if (!Name) 2288 return Name.takeError(); 2289 2290 if (*Name == ".rsrc" || *Name == ".rsrc$01") 2291 return load(O, S); 2292 } 2293 return createStringError(object_error::parse_failed, 2294 "no resource section found"); 2295 } 2296 2297 Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) { 2298 Obj = O; 2299 Section = S; 2300 Expected<StringRef> Contents = Section.getContents(); 2301 if (!Contents) 2302 return Contents.takeError(); 2303 BBS = BinaryByteStream(*Contents, llvm::endianness::little); 2304 const coff_section *COFFSect = Obj->getCOFFSection(Section); 2305 ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect); 2306 Relocs.reserve(OrigRelocs.size()); 2307 for (const coff_relocation &R : OrigRelocs) 2308 Relocs.push_back(&R); 2309 llvm::sort(Relocs, [](const coff_relocation *A, const coff_relocation *B) { 2310 return A->VirtualAddress < B->VirtualAddress; 2311 }); 2312 return Error::success(); 2313 } 2314 2315 Expected<StringRef> 2316 ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) { 2317 if (!Obj) 2318 return createStringError(object_error::parse_failed, "no object provided"); 2319 2320 // Find a potential relocation at the DataRVA field (first member of 2321 // the coff_resource_data_entry struct). 2322 const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry); 2323 ptrdiff_t EntryOffset = EntryPtr - BBS.data().data(); 2324 coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0), 2325 ulittle16_t(0)}; 2326 auto RelocsForOffset = 2327 std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget, 2328 [](const coff_relocation *A, const coff_relocation *B) { 2329 return A->VirtualAddress < B->VirtualAddress; 2330 }); 2331 2332 if (RelocsForOffset.first != RelocsForOffset.second) { 2333 // We found a relocation with the right offset. Check that it does have 2334 // the expected type. 2335 const coff_relocation &R = **RelocsForOffset.first; 2336 uint16_t RVAReloc; 2337 switch (Obj->getArch()) { 2338 case Triple::x86: 2339 RVAReloc = COFF::IMAGE_REL_I386_DIR32NB; 2340 break; 2341 case Triple::x86_64: 2342 RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB; 2343 break; 2344 case Triple::thumb: 2345 RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB; 2346 break; 2347 case Triple::aarch64: 2348 RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB; 2349 break; 2350 default: 2351 return createStringError(object_error::parse_failed, 2352 "unsupported architecture"); 2353 } 2354 if (R.Type != RVAReloc) 2355 return createStringError(object_error::parse_failed, 2356 "unexpected relocation type"); 2357 // Get the relocation's symbol 2358 Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex); 2359 if (!Sym) 2360 return Sym.takeError(); 2361 // And the symbol's section 2362 Expected<const coff_section *> Section = 2363 Obj->getSection(Sym->getSectionNumber()); 2364 if (!Section) 2365 return Section.takeError(); 2366 // Add the initial value of DataRVA to the symbol's offset to find the 2367 // data it points at. 2368 uint64_t Offset = Entry.DataRVA + Sym->getValue(); 2369 ArrayRef<uint8_t> Contents; 2370 if (Error E = Obj->getSectionContents(*Section, Contents)) 2371 return E; 2372 if (Offset + Entry.DataSize > Contents.size()) 2373 return createStringError(object_error::parse_failed, 2374 "data outside of section"); 2375 // Return a reference to the data inside the section. 2376 return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset, 2377 Entry.DataSize); 2378 } else { 2379 // Relocatable objects need a relocation for the DataRVA field. 2380 if (Obj->isRelocatableObject()) 2381 return createStringError(object_error::parse_failed, 2382 "no relocation found for DataRVA"); 2383 2384 // Locate the section that contains the address that DataRVA points at. 2385 uint64_t VA = Entry.DataRVA + Obj->getImageBase(); 2386 for (const SectionRef &S : Obj->sections()) { 2387 if (VA >= S.getAddress() && 2388 VA + Entry.DataSize <= S.getAddress() + S.getSize()) { 2389 uint64_t Offset = VA - S.getAddress(); 2390 Expected<StringRef> Contents = S.getContents(); 2391 if (!Contents) 2392 return Contents.takeError(); 2393 return Contents->substr(Offset, Entry.DataSize); 2394 } 2395 } 2396 return createStringError(object_error::parse_failed, 2397 "address not found in image"); 2398 } 2399 } 2400