brintos

brintos / llvm-project-archived public Read only

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