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/Debug.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include <cctype> 22 23 using namespace llvm; 24 using namespace object; 25 26 using support::ulittle8_t; 27 using support::ulittle16_t; 28 using support::ulittle32_t; 29 using support::little16_t; 30 31 // Returns false if size is greater than the buffer size. And sets ec. 32 static bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) { 33 if (M->getBufferSize() < Size) { 34 EC = object_error::unexpected_eof; 35 return false; 36 } 37 return true; 38 } 39 40 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. 41 // Returns unexpected_eof if error. 42 template<typename T> 43 static error_code getObject(const T *&Obj, const MemoryBuffer *M, 44 const uint8_t *Ptr, const size_t Size = sizeof(T)) { 45 uintptr_t Addr = uintptr_t(Ptr); 46 if (Addr + Size < Addr || 47 Addr + Size < Size || 48 Addr + Size > uintptr_t(M->getBufferEnd())) { 49 return object_error::unexpected_eof; 50 } 51 Obj = reinterpret_cast<const T *>(Addr); 52 return object_error::success; 53 } 54 55 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const { 56 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p); 57 58 # ifndef NDEBUG 59 // Verify that the symbol points to a valid entry in the symbol table. 60 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base()); 61 if (Offset < COFFHeader->PointerToSymbolTable 62 || Offset >= COFFHeader->PointerToSymbolTable 63 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol))) 64 report_fatal_error("Symbol was outside of symbol table."); 65 66 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol) 67 == 0 && "Symbol did not point to the beginning of a symbol"); 68 # endif 69 70 return Addr; 71 } 72 73 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { 74 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); 75 76 # ifndef NDEBUG 77 // Verify that the section points to a valid entry in the section table. 78 if (Addr < SectionTable 79 || Addr >= (SectionTable + COFFHeader->NumberOfSections)) 80 report_fatal_error("Section was outside of section table."); 81 82 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable); 83 assert(Offset % sizeof(coff_section) == 0 && 84 "Section did not point to the beginning of a section"); 85 # endif 86 87 return Addr; 88 } 89 90 error_code COFFObjectFile::getSymbolNext(DataRefImpl Ref, 91 SymbolRef &Result) const { 92 const coff_symbol *Symb = toSymb(Ref); 93 Symb += 1 + Symb->NumberOfAuxSymbols; 94 Ref.p = reinterpret_cast<uintptr_t>(Symb); 95 Result = SymbolRef(Ref, this); 96 return object_error::success; 97 } 98 99 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref, 100 StringRef &Result) const { 101 const coff_symbol *Symb = toSymb(Ref); 102 return getSymbolName(Symb, Result); 103 } 104 105 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref, 106 uint64_t &Result) const { 107 const coff_symbol *Symb = toSymb(Ref); 108 const coff_section *Section = NULL; 109 if (error_code EC = getSection(Symb->SectionNumber, Section)) 110 return EC; 111 112 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 113 Result = UnknownAddressOrSize; 114 else if (Section) 115 Result = Section->PointerToRawData + Symb->Value; 116 else 117 Result = Symb->Value; 118 return object_error::success; 119 } 120 121 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref, 122 uint64_t &Result) const { 123 const coff_symbol *Symb = toSymb(Ref); 124 const coff_section *Section = NULL; 125 if (error_code EC = getSection(Symb->SectionNumber, Section)) 126 return EC; 127 128 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 129 Result = UnknownAddressOrSize; 130 else if (Section) 131 Result = Section->VirtualAddress + Symb->Value; 132 else 133 Result = Symb->Value; 134 return object_error::success; 135 } 136 137 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref, 138 SymbolRef::Type &Result) const { 139 const coff_symbol *Symb = toSymb(Ref); 140 Result = SymbolRef::ST_Other; 141 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL && 142 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) { 143 Result = SymbolRef::ST_Unknown; 144 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) { 145 Result = SymbolRef::ST_Function; 146 } else { 147 uint32_t Characteristics = 0; 148 if (Symb->SectionNumber > 0) { 149 const coff_section *Section = NULL; 150 if (error_code EC = getSection(Symb->SectionNumber, Section)) 151 return EC; 152 Characteristics = Section->Characteristics; 153 } 154 if (Characteristics & COFF::IMAGE_SCN_MEM_READ && 155 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only. 156 Result = SymbolRef::ST_Data; 157 } 158 return object_error::success; 159 } 160 161 error_code COFFObjectFile::getSymbolFlags(DataRefImpl Ref, 162 uint32_t &Result) const { 163 const coff_symbol *Symb = toSymb(Ref); 164 Result = SymbolRef::SF_None; 165 166 // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common 167 168 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL && 169 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 170 Result |= SymbolRef::SF_Undefined; 171 172 // TODO: This are certainly too restrictive. 173 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL) 174 Result |= SymbolRef::SF_Global; 175 176 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) 177 Result |= SymbolRef::SF_Weak; 178 179 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE) 180 Result |= SymbolRef::SF_Absolute; 181 182 return object_error::success; 183 } 184 185 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref, 186 uint64_t &Result) const { 187 // FIXME: Return the correct size. This requires looking at all the symbols 188 // in the same section as this symbol, and looking for either the next 189 // symbol, or the end of the section. 190 const coff_symbol *Symb = toSymb(Ref); 191 const coff_section *Section = NULL; 192 if (error_code EC = getSection(Symb->SectionNumber, Section)) 193 return EC; 194 195 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 196 Result = UnknownAddressOrSize; 197 else if (Section) 198 Result = Section->SizeOfRawData - Symb->Value; 199 else 200 Result = 0; 201 return object_error::success; 202 } 203 204 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref, 205 section_iterator &Result) const { 206 const coff_symbol *Symb = toSymb(Ref); 207 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED) 208 Result = end_sections(); 209 else { 210 const coff_section *Sec = 0; 211 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC; 212 DataRefImpl Ref; 213 Ref.p = reinterpret_cast<uintptr_t>(Sec); 214 Result = section_iterator(SectionRef(Ref, this)); 215 } 216 return object_error::success; 217 } 218 219 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref, 220 uint64_t &Val) const { 221 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile"); 222 } 223 224 error_code COFFObjectFile::getSectionNext(DataRefImpl Ref, 225 SectionRef &Result) const { 226 const coff_section *Sec = toSec(Ref); 227 Sec += 1; 228 Ref.p = reinterpret_cast<uintptr_t>(Sec); 229 Result = SectionRef(Ref, this); 230 return object_error::success; 231 } 232 233 error_code COFFObjectFile::getSectionName(DataRefImpl Ref, 234 StringRef &Result) const { 235 const coff_section *Sec = toSec(Ref); 236 return getSectionName(Sec, Result); 237 } 238 239 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref, 240 uint64_t &Result) const { 241 const coff_section *Sec = toSec(Ref); 242 Result = Sec->VirtualAddress; 243 return object_error::success; 244 } 245 246 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref, 247 uint64_t &Result) const { 248 const coff_section *Sec = toSec(Ref); 249 Result = Sec->SizeOfRawData; 250 return object_error::success; 251 } 252 253 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref, 254 StringRef &Result) const { 255 const coff_section *Sec = toSec(Ref); 256 ArrayRef<uint8_t> Res; 257 error_code EC = getSectionContents(Sec, Res); 258 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size()); 259 return EC; 260 } 261 262 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref, 263 uint64_t &Res) const { 264 const coff_section *Sec = toSec(Ref); 265 if (!Sec) 266 return object_error::parse_failed; 267 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1); 268 return object_error::success; 269 } 270 271 error_code COFFObjectFile::isSectionText(DataRefImpl Ref, 272 bool &Result) const { 273 const coff_section *Sec = toSec(Ref); 274 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE; 275 return object_error::success; 276 } 277 278 error_code COFFObjectFile::isSectionData(DataRefImpl Ref, 279 bool &Result) const { 280 const coff_section *Sec = toSec(Ref); 281 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; 282 return object_error::success; 283 } 284 285 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref, 286 bool &Result) const { 287 const coff_section *Sec = toSec(Ref); 288 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 289 return object_error::success; 290 } 291 292 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref, 293 bool &Result) const { 294 // FIXME: Unimplemented 295 Result = true; 296 return object_error::success; 297 } 298 299 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref, 300 bool &Result) const { 301 const coff_section *Sec = toSec(Ref); 302 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 303 return object_error::success; 304 } 305 306 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref, 307 bool &Result) const { 308 // FIXME: Unimplemented. 309 Result = false; 310 return object_error::success; 311 } 312 313 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref, 314 bool &Result) const { 315 // FIXME: Unimplemented. 316 Result = false; 317 return object_error::success; 318 } 319 320 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef, 321 DataRefImpl SymbRef, 322 bool &Result) const { 323 const coff_section *Sec = toSec(SecRef); 324 const coff_symbol *Symb = toSymb(SymbRef); 325 const coff_section *SymbSec = 0; 326 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC; 327 if (SymbSec == Sec) 328 Result = true; 329 else 330 Result = false; 331 return object_error::success; 332 } 333 334 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { 335 const coff_section *Sec = toSec(Ref); 336 DataRefImpl Ret; 337 if (Sec->NumberOfRelocations == 0) 338 Ret.p = 0; 339 else 340 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations); 341 342 return relocation_iterator(RelocationRef(Ret, this)); 343 } 344 345 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { 346 const coff_section *Sec = toSec(Ref); 347 DataRefImpl Ret; 348 if (Sec->NumberOfRelocations == 0) 349 Ret.p = 0; 350 else 351 Ret.p = reinterpret_cast<uintptr_t>( 352 reinterpret_cast<const coff_relocation*>( 353 base() + Sec->PointerToRelocations) 354 + Sec->NumberOfRelocations); 355 356 return relocation_iterator(RelocationRef(Ret, this)); 357 } 358 359 // Initialize the pointer to the symbol table. 360 error_code COFFObjectFile::initSymbolTablePtr() { 361 if (error_code EC = getObject( 362 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable, 363 COFFHeader->NumberOfSymbols * sizeof(coff_symbol))) 364 return EC; 365 366 // Find string table. The first four byte of the string table contains the 367 // total size of the string table, including the size field itself. If the 368 // string table is empty, the value of the first four byte would be 4. 369 const uint8_t *StringTableAddr = 370 base() + COFFHeader->PointerToSymbolTable + 371 COFFHeader->NumberOfSymbols * sizeof(coff_symbol); 372 const ulittle32_t *StringTableSizePtr; 373 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr)) 374 return EC; 375 StringTableSize = *StringTableSizePtr; 376 if (error_code EC = 377 getObject(StringTable, Data, StringTableAddr, StringTableSize)) 378 return EC; 379 380 // Check that the string table is null terminated if has any in it. 381 if (StringTableSize < 4 || 382 (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)) 383 return object_error::parse_failed; 384 return object_error::success; 385 } 386 387 // Returns the file offset for the given RVA. 388 error_code COFFObjectFile::getRvaPtr(uint32_t Rva, uintptr_t &Res) const { 389 error_code EC; 390 for (section_iterator I = begin_sections(), E = end_sections(); I != E; 391 I.increment(EC)) { 392 if (EC) 393 return EC; 394 const coff_section *Section = getCOFFSection(I); 395 uint32_t SectionStart = Section->VirtualAddress; 396 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize; 397 if (SectionStart <= Rva && Rva < SectionEnd) { 398 uint32_t Offset = Rva - SectionStart; 399 Res = uintptr_t(base()) + Section->PointerToRawData + Offset; 400 return object_error::success; 401 } 402 } 403 return object_error::parse_failed; 404 } 405 406 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name 407 // table entry. 408 error_code COFFObjectFile:: 409 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const { 410 uintptr_t IntPtr = 0; 411 if (error_code EC = getRvaPtr(Rva, IntPtr)) 412 return EC; 413 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); 414 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); 415 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); 416 return object_error::success; 417 } 418 419 // Find the import table. 420 error_code COFFObjectFile::initImportTablePtr() { 421 // First, we get the RVA of the import table. If the file lacks a pointer to 422 // the import table, do nothing. 423 const data_directory *DataEntry; 424 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry)) 425 return object_error::success; 426 427 // Do nothing if the pointer to import table is NULL. 428 if (DataEntry->RelativeVirtualAddress == 0) 429 return object_error::success; 430 431 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; 432 NumberOfImportDirectory = DataEntry->Size / 433 sizeof(import_directory_table_entry); 434 435 // Find the section that contains the RVA. This is needed because the RVA is 436 // the import table's memory address which is different from its file offset. 437 uintptr_t IntPtr = 0; 438 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr)) 439 return EC; 440 ImportDirectory = reinterpret_cast< 441 const import_directory_table_entry *>(IntPtr); 442 return object_error::success; 443 } 444 445 // Find the export table. 446 error_code COFFObjectFile::initExportTablePtr() { 447 // First, we get the RVA of the export table. If the file lacks a pointer to 448 // the export table, do nothing. 449 const data_directory *DataEntry; 450 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) 451 return object_error::success; 452 453 // Do nothing if the pointer to export table is NULL. 454 if (DataEntry->RelativeVirtualAddress == 0) 455 return object_error::success; 456 457 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; 458 uintptr_t IntPtr = 0; 459 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr)) 460 return EC; 461 ExportDirectory = 462 reinterpret_cast<const export_directory_table_entry *>(IntPtr); 463 return object_error::success; 464 } 465 466 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC) 467 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(0), PE32Header(0), 468 DataDirectory(0), SectionTable(0), SymbolTable(0), StringTable(0), 469 StringTableSize(0), ImportDirectory(0), NumberOfImportDirectory(0), 470 ExportDirectory(0) { 471 // Check that we at least have enough room for a header. 472 if (!checkSize(Data, EC, sizeof(coff_file_header))) return; 473 474 // The current location in the file where we are looking at. 475 uint64_t CurPtr = 0; 476 477 // PE header is optional and is present only in executables. If it exists, 478 // it is placed right after COFF header. 479 bool HasPEHeader = false; 480 481 // Check if this is a PE/COFF file. 482 if (base()[0] == 0x4d && base()[1] == 0x5a) { 483 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte 484 // PE signature to find 'normal' COFF header. 485 if (!checkSize(Data, EC, 0x3c + 8)) return; 486 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c); 487 // Check the PE magic bytes. ("PE\0\0") 488 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) { 489 EC = object_error::parse_failed; 490 return; 491 } 492 CurPtr += 4; // Skip the PE magic bytes. 493 HasPEHeader = true; 494 } 495 496 if ((EC = getObject(COFFHeader, Data, base() + CurPtr))) 497 return; 498 CurPtr += sizeof(coff_file_header); 499 500 if (HasPEHeader) { 501 if ((EC = getObject(PE32Header, Data, base() + CurPtr))) 502 return; 503 if (PE32Header->Magic != 0x10b) { 504 // We only support PE32. If this is PE32 (not PE32+), the magic byte 505 // should be 0x10b. If this is not PE32, continue as if there's no PE 506 // header in this file. 507 PE32Header = 0; 508 } else if (PE32Header->NumberOfRvaAndSize > 0) { 509 const uint8_t *Addr = base() + CurPtr + sizeof(pe32_header); 510 uint64_t size = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize; 511 if ((EC = getObject(DataDirectory, Data, Addr, size))) 512 return; 513 } 514 CurPtr += COFFHeader->SizeOfOptionalHeader; 515 } 516 517 if (!COFFHeader->isImportLibrary()) 518 if ((EC = getObject(SectionTable, Data, base() + CurPtr, 519 COFFHeader->NumberOfSections * sizeof(coff_section)))) 520 return; 521 522 // Initialize the pointer to the symbol table. 523 if (COFFHeader->PointerToSymbolTable != 0) 524 if ((EC = initSymbolTablePtr())) 525 return; 526 527 // Initialize the pointer to the beginning of the import table. 528 if ((EC = initImportTablePtr())) 529 return; 530 531 // Initialize the pointer to the export table. 532 if ((EC = initExportTablePtr())) 533 return; 534 535 EC = object_error::success; 536 } 537 538 symbol_iterator COFFObjectFile::begin_symbols() const { 539 DataRefImpl Ret; 540 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable); 541 return symbol_iterator(SymbolRef(Ret, this)); 542 } 543 544 symbol_iterator COFFObjectFile::end_symbols() const { 545 // The symbol table ends where the string table begins. 546 DataRefImpl Ret; 547 Ret.p = reinterpret_cast<uintptr_t>(StringTable); 548 return symbol_iterator(SymbolRef(Ret, this)); 549 } 550 551 symbol_iterator COFFObjectFile::begin_dynamic_symbols() const { 552 // TODO: implement 553 report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile"); 554 } 555 556 symbol_iterator COFFObjectFile::end_dynamic_symbols() const { 557 // TODO: implement 558 report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile"); 559 } 560 561 library_iterator COFFObjectFile::begin_libraries_needed() const { 562 // TODO: implement 563 report_fatal_error("Libraries needed unimplemented in COFFObjectFile"); 564 } 565 566 library_iterator COFFObjectFile::end_libraries_needed() const { 567 // TODO: implement 568 report_fatal_error("Libraries needed unimplemented in COFFObjectFile"); 569 } 570 571 StringRef COFFObjectFile::getLoadName() const { 572 // COFF does not have this field. 573 return ""; 574 } 575 576 import_directory_iterator COFFObjectFile::import_directory_begin() const { 577 return import_directory_iterator( 578 ImportDirectoryEntryRef(ImportDirectory, 0, this)); 579 } 580 581 import_directory_iterator COFFObjectFile::import_directory_end() const { 582 return import_directory_iterator( 583 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this)); 584 } 585 586 export_directory_iterator COFFObjectFile::export_directory_begin() const { 587 return export_directory_iterator( 588 ExportDirectoryEntryRef(ExportDirectory, 0, this)); 589 } 590 591 export_directory_iterator COFFObjectFile::export_directory_end() const { 592 if (ExportDirectory == 0) 593 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this)); 594 ExportDirectoryEntryRef Ref(ExportDirectory, 595 ExportDirectory->AddressTableEntries, this); 596 return export_directory_iterator(Ref); 597 } 598 599 section_iterator COFFObjectFile::begin_sections() const { 600 DataRefImpl Ret; 601 Ret.p = reinterpret_cast<uintptr_t>(SectionTable); 602 return section_iterator(SectionRef(Ret, this)); 603 } 604 605 section_iterator COFFObjectFile::end_sections() const { 606 DataRefImpl Ret; 607 int NumSections = COFFHeader->isImportLibrary() 608 ? 0 : COFFHeader->NumberOfSections; 609 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections); 610 return section_iterator(SectionRef(Ret, this)); 611 } 612 613 uint8_t COFFObjectFile::getBytesInAddress() const { 614 return getArch() == Triple::x86_64 ? 8 : 4; 615 } 616 617 StringRef COFFObjectFile::getFileFormatName() const { 618 switch(COFFHeader->Machine) { 619 case COFF::IMAGE_FILE_MACHINE_I386: 620 return "COFF-i386"; 621 case COFF::IMAGE_FILE_MACHINE_AMD64: 622 return "COFF-x86-64"; 623 default: 624 return "COFF-<unknown arch>"; 625 } 626 } 627 628 unsigned COFFObjectFile::getArch() const { 629 switch(COFFHeader->Machine) { 630 case COFF::IMAGE_FILE_MACHINE_I386: 631 return Triple::x86; 632 case COFF::IMAGE_FILE_MACHINE_AMD64: 633 return Triple::x86_64; 634 default: 635 return Triple::UnknownArch; 636 } 637 } 638 639 // This method is kept here because lld uses this. As soon as we make 640 // lld to use getCOFFHeader, this method will be removed. 641 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const { 642 return getCOFFHeader(Res); 643 } 644 645 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const { 646 Res = COFFHeader; 647 return object_error::success; 648 } 649 650 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const { 651 Res = PE32Header; 652 return object_error::success; 653 } 654 655 error_code COFFObjectFile::getDataDirectory(uint32_t Index, 656 const data_directory *&Res) const { 657 // Error if if there's no data directory or the index is out of range. 658 if (!DataDirectory || Index > PE32Header->NumberOfRvaAndSize) 659 return object_error::parse_failed; 660 Res = &DataDirectory[Index]; 661 return object_error::success; 662 } 663 664 error_code COFFObjectFile::getSection(int32_t Index, 665 const coff_section *&Result) const { 666 // Check for special index values. 667 if (Index == COFF::IMAGE_SYM_UNDEFINED || 668 Index == COFF::IMAGE_SYM_ABSOLUTE || 669 Index == COFF::IMAGE_SYM_DEBUG) 670 Result = NULL; 671 else if (Index > 0 && Index <= COFFHeader->NumberOfSections) 672 // We already verified the section table data, so no need to check again. 673 Result = SectionTable + (Index - 1); 674 else 675 return object_error::parse_failed; 676 return object_error::success; 677 } 678 679 error_code COFFObjectFile::getString(uint32_t Offset, 680 StringRef &Result) const { 681 if (StringTableSize <= 4) 682 // Tried to get a string from an empty string table. 683 return object_error::parse_failed; 684 if (Offset >= StringTableSize) 685 return object_error::unexpected_eof; 686 Result = StringRef(StringTable + Offset); 687 return object_error::success; 688 } 689 690 error_code COFFObjectFile::getSymbol(uint32_t Index, 691 const coff_symbol *&Result) const { 692 if (Index < COFFHeader->NumberOfSymbols) 693 Result = SymbolTable + Index; 694 else 695 return object_error::parse_failed; 696 return object_error::success; 697 } 698 699 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol, 700 StringRef &Res) const { 701 // Check for string table entry. First 4 bytes are 0. 702 if (Symbol->Name.Offset.Zeroes == 0) { 703 uint32_t Offset = Symbol->Name.Offset.Offset; 704 if (error_code EC = getString(Offset, Res)) 705 return EC; 706 return object_error::success; 707 } 708 709 if (Symbol->Name.ShortName[7] == 0) 710 // Null terminated, let ::strlen figure out the length. 711 Res = StringRef(Symbol->Name.ShortName); 712 else 713 // Not null terminated, use all 8 bytes. 714 Res = StringRef(Symbol->Name.ShortName, 8); 715 return object_error::success; 716 } 717 718 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData( 719 const coff_symbol *Symbol) const { 720 const uint8_t *Aux = NULL; 721 722 if (Symbol->NumberOfAuxSymbols > 0) { 723 // AUX data comes immediately after the symbol in COFF 724 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1); 725 # ifndef NDEBUG 726 // Verify that the Aux symbol points to a valid entry in the symbol table. 727 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); 728 if (Offset < COFFHeader->PointerToSymbolTable 729 || Offset >= COFFHeader->PointerToSymbolTable 730 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol))) 731 report_fatal_error("Aux Symbol data was outside of symbol table."); 732 733 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol) 734 == 0 && "Aux Symbol data did not point to the beginning of a symbol"); 735 # endif 736 } 737 return ArrayRef<uint8_t>(Aux, 738 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol)); 739 } 740 741 error_code COFFObjectFile::getSectionName(const coff_section *Sec, 742 StringRef &Res) const { 743 StringRef Name; 744 if (Sec->Name[7] == 0) 745 // Null terminated, let ::strlen figure out the length. 746 Name = Sec->Name; 747 else 748 // Not null terminated, use all 8 bytes. 749 Name = StringRef(Sec->Name, 8); 750 751 // Check for string table entry. First byte is '/'. 752 if (Name[0] == '/') { 753 uint32_t Offset; 754 if (Name.substr(1).getAsInteger(10, Offset)) 755 return object_error::parse_failed; 756 if (error_code EC = getString(Offset, Name)) 757 return EC; 758 } 759 760 Res = Name; 761 return object_error::success; 762 } 763 764 error_code COFFObjectFile::getSectionContents(const coff_section *Sec, 765 ArrayRef<uint8_t> &Res) const { 766 // The only thing that we need to verify is that the contents is contained 767 // within the file bounds. We don't need to make sure it doesn't cover other 768 // data, as there's nothing that says that is not allowed. 769 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData; 770 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData; 771 if (ConEnd > uintptr_t(Data->getBufferEnd())) 772 return object_error::parse_failed; 773 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart), 774 Sec->SizeOfRawData); 775 return object_error::success; 776 } 777 778 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { 779 return reinterpret_cast<const coff_relocation*>(Rel.p); 780 } 781 782 error_code COFFObjectFile::getRelocationNext(DataRefImpl Rel, 783 RelocationRef &Res) const { 784 Rel.p = reinterpret_cast<uintptr_t>( 785 reinterpret_cast<const coff_relocation*>(Rel.p) + 1); 786 Res = RelocationRef(Rel, this); 787 return object_error::success; 788 } 789 790 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel, 791 uint64_t &Res) const { 792 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile"); 793 } 794 795 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel, 796 uint64_t &Res) const { 797 Res = toRel(Rel)->VirtualAddress; 798 return object_error::success; 799 } 800 801 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 802 const coff_relocation* R = toRel(Rel); 803 DataRefImpl Ref; 804 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex); 805 return symbol_iterator(SymbolRef(Ref, this)); 806 } 807 808 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel, 809 uint64_t &Res) const { 810 const coff_relocation* R = toRel(Rel); 811 Res = R->Type; 812 return object_error::success; 813 } 814 815 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const { 816 return toSec(It->getRawDataRefImpl()); 817 } 818 819 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const { 820 return toSymb(It->getRawDataRefImpl()); 821 } 822 823 const coff_relocation *COFFObjectFile::getCOFFRelocation( 824 relocation_iterator &It) const { 825 return toRel(It->getRawDataRefImpl()); 826 } 827 828 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \ 829 case COFF::enum: Res = #enum; break; 830 831 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel, 832 SmallVectorImpl<char> &Result) const { 833 const coff_relocation *Reloc = toRel(Rel); 834 StringRef Res; 835 switch (COFFHeader->Machine) { 836 case COFF::IMAGE_FILE_MACHINE_AMD64: 837 switch (Reloc->Type) { 838 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); 839 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); 840 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); 841 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); 842 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); 843 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); 844 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); 845 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); 846 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); 847 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); 848 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); 849 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); 850 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); 851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); 852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); 853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); 854 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); 855 default: 856 Res = "Unknown"; 857 } 858 break; 859 case COFF::IMAGE_FILE_MACHINE_I386: 860 switch (Reloc->Type) { 861 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); 862 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); 863 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); 864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); 865 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); 866 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); 867 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); 868 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); 869 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); 870 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); 871 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); 872 default: 873 Res = "Unknown"; 874 } 875 break; 876 default: 877 Res = "Unknown"; 878 } 879 Result.append(Res.begin(), Res.end()); 880 return object_error::success; 881 } 882 883 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME 884 885 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel, 886 SmallVectorImpl<char> &Result) const { 887 const coff_relocation *Reloc = toRel(Rel); 888 const coff_symbol *Symb = 0; 889 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC; 890 DataRefImpl Sym; 891 Sym.p = reinterpret_cast<uintptr_t>(Symb); 892 StringRef SymName; 893 if (error_code EC = getSymbolName(Sym, SymName)) return EC; 894 Result.append(SymName.begin(), SymName.end()); 895 return object_error::success; 896 } 897 898 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData, 899 LibraryRef &Result) const { 900 report_fatal_error("getLibraryNext not implemented in COFFObjectFile"); 901 } 902 903 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData, 904 StringRef &Result) const { 905 report_fatal_error("getLibraryPath not implemented in COFFObjectFile"); 906 } 907 908 bool ImportDirectoryEntryRef:: 909 operator==(const ImportDirectoryEntryRef &Other) const { 910 return ImportTable == Other.ImportTable && Index == Other.Index; 911 } 912 913 error_code 914 ImportDirectoryEntryRef::getNext(ImportDirectoryEntryRef &Result) const { 915 Result = ImportDirectoryEntryRef(ImportTable, Index + 1, OwningObject); 916 return object_error::success; 917 } 918 919 error_code ImportDirectoryEntryRef:: 920 getImportTableEntry(const import_directory_table_entry *&Result) const { 921 Result = ImportTable; 922 return object_error::success; 923 } 924 925 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const { 926 uintptr_t IntPtr = 0; 927 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr)) 928 return EC; 929 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 930 return object_error::success; 931 } 932 933 error_code ImportDirectoryEntryRef::getImportLookupEntry( 934 const import_lookup_table_entry32 *&Result) const { 935 uintptr_t IntPtr = 0; 936 if (error_code EC = 937 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr)) 938 return EC; 939 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr); 940 return object_error::success; 941 } 942 943 bool ExportDirectoryEntryRef:: 944 operator==(const ExportDirectoryEntryRef &Other) const { 945 return ExportTable == Other.ExportTable && Index == Other.Index; 946 } 947 948 error_code 949 ExportDirectoryEntryRef::getNext(ExportDirectoryEntryRef &Result) const { 950 Result = ExportDirectoryEntryRef(ExportTable, Index + 1, OwningObject); 951 return object_error::success; 952 } 953 954 // Returns the name of the current export symbol. If the symbol is exported only 955 // by ordinal, the empty string is set as a result. 956 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const { 957 uintptr_t IntPtr = 0; 958 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr)) 959 return EC; 960 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 961 return object_error::success; 962 } 963 964 // Returns the starting ordinal number. 965 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { 966 Result = ExportTable->OrdinalBase; 967 return object_error::success; 968 } 969 970 // Returns the export ordinal of the current export symbol. 971 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { 972 Result = ExportTable->OrdinalBase + Index; 973 return object_error::success; 974 } 975 976 // Returns the address of the current export symbol. 977 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { 978 uintptr_t IntPtr = 0; 979 if (error_code EC = OwningObject->getRvaPtr( 980 ExportTable->ExportAddressTableRVA, IntPtr)) 981 return EC; 982 const export_address_table_entry *entry = 983 reinterpret_cast<const export_address_table_entry *>(IntPtr); 984 Result = entry[Index].ExportRVA; 985 return object_error::success; 986 } 987 988 // Returns the name of the current export symbol. If the symbol is exported only 989 // by ordinal, the empty string is set as a result. 990 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { 991 uintptr_t IntPtr = 0; 992 if (error_code EC = OwningObject->getRvaPtr( 993 ExportTable->OrdinalTableRVA, IntPtr)) 994 return EC; 995 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); 996 997 uint32_t NumEntries = ExportTable->NumberOfNamePointers; 998 int Offset = 0; 999 for (const ulittle16_t *I = Start, *E = Start + NumEntries; 1000 I < E; ++I, ++Offset) { 1001 if (*I != Index) 1002 continue; 1003 if (error_code EC = OwningObject->getRvaPtr( 1004 ExportTable->NamePointerRVA, IntPtr)) 1005 return EC; 1006 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); 1007 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr)) 1008 return EC; 1009 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1010 return object_error::success; 1011 } 1012 Result = ""; 1013 return object_error::success; 1014 } 1015 1016 namespace llvm { 1017 ObjectFile *ObjectFile::createCOFFObjectFile(MemoryBuffer *Object) { 1018 error_code EC; 1019 return new COFFObjectFile(Object, EC); 1020 } 1021 } 1022