1 //===--- XCOFFObjectFile.cpp - XCOFF object file implementation -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the XCOFFObjectFile class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Object/XCOFFObjectFile.h" 14 #include "llvm/MC/SubtargetFeature.h" 15 #include "llvm/Support/DataExtractor.h" 16 #include <cstddef> 17 #include <cstring> 18 19 namespace llvm { 20 21 using namespace XCOFF; 22 23 namespace object { 24 25 static const uint8_t FunctionSym = 0x20; 26 static const uint8_t SymTypeMask = 0x07; 27 static const uint16_t NoRelMask = 0x0001; 28 29 // Checks that [Ptr, Ptr + Size) bytes fall inside the memory buffer 30 // 'M'. Returns a pointer to the underlying object on success. 31 template <typename T> 32 static Expected<const T *> getObject(MemoryBufferRef M, const void *Ptr, 33 const uint64_t Size = sizeof(T)) { 34 uintptr_t Addr = uintptr_t(Ptr); 35 if (Error E = Binary::checkOffset(M, Addr, Size)) 36 return std::move(E); 37 return reinterpret_cast<const T *>(Addr); 38 } 39 40 static uintptr_t getWithOffset(uintptr_t Base, ptrdiff_t Offset) { 41 return reinterpret_cast<uintptr_t>(reinterpret_cast<const char *>(Base) + 42 Offset); 43 } 44 45 template <typename T> static const T *viewAs(uintptr_t in) { 46 return reinterpret_cast<const T *>(in); 47 } 48 49 static StringRef generateXCOFFFixedNameStringRef(const char *Name) { 50 auto NulCharPtr = 51 static_cast<const char *>(memchr(Name, '\0', XCOFF::NameSize)); 52 return NulCharPtr ? StringRef(Name, NulCharPtr - Name) 53 : StringRef(Name, XCOFF::NameSize); 54 } 55 56 template <typename T> StringRef XCOFFSectionHeader<T>::getName() const { 57 const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this); 58 return generateXCOFFFixedNameStringRef(DerivedXCOFFSectionHeader.Name); 59 } 60 61 template <typename T> uint16_t XCOFFSectionHeader<T>::getSectionType() const { 62 const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this); 63 return DerivedXCOFFSectionHeader.Flags & SectionFlagsTypeMask; 64 } 65 66 template <typename T> 67 bool XCOFFSectionHeader<T>::isReservedSectionType() const { 68 return getSectionType() & SectionFlagsReservedMask; 69 } 70 71 bool XCOFFRelocation32::isRelocationSigned() const { 72 return Info & XR_SIGN_INDICATOR_MASK; 73 } 74 75 bool XCOFFRelocation32::isFixupIndicated() const { 76 return Info & XR_FIXUP_INDICATOR_MASK; 77 } 78 79 uint8_t XCOFFRelocation32::getRelocatedLength() const { 80 // The relocation encodes the bit length being relocated minus 1. Add back 81 // the 1 to get the actual length being relocated. 82 return (Info & XR_BIASED_LENGTH_MASK) + 1; 83 } 84 85 void XCOFFObjectFile::checkSectionAddress(uintptr_t Addr, 86 uintptr_t TableAddress) const { 87 if (Addr < TableAddress) 88 report_fatal_error("Section header outside of section header table."); 89 90 uintptr_t Offset = Addr - TableAddress; 91 if (Offset >= getSectionHeaderSize() * getNumberOfSections()) 92 report_fatal_error("Section header outside of section header table."); 93 94 if (Offset % getSectionHeaderSize() != 0) 95 report_fatal_error( 96 "Section header pointer does not point to a valid section header."); 97 } 98 99 const XCOFFSectionHeader32 * 100 XCOFFObjectFile::toSection32(DataRefImpl Ref) const { 101 assert(!is64Bit() && "32-bit interface called on 64-bit object file."); 102 #ifndef NDEBUG 103 checkSectionAddress(Ref.p, getSectionHeaderTableAddress()); 104 #endif 105 return viewAs<XCOFFSectionHeader32>(Ref.p); 106 } 107 108 const XCOFFSectionHeader64 * 109 XCOFFObjectFile::toSection64(DataRefImpl Ref) const { 110 assert(is64Bit() && "64-bit interface called on a 32-bit object file."); 111 #ifndef NDEBUG 112 checkSectionAddress(Ref.p, getSectionHeaderTableAddress()); 113 #endif 114 return viewAs<XCOFFSectionHeader64>(Ref.p); 115 } 116 117 const XCOFFSymbolEntry *XCOFFObjectFile::toSymbolEntry(DataRefImpl Ref) const { 118 assert(!is64Bit() && "Symbol table support not implemented for 64-bit."); 119 assert(Ref.p != 0 && "Symbol table pointer can not be nullptr!"); 120 #ifndef NDEBUG 121 checkSymbolEntryPointer(Ref.p); 122 #endif 123 auto SymEntPtr = viewAs<XCOFFSymbolEntry>(Ref.p); 124 return SymEntPtr; 125 } 126 127 const XCOFFFileHeader32 *XCOFFObjectFile::fileHeader32() const { 128 assert(!is64Bit() && "32-bit interface called on 64-bit object file."); 129 return static_cast<const XCOFFFileHeader32 *>(FileHeader); 130 } 131 132 const XCOFFFileHeader64 *XCOFFObjectFile::fileHeader64() const { 133 assert(is64Bit() && "64-bit interface called on a 32-bit object file."); 134 return static_cast<const XCOFFFileHeader64 *>(FileHeader); 135 } 136 137 const XCOFFSectionHeader32 * 138 XCOFFObjectFile::sectionHeaderTable32() const { 139 assert(!is64Bit() && "32-bit interface called on 64-bit object file."); 140 return static_cast<const XCOFFSectionHeader32 *>(SectionHeaderTable); 141 } 142 143 const XCOFFSectionHeader64 * 144 XCOFFObjectFile::sectionHeaderTable64() const { 145 assert(is64Bit() && "64-bit interface called on a 32-bit object file."); 146 return static_cast<const XCOFFSectionHeader64 *>(SectionHeaderTable); 147 } 148 149 void XCOFFObjectFile::moveSymbolNext(DataRefImpl &Symb) const { 150 const XCOFFSymbolEntry *SymEntPtr = toSymbolEntry(Symb); 151 SymEntPtr += SymEntPtr->NumberOfAuxEntries + 1; 152 #ifndef NDEBUG 153 // This function is used by basic_symbol_iterator, which allows to 154 // point to the end-of-symbol-table address. 155 if (reinterpret_cast<uintptr_t>(SymEntPtr) != getEndOfSymbolTableAddress()) 156 checkSymbolEntryPointer(reinterpret_cast<uintptr_t>(SymEntPtr)); 157 #endif 158 Symb.p = reinterpret_cast<uintptr_t>(SymEntPtr); 159 } 160 161 Expected<StringRef> 162 XCOFFObjectFile::getStringTableEntry(uint32_t Offset) const { 163 // The byte offset is relative to the start of the string table. 164 // A byte offset value of 0 is a null or zero-length symbol 165 // name. A byte offset in the range 1 to 3 (inclusive) points into the length 166 // field; as a soft-error recovery mechanism, we treat such cases as having an 167 // offset of 0. 168 if (Offset < 4) 169 return StringRef(nullptr, 0); 170 171 if (StringTable.Data != nullptr && StringTable.Size > Offset) 172 return (StringTable.Data + Offset); 173 174 return make_error<GenericBinaryError>("Bad offset for string table entry", 175 object_error::parse_failed); 176 } 177 178 Expected<StringRef> 179 XCOFFObjectFile::getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const { 180 if (CFileEntPtr->NameInStrTbl.Magic != 181 XCOFFSymbolEntry::NAME_IN_STR_TBL_MAGIC) 182 return generateXCOFFFixedNameStringRef(CFileEntPtr->Name); 183 return getStringTableEntry(CFileEntPtr->NameInStrTbl.Offset); 184 } 185 186 Expected<StringRef> XCOFFObjectFile::getSymbolName(DataRefImpl Symb) const { 187 const XCOFFSymbolEntry *SymEntPtr = toSymbolEntry(Symb); 188 189 // A storage class value with the high-order bit on indicates that the name is 190 // a symbolic debugger stabstring. 191 if (SymEntPtr->StorageClass & 0x80) 192 return StringRef("Unimplemented Debug Name"); 193 194 if (SymEntPtr->NameInStrTbl.Magic != XCOFFSymbolEntry::NAME_IN_STR_TBL_MAGIC) 195 return generateXCOFFFixedNameStringRef(SymEntPtr->SymbolName); 196 197 return getStringTableEntry(SymEntPtr->NameInStrTbl.Offset); 198 } 199 200 Expected<uint64_t> XCOFFObjectFile::getSymbolAddress(DataRefImpl Symb) const { 201 assert(!is64Bit() && "Symbol table support not implemented for 64-bit."); 202 return toSymbolEntry(Symb)->Value; 203 } 204 205 uint64_t XCOFFObjectFile::getSymbolValueImpl(DataRefImpl Symb) const { 206 assert(!is64Bit() && "Symbol table support not implemented for 64-bit."); 207 return toSymbolEntry(Symb)->Value; 208 } 209 210 uint64_t XCOFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const { 211 uint64_t Result = 0; 212 llvm_unreachable("Not yet implemented!"); 213 return Result; 214 } 215 216 Expected<SymbolRef::Type> 217 XCOFFObjectFile::getSymbolType(DataRefImpl Symb) const { 218 llvm_unreachable("Not yet implemented!"); 219 return SymbolRef::ST_Other; 220 } 221 222 Expected<section_iterator> 223 XCOFFObjectFile::getSymbolSection(DataRefImpl Symb) const { 224 const XCOFFSymbolEntry *SymEntPtr = toSymbolEntry(Symb); 225 int16_t SectNum = SymEntPtr->SectionNumber; 226 227 if (isReservedSectionNumber(SectNum)) 228 return section_end(); 229 230 Expected<DataRefImpl> ExpSec = getSectionByNum(SectNum); 231 if (!ExpSec) 232 return ExpSec.takeError(); 233 234 return section_iterator(SectionRef(ExpSec.get(), this)); 235 } 236 237 void XCOFFObjectFile::moveSectionNext(DataRefImpl &Sec) const { 238 const char *Ptr = reinterpret_cast<const char *>(Sec.p); 239 Sec.p = reinterpret_cast<uintptr_t>(Ptr + getSectionHeaderSize()); 240 } 241 242 Expected<StringRef> XCOFFObjectFile::getSectionName(DataRefImpl Sec) const { 243 return generateXCOFFFixedNameStringRef(getSectionNameInternal(Sec)); 244 } 245 246 uint64_t XCOFFObjectFile::getSectionAddress(DataRefImpl Sec) const { 247 // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t 248 // with MSVC. 249 if (is64Bit()) 250 return toSection64(Sec)->VirtualAddress; 251 252 return toSection32(Sec)->VirtualAddress; 253 } 254 255 uint64_t XCOFFObjectFile::getSectionIndex(DataRefImpl Sec) const { 256 // Section numbers in XCOFF are numbered beginning at 1. A section number of 257 // zero is used to indicate that a symbol is being imported or is undefined. 258 if (is64Bit()) 259 return toSection64(Sec) - sectionHeaderTable64() + 1; 260 else 261 return toSection32(Sec) - sectionHeaderTable32() + 1; 262 } 263 264 uint64_t XCOFFObjectFile::getSectionSize(DataRefImpl Sec) const { 265 // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t 266 // with MSVC. 267 if (is64Bit()) 268 return toSection64(Sec)->SectionSize; 269 270 return toSection32(Sec)->SectionSize; 271 } 272 273 Expected<ArrayRef<uint8_t>> 274 XCOFFObjectFile::getSectionContents(DataRefImpl Sec) const { 275 if (isSectionVirtual(Sec)) 276 return ArrayRef<uint8_t>(); 277 278 uint64_t OffsetToRaw; 279 if (is64Bit()) 280 OffsetToRaw = toSection64(Sec)->FileOffsetToRawData; 281 else 282 OffsetToRaw = toSection32(Sec)->FileOffsetToRawData; 283 284 const uint8_t * ContentStart = base() + OffsetToRaw; 285 uint64_t SectionSize = getSectionSize(Sec); 286 if (checkOffset(Data, uintptr_t(ContentStart), SectionSize)) 287 return make_error<BinaryError>(); 288 289 return makeArrayRef(ContentStart,SectionSize); 290 } 291 292 uint64_t XCOFFObjectFile::getSectionAlignment(DataRefImpl Sec) const { 293 uint64_t Result = 0; 294 llvm_unreachable("Not yet implemented!"); 295 return Result; 296 } 297 298 bool XCOFFObjectFile::isSectionCompressed(DataRefImpl Sec) const { 299 bool Result = false; 300 llvm_unreachable("Not yet implemented!"); 301 return Result; 302 } 303 304 bool XCOFFObjectFile::isSectionText(DataRefImpl Sec) const { 305 return getSectionFlags(Sec) & XCOFF::STYP_TEXT; 306 } 307 308 bool XCOFFObjectFile::isSectionData(DataRefImpl Sec) const { 309 uint32_t Flags = getSectionFlags(Sec); 310 return Flags & (XCOFF::STYP_DATA | XCOFF::STYP_TDATA); 311 } 312 313 bool XCOFFObjectFile::isSectionBSS(DataRefImpl Sec) const { 314 uint32_t Flags = getSectionFlags(Sec); 315 return Flags & (XCOFF::STYP_BSS | XCOFF::STYP_TBSS); 316 } 317 318 bool XCOFFObjectFile::isSectionVirtual(DataRefImpl Sec) const { 319 return is64Bit() ? toSection64(Sec)->FileOffsetToRawData == 0 320 : toSection32(Sec)->FileOffsetToRawData == 0; 321 } 322 323 relocation_iterator XCOFFObjectFile::section_rel_begin(DataRefImpl Sec) const { 324 if (is64Bit()) 325 report_fatal_error("64-bit support not implemented yet"); 326 const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec); 327 auto RelocationsOrErr = relocations(*SectionEntPtr); 328 if (Error E = RelocationsOrErr.takeError()) 329 return relocation_iterator(RelocationRef()); 330 DataRefImpl Ret; 331 Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().begin()); 332 return relocation_iterator(RelocationRef(Ret, this)); 333 } 334 335 relocation_iterator XCOFFObjectFile::section_rel_end(DataRefImpl Sec) const { 336 if (is64Bit()) 337 report_fatal_error("64-bit support not implemented yet"); 338 const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec); 339 auto RelocationsOrErr = relocations(*SectionEntPtr); 340 if (Error E = RelocationsOrErr.takeError()) 341 return relocation_iterator(RelocationRef()); 342 DataRefImpl Ret; 343 Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().end()); 344 return relocation_iterator(RelocationRef(Ret, this)); 345 } 346 347 void XCOFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { 348 Rel.p = reinterpret_cast<uintptr_t>(viewAs<XCOFFRelocation32>(Rel.p) + 1); 349 } 350 351 uint64_t XCOFFObjectFile::getRelocationOffset(DataRefImpl Rel) const { 352 if (is64Bit()) 353 report_fatal_error("64-bit support not implemented yet"); 354 const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p); 355 const XCOFFSectionHeader32 *Sec32 = sectionHeaderTable32(); 356 const uint32_t RelocAddress = Reloc->VirtualAddress; 357 const uint16_t NumberOfSections = getNumberOfSections(); 358 for (uint16_t i = 0; i < NumberOfSections; ++i) { 359 // Find which section this relocation is belonging to, and get the 360 // relocation offset relative to the start of the section. 361 if (Sec32->VirtualAddress <= RelocAddress && 362 RelocAddress < Sec32->VirtualAddress + Sec32->SectionSize) { 363 return RelocAddress - Sec32->VirtualAddress; 364 } 365 ++Sec32; 366 } 367 return InvalidRelocOffset; 368 } 369 370 symbol_iterator XCOFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 371 if (is64Bit()) 372 report_fatal_error("64-bit support not implemented yet"); 373 const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p); 374 const uint32_t Index = Reloc->SymbolIndex; 375 376 if (Index >= getLogicalNumberOfSymbolTableEntries32()) 377 return symbol_end(); 378 379 DataRefImpl SymDRI; 380 SymDRI.p = reinterpret_cast<uintptr_t>(getPointerToSymbolTable() + Index); 381 return symbol_iterator(SymbolRef(SymDRI, this)); 382 } 383 384 uint64_t XCOFFObjectFile::getRelocationType(DataRefImpl Rel) const { 385 if (is64Bit()) 386 report_fatal_error("64-bit support not implemented yet"); 387 return viewAs<XCOFFRelocation32>(Rel.p)->Type; 388 } 389 390 void XCOFFObjectFile::getRelocationTypeName( 391 DataRefImpl Rel, SmallVectorImpl<char> &Result) const { 392 if (is64Bit()) 393 report_fatal_error("64-bit support not implemented yet"); 394 const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p); 395 StringRef Res = XCOFF::getRelocationTypeString(Reloc->Type); 396 Result.append(Res.begin(), Res.end()); 397 } 398 399 Expected<uint32_t> XCOFFObjectFile::getSymbolFlags(DataRefImpl Symb) const { 400 uint32_t Result = 0; 401 llvm_unreachable("Not yet implemented!"); 402 return Result; 403 } 404 405 basic_symbol_iterator XCOFFObjectFile::symbol_begin() const { 406 if (is64Bit()) 407 report_fatal_error("64-bit support not implemented yet"); 408 DataRefImpl SymDRI; 409 SymDRI.p = reinterpret_cast<uintptr_t>(SymbolTblPtr); 410 return basic_symbol_iterator(SymbolRef(SymDRI, this)); 411 } 412 413 basic_symbol_iterator XCOFFObjectFile::symbol_end() const { 414 if (is64Bit()) 415 report_fatal_error("64-bit support not implemented yet"); 416 DataRefImpl SymDRI; 417 SymDRI.p = reinterpret_cast<uintptr_t>( 418 SymbolTblPtr + getLogicalNumberOfSymbolTableEntries32()); 419 return basic_symbol_iterator(SymbolRef(SymDRI, this)); 420 } 421 422 section_iterator XCOFFObjectFile::section_begin() const { 423 DataRefImpl DRI; 424 DRI.p = getSectionHeaderTableAddress(); 425 return section_iterator(SectionRef(DRI, this)); 426 } 427 428 section_iterator XCOFFObjectFile::section_end() const { 429 DataRefImpl DRI; 430 DRI.p = getWithOffset(getSectionHeaderTableAddress(), 431 getNumberOfSections() * getSectionHeaderSize()); 432 return section_iterator(SectionRef(DRI, this)); 433 } 434 435 uint8_t XCOFFObjectFile::getBytesInAddress() const { return is64Bit() ? 8 : 4; } 436 437 StringRef XCOFFObjectFile::getFileFormatName() const { 438 return is64Bit() ? "aix5coff64-rs6000" : "aixcoff-rs6000"; 439 } 440 441 Triple::ArchType XCOFFObjectFile::getArch() const { 442 return is64Bit() ? Triple::ppc64 : Triple::ppc; 443 } 444 445 SubtargetFeatures XCOFFObjectFile::getFeatures() const { 446 return SubtargetFeatures(); 447 } 448 449 bool XCOFFObjectFile::isRelocatableObject() const { 450 if (is64Bit()) 451 report_fatal_error("64-bit support not implemented yet"); 452 return !(fileHeader32()->Flags & NoRelMask); 453 } 454 455 Expected<uint64_t> XCOFFObjectFile::getStartAddress() const { 456 // TODO FIXME Should get from auxiliary_header->o_entry when support for the 457 // auxiliary_header is added. 458 return 0; 459 } 460 461 size_t XCOFFObjectFile::getFileHeaderSize() const { 462 return is64Bit() ? sizeof(XCOFFFileHeader64) : sizeof(XCOFFFileHeader32); 463 } 464 465 size_t XCOFFObjectFile::getSectionHeaderSize() const { 466 return is64Bit() ? sizeof(XCOFFSectionHeader64) : 467 sizeof(XCOFFSectionHeader32); 468 } 469 470 bool XCOFFObjectFile::is64Bit() const { 471 return Binary::ID_XCOFF64 == getType(); 472 } 473 474 uint16_t XCOFFObjectFile::getMagic() const { 475 return is64Bit() ? fileHeader64()->Magic : fileHeader32()->Magic; 476 } 477 478 Expected<DataRefImpl> XCOFFObjectFile::getSectionByNum(int16_t Num) const { 479 if (Num <= 0 || Num > getNumberOfSections()) 480 return errorCodeToError(object_error::invalid_section_index); 481 482 DataRefImpl DRI; 483 DRI.p = getWithOffset(getSectionHeaderTableAddress(), 484 getSectionHeaderSize() * (Num - 1)); 485 return DRI; 486 } 487 488 Expected<StringRef> 489 XCOFFObjectFile::getSymbolSectionName(const XCOFFSymbolEntry *SymEntPtr) const { 490 assert(!is64Bit() && "Symbol table support not implemented for 64-bit."); 491 int16_t SectionNum = SymEntPtr->SectionNumber; 492 493 switch (SectionNum) { 494 case XCOFF::N_DEBUG: 495 return "N_DEBUG"; 496 case XCOFF::N_ABS: 497 return "N_ABS"; 498 case XCOFF::N_UNDEF: 499 return "N_UNDEF"; 500 default: 501 Expected<DataRefImpl> SecRef = getSectionByNum(SectionNum); 502 if (SecRef) 503 return generateXCOFFFixedNameStringRef( 504 getSectionNameInternal(SecRef.get())); 505 return SecRef.takeError(); 506 } 507 } 508 509 bool XCOFFObjectFile::isReservedSectionNumber(int16_t SectionNumber) { 510 return (SectionNumber <= 0 && SectionNumber >= -2); 511 } 512 513 uint16_t XCOFFObjectFile::getNumberOfSections() const { 514 return is64Bit() ? fileHeader64()->NumberOfSections 515 : fileHeader32()->NumberOfSections; 516 } 517 518 int32_t XCOFFObjectFile::getTimeStamp() const { 519 return is64Bit() ? fileHeader64()->TimeStamp : fileHeader32()->TimeStamp; 520 } 521 522 uint16_t XCOFFObjectFile::getOptionalHeaderSize() const { 523 return is64Bit() ? fileHeader64()->AuxHeaderSize 524 : fileHeader32()->AuxHeaderSize; 525 } 526 527 uint32_t XCOFFObjectFile::getSymbolTableOffset32() const { 528 return fileHeader32()->SymbolTableOffset; 529 } 530 531 int32_t XCOFFObjectFile::getRawNumberOfSymbolTableEntries32() const { 532 // As far as symbol table size is concerned, if this field is negative it is 533 // to be treated as a 0. However since this field is also used for printing we 534 // don't want to truncate any negative values. 535 return fileHeader32()->NumberOfSymTableEntries; 536 } 537 538 uint32_t XCOFFObjectFile::getLogicalNumberOfSymbolTableEntries32() const { 539 return (fileHeader32()->NumberOfSymTableEntries >= 0 540 ? fileHeader32()->NumberOfSymTableEntries 541 : 0); 542 } 543 544 uint64_t XCOFFObjectFile::getSymbolTableOffset64() const { 545 return fileHeader64()->SymbolTableOffset; 546 } 547 548 uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries64() const { 549 return fileHeader64()->NumberOfSymTableEntries; 550 } 551 552 uintptr_t XCOFFObjectFile::getEndOfSymbolTableAddress() const { 553 uint32_t NumberOfSymTableEntries = 554 is64Bit() ? getNumberOfSymbolTableEntries64() 555 : getLogicalNumberOfSymbolTableEntries32(); 556 return getWithOffset(reinterpret_cast<uintptr_t>(SymbolTblPtr), 557 XCOFF::SymbolTableEntrySize * NumberOfSymTableEntries); 558 } 559 560 void XCOFFObjectFile::checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const { 561 if (SymbolEntPtr < reinterpret_cast<uintptr_t>(SymbolTblPtr)) 562 report_fatal_error("Symbol table entry is outside of symbol table."); 563 564 if (SymbolEntPtr >= getEndOfSymbolTableAddress()) 565 report_fatal_error("Symbol table entry is outside of symbol table."); 566 567 ptrdiff_t Offset = reinterpret_cast<const char *>(SymbolEntPtr) - 568 reinterpret_cast<const char *>(SymbolTblPtr); 569 570 if (Offset % XCOFF::SymbolTableEntrySize != 0) 571 report_fatal_error( 572 "Symbol table entry position is not valid inside of symbol table."); 573 } 574 575 uint32_t XCOFFObjectFile::getSymbolIndex(uintptr_t SymbolEntPtr) const { 576 return (reinterpret_cast<const char *>(SymbolEntPtr) - 577 reinterpret_cast<const char *>(SymbolTblPtr)) / 578 XCOFF::SymbolTableEntrySize; 579 } 580 581 Expected<StringRef> 582 XCOFFObjectFile::getSymbolNameByIndex(uint32_t Index) const { 583 if (is64Bit()) 584 report_fatal_error("64-bit symbol table support not implemented yet."); 585 586 if (Index >= getLogicalNumberOfSymbolTableEntries32()) 587 return errorCodeToError(object_error::invalid_symbol_index); 588 589 DataRefImpl SymDRI; 590 SymDRI.p = reinterpret_cast<uintptr_t>(getPointerToSymbolTable() + Index); 591 return getSymbolName(SymDRI); 592 } 593 594 uint16_t XCOFFObjectFile::getFlags() const { 595 return is64Bit() ? fileHeader64()->Flags : fileHeader32()->Flags; 596 } 597 598 const char *XCOFFObjectFile::getSectionNameInternal(DataRefImpl Sec) const { 599 return is64Bit() ? toSection64(Sec)->Name : toSection32(Sec)->Name; 600 } 601 602 uintptr_t XCOFFObjectFile::getSectionHeaderTableAddress() const { 603 return reinterpret_cast<uintptr_t>(SectionHeaderTable); 604 } 605 606 int32_t XCOFFObjectFile::getSectionFlags(DataRefImpl Sec) const { 607 return is64Bit() ? toSection64(Sec)->Flags : toSection32(Sec)->Flags; 608 } 609 610 XCOFFObjectFile::XCOFFObjectFile(unsigned int Type, MemoryBufferRef Object) 611 : ObjectFile(Type, Object) { 612 assert(Type == Binary::ID_XCOFF32 || Type == Binary::ID_XCOFF64); 613 } 614 615 ArrayRef<XCOFFSectionHeader64> XCOFFObjectFile::sections64() const { 616 assert(is64Bit() && "64-bit interface called for non 64-bit file."); 617 const XCOFFSectionHeader64 *TablePtr = sectionHeaderTable64(); 618 return ArrayRef<XCOFFSectionHeader64>(TablePtr, 619 TablePtr + getNumberOfSections()); 620 } 621 622 ArrayRef<XCOFFSectionHeader32> XCOFFObjectFile::sections32() const { 623 assert(!is64Bit() && "32-bit interface called for non 32-bit file."); 624 const XCOFFSectionHeader32 *TablePtr = sectionHeaderTable32(); 625 return ArrayRef<XCOFFSectionHeader32>(TablePtr, 626 TablePtr + getNumberOfSections()); 627 } 628 629 // In an XCOFF32 file, when the field value is 65535, then an STYP_OVRFLO 630 // section header contains the actual count of relocation entries in the s_paddr 631 // field. STYP_OVRFLO headers contain the section index of their corresponding 632 // sections as their raw "NumberOfRelocations" field value. 633 Expected<uint32_t> XCOFFObjectFile::getLogicalNumberOfRelocationEntries( 634 const XCOFFSectionHeader32 &Sec) const { 635 636 uint16_t SectionIndex = &Sec - sectionHeaderTable32() + 1; 637 638 if (Sec.NumberOfRelocations < XCOFF::RelocOverflow) 639 return Sec.NumberOfRelocations; 640 for (const auto &Sec : sections32()) { 641 if (Sec.Flags == XCOFF::STYP_OVRFLO && 642 Sec.NumberOfRelocations == SectionIndex) 643 return Sec.PhysicalAddress; 644 } 645 return errorCodeToError(object_error::parse_failed); 646 } 647 648 Expected<ArrayRef<XCOFFRelocation32>> 649 XCOFFObjectFile::relocations(const XCOFFSectionHeader32 &Sec) const { 650 uintptr_t RelocAddr = getWithOffset(reinterpret_cast<uintptr_t>(FileHeader), 651 Sec.FileOffsetToRelocationInfo); 652 auto NumRelocEntriesOrErr = getLogicalNumberOfRelocationEntries(Sec); 653 if (Error E = NumRelocEntriesOrErr.takeError()) 654 return std::move(E); 655 656 uint32_t NumRelocEntries = NumRelocEntriesOrErr.get(); 657 658 assert(sizeof(XCOFFRelocation32) == XCOFF::RelocationSerializationSize32); 659 auto RelocationOrErr = 660 getObject<XCOFFRelocation32>(Data, reinterpret_cast<void *>(RelocAddr), 661 NumRelocEntries * sizeof(XCOFFRelocation32)); 662 if (Error E = RelocationOrErr.takeError()) 663 return std::move(E); 664 665 const XCOFFRelocation32 *StartReloc = RelocationOrErr.get(); 666 667 return ArrayRef<XCOFFRelocation32>(StartReloc, StartReloc + NumRelocEntries); 668 } 669 670 Expected<XCOFFStringTable> 671 XCOFFObjectFile::parseStringTable(const XCOFFObjectFile *Obj, uint64_t Offset) { 672 // If there is a string table, then the buffer must contain at least 4 bytes 673 // for the string table's size. Not having a string table is not an error. 674 if (Error E = Binary::checkOffset( 675 Obj->Data, reinterpret_cast<uintptr_t>(Obj->base() + Offset), 4)) { 676 consumeError(std::move(E)); 677 return XCOFFStringTable{0, nullptr}; 678 } 679 680 // Read the size out of the buffer. 681 uint32_t Size = support::endian::read32be(Obj->base() + Offset); 682 683 // If the size is less then 4, then the string table is just a size and no 684 // string data. 685 if (Size <= 4) 686 return XCOFFStringTable{4, nullptr}; 687 688 auto StringTableOrErr = 689 getObject<char>(Obj->Data, Obj->base() + Offset, Size); 690 if (Error E = StringTableOrErr.takeError()) 691 return std::move(E); 692 693 const char *StringTablePtr = StringTableOrErr.get(); 694 if (StringTablePtr[Size - 1] != '\0') 695 return errorCodeToError(object_error::string_table_non_null_end); 696 697 return XCOFFStringTable{Size, StringTablePtr}; 698 } 699 700 Expected<std::unique_ptr<XCOFFObjectFile>> 701 XCOFFObjectFile::create(unsigned Type, MemoryBufferRef MBR) { 702 // Can't use std::make_unique because of the private constructor. 703 std::unique_ptr<XCOFFObjectFile> Obj; 704 Obj.reset(new XCOFFObjectFile(Type, MBR)); 705 706 uint64_t CurOffset = 0; 707 const auto *Base = Obj->base(); 708 MemoryBufferRef Data = Obj->Data; 709 710 // Parse file header. 711 auto FileHeaderOrErr = 712 getObject<void>(Data, Base + CurOffset, Obj->getFileHeaderSize()); 713 if (Error E = FileHeaderOrErr.takeError()) 714 return std::move(E); 715 Obj->FileHeader = FileHeaderOrErr.get(); 716 717 CurOffset += Obj->getFileHeaderSize(); 718 // TODO FIXME we don't have support for an optional header yet, so just skip 719 // past it. 720 CurOffset += Obj->getOptionalHeaderSize(); 721 722 // Parse the section header table if it is present. 723 if (Obj->getNumberOfSections()) { 724 auto SecHeadersOrErr = getObject<void>(Data, Base + CurOffset, 725 Obj->getNumberOfSections() * 726 Obj->getSectionHeaderSize()); 727 if (Error E = SecHeadersOrErr.takeError()) 728 return std::move(E); 729 Obj->SectionHeaderTable = SecHeadersOrErr.get(); 730 } 731 732 // 64-bit object supports only file header and section headers for now. 733 if (Obj->is64Bit()) 734 return std::move(Obj); 735 736 // If there is no symbol table we are done parsing the memory buffer. 737 if (Obj->getLogicalNumberOfSymbolTableEntries32() == 0) 738 return std::move(Obj); 739 740 // Parse symbol table. 741 CurOffset = Obj->fileHeader32()->SymbolTableOffset; 742 uint64_t SymbolTableSize = (uint64_t)(sizeof(XCOFFSymbolEntry)) * 743 Obj->getLogicalNumberOfSymbolTableEntries32(); 744 auto SymTableOrErr = 745 getObject<XCOFFSymbolEntry>(Data, Base + CurOffset, SymbolTableSize); 746 if (Error E = SymTableOrErr.takeError()) 747 return std::move(E); 748 Obj->SymbolTblPtr = SymTableOrErr.get(); 749 CurOffset += SymbolTableSize; 750 751 // Parse String table. 752 Expected<XCOFFStringTable> StringTableOrErr = 753 parseStringTable(Obj.get(), CurOffset); 754 if (Error E = StringTableOrErr.takeError()) 755 return std::move(E); 756 Obj->StringTable = StringTableOrErr.get(); 757 758 return std::move(Obj); 759 } 760 761 Expected<std::unique_ptr<ObjectFile>> 762 ObjectFile::createXCOFFObjectFile(MemoryBufferRef MemBufRef, 763 unsigned FileType) { 764 return XCOFFObjectFile::create(FileType, MemBufRef); 765 } 766 767 XCOFF::StorageClass XCOFFSymbolRef::getStorageClass() const { 768 return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->StorageClass; 769 } 770 771 uint8_t XCOFFSymbolRef::getNumberOfAuxEntries() const { 772 return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->NumberOfAuxEntries; 773 } 774 775 // TODO: The function needs to return an error if there is no csect auxiliary 776 // entry. 777 const XCOFFCsectAuxEnt32 *XCOFFSymbolRef::getXCOFFCsectAuxEnt32() const { 778 assert(!OwningObjectPtr->is64Bit() && 779 "32-bit interface called on 64-bit object file."); 780 assert(hasCsectAuxEnt() && "No Csect Auxiliary Entry is found."); 781 782 // In XCOFF32, the csect auxilliary entry is always the last auxiliary 783 // entry for the symbol. 784 uintptr_t AuxAddr = getWithOffset( 785 SymEntDataRef.p, XCOFF::SymbolTableEntrySize * getNumberOfAuxEntries()); 786 787 #ifndef NDEBUG 788 OwningObjectPtr->checkSymbolEntryPointer(AuxAddr); 789 #endif 790 791 return reinterpret_cast<const XCOFFCsectAuxEnt32 *>(AuxAddr); 792 } 793 794 uint16_t XCOFFSymbolRef::getType() const { 795 return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->SymbolType; 796 } 797 798 int16_t XCOFFSymbolRef::getSectionNumber() const { 799 return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->SectionNumber; 800 } 801 802 // TODO: The function name needs to be changed to express the purpose of the 803 // function. 804 bool XCOFFSymbolRef::hasCsectAuxEnt() const { 805 XCOFF::StorageClass SC = getStorageClass(); 806 return (SC == XCOFF::C_EXT || SC == XCOFF::C_WEAKEXT || 807 SC == XCOFF::C_HIDEXT); 808 } 809 810 bool XCOFFSymbolRef::isFunction() const { 811 if (OwningObjectPtr->is64Bit()) 812 report_fatal_error("64-bit support is unimplemented yet."); 813 814 if (getType() & FunctionSym) 815 return true; 816 817 if (!hasCsectAuxEnt()) 818 return false; 819 820 const XCOFFCsectAuxEnt32 *CsectAuxEnt = getXCOFFCsectAuxEnt32(); 821 822 // A function definition should be a label definition. 823 if ((CsectAuxEnt->SymbolAlignmentAndType & SymTypeMask) != XCOFF::XTY_LD) 824 return false; 825 826 if (CsectAuxEnt->StorageMappingClass != XCOFF::XMC_PR) 827 return false; 828 829 int16_t SectNum = getSectionNumber(); 830 Expected<DataRefImpl> SI = OwningObjectPtr->getSectionByNum(SectNum); 831 if (!SI) 832 return false; 833 834 return (OwningObjectPtr->getSectionFlags(SI.get()) & XCOFF::STYP_TEXT); 835 } 836 837 // Explictly instantiate template classes. 838 template struct XCOFFSectionHeader<XCOFFSectionHeader32>; 839 template struct XCOFFSectionHeader<XCOFFSectionHeader64>; 840 841 bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes) { 842 if (Bytes.size() < 4) 843 return false; 844 845 return support::endian::read32be(Bytes.data()) == 0; 846 } 847 848 static SmallString<32> parseParmsType(uint32_t Value, unsigned ParmsNum) { 849 SmallString<32> ParmsType; 850 for (unsigned I = 0; I < ParmsNum; ++I) { 851 if (I != 0) 852 ParmsType += ", "; 853 if ((Value & TracebackTable::ParmTypeIsFloatingBit) == 0) { 854 // Fixed parameter type. 855 ParmsType += "i"; 856 Value <<= 1; 857 } else { 858 if ((Value & TracebackTable::ParmTypeFloatingIsDoubleBit) == 0) 859 // Float parameter type. 860 ParmsType += "f"; 861 else 862 // Double parameter type. 863 ParmsType += "d"; 864 865 Value <<= 2; 866 } 867 } 868 return ParmsType; 869 } 870 871 Expected<XCOFFTracebackTable> XCOFFTracebackTable::create(const uint8_t *Ptr, 872 uint64_t &Size) { 873 Error Err = Error::success(); 874 XCOFFTracebackTable TBT(Ptr, Size, Err); 875 if (Err) 876 return std::move(Err); 877 return TBT; 878 } 879 880 XCOFFTracebackTable::XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size, 881 Error &Err) 882 : TBPtr(Ptr) { 883 ErrorAsOutParameter EAO(&Err); 884 DataExtractor DE(ArrayRef<uint8_t>(Ptr, Size), /*IsLittleEndian=*/false, 885 /*AddressSize=*/0); 886 DataExtractor::Cursor Cur(/*Offset=*/0); 887 888 // Skip 8 bytes of mandatory fields. 889 DE.getU64(Cur); 890 891 // Begin to parse optional fields. 892 if (Cur) { 893 unsigned ParmNum = getNumberOfFixedParms() + getNumberOfFPParms(); 894 895 // As long as there are no "fixed-point" or floating-point parameters, this 896 // field remains not present even when hasVectorInfo gives true and 897 // indicates the presence of vector parameters. 898 if (ParmNum > 0) { 899 uint32_t ParamsTypeValue = DE.getU32(Cur); 900 // TODO: when hasVectorInfo() is true, we need to implement a new version 901 // of parsing parameter type for vector info. 902 if (Cur && !hasVectorInfo()) 903 ParmsType = parseParmsType(ParamsTypeValue, ParmNum); 904 } 905 } 906 907 if (Cur && hasTraceBackTableOffset()) 908 TraceBackTableOffset = DE.getU32(Cur); 909 910 if (Cur && isInterruptHandler()) 911 HandlerMask = DE.getU32(Cur); 912 913 if (Cur && hasControlledStorage()) { 914 NumOfCtlAnchors = DE.getU32(Cur); 915 if (Cur && NumOfCtlAnchors) { 916 SmallVector<uint32_t, 8> Disp; 917 Disp.reserve(NumOfCtlAnchors.getValue()); 918 for (uint32_t I = 0; I < NumOfCtlAnchors && Cur; ++I) 919 Disp.push_back(DE.getU32(Cur)); 920 if (Cur) 921 ControlledStorageInfoDisp = std::move(Disp); 922 } 923 } 924 925 if (Cur && isFuncNamePresent()) { 926 uint16_t FunctionNameLen = DE.getU16(Cur); 927 if (Cur) 928 FunctionName = DE.getBytes(Cur, FunctionNameLen); 929 } 930 931 if (Cur && isAllocaUsed()) 932 AllocaRegister = DE.getU8(Cur); 933 934 // TODO: Need to parse vector info and extension table if there is one. 935 936 if (!Cur) 937 Err = Cur.takeError(); 938 Size = Cur.tell(); 939 } 940 941 #define GETBITWITHMASK(P, X) \ 942 (support::endian::read32be(TBPtr + (P)) & (TracebackTable::X)) 943 #define GETBITWITHMASKSHIFT(P, X, S) \ 944 ((support::endian::read32be(TBPtr + (P)) & (TracebackTable::X)) >> \ 945 (TracebackTable::S)) 946 947 uint8_t XCOFFTracebackTable::getVersion() const { 948 return GETBITWITHMASKSHIFT(0, VersionMask, VersionShift); 949 } 950 951 uint8_t XCOFFTracebackTable::getLanguageID() const { 952 return GETBITWITHMASKSHIFT(0, LanguageIdMask, LanguageIdShift); 953 } 954 955 bool XCOFFTracebackTable::isGlobalLinkage() const { 956 return GETBITWITHMASK(0, IsGlobaLinkageMask); 957 } 958 959 bool XCOFFTracebackTable::isOutOfLineEpilogOrPrologue() const { 960 return GETBITWITHMASK(0, IsOutOfLineEpilogOrPrologueMask); 961 } 962 963 bool XCOFFTracebackTable::hasTraceBackTableOffset() const { 964 return GETBITWITHMASK(0, HasTraceBackTableOffsetMask); 965 } 966 967 bool XCOFFTracebackTable::isInternalProcedure() const { 968 return GETBITWITHMASK(0, IsInternalProcedureMask); 969 } 970 971 bool XCOFFTracebackTable::hasControlledStorage() const { 972 return GETBITWITHMASK(0, HasControlledStorageMask); 973 } 974 975 bool XCOFFTracebackTable::isTOCless() const { 976 return GETBITWITHMASK(0, IsTOClessMask); 977 } 978 979 bool XCOFFTracebackTable::isFloatingPointPresent() const { 980 return GETBITWITHMASK(0, IsFloatingPointPresentMask); 981 } 982 983 bool XCOFFTracebackTable::isFloatingPointOperationLogOrAbortEnabled() const { 984 return GETBITWITHMASK(0, IsFloatingPointOperationLogOrAbortEnabledMask); 985 } 986 987 bool XCOFFTracebackTable::isInterruptHandler() const { 988 return GETBITWITHMASK(0, IsInterruptHandlerMask); 989 } 990 991 bool XCOFFTracebackTable::isFuncNamePresent() const { 992 return GETBITWITHMASK(0, IsFunctionNamePresentMask); 993 } 994 995 bool XCOFFTracebackTable::isAllocaUsed() const { 996 return GETBITWITHMASK(0, IsAllocaUsedMask); 997 } 998 999 uint8_t XCOFFTracebackTable::getOnConditionDirective() const { 1000 return GETBITWITHMASKSHIFT(0, OnConditionDirectiveMask, 1001 OnConditionDirectiveShift); 1002 } 1003 1004 bool XCOFFTracebackTable::isCRSaved() const { 1005 return GETBITWITHMASK(0, IsCRSavedMask); 1006 } 1007 1008 bool XCOFFTracebackTable::isLRSaved() const { 1009 return GETBITWITHMASK(0, IsLRSavedMask); 1010 } 1011 1012 bool XCOFFTracebackTable::isBackChainStored() const { 1013 return GETBITWITHMASK(4, IsBackChainStoredMask); 1014 } 1015 1016 bool XCOFFTracebackTable::isFixup() const { 1017 return GETBITWITHMASK(4, IsFixupMask); 1018 } 1019 1020 uint8_t XCOFFTracebackTable::getNumOfFPRsSaved() const { 1021 return GETBITWITHMASKSHIFT(4, FPRSavedMask, FPRSavedShift); 1022 } 1023 1024 bool XCOFFTracebackTable::hasExtensionTable() const { 1025 return GETBITWITHMASK(4, HasExtensionTableMask); 1026 } 1027 1028 bool XCOFFTracebackTable::hasVectorInfo() const { 1029 return GETBITWITHMASK(4, HasVectorInfoMask); 1030 } 1031 1032 uint8_t XCOFFTracebackTable::getNumofGPRsSaved() const { 1033 return GETBITWITHMASKSHIFT(4, GPRSavedMask, GPRSavedShift); 1034 } 1035 1036 uint8_t XCOFFTracebackTable::getNumberOfFixedParms() const { 1037 return GETBITWITHMASKSHIFT(4, NumberOfFixedParmsMask, 1038 NumberOfFixedParmsShift); 1039 } 1040 1041 uint8_t XCOFFTracebackTable::getNumberOfFPParms() const { 1042 return GETBITWITHMASKSHIFT(4, NumberOfFloatingPointParmsMask, 1043 NumberOfFloatingPointParmsShift); 1044 } 1045 1046 bool XCOFFTracebackTable::hasParmsOnStack() const { 1047 return GETBITWITHMASK(4, HasParmsOnStackMask); 1048 } 1049 1050 #undef GETBITWITHMASK 1051 #undef GETBITWITHMASKSHIFT 1052 } // namespace object 1053 } // namespace llvm 1054