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