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