1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file declares the COFFObjectFile class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Object/COFF.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringSwitch.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Support/COFF.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 #include <cctype> 23 #include <limits> 24 25 using namespace llvm; 26 using namespace object; 27 28 using support::ulittle16_t; 29 using support::ulittle32_t; 30 using support::ulittle64_t; 31 using support::little16_t; 32 33 // Returns false if size is greater than the buffer size. And sets ec. 34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) { 35 if (M.getBufferSize() < Size) { 36 EC = object_error::unexpected_eof; 37 return false; 38 } 39 return true; 40 } 41 42 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. 43 // Returns unexpected_eof if error. 44 template <typename T> 45 static std::error_code getObject(const T *&Obj, MemoryBufferRef M, 46 const uint8_t *Ptr, 47 const size_t Size = sizeof(T)) { 48 uintptr_t Addr = uintptr_t(Ptr); 49 if (Addr + Size < Addr || Addr + Size < Size || 50 Addr + Size > uintptr_t(M.getBufferEnd())) { 51 return object_error::unexpected_eof; 52 } 53 Obj = reinterpret_cast<const T *>(Addr); 54 return object_error::success; 55 } 56 57 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without 58 // prefixed slashes. 59 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) { 60 assert(Str.size() <= 6 && "String too long, possible overflow."); 61 if (Str.size() > 6) 62 return true; 63 64 uint64_t Value = 0; 65 while (!Str.empty()) { 66 unsigned CharVal; 67 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25 68 CharVal = Str[0] - 'A'; 69 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51 70 CharVal = Str[0] - 'a' + 26; 71 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61 72 CharVal = Str[0] - '0' + 52; 73 else if (Str[0] == '+') // 62 74 CharVal = 62; 75 else if (Str[0] == '/') // 63 76 CharVal = 63; 77 else 78 return true; 79 80 Value = (Value * 64) + CharVal; 81 Str = Str.substr(1); 82 } 83 84 if (Value > std::numeric_limits<uint32_t>::max()) 85 return true; 86 87 Result = static_cast<uint32_t>(Value); 88 return false; 89 } 90 91 template <typename coff_symbol_type> 92 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const { 93 const coff_symbol_type *Addr = 94 reinterpret_cast<const coff_symbol_type *>(Ref.p); 95 96 #ifndef NDEBUG 97 // Verify that the symbol points to a valid entry in the symbol table. 98 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base()); 99 if (Offset < getPointerToSymbolTable() || 100 Offset >= getPointerToSymbolTable() + 101 (getNumberOfSymbols() * sizeof(coff_symbol_type))) 102 report_fatal_error("Symbol was outside of symbol table."); 103 104 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && 105 "Symbol did not point to the beginning of a symbol"); 106 #endif 107 108 return Addr; 109 } 110 111 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { 112 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); 113 114 # ifndef NDEBUG 115 // Verify that the section points to a valid entry in the section table. 116 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections())) 117 report_fatal_error("Section was outside of section table."); 118 119 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable); 120 assert(Offset % sizeof(coff_section) == 0 && 121 "Section did not point to the beginning of a section"); 122 # endif 123 124 return Addr; 125 } 126 127 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const { 128 if (SymbolTable16) { 129 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref); 130 Symb += 1 + Symb->NumberOfAuxSymbols; 131 Ref.p = reinterpret_cast<uintptr_t>(Symb); 132 } else if (SymbolTable32) { 133 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref); 134 Symb += 1 + Symb->NumberOfAuxSymbols; 135 Ref.p = reinterpret_cast<uintptr_t>(Symb); 136 } else { 137 llvm_unreachable("no symbol table pointer!"); 138 } 139 } 140 141 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref, 142 StringRef &Result) const { 143 COFFSymbolRef Symb = getCOFFSymbol(Ref); 144 return getSymbolName(Symb, Result); 145 } 146 147 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref, 148 uint64_t &Result) const { 149 COFFSymbolRef Symb = getCOFFSymbol(Ref); 150 151 if (Symb.isAnyUndefined()) { 152 Result = UnknownAddressOrSize; 153 return object_error::success; 154 } 155 if (Symb.isCommon()) { 156 Result = UnknownAddressOrSize; 157 return object_error::success; 158 } 159 int32_t SectionNumber = Symb.getSectionNumber(); 160 if (!COFF::isReservedSectionNumber(SectionNumber)) { 161 const coff_section *Section = nullptr; 162 if (std::error_code EC = getSection(SectionNumber, Section)) 163 return EC; 164 165 Result = Section->VirtualAddress + Symb.getValue(); 166 return object_error::success; 167 } 168 169 Result = Symb.getValue(); 170 return object_error::success; 171 } 172 173 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref, 174 SymbolRef::Type &Result) const { 175 COFFSymbolRef Symb = getCOFFSymbol(Ref); 176 int32_t SectionNumber = Symb.getSectionNumber(); 177 Result = SymbolRef::ST_Other; 178 179 if (Symb.isAnyUndefined()) { 180 Result = SymbolRef::ST_Unknown; 181 } else if (Symb.isFunctionDefinition()) { 182 Result = SymbolRef::ST_Function; 183 } else if (Symb.isCommon()) { 184 Result = SymbolRef::ST_Data; 185 } else if (Symb.isFileRecord()) { 186 Result = SymbolRef::ST_File; 187 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG) { 188 Result = SymbolRef::ST_Debug; 189 } else if (!COFF::isReservedSectionNumber(SectionNumber)) { 190 const coff_section *Section = nullptr; 191 if (std::error_code EC = getSection(SectionNumber, Section)) 192 return EC; 193 uint32_t Characteristics = Section->Characteristics; 194 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE) 195 Result = SymbolRef::ST_Function; 196 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 197 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) 198 Result = SymbolRef::ST_Data; 199 } 200 return object_error::success; 201 } 202 203 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const { 204 COFFSymbolRef Symb = getCOFFSymbol(Ref); 205 uint32_t Result = SymbolRef::SF_None; 206 207 if (Symb.isExternal() || Symb.isWeakExternal()) 208 Result |= SymbolRef::SF_Global; 209 210 if (Symb.isWeakExternal()) 211 Result |= SymbolRef::SF_Weak; 212 213 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE) 214 Result |= SymbolRef::SF_Absolute; 215 216 if (Symb.isFileRecord()) 217 Result |= SymbolRef::SF_FormatSpecific; 218 219 if (Symb.isSectionDefinition()) 220 Result |= SymbolRef::SF_FormatSpecific; 221 222 if (Symb.isCommon()) 223 Result |= SymbolRef::SF_Common; 224 225 if (Symb.isAnyUndefined()) 226 Result |= SymbolRef::SF_Undefined; 227 228 return Result; 229 } 230 231 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref, 232 uint64_t &Result) const { 233 COFFSymbolRef Symb = getCOFFSymbol(Ref); 234 235 if (Symb.isAnyUndefined()) { 236 Result = UnknownAddressOrSize; 237 return object_error::success; 238 } 239 if (Symb.isCommon()) { 240 Result = Symb.getValue(); 241 return object_error::success; 242 } 243 if (Symb.isFunctionDefinition()) { 244 ArrayRef<uint8_t> AuxData = getSymbolAuxData(Symb); 245 if (!AuxData.empty()) { 246 const auto *CAFD = 247 reinterpret_cast<const coff_aux_function_definition *>( 248 AuxData.data()); 249 Result = CAFD->TotalSize; 250 return object_error::success; 251 } 252 } 253 // FIXME: Return the correct size. This requires looking at all the symbols 254 // in the same section as this symbol, and looking for either the next 255 // symbol, or the end of the section. 256 int32_t SectionNumber = Symb.getSectionNumber(); 257 if (!COFF::isReservedSectionNumber(SectionNumber)) { 258 const coff_section *Section = nullptr; 259 if (std::error_code EC = getSection(SectionNumber, Section)) 260 return EC; 261 262 Result = Section->SizeOfRawData - Symb.getValue(); 263 return object_error::success; 264 } 265 266 Result = 0; 267 return object_error::success; 268 } 269 270 std::error_code 271 COFFObjectFile::getSymbolSection(DataRefImpl Ref, 272 section_iterator &Result) const { 273 COFFSymbolRef Symb = getCOFFSymbol(Ref); 274 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) { 275 Result = section_end(); 276 } else { 277 const coff_section *Sec = nullptr; 278 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec)) 279 return EC; 280 DataRefImpl Ref; 281 Ref.p = reinterpret_cast<uintptr_t>(Sec); 282 Result = section_iterator(SectionRef(Ref, this)); 283 } 284 return object_error::success; 285 } 286 287 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const { 288 const coff_section *Sec = toSec(Ref); 289 Sec += 1; 290 Ref.p = reinterpret_cast<uintptr_t>(Sec); 291 } 292 293 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref, 294 StringRef &Result) const { 295 const coff_section *Sec = toSec(Ref); 296 return getSectionName(Sec, Result); 297 } 298 299 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const { 300 const coff_section *Sec = toSec(Ref); 301 return Sec->VirtualAddress; 302 } 303 304 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const { 305 return getSectionSize(toSec(Ref)); 306 } 307 308 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref, 309 StringRef &Result) const { 310 const coff_section *Sec = toSec(Ref); 311 ArrayRef<uint8_t> Res; 312 std::error_code EC = getSectionContents(Sec, Res); 313 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size()); 314 return EC; 315 } 316 317 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const { 318 const coff_section *Sec = toSec(Ref); 319 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1); 320 } 321 322 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const { 323 const coff_section *Sec = toSec(Ref); 324 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE; 325 } 326 327 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const { 328 const coff_section *Sec = toSec(Ref); 329 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; 330 } 331 332 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const { 333 const coff_section *Sec = toSec(Ref); 334 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 335 } 336 337 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const { 338 // FIXME: Unimplemented 339 return true; 340 } 341 342 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const { 343 const coff_section *Sec = toSec(Ref); 344 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 345 } 346 347 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const { 348 // FIXME: Unimplemented. 349 return false; 350 } 351 352 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const { 353 // FIXME: Unimplemented. 354 return false; 355 } 356 357 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef, 358 DataRefImpl SymbRef) const { 359 const coff_section *Sec = toSec(SecRef); 360 COFFSymbolRef Symb = getCOFFSymbol(SymbRef); 361 int32_t SecNumber = (Sec - SectionTable) + 1; 362 return SecNumber == Symb.getSectionNumber(); 363 } 364 365 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { 366 const coff_section *Sec = toSec(Ref); 367 DataRefImpl Ret; 368 if (Sec->NumberOfRelocations == 0) { 369 Ret.p = 0; 370 } else { 371 auto begin = reinterpret_cast<const coff_relocation*>( 372 base() + Sec->PointerToRelocations); 373 if (Sec->hasExtendedRelocations()) { 374 // Skip the first relocation entry repurposed to store the number of 375 // relocations. 376 begin++; 377 } 378 Ret.p = reinterpret_cast<uintptr_t>(begin); 379 } 380 return relocation_iterator(RelocationRef(Ret, this)); 381 } 382 383 static uint32_t getNumberOfRelocations(const coff_section *Sec, 384 const uint8_t *base) { 385 // The field for the number of relocations in COFF section table is only 386 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to 387 // NumberOfRelocations field, and the actual relocation count is stored in the 388 // VirtualAddress field in the first relocation entry. 389 if (Sec->hasExtendedRelocations()) { 390 auto *FirstReloc = reinterpret_cast<const coff_relocation*>( 391 base + Sec->PointerToRelocations); 392 return FirstReloc->VirtualAddress; 393 } 394 return Sec->NumberOfRelocations; 395 } 396 397 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { 398 const coff_section *Sec = toSec(Ref); 399 DataRefImpl Ret; 400 if (Sec->NumberOfRelocations == 0) { 401 Ret.p = 0; 402 } else { 403 auto begin = reinterpret_cast<const coff_relocation*>( 404 base() + Sec->PointerToRelocations); 405 uint32_t NumReloc = getNumberOfRelocations(Sec, base()); 406 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc); 407 } 408 return relocation_iterator(RelocationRef(Ret, this)); 409 } 410 411 // Initialize the pointer to the symbol table. 412 std::error_code COFFObjectFile::initSymbolTablePtr() { 413 if (COFFHeader) 414 if (std::error_code EC = 415 getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(), 416 getNumberOfSymbols() * getSymbolTableEntrySize())) 417 return EC; 418 419 if (COFFBigObjHeader) 420 if (std::error_code EC = 421 getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(), 422 getNumberOfSymbols() * getSymbolTableEntrySize())) 423 return EC; 424 425 // Find string table. The first four byte of the string table contains the 426 // total size of the string table, including the size field itself. If the 427 // string table is empty, the value of the first four byte would be 4. 428 const uint8_t *StringTableAddr = 429 base() + getPointerToSymbolTable() + 430 getNumberOfSymbols() * getSymbolTableEntrySize(); 431 const ulittle32_t *StringTableSizePtr; 432 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr)) 433 return EC; 434 StringTableSize = *StringTableSizePtr; 435 if (std::error_code EC = 436 getObject(StringTable, Data, StringTableAddr, StringTableSize)) 437 return EC; 438 439 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some 440 // tools like cvtres write a size of 0 for an empty table instead of 4. 441 if (StringTableSize < 4) 442 StringTableSize = 4; 443 444 // Check that the string table is null terminated if has any in it. 445 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0) 446 return object_error::parse_failed; 447 return object_error::success; 448 } 449 450 // Returns the file offset for the given VA. 451 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const { 452 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase 453 : (uint64_t)PE32PlusHeader->ImageBase; 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 object_error::success; 469 } 470 } 471 return object_error::parse_failed; 472 } 473 474 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name 475 // table entry. 476 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint, 477 StringRef &Name) const { 478 uintptr_t IntPtr = 0; 479 if (std::error_code EC = getRvaPtr(Rva, IntPtr)) 480 return EC; 481 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); 482 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); 483 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); 484 return object_error::success; 485 } 486 487 // Find the import table. 488 std::error_code COFFObjectFile::initImportTablePtr() { 489 // First, we get the RVA of the import table. If the file lacks a pointer to 490 // the import table, do nothing. 491 const data_directory *DataEntry; 492 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry)) 493 return object_error::success; 494 495 // Do nothing if the pointer to import table is NULL. 496 if (DataEntry->RelativeVirtualAddress == 0) 497 return object_error::success; 498 499 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; 500 // -1 because the last entry is the null entry. 501 NumberOfImportDirectory = DataEntry->Size / 502 sizeof(import_directory_table_entry) - 1; 503 504 // Find the section that contains the RVA. This is needed because the RVA is 505 // the import table's memory address which is different from its file offset. 506 uintptr_t IntPtr = 0; 507 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr)) 508 return EC; 509 ImportDirectory = reinterpret_cast< 510 const import_directory_table_entry *>(IntPtr); 511 return object_error::success; 512 } 513 514 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory. 515 std::error_code COFFObjectFile::initDelayImportTablePtr() { 516 const data_directory *DataEntry; 517 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry)) 518 return object_error::success; 519 if (DataEntry->RelativeVirtualAddress == 0) 520 return object_error::success; 521 522 uint32_t RVA = DataEntry->RelativeVirtualAddress; 523 NumberOfDelayImportDirectory = DataEntry->Size / 524 sizeof(delay_import_directory_table_entry) - 1; 525 526 uintptr_t IntPtr = 0; 527 if (std::error_code EC = getRvaPtr(RVA, IntPtr)) 528 return EC; 529 DelayImportDirectory = reinterpret_cast< 530 const delay_import_directory_table_entry *>(IntPtr); 531 return object_error::success; 532 } 533 534 // Find the export table. 535 std::error_code COFFObjectFile::initExportTablePtr() { 536 // First, we get the RVA of the export table. If the file lacks a pointer to 537 // the export table, do nothing. 538 const data_directory *DataEntry; 539 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) 540 return object_error::success; 541 542 // Do nothing if the pointer to export table is NULL. 543 if (DataEntry->RelativeVirtualAddress == 0) 544 return object_error::success; 545 546 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; 547 uintptr_t IntPtr = 0; 548 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr)) 549 return EC; 550 ExportDirectory = 551 reinterpret_cast<const export_directory_table_entry *>(IntPtr); 552 return object_error::success; 553 } 554 555 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC) 556 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr), 557 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr), 558 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr), 559 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0), 560 ImportDirectory(nullptr), NumberOfImportDirectory(0), 561 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0), 562 ExportDirectory(nullptr) { 563 // Check that we at least have enough room for a header. 564 if (!checkSize(Data, EC, sizeof(coff_file_header))) 565 return; 566 567 // The current location in the file where we are looking at. 568 uint64_t CurPtr = 0; 569 570 // PE header is optional and is present only in executables. If it exists, 571 // it is placed right after COFF header. 572 bool HasPEHeader = false; 573 574 // Check if this is a PE/COFF file. 575 if (base()[0] == 0x4d && base()[1] == 0x5a) { 576 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte 577 // PE signature to find 'normal' COFF header. 578 if (!checkSize(Data, EC, 0x3c + 8)) 579 return; 580 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c); 581 // Check the PE magic bytes. ("PE\0\0") 582 if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 583 0) { 584 EC = object_error::parse_failed; 585 return; 586 } 587 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes. 588 HasPEHeader = true; 589 } 590 591 if ((EC = getObject(COFFHeader, Data, base() + CurPtr))) 592 return; 593 594 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF 595 // import libraries share a common prefix but bigobj is more restrictive. 596 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN && 597 COFFHeader->NumberOfSections == uint16_t(0xffff) && 598 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) { 599 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr))) 600 return; 601 602 // Verify that we are dealing with bigobj. 603 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion && 604 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic, 605 sizeof(COFF::BigObjMagic)) == 0) { 606 COFFHeader = nullptr; 607 CurPtr += sizeof(coff_bigobj_file_header); 608 } else { 609 // It's not a bigobj. 610 COFFBigObjHeader = nullptr; 611 } 612 } 613 if (COFFHeader) { 614 // The prior checkSize call may have failed. This isn't a hard error 615 // because we were just trying to sniff out bigobj. 616 EC = object_error::success; 617 CurPtr += sizeof(coff_file_header); 618 619 if (COFFHeader->isImportLibrary()) 620 return; 621 } 622 623 if (HasPEHeader) { 624 const pe32_header *Header; 625 if ((EC = getObject(Header, Data, base() + CurPtr))) 626 return; 627 628 const uint8_t *DataDirAddr; 629 uint64_t DataDirSize; 630 if (Header->Magic == 0x10b) { 631 PE32Header = Header; 632 DataDirAddr = base() + CurPtr + sizeof(pe32_header); 633 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize; 634 } else if (Header->Magic == 0x20b) { 635 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header); 636 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header); 637 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize; 638 } else { 639 // It's neither PE32 nor PE32+. 640 EC = object_error::parse_failed; 641 return; 642 } 643 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))) 644 return; 645 CurPtr += COFFHeader->SizeOfOptionalHeader; 646 } 647 648 if ((EC = getObject(SectionTable, Data, base() + CurPtr, 649 getNumberOfSections() * sizeof(coff_section)))) 650 return; 651 652 // Initialize the pointer to the symbol table. 653 if (getPointerToSymbolTable() != 0) 654 if ((EC = initSymbolTablePtr())) 655 return; 656 657 // Initialize the pointer to the beginning of the import table. 658 if ((EC = initImportTablePtr())) 659 return; 660 if ((EC = initDelayImportTablePtr())) 661 return; 662 663 // Initialize the pointer to the export table. 664 if ((EC = initExportTablePtr())) 665 return; 666 667 EC = object_error::success; 668 } 669 670 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const { 671 DataRefImpl Ret; 672 Ret.p = getSymbolTable(); 673 return basic_symbol_iterator(SymbolRef(Ret, this)); 674 } 675 676 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const { 677 // The symbol table ends where the string table begins. 678 DataRefImpl Ret; 679 Ret.p = reinterpret_cast<uintptr_t>(StringTable); 680 return basic_symbol_iterator(SymbolRef(Ret, this)); 681 } 682 683 import_directory_iterator COFFObjectFile::import_directory_begin() const { 684 return import_directory_iterator( 685 ImportDirectoryEntryRef(ImportDirectory, 0, this)); 686 } 687 688 import_directory_iterator COFFObjectFile::import_directory_end() const { 689 return import_directory_iterator( 690 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this)); 691 } 692 693 delay_import_directory_iterator 694 COFFObjectFile::delay_import_directory_begin() const { 695 return delay_import_directory_iterator( 696 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this)); 697 } 698 699 delay_import_directory_iterator 700 COFFObjectFile::delay_import_directory_end() const { 701 return delay_import_directory_iterator( 702 DelayImportDirectoryEntryRef( 703 DelayImportDirectory, NumberOfDelayImportDirectory, this)); 704 } 705 706 export_directory_iterator COFFObjectFile::export_directory_begin() const { 707 return export_directory_iterator( 708 ExportDirectoryEntryRef(ExportDirectory, 0, this)); 709 } 710 711 export_directory_iterator COFFObjectFile::export_directory_end() const { 712 if (!ExportDirectory) 713 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this)); 714 ExportDirectoryEntryRef Ref(ExportDirectory, 715 ExportDirectory->AddressTableEntries, this); 716 return export_directory_iterator(Ref); 717 } 718 719 section_iterator COFFObjectFile::section_begin() const { 720 DataRefImpl Ret; 721 Ret.p = reinterpret_cast<uintptr_t>(SectionTable); 722 return section_iterator(SectionRef(Ret, this)); 723 } 724 725 section_iterator COFFObjectFile::section_end() const { 726 DataRefImpl Ret; 727 int NumSections = 728 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections(); 729 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections); 730 return section_iterator(SectionRef(Ret, this)); 731 } 732 733 uint8_t COFFObjectFile::getBytesInAddress() const { 734 return getArch() == Triple::x86_64 ? 8 : 4; 735 } 736 737 StringRef COFFObjectFile::getFileFormatName() const { 738 switch(getMachine()) { 739 case COFF::IMAGE_FILE_MACHINE_I386: 740 return "COFF-i386"; 741 case COFF::IMAGE_FILE_MACHINE_AMD64: 742 return "COFF-x86-64"; 743 case COFF::IMAGE_FILE_MACHINE_ARMNT: 744 return "COFF-ARM"; 745 default: 746 return "COFF-<unknown arch>"; 747 } 748 } 749 750 unsigned COFFObjectFile::getArch() const { 751 switch (getMachine()) { 752 case COFF::IMAGE_FILE_MACHINE_I386: 753 return Triple::x86; 754 case COFF::IMAGE_FILE_MACHINE_AMD64: 755 return Triple::x86_64; 756 case COFF::IMAGE_FILE_MACHINE_ARMNT: 757 return Triple::thumb; 758 default: 759 return Triple::UnknownArch; 760 } 761 } 762 763 iterator_range<import_directory_iterator> 764 COFFObjectFile::import_directories() const { 765 return make_range(import_directory_begin(), import_directory_end()); 766 } 767 768 iterator_range<delay_import_directory_iterator> 769 COFFObjectFile::delay_import_directories() const { 770 return make_range(delay_import_directory_begin(), 771 delay_import_directory_end()); 772 } 773 774 iterator_range<export_directory_iterator> 775 COFFObjectFile::export_directories() const { 776 return make_range(export_directory_begin(), export_directory_end()); 777 } 778 779 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const { 780 Res = PE32Header; 781 return object_error::success; 782 } 783 784 std::error_code 785 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const { 786 Res = PE32PlusHeader; 787 return object_error::success; 788 } 789 790 std::error_code 791 COFFObjectFile::getDataDirectory(uint32_t Index, 792 const data_directory *&Res) const { 793 // Error if if there's no data directory or the index is out of range. 794 if (!DataDirectory) 795 return object_error::parse_failed; 796 assert(PE32Header || PE32PlusHeader); 797 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize 798 : PE32PlusHeader->NumberOfRvaAndSize; 799 if (Index > NumEnt) 800 return object_error::parse_failed; 801 Res = &DataDirectory[Index]; 802 return object_error::success; 803 } 804 805 std::error_code COFFObjectFile::getSection(int32_t Index, 806 const coff_section *&Result) const { 807 // Check for special index values. 808 if (COFF::isReservedSectionNumber(Index)) 809 Result = nullptr; 810 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections()) 811 // We already verified the section table data, so no need to check again. 812 Result = SectionTable + (Index - 1); 813 else 814 return object_error::parse_failed; 815 return object_error::success; 816 } 817 818 std::error_code COFFObjectFile::getString(uint32_t Offset, 819 StringRef &Result) const { 820 if (StringTableSize <= 4) 821 // Tried to get a string from an empty string table. 822 return object_error::parse_failed; 823 if (Offset >= StringTableSize) 824 return object_error::unexpected_eof; 825 Result = StringRef(StringTable + Offset); 826 return object_error::success; 827 } 828 829 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol, 830 StringRef &Res) const { 831 // Check for string table entry. First 4 bytes are 0. 832 if (Symbol.getStringTableOffset().Zeroes == 0) { 833 uint32_t Offset = Symbol.getStringTableOffset().Offset; 834 if (std::error_code EC = getString(Offset, Res)) 835 return EC; 836 return object_error::success; 837 } 838 839 if (Symbol.getShortName()[COFF::NameSize - 1] == 0) 840 // Null terminated, let ::strlen figure out the length. 841 Res = StringRef(Symbol.getShortName()); 842 else 843 // Not null terminated, use all 8 bytes. 844 Res = StringRef(Symbol.getShortName(), COFF::NameSize); 845 return object_error::success; 846 } 847 848 ArrayRef<uint8_t> 849 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const { 850 const uint8_t *Aux = nullptr; 851 852 size_t SymbolSize = getSymbolTableEntrySize(); 853 if (Symbol.getNumberOfAuxSymbols() > 0) { 854 // AUX data comes immediately after the symbol in COFF 855 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize; 856 # ifndef NDEBUG 857 // Verify that the Aux symbol points to a valid entry in the symbol table. 858 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); 859 if (Offset < getPointerToSymbolTable() || 860 Offset >= 861 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize)) 862 report_fatal_error("Aux Symbol data was outside of symbol table."); 863 864 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 && 865 "Aux Symbol data did not point to the beginning of a symbol"); 866 # endif 867 } 868 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize); 869 } 870 871 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec, 872 StringRef &Res) const { 873 StringRef Name; 874 if (Sec->Name[COFF::NameSize - 1] == 0) 875 // Null terminated, let ::strlen figure out the length. 876 Name = Sec->Name; 877 else 878 // Not null terminated, use all 8 bytes. 879 Name = StringRef(Sec->Name, COFF::NameSize); 880 881 // Check for string table entry. First byte is '/'. 882 if (Name[0] == '/') { 883 uint32_t Offset; 884 if (Name[1] == '/') { 885 if (decodeBase64StringEntry(Name.substr(2), Offset)) 886 return object_error::parse_failed; 887 } else { 888 if (Name.substr(1).getAsInteger(10, Offset)) 889 return object_error::parse_failed; 890 } 891 if (std::error_code EC = getString(Offset, Name)) 892 return EC; 893 } 894 895 Res = Name; 896 return object_error::success; 897 } 898 899 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const { 900 // SizeOfRawData and VirtualSize change what they represent depending on 901 // whether or not we have an executable image. 902 // 903 // For object files, SizeOfRawData contains the size of section's data; 904 // VirtualSize is always zero. 905 // 906 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the 907 // actual section size is in VirtualSize. It is possible for VirtualSize to 908 // be greater than SizeOfRawData; the contents past that point should be 909 // considered to be zero. 910 uint32_t SectionSize; 911 if (Sec->VirtualSize) 912 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData); 913 else 914 SectionSize = Sec->SizeOfRawData; 915 916 return SectionSize; 917 } 918 919 std::error_code 920 COFFObjectFile::getSectionContents(const coff_section *Sec, 921 ArrayRef<uint8_t> &Res) const { 922 // PointerToRawData and SizeOfRawData won't make sense for BSS sections, 923 // don't do anything interesting for them. 924 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 && 925 "BSS sections don't have contents!"); 926 // The only thing that we need to verify is that the contents is contained 927 // within the file bounds. We don't need to make sure it doesn't cover other 928 // data, as there's nothing that says that is not allowed. 929 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData; 930 uint32_t SectionSize = getSectionSize(Sec); 931 uintptr_t ConEnd = ConStart + SectionSize; 932 if (ConEnd > uintptr_t(Data.getBufferEnd())) 933 return object_error::parse_failed; 934 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize); 935 return object_error::success; 936 } 937 938 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { 939 return reinterpret_cast<const coff_relocation*>(Rel.p); 940 } 941 942 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { 943 Rel.p = reinterpret_cast<uintptr_t>( 944 reinterpret_cast<const coff_relocation*>(Rel.p) + 1); 945 } 946 947 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel, 948 uint64_t &Res) const { 949 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile"); 950 } 951 952 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel, 953 uint64_t &Res) const { 954 Res = toRel(Rel)->VirtualAddress; 955 return object_error::success; 956 } 957 958 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 959 const coff_relocation *R = toRel(Rel); 960 DataRefImpl Ref; 961 if (SymbolTable16) 962 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex); 963 else if (SymbolTable32) 964 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex); 965 else 966 llvm_unreachable("no symbol table pointer!"); 967 return symbol_iterator(SymbolRef(Ref, this)); 968 } 969 970 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel, 971 uint64_t &Res) const { 972 const coff_relocation* R = toRel(Rel); 973 Res = R->Type; 974 return object_error::success; 975 } 976 977 const coff_section * 978 COFFObjectFile::getCOFFSection(const SectionRef &Section) const { 979 return toSec(Section.getRawDataRefImpl()); 980 } 981 982 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const { 983 if (SymbolTable16) 984 return toSymb<coff_symbol16>(Ref); 985 if (SymbolTable32) 986 return toSymb<coff_symbol32>(Ref); 987 llvm_unreachable("no symbol table pointer!"); 988 } 989 990 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const { 991 return getCOFFSymbol(Symbol.getRawDataRefImpl()); 992 } 993 994 const coff_relocation * 995 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const { 996 return toRel(Reloc.getRawDataRefImpl()); 997 } 998 999 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \ 1000 case COFF::reloc_type: \ 1001 Res = #reloc_type; \ 1002 break; 1003 1004 std::error_code 1005 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel, 1006 SmallVectorImpl<char> &Result) const { 1007 const coff_relocation *Reloc = toRel(Rel); 1008 StringRef Res; 1009 switch (getMachine()) { 1010 case COFF::IMAGE_FILE_MACHINE_AMD64: 1011 switch (Reloc->Type) { 1012 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); 1013 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); 1014 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); 1015 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); 1016 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); 1017 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); 1018 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); 1019 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); 1020 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); 1021 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); 1022 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); 1023 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); 1024 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); 1025 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); 1026 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); 1027 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); 1028 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); 1029 default: 1030 Res = "Unknown"; 1031 } 1032 break; 1033 case COFF::IMAGE_FILE_MACHINE_ARMNT: 1034 switch (Reloc->Type) { 1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE); 1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32); 1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB); 1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24); 1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11); 1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN); 1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24); 1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11); 1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION); 1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL); 1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A); 1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T); 1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T); 1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T); 1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T); 1050 default: 1051 Res = "Unknown"; 1052 } 1053 break; 1054 case COFF::IMAGE_FILE_MACHINE_I386: 1055 switch (Reloc->Type) { 1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); 1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); 1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); 1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); 1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); 1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); 1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); 1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); 1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); 1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); 1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); 1067 default: 1068 Res = "Unknown"; 1069 } 1070 break; 1071 default: 1072 Res = "Unknown"; 1073 } 1074 Result.append(Res.begin(), Res.end()); 1075 return object_error::success; 1076 } 1077 1078 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME 1079 1080 std::error_code 1081 COFFObjectFile::getRelocationValueString(DataRefImpl Rel, 1082 SmallVectorImpl<char> &Result) const { 1083 const coff_relocation *Reloc = toRel(Rel); 1084 DataRefImpl Sym; 1085 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex); 1086 if (std::error_code EC = Symb.getError()) 1087 return EC; 1088 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr()); 1089 StringRef SymName; 1090 if (std::error_code EC = getSymbolName(Sym, SymName)) 1091 return EC; 1092 Result.append(SymName.begin(), SymName.end()); 1093 return object_error::success; 1094 } 1095 1096 bool COFFObjectFile::isRelocatableObject() const { 1097 return !DataDirectory; 1098 } 1099 1100 bool ImportDirectoryEntryRef:: 1101 operator==(const ImportDirectoryEntryRef &Other) const { 1102 return ImportTable == Other.ImportTable && Index == Other.Index; 1103 } 1104 1105 void ImportDirectoryEntryRef::moveNext() { 1106 ++Index; 1107 } 1108 1109 std::error_code ImportDirectoryEntryRef::getImportTableEntry( 1110 const import_directory_table_entry *&Result) const { 1111 Result = ImportTable + Index; 1112 return object_error::success; 1113 } 1114 1115 static imported_symbol_iterator 1116 makeImportedSymbolIterator(const COFFObjectFile *Object, 1117 uintptr_t Ptr, int Index) { 1118 if (Object->getBytesInAddress() == 4) { 1119 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr); 1120 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1121 } 1122 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr); 1123 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1124 } 1125 1126 static imported_symbol_iterator 1127 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) { 1128 uintptr_t IntPtr = 0; 1129 Object->getRvaPtr(RVA, IntPtr); 1130 return makeImportedSymbolIterator(Object, IntPtr, 0); 1131 } 1132 1133 static imported_symbol_iterator 1134 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) { 1135 uintptr_t IntPtr = 0; 1136 Object->getRvaPtr(RVA, IntPtr); 1137 // Forward the pointer to the last entry which is null. 1138 int Index = 0; 1139 if (Object->getBytesInAddress() == 4) { 1140 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr); 1141 while (*Entry++) 1142 ++Index; 1143 } else { 1144 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr); 1145 while (*Entry++) 1146 ++Index; 1147 } 1148 return makeImportedSymbolIterator(Object, IntPtr, Index); 1149 } 1150 1151 imported_symbol_iterator 1152 ImportDirectoryEntryRef::imported_symbol_begin() const { 1153 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA, 1154 OwningObject); 1155 } 1156 1157 imported_symbol_iterator 1158 ImportDirectoryEntryRef::imported_symbol_end() const { 1159 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA, 1160 OwningObject); 1161 } 1162 1163 iterator_range<imported_symbol_iterator> 1164 ImportDirectoryEntryRef::imported_symbols() const { 1165 return make_range(imported_symbol_begin(), imported_symbol_end()); 1166 } 1167 1168 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const { 1169 uintptr_t IntPtr = 0; 1170 if (std::error_code EC = 1171 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr)) 1172 return EC; 1173 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1174 return object_error::success; 1175 } 1176 1177 std::error_code 1178 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const { 1179 Result = ImportTable[Index].ImportLookupTableRVA; 1180 return object_error::success; 1181 } 1182 1183 std::error_code 1184 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const { 1185 Result = ImportTable[Index].ImportAddressTableRVA; 1186 return object_error::success; 1187 } 1188 1189 std::error_code ImportDirectoryEntryRef::getImportLookupEntry( 1190 const import_lookup_table_entry32 *&Result) const { 1191 uintptr_t IntPtr = 0; 1192 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA; 1193 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1194 return EC; 1195 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr); 1196 return object_error::success; 1197 } 1198 1199 bool DelayImportDirectoryEntryRef:: 1200 operator==(const DelayImportDirectoryEntryRef &Other) const { 1201 return Table == Other.Table && Index == Other.Index; 1202 } 1203 1204 void DelayImportDirectoryEntryRef::moveNext() { 1205 ++Index; 1206 } 1207 1208 imported_symbol_iterator 1209 DelayImportDirectoryEntryRef::imported_symbol_begin() const { 1210 return importedSymbolBegin(Table[Index].DelayImportNameTable, 1211 OwningObject); 1212 } 1213 1214 imported_symbol_iterator 1215 DelayImportDirectoryEntryRef::imported_symbol_end() const { 1216 return importedSymbolEnd(Table[Index].DelayImportNameTable, 1217 OwningObject); 1218 } 1219 1220 iterator_range<imported_symbol_iterator> 1221 DelayImportDirectoryEntryRef::imported_symbols() const { 1222 return make_range(imported_symbol_begin(), imported_symbol_end()); 1223 } 1224 1225 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const { 1226 uintptr_t IntPtr = 0; 1227 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr)) 1228 return EC; 1229 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1230 return object_error::success; 1231 } 1232 1233 std::error_code DelayImportDirectoryEntryRef:: 1234 getDelayImportTable(const delay_import_directory_table_entry *&Result) const { 1235 Result = Table; 1236 return object_error::success; 1237 } 1238 1239 bool ExportDirectoryEntryRef:: 1240 operator==(const ExportDirectoryEntryRef &Other) const { 1241 return ExportTable == Other.ExportTable && Index == Other.Index; 1242 } 1243 1244 void ExportDirectoryEntryRef::moveNext() { 1245 ++Index; 1246 } 1247 1248 // Returns the name of the current export symbol. If the symbol is exported only 1249 // by ordinal, the empty string is set as a result. 1250 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const { 1251 uintptr_t IntPtr = 0; 1252 if (std::error_code EC = 1253 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr)) 1254 return EC; 1255 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1256 return object_error::success; 1257 } 1258 1259 // Returns the starting ordinal number. 1260 std::error_code 1261 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { 1262 Result = ExportTable->OrdinalBase; 1263 return object_error::success; 1264 } 1265 1266 // Returns the export ordinal of the current export symbol. 1267 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { 1268 Result = ExportTable->OrdinalBase + Index; 1269 return object_error::success; 1270 } 1271 1272 // Returns the address of the current export symbol. 1273 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { 1274 uintptr_t IntPtr = 0; 1275 if (std::error_code EC = 1276 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr)) 1277 return EC; 1278 const export_address_table_entry *entry = 1279 reinterpret_cast<const export_address_table_entry *>(IntPtr); 1280 Result = entry[Index].ExportRVA; 1281 return object_error::success; 1282 } 1283 1284 // Returns the name of the current export symbol. If the symbol is exported only 1285 // by ordinal, the empty string is set as a result. 1286 std::error_code 1287 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { 1288 uintptr_t IntPtr = 0; 1289 if (std::error_code EC = 1290 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr)) 1291 return EC; 1292 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); 1293 1294 uint32_t NumEntries = ExportTable->NumberOfNamePointers; 1295 int Offset = 0; 1296 for (const ulittle16_t *I = Start, *E = Start + NumEntries; 1297 I < E; ++I, ++Offset) { 1298 if (*I != Index) 1299 continue; 1300 if (std::error_code EC = 1301 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr)) 1302 return EC; 1303 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); 1304 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr)) 1305 return EC; 1306 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1307 return object_error::success; 1308 } 1309 Result = ""; 1310 return object_error::success; 1311 } 1312 1313 bool ImportedSymbolRef:: 1314 operator==(const ImportedSymbolRef &Other) const { 1315 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64 1316 && Index == Other.Index; 1317 } 1318 1319 void ImportedSymbolRef::moveNext() { 1320 ++Index; 1321 } 1322 1323 std::error_code 1324 ImportedSymbolRef::getSymbolName(StringRef &Result) const { 1325 uint32_t RVA; 1326 if (Entry32) { 1327 // If a symbol is imported only by ordinal, it has no name. 1328 if (Entry32[Index].isOrdinal()) 1329 return object_error::success; 1330 RVA = Entry32[Index].getHintNameRVA(); 1331 } else { 1332 if (Entry64[Index].isOrdinal()) 1333 return object_error::success; 1334 RVA = Entry64[Index].getHintNameRVA(); 1335 } 1336 uintptr_t IntPtr = 0; 1337 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1338 return EC; 1339 // +2 because the first two bytes is hint. 1340 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2)); 1341 return object_error::success; 1342 } 1343 1344 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const { 1345 uint32_t RVA; 1346 if (Entry32) { 1347 if (Entry32[Index].isOrdinal()) { 1348 Result = Entry32[Index].getOrdinal(); 1349 return object_error::success; 1350 } 1351 RVA = Entry32[Index].getHintNameRVA(); 1352 } else { 1353 if (Entry64[Index].isOrdinal()) { 1354 Result = Entry64[Index].getOrdinal(); 1355 return object_error::success; 1356 } 1357 RVA = Entry64[Index].getHintNameRVA(); 1358 } 1359 uintptr_t IntPtr = 0; 1360 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1361 return EC; 1362 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr); 1363 return object_error::success; 1364 } 1365 1366 ErrorOr<std::unique_ptr<COFFObjectFile>> 1367 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) { 1368 std::error_code EC; 1369 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC)); 1370 if (EC) 1371 return EC; 1372 return std::move(Ret); 1373 } 1374