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