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