1 //===- ELFObject.cpp ------------------------------------------------------===// 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 #include "ELFObject.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/ADT/StringRef.h" 13 #include "llvm/ADT/Twine.h" 14 #include "llvm/ADT/iterator_range.h" 15 #include "llvm/BinaryFormat/ELF.h" 16 #include "llvm/MC/MCTargetOptions.h" 17 #include "llvm/Object/ELF.h" 18 #include "llvm/Object/ELFObjectFile.h" 19 #include "llvm/Support/Compression.h" 20 #include "llvm/Support/Endian.h" 21 #include "llvm/Support/ErrorHandling.h" 22 #include "llvm/Support/FileOutputBuffer.h" 23 #include "llvm/Support/Path.h" 24 #include <algorithm> 25 #include <cstddef> 26 #include <cstdint> 27 #include <iterator> 28 #include <unordered_set> 29 #include <utility> 30 #include <vector> 31 32 using namespace llvm; 33 using namespace llvm::ELF; 34 using namespace llvm::objcopy::elf; 35 using namespace llvm::object; 36 37 template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) { 38 uint8_t *B = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + 39 Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr); 40 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B); 41 Phdr.p_type = Seg.Type; 42 Phdr.p_flags = Seg.Flags; 43 Phdr.p_offset = Seg.Offset; 44 Phdr.p_vaddr = Seg.VAddr; 45 Phdr.p_paddr = Seg.PAddr; 46 Phdr.p_filesz = Seg.FileSize; 47 Phdr.p_memsz = Seg.MemSize; 48 Phdr.p_align = Seg.Align; 49 } 50 51 Error SectionBase::removeSectionReferences( 52 bool, function_ref<bool(const SectionBase *)>) { 53 return Error::success(); 54 } 55 56 Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)>) { 57 return Error::success(); 58 } 59 60 Error SectionBase::initialize(SectionTableRef) { return Error::success(); } 61 void SectionBase::finalize() {} 62 void SectionBase::markSymbols() {} 63 void SectionBase::replaceSectionReferences( 64 const DenseMap<SectionBase *, SectionBase *> &) {} 65 void SectionBase::onRemove() {} 66 67 template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) { 68 uint8_t *B = 69 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Sec.HeaderOffset; 70 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B); 71 Shdr.sh_name = Sec.NameIndex; 72 Shdr.sh_type = Sec.Type; 73 Shdr.sh_flags = Sec.Flags; 74 Shdr.sh_addr = Sec.Addr; 75 Shdr.sh_offset = Sec.Offset; 76 Shdr.sh_size = Sec.Size; 77 Shdr.sh_link = Sec.Link; 78 Shdr.sh_info = Sec.Info; 79 Shdr.sh_addralign = Sec.Align; 80 Shdr.sh_entsize = Sec.EntrySize; 81 } 82 83 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(Section &) { 84 return Error::success(); 85 } 86 87 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(OwnedDataSection &) { 88 return Error::success(); 89 } 90 91 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(StringTableSection &) { 92 return Error::success(); 93 } 94 95 template <class ELFT> 96 Error ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &) { 97 return Error::success(); 98 } 99 100 template <class ELFT> 101 Error ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) { 102 Sec.EntrySize = sizeof(Elf_Sym); 103 Sec.Size = Sec.Symbols.size() * Sec.EntrySize; 104 // Align to the largest field in Elf_Sym. 105 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word); 106 return Error::success(); 107 } 108 109 template <class ELFT> 110 Error ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) { 111 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela); 112 Sec.Size = Sec.Relocations.size() * Sec.EntrySize; 113 // Align to the largest field in Elf_Rel(a). 114 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word); 115 return Error::success(); 116 } 117 118 template <class ELFT> 119 Error ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &) { 120 return Error::success(); 121 } 122 123 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(GroupSection &Sec) { 124 Sec.Size = sizeof(Elf_Word) + Sec.GroupMembers.size() * sizeof(Elf_Word); 125 return Error::success(); 126 } 127 128 template <class ELFT> 129 Error ELFSectionSizer<ELFT>::visit(SectionIndexSection &) { 130 return Error::success(); 131 } 132 133 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(CompressedSection &) { 134 return Error::success(); 135 } 136 137 template <class ELFT> 138 Error ELFSectionSizer<ELFT>::visit(DecompressedSection &) { 139 return Error::success(); 140 } 141 142 Error BinarySectionWriter::visit(const SectionIndexSection &Sec) { 143 return createStringError(errc::operation_not_permitted, 144 "cannot write symbol section index table '" + 145 Sec.Name + "' "); 146 } 147 148 Error BinarySectionWriter::visit(const SymbolTableSection &Sec) { 149 return createStringError(errc::operation_not_permitted, 150 "cannot write symbol table '" + Sec.Name + 151 "' out to binary"); 152 } 153 154 Error BinarySectionWriter::visit(const RelocationSection &Sec) { 155 return createStringError(errc::operation_not_permitted, 156 "cannot write relocation section '" + Sec.Name + 157 "' out to binary"); 158 } 159 160 Error BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) { 161 return createStringError(errc::operation_not_permitted, 162 "cannot write '" + Sec.Name + "' out to binary"); 163 } 164 165 Error BinarySectionWriter::visit(const GroupSection &Sec) { 166 return createStringError(errc::operation_not_permitted, 167 "cannot write '" + Sec.Name + "' out to binary"); 168 } 169 170 Error SectionWriter::visit(const Section &Sec) { 171 if (Sec.Type != SHT_NOBITS) 172 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset); 173 174 return Error::success(); 175 } 176 177 static bool addressOverflows32bit(uint64_t Addr) { 178 // Sign extended 32 bit addresses (e.g 0xFFFFFFFF80000000) are ok 179 return Addr > UINT32_MAX && Addr + 0x80000000 > UINT32_MAX; 180 } 181 182 template <class T> static T checkedGetHex(StringRef S) { 183 T Value; 184 bool Fail = S.getAsInteger(16, Value); 185 assert(!Fail); 186 (void)Fail; 187 return Value; 188 } 189 190 // Fills exactly Len bytes of buffer with hexadecimal characters 191 // representing value 'X' 192 template <class T, class Iterator> 193 static Iterator toHexStr(T X, Iterator It, size_t Len) { 194 // Fill range with '0' 195 std::fill(It, It + Len, '0'); 196 197 for (long I = Len - 1; I >= 0; --I) { 198 unsigned char Mod = static_cast<unsigned char>(X) & 15; 199 *(It + I) = hexdigit(Mod, false); 200 X >>= 4; 201 } 202 assert(X == 0); 203 return It + Len; 204 } 205 206 uint8_t IHexRecord::getChecksum(StringRef S) { 207 assert((S.size() & 1) == 0); 208 uint8_t Checksum = 0; 209 while (!S.empty()) { 210 Checksum += checkedGetHex<uint8_t>(S.take_front(2)); 211 S = S.drop_front(2); 212 } 213 return -Checksum; 214 } 215 216 IHexLineData IHexRecord::getLine(uint8_t Type, uint16_t Addr, 217 ArrayRef<uint8_t> Data) { 218 IHexLineData Line(getLineLength(Data.size())); 219 assert(Line.size()); 220 auto Iter = Line.begin(); 221 *Iter++ = ':'; 222 Iter = toHexStr(Data.size(), Iter, 2); 223 Iter = toHexStr(Addr, Iter, 4); 224 Iter = toHexStr(Type, Iter, 2); 225 for (uint8_t X : Data) 226 Iter = toHexStr(X, Iter, 2); 227 StringRef S(Line.data() + 1, std::distance(Line.begin() + 1, Iter)); 228 Iter = toHexStr(getChecksum(S), Iter, 2); 229 *Iter++ = '\r'; 230 *Iter++ = '\n'; 231 assert(Iter == Line.end()); 232 return Line; 233 } 234 235 static Error checkRecord(const IHexRecord &R) { 236 switch (R.Type) { 237 case IHexRecord::Data: 238 if (R.HexData.size() == 0) 239 return createStringError( 240 errc::invalid_argument, 241 "zero data length is not allowed for data records"); 242 break; 243 case IHexRecord::EndOfFile: 244 break; 245 case IHexRecord::SegmentAddr: 246 // 20-bit segment address. Data length must be 2 bytes 247 // (4 bytes in hex) 248 if (R.HexData.size() != 4) 249 return createStringError( 250 errc::invalid_argument, 251 "segment address data should be 2 bytes in size"); 252 break; 253 case IHexRecord::StartAddr80x86: 254 case IHexRecord::StartAddr: 255 if (R.HexData.size() != 8) 256 return createStringError(errc::invalid_argument, 257 "start address data should be 4 bytes in size"); 258 // According to Intel HEX specification '03' record 259 // only specifies the code address within the 20-bit 260 // segmented address space of the 8086/80186. This 261 // means 12 high order bits should be zeroes. 262 if (R.Type == IHexRecord::StartAddr80x86 && 263 R.HexData.take_front(3) != "000") 264 return createStringError(errc::invalid_argument, 265 "start address exceeds 20 bit for 80x86"); 266 break; 267 case IHexRecord::ExtendedAddr: 268 // 16-31 bits of linear base address 269 if (R.HexData.size() != 4) 270 return createStringError( 271 errc::invalid_argument, 272 "extended address data should be 2 bytes in size"); 273 break; 274 default: 275 // Unknown record type 276 return createStringError(errc::invalid_argument, "unknown record type: %u", 277 static_cast<unsigned>(R.Type)); 278 } 279 return Error::success(); 280 } 281 282 // Checks that IHEX line contains valid characters. 283 // This allows converting hexadecimal data to integers 284 // without extra verification. 285 static Error checkChars(StringRef Line) { 286 assert(!Line.empty()); 287 if (Line[0] != ':') 288 return createStringError(errc::invalid_argument, 289 "missing ':' in the beginning of line."); 290 291 for (size_t Pos = 1; Pos < Line.size(); ++Pos) 292 if (hexDigitValue(Line[Pos]) == -1U) 293 return createStringError(errc::invalid_argument, 294 "invalid character at position %zu.", Pos + 1); 295 return Error::success(); 296 } 297 298 Expected<IHexRecord> IHexRecord::parse(StringRef Line) { 299 assert(!Line.empty()); 300 301 // ':' + Length + Address + Type + Checksum with empty data ':LLAAAATTCC' 302 if (Line.size() < 11) 303 return createStringError(errc::invalid_argument, 304 "line is too short: %zu chars.", Line.size()); 305 306 if (Error E = checkChars(Line)) 307 return std::move(E); 308 309 IHexRecord Rec; 310 size_t DataLen = checkedGetHex<uint8_t>(Line.substr(1, 2)); 311 if (Line.size() != getLength(DataLen)) 312 return createStringError(errc::invalid_argument, 313 "invalid line length %zu (should be %zu)", 314 Line.size(), getLength(DataLen)); 315 316 Rec.Addr = checkedGetHex<uint16_t>(Line.substr(3, 4)); 317 Rec.Type = checkedGetHex<uint8_t>(Line.substr(7, 2)); 318 Rec.HexData = Line.substr(9, DataLen * 2); 319 320 if (getChecksum(Line.drop_front(1)) != 0) 321 return createStringError(errc::invalid_argument, "incorrect checksum."); 322 if (Error E = checkRecord(Rec)) 323 return std::move(E); 324 return Rec; 325 } 326 327 static uint64_t sectionPhysicalAddr(const SectionBase *Sec) { 328 Segment *Seg = Sec->ParentSegment; 329 if (Seg && Seg->Type != ELF::PT_LOAD) 330 Seg = nullptr; 331 return Seg ? Seg->PAddr + Sec->OriginalOffset - Seg->OriginalOffset 332 : Sec->Addr; 333 } 334 335 void IHexSectionWriterBase::writeSection(const SectionBase *Sec, 336 ArrayRef<uint8_t> Data) { 337 assert(Data.size() == Sec->Size); 338 const uint32_t ChunkSize = 16; 339 uint32_t Addr = sectionPhysicalAddr(Sec) & 0xFFFFFFFFU; 340 while (!Data.empty()) { 341 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize); 342 if (Addr > SegmentAddr + BaseAddr + 0xFFFFU) { 343 if (Addr > 0xFFFFFU) { 344 // Write extended address record, zeroing segment address 345 // if needed. 346 if (SegmentAddr != 0) 347 SegmentAddr = writeSegmentAddr(0U); 348 BaseAddr = writeBaseAddr(Addr); 349 } else { 350 // We can still remain 16-bit 351 SegmentAddr = writeSegmentAddr(Addr); 352 } 353 } 354 uint64_t SegOffset = Addr - BaseAddr - SegmentAddr; 355 assert(SegOffset <= 0xFFFFU); 356 DataSize = std::min(DataSize, 0x10000U - SegOffset); 357 writeData(0, SegOffset, Data.take_front(DataSize)); 358 Addr += DataSize; 359 Data = Data.drop_front(DataSize); 360 } 361 } 362 363 uint64_t IHexSectionWriterBase::writeSegmentAddr(uint64_t Addr) { 364 assert(Addr <= 0xFFFFFU); 365 uint8_t Data[] = {static_cast<uint8_t>((Addr & 0xF0000U) >> 12), 0}; 366 writeData(2, 0, Data); 367 return Addr & 0xF0000U; 368 } 369 370 uint64_t IHexSectionWriterBase::writeBaseAddr(uint64_t Addr) { 371 assert(Addr <= 0xFFFFFFFFU); 372 uint64_t Base = Addr & 0xFFFF0000U; 373 uint8_t Data[] = {static_cast<uint8_t>(Base >> 24), 374 static_cast<uint8_t>((Base >> 16) & 0xFF)}; 375 writeData(4, 0, Data); 376 return Base; 377 } 378 379 void IHexSectionWriterBase::writeData(uint8_t, uint16_t, 380 ArrayRef<uint8_t> Data) { 381 Offset += IHexRecord::getLineLength(Data.size()); 382 } 383 384 Error IHexSectionWriterBase::visit(const Section &Sec) { 385 writeSection(&Sec, Sec.Contents); 386 return Error::success(); 387 } 388 389 Error IHexSectionWriterBase::visit(const OwnedDataSection &Sec) { 390 writeSection(&Sec, Sec.Data); 391 return Error::success(); 392 } 393 394 Error IHexSectionWriterBase::visit(const StringTableSection &Sec) { 395 // Check that sizer has already done its work 396 assert(Sec.Size == Sec.StrTabBuilder.getSize()); 397 // We are free to pass an invalid pointer to writeSection as long 398 // as we don't actually write any data. The real writer class has 399 // to override this method . 400 writeSection(&Sec, {nullptr, static_cast<size_t>(Sec.Size)}); 401 return Error::success(); 402 } 403 404 Error IHexSectionWriterBase::visit(const DynamicRelocationSection &Sec) { 405 writeSection(&Sec, Sec.Contents); 406 return Error::success(); 407 } 408 409 void IHexSectionWriter::writeData(uint8_t Type, uint16_t Addr, 410 ArrayRef<uint8_t> Data) { 411 IHexLineData HexData = IHexRecord::getLine(Type, Addr, Data); 412 memcpy(Out.getBufferStart() + Offset, HexData.data(), HexData.size()); 413 Offset += HexData.size(); 414 } 415 416 Error IHexSectionWriter::visit(const StringTableSection &Sec) { 417 assert(Sec.Size == Sec.StrTabBuilder.getSize()); 418 std::vector<uint8_t> Data(Sec.Size); 419 Sec.StrTabBuilder.write(Data.data()); 420 writeSection(&Sec, Data); 421 return Error::success(); 422 } 423 424 Error Section::accept(SectionVisitor &Visitor) const { 425 return Visitor.visit(*this); 426 } 427 428 Error Section::accept(MutableSectionVisitor &Visitor) { 429 return Visitor.visit(*this); 430 } 431 432 void Section::restoreSymTabLink(SymbolTableSection &SymTab) { 433 if (HasSymTabLink) { 434 assert(LinkSection == nullptr); 435 LinkSection = &SymTab; 436 } 437 } 438 439 Error SectionWriter::visit(const OwnedDataSection &Sec) { 440 llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset); 441 return Error::success(); 442 } 443 444 template <class ELFT> 445 Error ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) { 446 ArrayRef<uint8_t> Compressed = 447 Sec.OriginalData.slice(sizeof(Elf_Chdr_Impl<ELFT>)); 448 SmallVector<uint8_t, 128> Decompressed; 449 DebugCompressionType Type; 450 switch (Sec.ChType) { 451 case ELFCOMPRESS_ZLIB: 452 Type = DebugCompressionType::Zlib; 453 break; 454 case ELFCOMPRESS_ZSTD: 455 Type = DebugCompressionType::Zstd; 456 break; 457 default: 458 return createStringError(errc::invalid_argument, 459 "--decompress-debug-sections: ch_type (" + 460 Twine(Sec.ChType) + ") of section '" + 461 Sec.Name + "' is unsupported"); 462 } 463 if (auto *Reason = 464 compression::getReasonIfUnsupported(compression::formatFor(Type))) 465 return createStringError(errc::invalid_argument, 466 "failed to decompress section '" + Sec.Name + 467 "': " + Reason); 468 if (Error E = compression::decompress(Type, Compressed, Decompressed, 469 static_cast<size_t>(Sec.Size))) 470 return createStringError(errc::invalid_argument, 471 "failed to decompress section '" + Sec.Name + 472 "': " + toString(std::move(E))); 473 474 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset; 475 std::copy(Decompressed.begin(), Decompressed.end(), Buf); 476 477 return Error::success(); 478 } 479 480 Error BinarySectionWriter::visit(const DecompressedSection &Sec) { 481 return createStringError(errc::operation_not_permitted, 482 "cannot write compressed section '" + Sec.Name + 483 "' "); 484 } 485 486 Error DecompressedSection::accept(SectionVisitor &Visitor) const { 487 return Visitor.visit(*this); 488 } 489 490 Error DecompressedSection::accept(MutableSectionVisitor &Visitor) { 491 return Visitor.visit(*this); 492 } 493 494 Error OwnedDataSection::accept(SectionVisitor &Visitor) const { 495 return Visitor.visit(*this); 496 } 497 498 Error OwnedDataSection::accept(MutableSectionVisitor &Visitor) { 499 return Visitor.visit(*this); 500 } 501 502 void OwnedDataSection::appendHexData(StringRef HexData) { 503 assert((HexData.size() & 1) == 0); 504 while (!HexData.empty()) { 505 Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2))); 506 HexData = HexData.drop_front(2); 507 } 508 Size = Data.size(); 509 } 510 511 Error BinarySectionWriter::visit(const CompressedSection &Sec) { 512 return createStringError(errc::operation_not_permitted, 513 "cannot write compressed section '" + Sec.Name + 514 "' "); 515 } 516 517 template <class ELFT> 518 Error ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) { 519 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset; 520 Elf_Chdr_Impl<ELFT> Chdr = {}; 521 switch (Sec.CompressionType) { 522 case DebugCompressionType::None: 523 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf); 524 return Error::success(); 525 case DebugCompressionType::Zlib: 526 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB; 527 break; 528 case DebugCompressionType::Zstd: 529 Chdr.ch_type = ELF::ELFCOMPRESS_ZSTD; 530 break; 531 } 532 Chdr.ch_size = Sec.DecompressedSize; 533 Chdr.ch_addralign = Sec.DecompressedAlign; 534 memcpy(Buf, &Chdr, sizeof(Chdr)); 535 Buf += sizeof(Chdr); 536 537 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf); 538 return Error::success(); 539 } 540 541 CompressedSection::CompressedSection(const SectionBase &Sec, 542 DebugCompressionType CompressionType, 543 bool Is64Bits) 544 : SectionBase(Sec), CompressionType(CompressionType), 545 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) { 546 compression::compress(compression::Params(CompressionType), OriginalData, 547 CompressedData); 548 549 Flags |= ELF::SHF_COMPRESSED; 550 size_t ChdrSize = Is64Bits ? sizeof(object::Elf_Chdr_Impl<object::ELF64LE>) 551 : sizeof(object::Elf_Chdr_Impl<object::ELF32LE>); 552 Size = ChdrSize + CompressedData.size(); 553 Align = 8; 554 } 555 556 CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData, 557 uint32_t ChType, uint64_t DecompressedSize, 558 uint64_t DecompressedAlign) 559 : ChType(ChType), CompressionType(DebugCompressionType::None), 560 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) { 561 OriginalData = CompressedData; 562 } 563 564 Error CompressedSection::accept(SectionVisitor &Visitor) const { 565 return Visitor.visit(*this); 566 } 567 568 Error CompressedSection::accept(MutableSectionVisitor &Visitor) { 569 return Visitor.visit(*this); 570 } 571 572 void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); } 573 574 uint32_t StringTableSection::findIndex(StringRef Name) const { 575 return StrTabBuilder.getOffset(Name); 576 } 577 578 void StringTableSection::prepareForLayout() { 579 StrTabBuilder.finalize(); 580 Size = StrTabBuilder.getSize(); 581 } 582 583 Error SectionWriter::visit(const StringTableSection &Sec) { 584 Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) + 585 Sec.Offset); 586 return Error::success(); 587 } 588 589 Error StringTableSection::accept(SectionVisitor &Visitor) const { 590 return Visitor.visit(*this); 591 } 592 593 Error StringTableSection::accept(MutableSectionVisitor &Visitor) { 594 return Visitor.visit(*this); 595 } 596 597 template <class ELFT> 598 Error ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) { 599 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset; 600 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf)); 601 return Error::success(); 602 } 603 604 Error SectionIndexSection::initialize(SectionTableRef SecTable) { 605 Size = 0; 606 Expected<SymbolTableSection *> Sec = 607 SecTable.getSectionOfType<SymbolTableSection>( 608 Link, 609 "Link field value " + Twine(Link) + " in section " + Name + 610 " is invalid", 611 "Link field value " + Twine(Link) + " in section " + Name + 612 " is not a symbol table"); 613 if (!Sec) 614 return Sec.takeError(); 615 616 setSymTab(*Sec); 617 Symbols->setShndxTable(this); 618 return Error::success(); 619 } 620 621 void SectionIndexSection::finalize() { Link = Symbols->Index; } 622 623 Error SectionIndexSection::accept(SectionVisitor &Visitor) const { 624 return Visitor.visit(*this); 625 } 626 627 Error SectionIndexSection::accept(MutableSectionVisitor &Visitor) { 628 return Visitor.visit(*this); 629 } 630 631 static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) { 632 switch (Index) { 633 case SHN_ABS: 634 case SHN_COMMON: 635 return true; 636 } 637 638 if (Machine == EM_AMDGPU) { 639 return Index == SHN_AMDGPU_LDS; 640 } 641 642 if (Machine == EM_MIPS) { 643 switch (Index) { 644 case SHN_MIPS_ACOMMON: 645 case SHN_MIPS_SCOMMON: 646 case SHN_MIPS_SUNDEFINED: 647 return true; 648 } 649 } 650 651 if (Machine == EM_HEXAGON) { 652 switch (Index) { 653 case SHN_HEXAGON_SCOMMON: 654 case SHN_HEXAGON_SCOMMON_1: 655 case SHN_HEXAGON_SCOMMON_2: 656 case SHN_HEXAGON_SCOMMON_4: 657 case SHN_HEXAGON_SCOMMON_8: 658 return true; 659 } 660 } 661 return false; 662 } 663 664 // Large indexes force us to clarify exactly what this function should do. This 665 // function should return the value that will appear in st_shndx when written 666 // out. 667 uint16_t Symbol::getShndx() const { 668 if (DefinedIn != nullptr) { 669 if (DefinedIn->Index >= SHN_LORESERVE) 670 return SHN_XINDEX; 671 return DefinedIn->Index; 672 } 673 674 if (ShndxType == SYMBOL_SIMPLE_INDEX) { 675 // This means that we don't have a defined section but we do need to 676 // output a legitimate section index. 677 return SHN_UNDEF; 678 } 679 680 assert(ShndxType == SYMBOL_ABS || ShndxType == SYMBOL_COMMON || 681 (ShndxType >= SYMBOL_LOPROC && ShndxType <= SYMBOL_HIPROC) || 682 (ShndxType >= SYMBOL_LOOS && ShndxType <= SYMBOL_HIOS)); 683 return static_cast<uint16_t>(ShndxType); 684 } 685 686 bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; } 687 688 void SymbolTableSection::assignIndices() { 689 uint32_t Index = 0; 690 for (auto &Sym : Symbols) { 691 if (Sym->Index != Index) 692 IndicesChanged = true; 693 Sym->Index = Index++; 694 } 695 } 696 697 void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type, 698 SectionBase *DefinedIn, uint64_t Value, 699 uint8_t Visibility, uint16_t Shndx, 700 uint64_t SymbolSize) { 701 Symbol Sym; 702 Sym.Name = Name.str(); 703 Sym.Binding = Bind; 704 Sym.Type = Type; 705 Sym.DefinedIn = DefinedIn; 706 if (DefinedIn != nullptr) 707 DefinedIn->HasSymbol = true; 708 if (DefinedIn == nullptr) { 709 if (Shndx >= SHN_LORESERVE) 710 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx); 711 else 712 Sym.ShndxType = SYMBOL_SIMPLE_INDEX; 713 } 714 Sym.Value = Value; 715 Sym.Visibility = Visibility; 716 Sym.Size = SymbolSize; 717 Sym.Index = Symbols.size(); 718 Symbols.emplace_back(std::make_unique<Symbol>(Sym)); 719 Size += this->EntrySize; 720 } 721 722 Error SymbolTableSection::removeSectionReferences( 723 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) { 724 if (ToRemove(SectionIndexTable)) 725 SectionIndexTable = nullptr; 726 if (ToRemove(SymbolNames)) { 727 if (!AllowBrokenLinks) 728 return createStringError( 729 llvm::errc::invalid_argument, 730 "string table '%s' cannot be removed because it is " 731 "referenced by the symbol table '%s'", 732 SymbolNames->Name.data(), this->Name.data()); 733 SymbolNames = nullptr; 734 } 735 return removeSymbols( 736 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); }); 737 } 738 739 void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) { 740 for (SymPtr &Sym : llvm::drop_begin(Symbols)) 741 Callable(*Sym); 742 std::stable_partition( 743 std::begin(Symbols), std::end(Symbols), 744 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; }); 745 assignIndices(); 746 } 747 748 Error SymbolTableSection::removeSymbols( 749 function_ref<bool(const Symbol &)> ToRemove) { 750 Symbols.erase( 751 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols), 752 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }), 753 std::end(Symbols)); 754 auto PrevSize = Size; 755 Size = Symbols.size() * EntrySize; 756 if (Size < PrevSize) 757 IndicesChanged = true; 758 assignIndices(); 759 return Error::success(); 760 } 761 762 void SymbolTableSection::replaceSectionReferences( 763 const DenseMap<SectionBase *, SectionBase *> &FromTo) { 764 for (std::unique_ptr<Symbol> &Sym : Symbols) 765 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn)) 766 Sym->DefinedIn = To; 767 } 768 769 Error SymbolTableSection::initialize(SectionTableRef SecTable) { 770 Size = 0; 771 Expected<StringTableSection *> Sec = 772 SecTable.getSectionOfType<StringTableSection>( 773 Link, 774 "Symbol table has link index of " + Twine(Link) + 775 " which is not a valid index", 776 "Symbol table has link index of " + Twine(Link) + 777 " which is not a string table"); 778 if (!Sec) 779 return Sec.takeError(); 780 781 setStrTab(*Sec); 782 return Error::success(); 783 } 784 785 void SymbolTableSection::finalize() { 786 uint32_t MaxLocalIndex = 0; 787 for (std::unique_ptr<Symbol> &Sym : Symbols) { 788 Sym->NameIndex = 789 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name); 790 if (Sym->Binding == STB_LOCAL) 791 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index); 792 } 793 // Now we need to set the Link and Info fields. 794 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index; 795 Info = MaxLocalIndex + 1; 796 } 797 798 void SymbolTableSection::prepareForLayout() { 799 // Reserve proper amount of space in section index table, so we can 800 // layout sections correctly. We will fill the table with correct 801 // indexes later in fillShdnxTable. 802 if (SectionIndexTable) 803 SectionIndexTable->reserve(Symbols.size()); 804 805 // Add all of our strings to SymbolNames so that SymbolNames has the right 806 // size before layout is decided. 807 // If the symbol names section has been removed, don't try to add strings to 808 // the table. 809 if (SymbolNames != nullptr) 810 for (std::unique_ptr<Symbol> &Sym : Symbols) 811 SymbolNames->addString(Sym->Name); 812 } 813 814 void SymbolTableSection::fillShndxTable() { 815 if (SectionIndexTable == nullptr) 816 return; 817 // Fill section index table with real section indexes. This function must 818 // be called after assignOffsets. 819 for (const std::unique_ptr<Symbol> &Sym : Symbols) { 820 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE) 821 SectionIndexTable->addIndex(Sym->DefinedIn->Index); 822 else 823 SectionIndexTable->addIndex(SHN_UNDEF); 824 } 825 } 826 827 Expected<const Symbol *> 828 SymbolTableSection::getSymbolByIndex(uint32_t Index) const { 829 if (Symbols.size() <= Index) 830 return createStringError(errc::invalid_argument, 831 "invalid symbol index: " + Twine(Index)); 832 return Symbols[Index].get(); 833 } 834 835 Expected<Symbol *> SymbolTableSection::getSymbolByIndex(uint32_t Index) { 836 Expected<const Symbol *> Sym = 837 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index); 838 if (!Sym) 839 return Sym.takeError(); 840 841 return const_cast<Symbol *>(*Sym); 842 } 843 844 template <class ELFT> 845 Error ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) { 846 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset); 847 // Loop though symbols setting each entry of the symbol table. 848 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) { 849 Sym->st_name = Symbol->NameIndex; 850 Sym->st_value = Symbol->Value; 851 Sym->st_size = Symbol->Size; 852 Sym->st_other = Symbol->Visibility; 853 Sym->setBinding(Symbol->Binding); 854 Sym->setType(Symbol->Type); 855 Sym->st_shndx = Symbol->getShndx(); 856 ++Sym; 857 } 858 return Error::success(); 859 } 860 861 Error SymbolTableSection::accept(SectionVisitor &Visitor) const { 862 return Visitor.visit(*this); 863 } 864 865 Error SymbolTableSection::accept(MutableSectionVisitor &Visitor) { 866 return Visitor.visit(*this); 867 } 868 869 StringRef RelocationSectionBase::getNamePrefix() const { 870 switch (Type) { 871 case SHT_REL: 872 return ".rel"; 873 case SHT_RELA: 874 return ".rela"; 875 default: 876 llvm_unreachable("not a relocation section"); 877 } 878 } 879 880 Error RelocationSection::removeSectionReferences( 881 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) { 882 if (ToRemove(Symbols)) { 883 if (!AllowBrokenLinks) 884 return createStringError( 885 llvm::errc::invalid_argument, 886 "symbol table '%s' cannot be removed because it is " 887 "referenced by the relocation section '%s'", 888 Symbols->Name.data(), this->Name.data()); 889 Symbols = nullptr; 890 } 891 892 for (const Relocation &R : Relocations) { 893 if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn || 894 !ToRemove(R.RelocSymbol->DefinedIn)) 895 continue; 896 return createStringError(llvm::errc::invalid_argument, 897 "section '%s' cannot be removed: (%s+0x%" PRIx64 898 ") has relocation against symbol '%s'", 899 R.RelocSymbol->DefinedIn->Name.data(), 900 SecToApplyRel->Name.data(), R.Offset, 901 R.RelocSymbol->Name.c_str()); 902 } 903 904 return Error::success(); 905 } 906 907 template <class SymTabType> 908 Error RelocSectionWithSymtabBase<SymTabType>::initialize( 909 SectionTableRef SecTable) { 910 if (Link != SHN_UNDEF) { 911 Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>( 912 Link, 913 "Link field value " + Twine(Link) + " in section " + Name + 914 " is invalid", 915 "Link field value " + Twine(Link) + " in section " + Name + 916 " is not a symbol table"); 917 if (!Sec) 918 return Sec.takeError(); 919 920 setSymTab(*Sec); 921 } 922 923 if (Info != SHN_UNDEF) { 924 Expected<SectionBase *> Sec = 925 SecTable.getSection(Info, "Info field value " + Twine(Info) + 926 " in section " + Name + " is invalid"); 927 if (!Sec) 928 return Sec.takeError(); 929 930 setSection(*Sec); 931 } else 932 setSection(nullptr); 933 934 return Error::success(); 935 } 936 937 template <class SymTabType> 938 void RelocSectionWithSymtabBase<SymTabType>::finalize() { 939 this->Link = Symbols ? Symbols->Index : 0; 940 941 if (SecToApplyRel != nullptr) 942 this->Info = SecToApplyRel->Index; 943 } 944 945 template <class ELFT> 946 static void setAddend(Elf_Rel_Impl<ELFT, false> &, uint64_t) {} 947 948 template <class ELFT> 949 static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) { 950 Rela.r_addend = Addend; 951 } 952 953 template <class RelRange, class T> 954 static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) { 955 for (const auto &Reloc : Relocations) { 956 Buf->r_offset = Reloc.Offset; 957 setAddend(*Buf, Reloc.Addend); 958 Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0, 959 Reloc.Type, IsMips64EL); 960 ++Buf; 961 } 962 } 963 964 template <class ELFT> 965 Error ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) { 966 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset; 967 if (Sec.Type == SHT_REL) 968 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf), 969 Sec.getObject().IsMips64EL); 970 else 971 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf), 972 Sec.getObject().IsMips64EL); 973 return Error::success(); 974 } 975 976 Error RelocationSection::accept(SectionVisitor &Visitor) const { 977 return Visitor.visit(*this); 978 } 979 980 Error RelocationSection::accept(MutableSectionVisitor &Visitor) { 981 return Visitor.visit(*this); 982 } 983 984 Error RelocationSection::removeSymbols( 985 function_ref<bool(const Symbol &)> ToRemove) { 986 for (const Relocation &Reloc : Relocations) 987 if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol)) 988 return createStringError( 989 llvm::errc::invalid_argument, 990 "not stripping symbol '%s' because it is named in a relocation", 991 Reloc.RelocSymbol->Name.data()); 992 return Error::success(); 993 } 994 995 void RelocationSection::markSymbols() { 996 for (const Relocation &Reloc : Relocations) 997 if (Reloc.RelocSymbol) 998 Reloc.RelocSymbol->Referenced = true; 999 } 1000 1001 void RelocationSection::replaceSectionReferences( 1002 const DenseMap<SectionBase *, SectionBase *> &FromTo) { 1003 // Update the target section if it was replaced. 1004 if (SectionBase *To = FromTo.lookup(SecToApplyRel)) 1005 SecToApplyRel = To; 1006 } 1007 1008 Error SectionWriter::visit(const DynamicRelocationSection &Sec) { 1009 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset); 1010 return Error::success(); 1011 } 1012 1013 Error DynamicRelocationSection::accept(SectionVisitor &Visitor) const { 1014 return Visitor.visit(*this); 1015 } 1016 1017 Error DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) { 1018 return Visitor.visit(*this); 1019 } 1020 1021 Error DynamicRelocationSection::removeSectionReferences( 1022 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) { 1023 if (ToRemove(Symbols)) { 1024 if (!AllowBrokenLinks) 1025 return createStringError( 1026 llvm::errc::invalid_argument, 1027 "symbol table '%s' cannot be removed because it is " 1028 "referenced by the relocation section '%s'", 1029 Symbols->Name.data(), this->Name.data()); 1030 Symbols = nullptr; 1031 } 1032 1033 // SecToApplyRel contains a section referenced by sh_info field. It keeps 1034 // a section to which the relocation section applies. When we remove any 1035 // sections we also remove their relocation sections. Since we do that much 1036 // earlier, this assert should never be triggered. 1037 assert(!SecToApplyRel || !ToRemove(SecToApplyRel)); 1038 return Error::success(); 1039 } 1040 1041 Error Section::removeSectionReferences( 1042 bool AllowBrokenDependency, 1043 function_ref<bool(const SectionBase *)> ToRemove) { 1044 if (ToRemove(LinkSection)) { 1045 if (!AllowBrokenDependency) 1046 return createStringError(llvm::errc::invalid_argument, 1047 "section '%s' cannot be removed because it is " 1048 "referenced by the section '%s'", 1049 LinkSection->Name.data(), this->Name.data()); 1050 LinkSection = nullptr; 1051 } 1052 return Error::success(); 1053 } 1054 1055 void GroupSection::finalize() { 1056 this->Info = Sym ? Sym->Index : 0; 1057 this->Link = SymTab ? SymTab->Index : 0; 1058 // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global 1059 // status is not part of the equation. If Sym is localized, the intention is 1060 // likely to make the group fully localized. Drop GRP_COMDAT to suppress 1061 // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc 1062 if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL) 1063 this->FlagWord &= ~GRP_COMDAT; 1064 } 1065 1066 Error GroupSection::removeSectionReferences( 1067 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) { 1068 if (ToRemove(SymTab)) { 1069 if (!AllowBrokenLinks) 1070 return createStringError( 1071 llvm::errc::invalid_argument, 1072 "section '.symtab' cannot be removed because it is " 1073 "referenced by the group section '%s'", 1074 this->Name.data()); 1075 SymTab = nullptr; 1076 Sym = nullptr; 1077 } 1078 llvm::erase_if(GroupMembers, ToRemove); 1079 return Error::success(); 1080 } 1081 1082 Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) { 1083 if (ToRemove(*Sym)) 1084 return createStringError(llvm::errc::invalid_argument, 1085 "symbol '%s' cannot be removed because it is " 1086 "referenced by the section '%s[%d]'", 1087 Sym->Name.data(), this->Name.data(), this->Index); 1088 return Error::success(); 1089 } 1090 1091 void GroupSection::markSymbols() { 1092 if (Sym) 1093 Sym->Referenced = true; 1094 } 1095 1096 void GroupSection::replaceSectionReferences( 1097 const DenseMap<SectionBase *, SectionBase *> &FromTo) { 1098 for (SectionBase *&Sec : GroupMembers) 1099 if (SectionBase *To = FromTo.lookup(Sec)) 1100 Sec = To; 1101 } 1102 1103 void GroupSection::onRemove() { 1104 // As the header section of the group is removed, drop the Group flag in its 1105 // former members. 1106 for (SectionBase *Sec : GroupMembers) 1107 Sec->Flags &= ~SHF_GROUP; 1108 } 1109 1110 Error Section::initialize(SectionTableRef SecTable) { 1111 if (Link == ELF::SHN_UNDEF) 1112 return Error::success(); 1113 1114 Expected<SectionBase *> Sec = 1115 SecTable.getSection(Link, "Link field value " + Twine(Link) + 1116 " in section " + Name + " is invalid"); 1117 if (!Sec) 1118 return Sec.takeError(); 1119 1120 LinkSection = *Sec; 1121 1122 if (LinkSection->Type == ELF::SHT_SYMTAB) { 1123 HasSymTabLink = true; 1124 LinkSection = nullptr; 1125 } 1126 1127 return Error::success(); 1128 } 1129 1130 void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; } 1131 1132 void GnuDebugLinkSection::init(StringRef File) { 1133 FileName = sys::path::filename(File); 1134 // The format for the .gnu_debuglink starts with the file name and is 1135 // followed by a null terminator and then the CRC32 of the file. The CRC32 1136 // should be 4 byte aligned. So we add the FileName size, a 1 for the null 1137 // byte, and then finally push the size to alignment and add 4. 1138 Size = alignTo(FileName.size() + 1, 4) + 4; 1139 // The CRC32 will only be aligned if we align the whole section. 1140 Align = 4; 1141 Type = OriginalType = ELF::SHT_PROGBITS; 1142 Name = ".gnu_debuglink"; 1143 // For sections not found in segments, OriginalOffset is only used to 1144 // establish the order that sections should go in. By using the maximum 1145 // possible offset we cause this section to wind up at the end. 1146 OriginalOffset = std::numeric_limits<uint64_t>::max(); 1147 } 1148 1149 GnuDebugLinkSection::GnuDebugLinkSection(StringRef File, 1150 uint32_t PrecomputedCRC) 1151 : FileName(File), CRC32(PrecomputedCRC) { 1152 init(File); 1153 } 1154 1155 template <class ELFT> 1156 Error ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) { 1157 unsigned char *Buf = 1158 reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset; 1159 Elf_Word *CRC = 1160 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word)); 1161 *CRC = Sec.CRC32; 1162 llvm::copy(Sec.FileName, Buf); 1163 return Error::success(); 1164 } 1165 1166 Error GnuDebugLinkSection::accept(SectionVisitor &Visitor) const { 1167 return Visitor.visit(*this); 1168 } 1169 1170 Error GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) { 1171 return Visitor.visit(*this); 1172 } 1173 1174 template <class ELFT> 1175 Error ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) { 1176 ELF::Elf32_Word *Buf = 1177 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset); 1178 support::endian::write32<ELFT::TargetEndianness>(Buf++, Sec.FlagWord); 1179 for (SectionBase *S : Sec.GroupMembers) 1180 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index); 1181 return Error::success(); 1182 } 1183 1184 Error GroupSection::accept(SectionVisitor &Visitor) const { 1185 return Visitor.visit(*this); 1186 } 1187 1188 Error GroupSection::accept(MutableSectionVisitor &Visitor) { 1189 return Visitor.visit(*this); 1190 } 1191 1192 // Returns true IFF a section is wholly inside the range of a segment 1193 static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) { 1194 // If a section is empty it should be treated like it has a size of 1. This is 1195 // to clarify the case when an empty section lies on a boundary between two 1196 // segments and ensures that the section "belongs" to the second segment and 1197 // not the first. 1198 uint64_t SecSize = Sec.Size ? Sec.Size : 1; 1199 1200 // Ignore just added sections. 1201 if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max()) 1202 return false; 1203 1204 if (Sec.Type == SHT_NOBITS) { 1205 if (!(Sec.Flags & SHF_ALLOC)) 1206 return false; 1207 1208 bool SectionIsTLS = Sec.Flags & SHF_TLS; 1209 bool SegmentIsTLS = Seg.Type == PT_TLS; 1210 if (SectionIsTLS != SegmentIsTLS) 1211 return false; 1212 1213 return Seg.VAddr <= Sec.Addr && 1214 Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize; 1215 } 1216 1217 return Seg.Offset <= Sec.OriginalOffset && 1218 Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize; 1219 } 1220 1221 // Returns true IFF a segment's original offset is inside of another segment's 1222 // range. 1223 static bool segmentOverlapsSegment(const Segment &Child, 1224 const Segment &Parent) { 1225 1226 return Parent.OriginalOffset <= Child.OriginalOffset && 1227 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset; 1228 } 1229 1230 static bool compareSegmentsByOffset(const Segment *A, const Segment *B) { 1231 // Any segment without a parent segment should come before a segment 1232 // that has a parent segment. 1233 if (A->OriginalOffset < B->OriginalOffset) 1234 return true; 1235 if (A->OriginalOffset > B->OriginalOffset) 1236 return false; 1237 return A->Index < B->Index; 1238 } 1239 1240 void BasicELFBuilder::initFileHeader() { 1241 Obj->Flags = 0x0; 1242 Obj->Type = ET_REL; 1243 Obj->OSABI = ELFOSABI_NONE; 1244 Obj->ABIVersion = 0; 1245 Obj->Entry = 0x0; 1246 Obj->Machine = EM_NONE; 1247 Obj->Version = 1; 1248 } 1249 1250 void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; } 1251 1252 StringTableSection *BasicELFBuilder::addStrTab() { 1253 auto &StrTab = Obj->addSection<StringTableSection>(); 1254 StrTab.Name = ".strtab"; 1255 1256 Obj->SectionNames = &StrTab; 1257 return &StrTab; 1258 } 1259 1260 SymbolTableSection *BasicELFBuilder::addSymTab(StringTableSection *StrTab) { 1261 auto &SymTab = Obj->addSection<SymbolTableSection>(); 1262 1263 SymTab.Name = ".symtab"; 1264 SymTab.Link = StrTab->Index; 1265 1266 // The symbol table always needs a null symbol 1267 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0); 1268 1269 Obj->SymbolTable = &SymTab; 1270 return &SymTab; 1271 } 1272 1273 Error BasicELFBuilder::initSections() { 1274 for (SectionBase &Sec : Obj->sections()) 1275 if (Error Err = Sec.initialize(Obj->sections())) 1276 return Err; 1277 1278 return Error::success(); 1279 } 1280 1281 void BinaryELFBuilder::addData(SymbolTableSection *SymTab) { 1282 auto Data = ArrayRef<uint8_t>( 1283 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()), 1284 MemBuf->getBufferSize()); 1285 auto &DataSection = Obj->addSection<Section>(Data); 1286 DataSection.Name = ".data"; 1287 DataSection.Type = ELF::SHT_PROGBITS; 1288 DataSection.Size = Data.size(); 1289 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 1290 1291 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str(); 1292 std::replace_if( 1293 std::begin(SanitizedFilename), std::end(SanitizedFilename), 1294 [](char C) { return !isAlnum(C); }, '_'); 1295 Twine Prefix = Twine("_binary_") + SanitizedFilename; 1296 1297 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection, 1298 /*Value=*/0, NewSymbolVisibility, 0, 0); 1299 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection, 1300 /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0); 1301 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr, 1302 /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS, 1303 0); 1304 } 1305 1306 Expected<std::unique_ptr<Object>> BinaryELFBuilder::build() { 1307 initFileHeader(); 1308 initHeaderSegment(); 1309 1310 SymbolTableSection *SymTab = addSymTab(addStrTab()); 1311 if (Error Err = initSections()) 1312 return std::move(Err); 1313 addData(SymTab); 1314 1315 return std::move(Obj); 1316 } 1317 1318 // Adds sections from IHEX data file. Data should have been 1319 // fully validated by this time. 1320 void IHexELFBuilder::addDataSections() { 1321 OwnedDataSection *Section = nullptr; 1322 uint64_t SegmentAddr = 0, BaseAddr = 0; 1323 uint32_t SecNo = 1; 1324 1325 for (const IHexRecord &R : Records) { 1326 uint64_t RecAddr; 1327 switch (R.Type) { 1328 case IHexRecord::Data: 1329 // Ignore empty data records 1330 if (R.HexData.empty()) 1331 continue; 1332 RecAddr = R.Addr + SegmentAddr + BaseAddr; 1333 if (!Section || Section->Addr + Section->Size != RecAddr) { 1334 // OriginalOffset field is only used to sort sections before layout, so 1335 // instead of keeping track of real offsets in IHEX file, and as 1336 // layoutSections() and layoutSectionsForOnlyKeepDebug() use 1337 // llvm::stable_sort(), we can just set it to a constant (zero). 1338 Section = &Obj->addSection<OwnedDataSection>( 1339 ".sec" + std::to_string(SecNo), RecAddr, 1340 ELF::SHF_ALLOC | ELF::SHF_WRITE, 0); 1341 SecNo++; 1342 } 1343 Section->appendHexData(R.HexData); 1344 break; 1345 case IHexRecord::EndOfFile: 1346 break; 1347 case IHexRecord::SegmentAddr: 1348 // 20-bit segment address. 1349 SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4; 1350 break; 1351 case IHexRecord::StartAddr80x86: 1352 case IHexRecord::StartAddr: 1353 Obj->Entry = checkedGetHex<uint32_t>(R.HexData); 1354 assert(Obj->Entry <= 0xFFFFFU); 1355 break; 1356 case IHexRecord::ExtendedAddr: 1357 // 16-31 bits of linear base address 1358 BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16; 1359 break; 1360 default: 1361 llvm_unreachable("unknown record type"); 1362 } 1363 } 1364 } 1365 1366 Expected<std::unique_ptr<Object>> IHexELFBuilder::build() { 1367 initFileHeader(); 1368 initHeaderSegment(); 1369 StringTableSection *StrTab = addStrTab(); 1370 addSymTab(StrTab); 1371 if (Error Err = initSections()) 1372 return std::move(Err); 1373 addDataSections(); 1374 1375 return std::move(Obj); 1376 } 1377 1378 template <class ELFT> 1379 ELFBuilder<ELFT>::ELFBuilder(const ELFObjectFile<ELFT> &ElfObj, Object &Obj, 1380 std::optional<StringRef> ExtractPartition) 1381 : ElfFile(ElfObj.getELFFile()), Obj(Obj), 1382 ExtractPartition(ExtractPartition) { 1383 Obj.IsMips64EL = ElfFile.isMips64EL(); 1384 } 1385 1386 template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) { 1387 for (Segment &Parent : Obj.segments()) { 1388 // Every segment will overlap with itself but we don't want a segment to 1389 // be its own parent so we avoid that situation. 1390 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) { 1391 // We want a canonical "most parental" segment but this requires 1392 // inspecting the ParentSegment. 1393 if (compareSegmentsByOffset(&Parent, &Child)) 1394 if (Child.ParentSegment == nullptr || 1395 compareSegmentsByOffset(&Parent, Child.ParentSegment)) { 1396 Child.ParentSegment = &Parent; 1397 } 1398 } 1399 } 1400 } 1401 1402 template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() { 1403 if (!ExtractPartition) 1404 return Error::success(); 1405 1406 for (const SectionBase &Sec : Obj.sections()) { 1407 if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) { 1408 EhdrOffset = Sec.Offset; 1409 return Error::success(); 1410 } 1411 } 1412 return createStringError(errc::invalid_argument, 1413 "could not find partition named '" + 1414 *ExtractPartition + "'"); 1415 } 1416 1417 template <class ELFT> 1418 Error ELFBuilder<ELFT>::readProgramHeaders(const ELFFile<ELFT> &HeadersFile) { 1419 uint32_t Index = 0; 1420 1421 Expected<typename ELFFile<ELFT>::Elf_Phdr_Range> Headers = 1422 HeadersFile.program_headers(); 1423 if (!Headers) 1424 return Headers.takeError(); 1425 1426 for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) { 1427 if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize()) 1428 return createStringError( 1429 errc::invalid_argument, 1430 "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) + 1431 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) + 1432 " goes past the end of the file"); 1433 1434 ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset, 1435 (size_t)Phdr.p_filesz}; 1436 Segment &Seg = Obj.addSegment(Data); 1437 Seg.Type = Phdr.p_type; 1438 Seg.Flags = Phdr.p_flags; 1439 Seg.OriginalOffset = Phdr.p_offset + EhdrOffset; 1440 Seg.Offset = Phdr.p_offset + EhdrOffset; 1441 Seg.VAddr = Phdr.p_vaddr; 1442 Seg.PAddr = Phdr.p_paddr; 1443 Seg.FileSize = Phdr.p_filesz; 1444 Seg.MemSize = Phdr.p_memsz; 1445 Seg.Align = Phdr.p_align; 1446 Seg.Index = Index++; 1447 for (SectionBase &Sec : Obj.sections()) 1448 if (sectionWithinSegment(Sec, Seg)) { 1449 Seg.addSection(&Sec); 1450 if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset) 1451 Sec.ParentSegment = &Seg; 1452 } 1453 } 1454 1455 auto &ElfHdr = Obj.ElfHdrSegment; 1456 ElfHdr.Index = Index++; 1457 ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset; 1458 1459 const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader(); 1460 auto &PrHdr = Obj.ProgramHdrSegment; 1461 PrHdr.Type = PT_PHDR; 1462 PrHdr.Flags = 0; 1463 // The spec requires us to have p_vaddr % p_align == p_offset % p_align. 1464 // Whereas this works automatically for ElfHdr, here OriginalOffset is 1465 // always non-zero and to ensure the equation we assign the same value to 1466 // VAddr as well. 1467 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff; 1468 PrHdr.PAddr = 0; 1469 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum; 1470 // The spec requires us to naturally align all the fields. 1471 PrHdr.Align = sizeof(Elf_Addr); 1472 PrHdr.Index = Index++; 1473 1474 // Now we do an O(n^2) loop through the segments in order to match up 1475 // segments. 1476 for (Segment &Child : Obj.segments()) 1477 setParentSegment(Child); 1478 setParentSegment(ElfHdr); 1479 setParentSegment(PrHdr); 1480 1481 return Error::success(); 1482 } 1483 1484 template <class ELFT> 1485 Error ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) { 1486 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0) 1487 return createStringError(errc::invalid_argument, 1488 "invalid alignment " + Twine(GroupSec->Align) + 1489 " of group section '" + GroupSec->Name + "'"); 1490 SectionTableRef SecTable = Obj.sections(); 1491 if (GroupSec->Link != SHN_UNDEF) { 1492 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>( 1493 GroupSec->Link, 1494 "link field value '" + Twine(GroupSec->Link) + "' in section '" + 1495 GroupSec->Name + "' is invalid", 1496 "link field value '" + Twine(GroupSec->Link) + "' in section '" + 1497 GroupSec->Name + "' is not a symbol table"); 1498 if (!SymTab) 1499 return SymTab.takeError(); 1500 1501 Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info); 1502 if (!Sym) 1503 return createStringError(errc::invalid_argument, 1504 "info field value '" + Twine(GroupSec->Info) + 1505 "' in section '" + GroupSec->Name + 1506 "' is not a valid symbol index"); 1507 GroupSec->setSymTab(*SymTab); 1508 GroupSec->setSymbol(*Sym); 1509 } 1510 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) || 1511 GroupSec->Contents.empty()) 1512 return createStringError(errc::invalid_argument, 1513 "the content of the section " + GroupSec->Name + 1514 " is malformed"); 1515 const ELF::Elf32_Word *Word = 1516 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data()); 1517 const ELF::Elf32_Word *End = 1518 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word); 1519 GroupSec->setFlagWord( 1520 support::endian::read32<ELFT::TargetEndianness>(Word++)); 1521 for (; Word != End; ++Word) { 1522 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word); 1523 Expected<SectionBase *> Sec = SecTable.getSection( 1524 Index, "group member index " + Twine(Index) + " in section '" + 1525 GroupSec->Name + "' is invalid"); 1526 if (!Sec) 1527 return Sec.takeError(); 1528 1529 GroupSec->addMember(*Sec); 1530 } 1531 1532 return Error::success(); 1533 } 1534 1535 template <class ELFT> 1536 Error ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) { 1537 Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index); 1538 if (!Shdr) 1539 return Shdr.takeError(); 1540 1541 Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr); 1542 if (!StrTabData) 1543 return StrTabData.takeError(); 1544 1545 ArrayRef<Elf_Word> ShndxData; 1546 1547 Expected<typename ELFFile<ELFT>::Elf_Sym_Range> Symbols = 1548 ElfFile.symbols(*Shdr); 1549 if (!Symbols) 1550 return Symbols.takeError(); 1551 1552 for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) { 1553 SectionBase *DefSection = nullptr; 1554 1555 Expected<StringRef> Name = Sym.getName(*StrTabData); 1556 if (!Name) 1557 return Name.takeError(); 1558 1559 if (Sym.st_shndx == SHN_XINDEX) { 1560 if (SymTab->getShndxTable() == nullptr) 1561 return createStringError(errc::invalid_argument, 1562 "symbol '" + *Name + 1563 "' has index SHN_XINDEX but no " 1564 "SHT_SYMTAB_SHNDX section exists"); 1565 if (ShndxData.data() == nullptr) { 1566 Expected<const Elf_Shdr *> ShndxSec = 1567 ElfFile.getSection(SymTab->getShndxTable()->Index); 1568 if (!ShndxSec) 1569 return ShndxSec.takeError(); 1570 1571 Expected<ArrayRef<Elf_Word>> Data = 1572 ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec); 1573 if (!Data) 1574 return Data.takeError(); 1575 1576 ShndxData = *Data; 1577 if (ShndxData.size() != Symbols->size()) 1578 return createStringError( 1579 errc::invalid_argument, 1580 "symbol section index table does not have the same number of " 1581 "entries as the symbol table"); 1582 } 1583 Elf_Word Index = ShndxData[&Sym - Symbols->begin()]; 1584 Expected<SectionBase *> Sec = Obj.sections().getSection( 1585 Index, 1586 "symbol '" + *Name + "' has invalid section index " + Twine(Index)); 1587 if (!Sec) 1588 return Sec.takeError(); 1589 1590 DefSection = *Sec; 1591 } else if (Sym.st_shndx >= SHN_LORESERVE) { 1592 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) { 1593 return createStringError( 1594 errc::invalid_argument, 1595 "symbol '" + *Name + 1596 "' has unsupported value greater than or equal " 1597 "to SHN_LORESERVE: " + 1598 Twine(Sym.st_shndx)); 1599 } 1600 } else if (Sym.st_shndx != SHN_UNDEF) { 1601 Expected<SectionBase *> Sec = Obj.sections().getSection( 1602 Sym.st_shndx, "symbol '" + *Name + 1603 "' is defined has invalid section index " + 1604 Twine(Sym.st_shndx)); 1605 if (!Sec) 1606 return Sec.takeError(); 1607 1608 DefSection = *Sec; 1609 } 1610 1611 SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection, 1612 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size); 1613 } 1614 1615 return Error::success(); 1616 } 1617 1618 template <class ELFT> 1619 static void getAddend(uint64_t &, const Elf_Rel_Impl<ELFT, false> &) {} 1620 1621 template <class ELFT> 1622 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) { 1623 ToSet = Rela.r_addend; 1624 } 1625 1626 template <class T> 1627 static Error initRelocations(RelocationSection *Relocs, T RelRange) { 1628 for (const auto &Rel : RelRange) { 1629 Relocation ToAdd; 1630 ToAdd.Offset = Rel.r_offset; 1631 getAddend(ToAdd.Addend, Rel); 1632 ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL); 1633 1634 if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) { 1635 if (!Relocs->getObject().SymbolTable) 1636 return createStringError( 1637 errc::invalid_argument, 1638 "'" + Relocs->Name + "': relocation references symbol with index " + 1639 Twine(Sym) + ", but there is no symbol table"); 1640 Expected<Symbol *> SymByIndex = 1641 Relocs->getObject().SymbolTable->getSymbolByIndex(Sym); 1642 if (!SymByIndex) 1643 return SymByIndex.takeError(); 1644 1645 ToAdd.RelocSymbol = *SymByIndex; 1646 } 1647 1648 Relocs->addRelocation(ToAdd); 1649 } 1650 1651 return Error::success(); 1652 } 1653 1654 Expected<SectionBase *> SectionTableRef::getSection(uint32_t Index, 1655 Twine ErrMsg) { 1656 if (Index == SHN_UNDEF || Index > Sections.size()) 1657 return createStringError(errc::invalid_argument, ErrMsg); 1658 return Sections[Index - 1].get(); 1659 } 1660 1661 template <class T> 1662 Expected<T *> SectionTableRef::getSectionOfType(uint32_t Index, 1663 Twine IndexErrMsg, 1664 Twine TypeErrMsg) { 1665 Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg); 1666 if (!BaseSec) 1667 return BaseSec.takeError(); 1668 1669 if (T *Sec = dyn_cast<T>(*BaseSec)) 1670 return Sec; 1671 1672 return createStringError(errc::invalid_argument, TypeErrMsg); 1673 } 1674 1675 template <class ELFT> 1676 Expected<SectionBase &> ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) { 1677 switch (Shdr.sh_type) { 1678 case SHT_REL: 1679 case SHT_RELA: 1680 if (Shdr.sh_flags & SHF_ALLOC) { 1681 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr)) 1682 return Obj.addSection<DynamicRelocationSection>(*Data); 1683 else 1684 return Data.takeError(); 1685 } 1686 return Obj.addSection<RelocationSection>(Obj); 1687 case SHT_STRTAB: 1688 // If a string table is allocated we don't want to mess with it. That would 1689 // mean altering the memory image. There are no special link types or 1690 // anything so we can just use a Section. 1691 if (Shdr.sh_flags & SHF_ALLOC) { 1692 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr)) 1693 return Obj.addSection<Section>(*Data); 1694 else 1695 return Data.takeError(); 1696 } 1697 return Obj.addSection<StringTableSection>(); 1698 case SHT_HASH: 1699 case SHT_GNU_HASH: 1700 // Hash tables should refer to SHT_DYNSYM which we're not going to change. 1701 // Because of this we don't need to mess with the hash tables either. 1702 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr)) 1703 return Obj.addSection<Section>(*Data); 1704 else 1705 return Data.takeError(); 1706 case SHT_GROUP: 1707 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr)) 1708 return Obj.addSection<GroupSection>(*Data); 1709 else 1710 return Data.takeError(); 1711 case SHT_DYNSYM: 1712 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr)) 1713 return Obj.addSection<DynamicSymbolTableSection>(*Data); 1714 else 1715 return Data.takeError(); 1716 case SHT_DYNAMIC: 1717 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr)) 1718 return Obj.addSection<DynamicSection>(*Data); 1719 else 1720 return Data.takeError(); 1721 case SHT_SYMTAB: { 1722 // Multiple SHT_SYMTAB sections are forbidden by the ELF gABI. 1723 if (Obj.SymbolTable != nullptr) 1724 return createStringError(llvm::errc::invalid_argument, 1725 "found multiple SHT_SYMTAB sections"); 1726 auto &SymTab = Obj.addSection<SymbolTableSection>(); 1727 Obj.SymbolTable = &SymTab; 1728 return SymTab; 1729 } 1730 case SHT_SYMTAB_SHNDX: { 1731 auto &ShndxSection = Obj.addSection<SectionIndexSection>(); 1732 Obj.SectionIndexTable = &ShndxSection; 1733 return ShndxSection; 1734 } 1735 case SHT_NOBITS: 1736 return Obj.addSection<Section>(ArrayRef<uint8_t>()); 1737 default: { 1738 Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr); 1739 if (!Data) 1740 return Data.takeError(); 1741 1742 Expected<StringRef> Name = ElfFile.getSectionName(Shdr); 1743 if (!Name) 1744 return Name.takeError(); 1745 1746 if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED)) 1747 return Obj.addSection<Section>(*Data); 1748 auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data()); 1749 return Obj.addSection<CompressedSection>(CompressedSection( 1750 *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign)); 1751 } 1752 } 1753 } 1754 1755 template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() { 1756 uint32_t Index = 0; 1757 Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections = 1758 ElfFile.sections(); 1759 if (!Sections) 1760 return Sections.takeError(); 1761 1762 for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) { 1763 if (Index == 0) { 1764 ++Index; 1765 continue; 1766 } 1767 Expected<SectionBase &> Sec = makeSection(Shdr); 1768 if (!Sec) 1769 return Sec.takeError(); 1770 1771 Expected<StringRef> SecName = ElfFile.getSectionName(Shdr); 1772 if (!SecName) 1773 return SecName.takeError(); 1774 Sec->Name = SecName->str(); 1775 Sec->Type = Sec->OriginalType = Shdr.sh_type; 1776 Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags; 1777 Sec->Addr = Shdr.sh_addr; 1778 Sec->Offset = Shdr.sh_offset; 1779 Sec->OriginalOffset = Shdr.sh_offset; 1780 Sec->Size = Shdr.sh_size; 1781 Sec->Link = Shdr.sh_link; 1782 Sec->Info = Shdr.sh_info; 1783 Sec->Align = Shdr.sh_addralign; 1784 Sec->EntrySize = Shdr.sh_entsize; 1785 Sec->Index = Index++; 1786 Sec->OriginalIndex = Sec->Index; 1787 Sec->OriginalData = ArrayRef<uint8_t>( 1788 ElfFile.base() + Shdr.sh_offset, 1789 (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size); 1790 } 1791 1792 return Error::success(); 1793 } 1794 1795 template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) { 1796 uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx; 1797 if (ShstrIndex == SHN_XINDEX) { 1798 Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0); 1799 if (!Sec) 1800 return Sec.takeError(); 1801 1802 ShstrIndex = (*Sec)->sh_link; 1803 } 1804 1805 if (ShstrIndex == SHN_UNDEF) 1806 Obj.HadShdrs = false; 1807 else { 1808 Expected<StringTableSection *> Sec = 1809 Obj.sections().template getSectionOfType<StringTableSection>( 1810 ShstrIndex, 1811 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " + 1812 " is invalid", 1813 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " + 1814 " does not reference a string table"); 1815 if (!Sec) 1816 return Sec.takeError(); 1817 1818 Obj.SectionNames = *Sec; 1819 } 1820 1821 // If a section index table exists we'll need to initialize it before we 1822 // initialize the symbol table because the symbol table might need to 1823 // reference it. 1824 if (Obj.SectionIndexTable) 1825 if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections())) 1826 return Err; 1827 1828 // Now that all of the sections have been added we can fill out some extra 1829 // details about symbol tables. We need the symbol table filled out before 1830 // any relocations. 1831 if (Obj.SymbolTable) { 1832 if (Error Err = Obj.SymbolTable->initialize(Obj.sections())) 1833 return Err; 1834 if (Error Err = initSymbolTable(Obj.SymbolTable)) 1835 return Err; 1836 } else if (EnsureSymtab) { 1837 if (Error Err = Obj.addNewSymbolTable()) 1838 return Err; 1839 } 1840 1841 // Now that all sections and symbols have been added we can add 1842 // relocations that reference symbols and set the link and info fields for 1843 // relocation sections. 1844 for (SectionBase &Sec : Obj.sections()) { 1845 if (&Sec == Obj.SymbolTable) 1846 continue; 1847 if (Error Err = Sec.initialize(Obj.sections())) 1848 return Err; 1849 if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) { 1850 Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections = 1851 ElfFile.sections(); 1852 if (!Sections) 1853 return Sections.takeError(); 1854 1855 const typename ELFFile<ELFT>::Elf_Shdr *Shdr = 1856 Sections->begin() + RelSec->Index; 1857 if (RelSec->Type == SHT_REL) { 1858 Expected<typename ELFFile<ELFT>::Elf_Rel_Range> Rels = 1859 ElfFile.rels(*Shdr); 1860 if (!Rels) 1861 return Rels.takeError(); 1862 1863 if (Error Err = initRelocations(RelSec, *Rels)) 1864 return Err; 1865 } else { 1866 Expected<typename ELFFile<ELFT>::Elf_Rela_Range> Relas = 1867 ElfFile.relas(*Shdr); 1868 if (!Relas) 1869 return Relas.takeError(); 1870 1871 if (Error Err = initRelocations(RelSec, *Relas)) 1872 return Err; 1873 } 1874 } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) { 1875 if (Error Err = initGroupSection(GroupSec)) 1876 return Err; 1877 } 1878 } 1879 1880 return Error::success(); 1881 } 1882 1883 template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) { 1884 if (Error E = readSectionHeaders()) 1885 return E; 1886 if (Error E = findEhdrOffset()) 1887 return E; 1888 1889 // The ELFFile whose ELF headers and program headers are copied into the 1890 // output file. Normally the same as ElfFile, but if we're extracting a 1891 // loadable partition it will point to the partition's headers. 1892 Expected<ELFFile<ELFT>> HeadersFile = ELFFile<ELFT>::create(toStringRef( 1893 {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset})); 1894 if (!HeadersFile) 1895 return HeadersFile.takeError(); 1896 1897 const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader(); 1898 Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64; 1899 Obj.OSABI = Ehdr.e_ident[EI_OSABI]; 1900 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION]; 1901 Obj.Type = Ehdr.e_type; 1902 Obj.Machine = Ehdr.e_machine; 1903 Obj.Version = Ehdr.e_version; 1904 Obj.Entry = Ehdr.e_entry; 1905 Obj.Flags = Ehdr.e_flags; 1906 1907 if (Error E = readSections(EnsureSymtab)) 1908 return E; 1909 return readProgramHeaders(*HeadersFile); 1910 } 1911 1912 Writer::~Writer() = default; 1913 1914 Reader::~Reader() = default; 1915 1916 Expected<std::unique_ptr<Object>> 1917 BinaryReader::create(bool /*EnsureSymtab*/) const { 1918 return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build(); 1919 } 1920 1921 Expected<std::vector<IHexRecord>> IHexReader::parse() const { 1922 SmallVector<StringRef, 16> Lines; 1923 std::vector<IHexRecord> Records; 1924 bool HasSections = false; 1925 1926 MemBuf->getBuffer().split(Lines, '\n'); 1927 Records.reserve(Lines.size()); 1928 for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) { 1929 StringRef Line = Lines[LineNo - 1].trim(); 1930 if (Line.empty()) 1931 continue; 1932 1933 Expected<IHexRecord> R = IHexRecord::parse(Line); 1934 if (!R) 1935 return parseError(LineNo, R.takeError()); 1936 if (R->Type == IHexRecord::EndOfFile) 1937 break; 1938 HasSections |= (R->Type == IHexRecord::Data); 1939 Records.push_back(*R); 1940 } 1941 if (!HasSections) 1942 return parseError(-1U, "no sections"); 1943 1944 return std::move(Records); 1945 } 1946 1947 Expected<std::unique_ptr<Object>> 1948 IHexReader::create(bool /*EnsureSymtab*/) const { 1949 Expected<std::vector<IHexRecord>> Records = parse(); 1950 if (!Records) 1951 return Records.takeError(); 1952 1953 return IHexELFBuilder(*Records).build(); 1954 } 1955 1956 Expected<std::unique_ptr<Object>> ELFReader::create(bool EnsureSymtab) const { 1957 auto Obj = std::make_unique<Object>(); 1958 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) { 1959 ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition); 1960 if (Error Err = Builder.build(EnsureSymtab)) 1961 return std::move(Err); 1962 return std::move(Obj); 1963 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) { 1964 ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition); 1965 if (Error Err = Builder.build(EnsureSymtab)) 1966 return std::move(Err); 1967 return std::move(Obj); 1968 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) { 1969 ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition); 1970 if (Error Err = Builder.build(EnsureSymtab)) 1971 return std::move(Err); 1972 return std::move(Obj); 1973 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) { 1974 ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition); 1975 if (Error Err = Builder.build(EnsureSymtab)) 1976 return std::move(Err); 1977 return std::move(Obj); 1978 } 1979 return createStringError(errc::invalid_argument, "invalid file type"); 1980 } 1981 1982 template <class ELFT> void ELFWriter<ELFT>::writeEhdr() { 1983 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart()); 1984 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0); 1985 Ehdr.e_ident[EI_MAG0] = 0x7f; 1986 Ehdr.e_ident[EI_MAG1] = 'E'; 1987 Ehdr.e_ident[EI_MAG2] = 'L'; 1988 Ehdr.e_ident[EI_MAG3] = 'F'; 1989 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32; 1990 Ehdr.e_ident[EI_DATA] = 1991 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB; 1992 Ehdr.e_ident[EI_VERSION] = EV_CURRENT; 1993 Ehdr.e_ident[EI_OSABI] = Obj.OSABI; 1994 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion; 1995 1996 Ehdr.e_type = Obj.Type; 1997 Ehdr.e_machine = Obj.Machine; 1998 Ehdr.e_version = Obj.Version; 1999 Ehdr.e_entry = Obj.Entry; 2000 // We have to use the fully-qualified name llvm::size 2001 // since some compilers complain on ambiguous resolution. 2002 Ehdr.e_phnum = llvm::size(Obj.segments()); 2003 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0; 2004 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0; 2005 Ehdr.e_flags = Obj.Flags; 2006 Ehdr.e_ehsize = sizeof(Elf_Ehdr); 2007 if (WriteSectionHeaders && Obj.sections().size() != 0) { 2008 Ehdr.e_shentsize = sizeof(Elf_Shdr); 2009 Ehdr.e_shoff = Obj.SHOff; 2010 // """ 2011 // If the number of sections is greater than or equal to 2012 // SHN_LORESERVE (0xff00), this member has the value zero and the actual 2013 // number of section header table entries is contained in the sh_size field 2014 // of the section header at index 0. 2015 // """ 2016 auto Shnum = Obj.sections().size() + 1; 2017 if (Shnum >= SHN_LORESERVE) 2018 Ehdr.e_shnum = 0; 2019 else 2020 Ehdr.e_shnum = Shnum; 2021 // """ 2022 // If the section name string table section index is greater than or equal 2023 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff) 2024 // and the actual index of the section name string table section is 2025 // contained in the sh_link field of the section header at index 0. 2026 // """ 2027 if (Obj.SectionNames->Index >= SHN_LORESERVE) 2028 Ehdr.e_shstrndx = SHN_XINDEX; 2029 else 2030 Ehdr.e_shstrndx = Obj.SectionNames->Index; 2031 } else { 2032 Ehdr.e_shentsize = 0; 2033 Ehdr.e_shoff = 0; 2034 Ehdr.e_shnum = 0; 2035 Ehdr.e_shstrndx = 0; 2036 } 2037 } 2038 2039 template <class ELFT> void ELFWriter<ELFT>::writePhdrs() { 2040 for (auto &Seg : Obj.segments()) 2041 writePhdr(Seg); 2042 } 2043 2044 template <class ELFT> void ELFWriter<ELFT>::writeShdrs() { 2045 // This reference serves to write the dummy section header at the begining 2046 // of the file. It is not used for anything else 2047 Elf_Shdr &Shdr = 2048 *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff); 2049 Shdr.sh_name = 0; 2050 Shdr.sh_type = SHT_NULL; 2051 Shdr.sh_flags = 0; 2052 Shdr.sh_addr = 0; 2053 Shdr.sh_offset = 0; 2054 // See writeEhdr for why we do this. 2055 uint64_t Shnum = Obj.sections().size() + 1; 2056 if (Shnum >= SHN_LORESERVE) 2057 Shdr.sh_size = Shnum; 2058 else 2059 Shdr.sh_size = 0; 2060 // See writeEhdr for why we do this. 2061 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE) 2062 Shdr.sh_link = Obj.SectionNames->Index; 2063 else 2064 Shdr.sh_link = 0; 2065 Shdr.sh_info = 0; 2066 Shdr.sh_addralign = 0; 2067 Shdr.sh_entsize = 0; 2068 2069 for (SectionBase &Sec : Obj.sections()) 2070 writeShdr(Sec); 2071 } 2072 2073 template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() { 2074 for (SectionBase &Sec : Obj.sections()) 2075 // Segments are responsible for writing their contents, so only write the 2076 // section data if the section is not in a segment. Note that this renders 2077 // sections in segments effectively immutable. 2078 if (Sec.ParentSegment == nullptr) 2079 if (Error Err = Sec.accept(*SecWriter)) 2080 return Err; 2081 2082 return Error::success(); 2083 } 2084 2085 template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() { 2086 for (Segment &Seg : Obj.segments()) { 2087 size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size()); 2088 std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(), 2089 Size); 2090 } 2091 2092 for (auto it : Obj.getUpdatedSections()) { 2093 SectionBase *Sec = it.first; 2094 ArrayRef<uint8_t> Data = it.second; 2095 2096 auto *Parent = Sec->ParentSegment; 2097 assert(Parent && "This section should've been part of a segment."); 2098 uint64_t Offset = 2099 Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset; 2100 llvm::copy(Data, Buf->getBufferStart() + Offset); 2101 } 2102 2103 // Iterate over removed sections and overwrite their old data with zeroes. 2104 for (auto &Sec : Obj.removedSections()) { 2105 Segment *Parent = Sec.ParentSegment; 2106 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0) 2107 continue; 2108 uint64_t Offset = 2109 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset; 2110 std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size); 2111 } 2112 } 2113 2114 template <class ELFT> 2115 ELFWriter<ELFT>::ELFWriter(Object &Obj, raw_ostream &Buf, bool WSH, 2116 bool OnlyKeepDebug) 2117 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs), 2118 OnlyKeepDebug(OnlyKeepDebug) {} 2119 2120 Error Object::updateSection(StringRef Name, ArrayRef<uint8_t> Data) { 2121 auto It = llvm::find_if(Sections, 2122 [&](const SecPtr &Sec) { return Sec->Name == Name; }); 2123 if (It == Sections.end()) 2124 return createStringError(errc::invalid_argument, "section '%s' not found", 2125 Name.str().c_str()); 2126 2127 auto *OldSec = It->get(); 2128 if (!OldSec->hasContents()) 2129 return createStringError( 2130 errc::invalid_argument, 2131 "section '%s' cannot be updated because it does not have contents", 2132 Name.str().c_str()); 2133 2134 if (Data.size() > OldSec->Size && OldSec->ParentSegment) 2135 return createStringError(errc::invalid_argument, 2136 "cannot fit data of size %zu into section '%s' " 2137 "with size %" PRIu64 " that is part of a segment", 2138 Data.size(), Name.str().c_str(), OldSec->Size); 2139 2140 if (!OldSec->ParentSegment) { 2141 *It = std::make_unique<OwnedDataSection>(*OldSec, Data); 2142 } else { 2143 // The segment writer will be in charge of updating these contents. 2144 OldSec->Size = Data.size(); 2145 UpdatedSections[OldSec] = Data; 2146 } 2147 2148 return Error::success(); 2149 } 2150 2151 Error Object::removeSections( 2152 bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) { 2153 2154 auto Iter = std::stable_partition( 2155 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) { 2156 if (ToRemove(*Sec)) 2157 return false; 2158 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) { 2159 if (auto ToRelSec = RelSec->getSection()) 2160 return !ToRemove(*ToRelSec); 2161 } 2162 return true; 2163 }); 2164 if (SymbolTable != nullptr && ToRemove(*SymbolTable)) 2165 SymbolTable = nullptr; 2166 if (SectionNames != nullptr && ToRemove(*SectionNames)) 2167 SectionNames = nullptr; 2168 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable)) 2169 SectionIndexTable = nullptr; 2170 // Now make sure there are no remaining references to the sections that will 2171 // be removed. Sometimes it is impossible to remove a reference so we emit 2172 // an error here instead. 2173 std::unordered_set<const SectionBase *> RemoveSections; 2174 RemoveSections.reserve(std::distance(Iter, std::end(Sections))); 2175 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) { 2176 for (auto &Segment : Segments) 2177 Segment->removeSection(RemoveSec.get()); 2178 RemoveSec->onRemove(); 2179 RemoveSections.insert(RemoveSec.get()); 2180 } 2181 2182 // For each section that remains alive, we want to remove the dead references. 2183 // This either might update the content of the section (e.g. remove symbols 2184 // from symbol table that belongs to removed section) or trigger an error if 2185 // a live section critically depends on a section being removed somehow 2186 // (e.g. the removed section is referenced by a relocation). 2187 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) { 2188 if (Error E = KeepSec->removeSectionReferences( 2189 AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) { 2190 return RemoveSections.find(Sec) != RemoveSections.end(); 2191 })) 2192 return E; 2193 } 2194 2195 // Transfer removed sections into the Object RemovedSections container for use 2196 // later. 2197 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections)); 2198 // Now finally get rid of them all together. 2199 Sections.erase(Iter, std::end(Sections)); 2200 return Error::success(); 2201 } 2202 2203 Error Object::replaceSections( 2204 const DenseMap<SectionBase *, SectionBase *> &FromTo) { 2205 auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) { 2206 return Lhs->Index < Rhs->Index; 2207 }; 2208 assert(llvm::is_sorted(Sections, SectionIndexLess) && 2209 "Sections are expected to be sorted by Index"); 2210 // Set indices of new sections so that they can be later sorted into positions 2211 // of removed ones. 2212 for (auto &I : FromTo) 2213 I.second->Index = I.first->Index; 2214 2215 // Notify all sections about the replacement. 2216 for (auto &Sec : Sections) 2217 Sec->replaceSectionReferences(FromTo); 2218 2219 if (Error E = removeSections( 2220 /*AllowBrokenLinks=*/false, 2221 [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; })) 2222 return E; 2223 llvm::sort(Sections, SectionIndexLess); 2224 return Error::success(); 2225 } 2226 2227 Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) { 2228 if (SymbolTable) 2229 for (const SecPtr &Sec : Sections) 2230 if (Error E = Sec->removeSymbols(ToRemove)) 2231 return E; 2232 return Error::success(); 2233 } 2234 2235 Error Object::addNewSymbolTable() { 2236 assert(!SymbolTable && "Object must not has a SymbolTable."); 2237 2238 // Reuse an existing SHT_STRTAB section if it exists. 2239 StringTableSection *StrTab = nullptr; 2240 for (SectionBase &Sec : sections()) { 2241 if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) { 2242 StrTab = static_cast<StringTableSection *>(&Sec); 2243 2244 // Prefer a string table that is not the section header string table, if 2245 // such a table exists. 2246 if (SectionNames != &Sec) 2247 break; 2248 } 2249 } 2250 if (!StrTab) 2251 StrTab = &addSection<StringTableSection>(); 2252 2253 SymbolTableSection &SymTab = addSection<SymbolTableSection>(); 2254 SymTab.Name = ".symtab"; 2255 SymTab.Link = StrTab->Index; 2256 if (Error Err = SymTab.initialize(sections())) 2257 return Err; 2258 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0); 2259 2260 SymbolTable = &SymTab; 2261 2262 return Error::success(); 2263 } 2264 2265 // Orders segments such that if x = y->ParentSegment then y comes before x. 2266 static void orderSegments(std::vector<Segment *> &Segments) { 2267 llvm::stable_sort(Segments, compareSegmentsByOffset); 2268 } 2269 2270 // This function finds a consistent layout for a list of segments starting from 2271 // an Offset. It assumes that Segments have been sorted by orderSegments and 2272 // returns an Offset one past the end of the last segment. 2273 static uint64_t layoutSegments(std::vector<Segment *> &Segments, 2274 uint64_t Offset) { 2275 assert(llvm::is_sorted(Segments, compareSegmentsByOffset)); 2276 // The only way a segment should move is if a section was between two 2277 // segments and that section was removed. If that section isn't in a segment 2278 // then it's acceptable, but not ideal, to simply move it to after the 2279 // segments. So we can simply layout segments one after the other accounting 2280 // for alignment. 2281 for (Segment *Seg : Segments) { 2282 // We assume that segments have been ordered by OriginalOffset and Index 2283 // such that a parent segment will always come before a child segment in 2284 // OrderedSegments. This means that the Offset of the ParentSegment should 2285 // already be set and we can set our offset relative to it. 2286 if (Seg->ParentSegment != nullptr) { 2287 Segment *Parent = Seg->ParentSegment; 2288 Seg->Offset = 2289 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset; 2290 } else { 2291 Seg->Offset = 2292 alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr); 2293 } 2294 Offset = std::max(Offset, Seg->Offset + Seg->FileSize); 2295 } 2296 return Offset; 2297 } 2298 2299 // This function finds a consistent layout for a list of sections. It assumes 2300 // that the ->ParentSegment of each section has already been laid out. The 2301 // supplied starting Offset is used for the starting offset of any section that 2302 // does not have a ParentSegment. It returns either the offset given if all 2303 // sections had a ParentSegment or an offset one past the last section if there 2304 // was a section that didn't have a ParentSegment. 2305 template <class Range> 2306 static uint64_t layoutSections(Range Sections, uint64_t Offset) { 2307 // Now the offset of every segment has been set we can assign the offsets 2308 // of each section. For sections that are covered by a segment we should use 2309 // the segment's original offset and the section's original offset to compute 2310 // the offset from the start of the segment. Using the offset from the start 2311 // of the segment we can assign a new offset to the section. For sections not 2312 // covered by segments we can just bump Offset to the next valid location. 2313 // While it is not necessary, layout the sections in the order based on their 2314 // original offsets to resemble the input file as close as possible. 2315 std::vector<SectionBase *> OutOfSegmentSections; 2316 uint32_t Index = 1; 2317 for (auto &Sec : Sections) { 2318 Sec.Index = Index++; 2319 if (Sec.ParentSegment != nullptr) { 2320 const Segment &Segment = *Sec.ParentSegment; 2321 Sec.Offset = 2322 Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset); 2323 } else 2324 OutOfSegmentSections.push_back(&Sec); 2325 } 2326 2327 llvm::stable_sort(OutOfSegmentSections, 2328 [](const SectionBase *Lhs, const SectionBase *Rhs) { 2329 return Lhs->OriginalOffset < Rhs->OriginalOffset; 2330 }); 2331 for (auto *Sec : OutOfSegmentSections) { 2332 Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align); 2333 Sec->Offset = Offset; 2334 if (Sec->Type != SHT_NOBITS) 2335 Offset += Sec->Size; 2336 } 2337 return Offset; 2338 } 2339 2340 // Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus 2341 // occupy no space in the file. 2342 static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off) { 2343 // The layout algorithm requires the sections to be handled in the order of 2344 // their offsets in the input file, at least inside segments. 2345 std::vector<SectionBase *> Sections; 2346 Sections.reserve(Obj.sections().size()); 2347 uint32_t Index = 1; 2348 for (auto &Sec : Obj.sections()) { 2349 Sec.Index = Index++; 2350 Sections.push_back(&Sec); 2351 } 2352 llvm::stable_sort(Sections, 2353 [](const SectionBase *Lhs, const SectionBase *Rhs) { 2354 return Lhs->OriginalOffset < Rhs->OriginalOffset; 2355 }); 2356 2357 for (auto *Sec : Sections) { 2358 auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD 2359 ? Sec->ParentSegment->firstSection() 2360 : nullptr; 2361 2362 // The first section in a PT_LOAD has to have congruent offset and address 2363 // modulo the alignment, which usually equals the maximum page size. 2364 if (FirstSec && FirstSec == Sec) 2365 Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr); 2366 2367 // sh_offset is not significant for SHT_NOBITS sections, but the congruence 2368 // rule must be followed if it is the first section in a PT_LOAD. Do not 2369 // advance Off. 2370 if (Sec->Type == SHT_NOBITS) { 2371 Sec->Offset = Off; 2372 continue; 2373 } 2374 2375 if (!FirstSec) { 2376 // FirstSec being nullptr generally means that Sec does not have the 2377 // SHF_ALLOC flag. 2378 Off = Sec->Align ? alignTo(Off, Sec->Align) : Off; 2379 } else if (FirstSec != Sec) { 2380 // The offset is relative to the first section in the PT_LOAD segment. Use 2381 // sh_offset for non-SHF_ALLOC sections. 2382 Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset; 2383 } 2384 Sec->Offset = Off; 2385 Off += Sec->Size; 2386 } 2387 return Off; 2388 } 2389 2390 // Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values 2391 // have been updated. 2392 static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments, 2393 uint64_t HdrEnd) { 2394 uint64_t MaxOffset = 0; 2395 for (Segment *Seg : Segments) { 2396 if (Seg->Type == PT_PHDR) 2397 continue; 2398 2399 // The segment offset is generally the offset of the first section. 2400 // 2401 // For a segment containing no section (see sectionWithinSegment), if it has 2402 // a parent segment, copy the parent segment's offset field. This works for 2403 // empty PT_TLS. If no parent segment, use 0: the segment is not useful for 2404 // debugging anyway. 2405 const SectionBase *FirstSec = Seg->firstSection(); 2406 uint64_t Offset = 2407 FirstSec ? FirstSec->Offset 2408 : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0); 2409 uint64_t FileSize = 0; 2410 for (const SectionBase *Sec : Seg->Sections) { 2411 uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size; 2412 if (Sec->Offset + Size > Offset) 2413 FileSize = std::max(FileSize, Sec->Offset + Size - Offset); 2414 } 2415 2416 // If the segment includes EHDR and program headers, don't make it smaller 2417 // than the headers. 2418 if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) { 2419 FileSize += Offset - Seg->Offset; 2420 Offset = Seg->Offset; 2421 FileSize = std::max(FileSize, HdrEnd - Offset); 2422 } 2423 2424 Seg->Offset = Offset; 2425 Seg->FileSize = FileSize; 2426 MaxOffset = std::max(MaxOffset, Offset + FileSize); 2427 } 2428 return MaxOffset; 2429 } 2430 2431 template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() { 2432 Segment &ElfHdr = Obj.ElfHdrSegment; 2433 ElfHdr.Type = PT_PHDR; 2434 ElfHdr.Flags = 0; 2435 ElfHdr.VAddr = 0; 2436 ElfHdr.PAddr = 0; 2437 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr); 2438 ElfHdr.Align = 0; 2439 } 2440 2441 template <class ELFT> void ELFWriter<ELFT>::assignOffsets() { 2442 // We need a temporary list of segments that has a special order to it 2443 // so that we know that anytime ->ParentSegment is set that segment has 2444 // already had its offset properly set. 2445 std::vector<Segment *> OrderedSegments; 2446 for (Segment &Segment : Obj.segments()) 2447 OrderedSegments.push_back(&Segment); 2448 OrderedSegments.push_back(&Obj.ElfHdrSegment); 2449 OrderedSegments.push_back(&Obj.ProgramHdrSegment); 2450 orderSegments(OrderedSegments); 2451 2452 uint64_t Offset; 2453 if (OnlyKeepDebug) { 2454 // For --only-keep-debug, the sections that did not preserve contents were 2455 // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and 2456 // then rewrite p_offset/p_filesz of program headers. 2457 uint64_t HdrEnd = 2458 sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr); 2459 Offset = layoutSectionsForOnlyKeepDebug(Obj, HdrEnd); 2460 Offset = std::max(Offset, 2461 layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd)); 2462 } else { 2463 // Offset is used as the start offset of the first segment to be laid out. 2464 // Since the ELF Header (ElfHdrSegment) must be at the start of the file, 2465 // we start at offset 0. 2466 Offset = layoutSegments(OrderedSegments, 0); 2467 Offset = layoutSections(Obj.sections(), Offset); 2468 } 2469 // If we need to write the section header table out then we need to align the 2470 // Offset so that SHOffset is valid. 2471 if (WriteSectionHeaders) 2472 Offset = alignTo(Offset, sizeof(Elf_Addr)); 2473 Obj.SHOff = Offset; 2474 } 2475 2476 template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const { 2477 // We already have the section header offset so we can calculate the total 2478 // size by just adding up the size of each section header. 2479 if (!WriteSectionHeaders) 2480 return Obj.SHOff; 2481 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr. 2482 return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr); 2483 } 2484 2485 template <class ELFT> Error ELFWriter<ELFT>::write() { 2486 // Segment data must be written first, so that the ELF header and program 2487 // header tables can overwrite it, if covered by a segment. 2488 writeSegmentData(); 2489 writeEhdr(); 2490 writePhdrs(); 2491 if (Error E = writeSectionData()) 2492 return E; 2493 if (WriteSectionHeaders) 2494 writeShdrs(); 2495 2496 // TODO: Implement direct writing to the output stream (without intermediate 2497 // memory buffer Buf). 2498 Out.write(Buf->getBufferStart(), Buf->getBufferSize()); 2499 return Error::success(); 2500 } 2501 2502 static Error removeUnneededSections(Object &Obj) { 2503 // We can remove an empty symbol table from non-relocatable objects. 2504 // Relocatable objects typically have relocation sections whose 2505 // sh_link field points to .symtab, so we can't remove .symtab 2506 // even if it is empty. 2507 if (Obj.isRelocatable() || Obj.SymbolTable == nullptr || 2508 !Obj.SymbolTable->empty()) 2509 return Error::success(); 2510 2511 // .strtab can be used for section names. In such a case we shouldn't 2512 // remove it. 2513 auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames 2514 ? nullptr 2515 : Obj.SymbolTable->getStrTab(); 2516 return Obj.removeSections(false, [&](const SectionBase &Sec) { 2517 return &Sec == Obj.SymbolTable || &Sec == StrTab; 2518 }); 2519 } 2520 2521 template <class ELFT> Error ELFWriter<ELFT>::finalize() { 2522 // It could happen that SectionNames has been removed and yet the user wants 2523 // a section header table output. We need to throw an error if a user tries 2524 // to do that. 2525 if (Obj.SectionNames == nullptr && WriteSectionHeaders) 2526 return createStringError(llvm::errc::invalid_argument, 2527 "cannot write section header table because " 2528 "section header string table was removed"); 2529 2530 if (Error E = removeUnneededSections(Obj)) 2531 return E; 2532 2533 // If the .symtab indices have not been changed, restore the sh_link to 2534 // .symtab for sections that were linked to .symtab. 2535 if (Obj.SymbolTable && !Obj.SymbolTable->indicesChanged()) 2536 for (SectionBase &Sec : Obj.sections()) 2537 Sec.restoreSymTabLink(*Obj.SymbolTable); 2538 2539 // We need to assign indexes before we perform layout because we need to know 2540 // if we need large indexes or not. We can assign indexes first and check as 2541 // we go to see if we will actully need large indexes. 2542 bool NeedsLargeIndexes = false; 2543 if (Obj.sections().size() >= SHN_LORESERVE) { 2544 SectionTableRef Sections = Obj.sections(); 2545 // Sections doesn't include the null section header, so account for this 2546 // when skipping the first N sections. 2547 NeedsLargeIndexes = 2548 any_of(drop_begin(Sections, SHN_LORESERVE - 1), 2549 [](const SectionBase &Sec) { return Sec.HasSymbol; }); 2550 // TODO: handle case where only one section needs the large index table but 2551 // only needs it because the large index table hasn't been removed yet. 2552 } 2553 2554 if (NeedsLargeIndexes) { 2555 // This means we definitely need to have a section index table but if we 2556 // already have one then we should use it instead of making a new one. 2557 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) { 2558 // Addition of a section to the end does not invalidate the indexes of 2559 // other sections and assigns the correct index to the new section. 2560 auto &Shndx = Obj.addSection<SectionIndexSection>(); 2561 Obj.SymbolTable->setShndxTable(&Shndx); 2562 Shndx.setSymTab(Obj.SymbolTable); 2563 } 2564 } else { 2565 // Since we don't need SectionIndexTable we should remove it and all 2566 // references to it. 2567 if (Obj.SectionIndexTable != nullptr) { 2568 // We do not support sections referring to the section index table. 2569 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/, 2570 [this](const SectionBase &Sec) { 2571 return &Sec == Obj.SectionIndexTable; 2572 })) 2573 return E; 2574 } 2575 } 2576 2577 // Make sure we add the names of all the sections. Importantly this must be 2578 // done after we decide to add or remove SectionIndexes. 2579 if (Obj.SectionNames != nullptr) 2580 for (const SectionBase &Sec : Obj.sections()) 2581 Obj.SectionNames->addString(Sec.Name); 2582 2583 initEhdrSegment(); 2584 2585 // Before we can prepare for layout the indexes need to be finalized. 2586 // Also, the output arch may not be the same as the input arch, so fix up 2587 // size-related fields before doing layout calculations. 2588 uint64_t Index = 0; 2589 auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>(); 2590 for (SectionBase &Sec : Obj.sections()) { 2591 Sec.Index = Index++; 2592 if (Error Err = Sec.accept(*SecSizer)) 2593 return Err; 2594 } 2595 2596 // The symbol table does not update all other sections on update. For 2597 // instance, symbol names are not added as new symbols are added. This means 2598 // that some sections, like .strtab, don't yet have their final size. 2599 if (Obj.SymbolTable != nullptr) 2600 Obj.SymbolTable->prepareForLayout(); 2601 2602 // Now that all strings are added we want to finalize string table builders, 2603 // because that affects section sizes which in turn affects section offsets. 2604 for (SectionBase &Sec : Obj.sections()) 2605 if (auto StrTab = dyn_cast<StringTableSection>(&Sec)) 2606 StrTab->prepareForLayout(); 2607 2608 assignOffsets(); 2609 2610 // layoutSections could have modified section indexes, so we need 2611 // to fill the index table after assignOffsets. 2612 if (Obj.SymbolTable != nullptr) 2613 Obj.SymbolTable->fillShndxTable(); 2614 2615 // Finally now that all offsets and indexes have been set we can finalize any 2616 // remaining issues. 2617 uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr); 2618 for (SectionBase &Sec : Obj.sections()) { 2619 Sec.HeaderOffset = Offset; 2620 Offset += sizeof(Elf_Shdr); 2621 if (WriteSectionHeaders) 2622 Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name); 2623 Sec.finalize(); 2624 } 2625 2626 size_t TotalSize = totalSize(); 2627 Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize); 2628 if (!Buf) 2629 return createStringError(errc::not_enough_memory, 2630 "failed to allocate memory buffer of " + 2631 Twine::utohexstr(TotalSize) + " bytes"); 2632 2633 SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf); 2634 return Error::success(); 2635 } 2636 2637 Error BinaryWriter::write() { 2638 for (const SectionBase &Sec : Obj.allocSections()) 2639 if (Error Err = Sec.accept(*SecWriter)) 2640 return Err; 2641 2642 // TODO: Implement direct writing to the output stream (without intermediate 2643 // memory buffer Buf). 2644 Out.write(Buf->getBufferStart(), Buf->getBufferSize()); 2645 return Error::success(); 2646 } 2647 2648 Error BinaryWriter::finalize() { 2649 // Compute the section LMA based on its sh_offset and the containing segment's 2650 // p_offset and p_paddr. Also compute the minimum LMA of all non-empty 2651 // sections as MinAddr. In the output, the contents between address 0 and 2652 // MinAddr will be skipped. 2653 uint64_t MinAddr = UINT64_MAX; 2654 for (SectionBase &Sec : Obj.allocSections()) { 2655 if (Sec.ParentSegment != nullptr) 2656 Sec.Addr = 2657 Sec.Offset - Sec.ParentSegment->Offset + Sec.ParentSegment->PAddr; 2658 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) 2659 MinAddr = std::min(MinAddr, Sec.Addr); 2660 } 2661 2662 // Now that every section has been laid out we just need to compute the total 2663 // file size. This might not be the same as the offset returned by 2664 // layoutSections, because we want to truncate the last segment to the end of 2665 // its last non-empty section, to match GNU objcopy's behaviour. 2666 TotalSize = 0; 2667 for (SectionBase &Sec : Obj.allocSections()) 2668 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) { 2669 Sec.Offset = Sec.Addr - MinAddr; 2670 TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size); 2671 } 2672 2673 Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize); 2674 if (!Buf) 2675 return createStringError(errc::not_enough_memory, 2676 "failed to allocate memory buffer of " + 2677 Twine::utohexstr(TotalSize) + " bytes"); 2678 SecWriter = std::make_unique<BinarySectionWriter>(*Buf); 2679 return Error::success(); 2680 } 2681 2682 bool IHexWriter::SectionCompare::operator()(const SectionBase *Lhs, 2683 const SectionBase *Rhs) const { 2684 return (sectionPhysicalAddr(Lhs) & 0xFFFFFFFFU) < 2685 (sectionPhysicalAddr(Rhs) & 0xFFFFFFFFU); 2686 } 2687 2688 uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) { 2689 IHexLineData HexData; 2690 uint8_t Data[4] = {}; 2691 // We don't write entry point record if entry is zero. 2692 if (Obj.Entry == 0) 2693 return 0; 2694 2695 if (Obj.Entry <= 0xFFFFFU) { 2696 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF; 2697 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry), 2698 support::big); 2699 HexData = IHexRecord::getLine(IHexRecord::StartAddr80x86, 0, Data); 2700 } else { 2701 support::endian::write(Data, static_cast<uint32_t>(Obj.Entry), 2702 support::big); 2703 HexData = IHexRecord::getLine(IHexRecord::StartAddr, 0, Data); 2704 } 2705 memcpy(Buf, HexData.data(), HexData.size()); 2706 return HexData.size(); 2707 } 2708 2709 uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) { 2710 IHexLineData HexData = IHexRecord::getLine(IHexRecord::EndOfFile, 0, {}); 2711 memcpy(Buf, HexData.data(), HexData.size()); 2712 return HexData.size(); 2713 } 2714 2715 Error IHexWriter::write() { 2716 IHexSectionWriter Writer(*Buf); 2717 // Write sections. 2718 for (const SectionBase *Sec : Sections) 2719 if (Error Err = Sec->accept(Writer)) 2720 return Err; 2721 2722 uint64_t Offset = Writer.getBufferOffset(); 2723 // Write entry point address. 2724 Offset += writeEntryPointRecord( 2725 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset); 2726 // Write EOF. 2727 Offset += writeEndOfFileRecord( 2728 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset); 2729 assert(Offset == TotalSize); 2730 2731 // TODO: Implement direct writing to the output stream (without intermediate 2732 // memory buffer Buf). 2733 Out.write(Buf->getBufferStart(), Buf->getBufferSize()); 2734 return Error::success(); 2735 } 2736 2737 Error IHexWriter::checkSection(const SectionBase &Sec) { 2738 uint64_t Addr = sectionPhysicalAddr(&Sec); 2739 if (addressOverflows32bit(Addr) || addressOverflows32bit(Addr + Sec.Size - 1)) 2740 return createStringError( 2741 errc::invalid_argument, 2742 "Section '%s' address range [0x%llx, 0x%llx] is not 32 bit", 2743 Sec.Name.c_str(), Addr, Addr + Sec.Size - 1); 2744 return Error::success(); 2745 } 2746 2747 Error IHexWriter::finalize() { 2748 // We can't write 64-bit addresses. 2749 if (addressOverflows32bit(Obj.Entry)) 2750 return createStringError(errc::invalid_argument, 2751 "Entry point address 0x%llx overflows 32 bits", 2752 Obj.Entry); 2753 2754 for (const SectionBase &Sec : Obj.sections()) 2755 if ((Sec.Flags & ELF::SHF_ALLOC) && Sec.Type != ELF::SHT_NOBITS && 2756 Sec.Size > 0) { 2757 if (Error E = checkSection(Sec)) 2758 return E; 2759 Sections.insert(&Sec); 2760 } 2761 2762 std::unique_ptr<WritableMemoryBuffer> EmptyBuffer = 2763 WritableMemoryBuffer::getNewMemBuffer(0); 2764 if (!EmptyBuffer) 2765 return createStringError(errc::not_enough_memory, 2766 "failed to allocate memory buffer of 0 bytes"); 2767 2768 IHexSectionWriterBase LengthCalc(*EmptyBuffer); 2769 for (const SectionBase *Sec : Sections) 2770 if (Error Err = Sec->accept(LengthCalc)) 2771 return Err; 2772 2773 // We need space to write section records + StartAddress record 2774 // (if start adress is not zero) + EndOfFile record. 2775 TotalSize = LengthCalc.getBufferOffset() + 2776 (Obj.Entry ? IHexRecord::getLineLength(4) : 0) + 2777 IHexRecord::getLineLength(0); 2778 2779 Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize); 2780 if (!Buf) 2781 return createStringError(errc::not_enough_memory, 2782 "failed to allocate memory buffer of " + 2783 Twine::utohexstr(TotalSize) + " bytes"); 2784 2785 return Error::success(); 2786 } 2787 2788 namespace llvm { 2789 namespace objcopy { 2790 namespace elf { 2791 2792 template class ELFBuilder<ELF64LE>; 2793 template class ELFBuilder<ELF64BE>; 2794 template class ELFBuilder<ELF32LE>; 2795 template class ELFBuilder<ELF32BE>; 2796 2797 template class ELFWriter<ELF64LE>; 2798 template class ELFWriter<ELF64BE>; 2799 template class ELFWriter<ELF32LE>; 2800 template class ELFWriter<ELF32BE>; 2801 2802 } // end namespace elf 2803 } // end namespace objcopy 2804 } // end namespace llvm 2805