xref: /freebsd-src/contrib/llvm-project/llvm/lib/ObjCopy/ELF/ELFObject.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
181ad6265SDimitry Andric //===- ELFObject.cpp ------------------------------------------------------===//
281ad6265SDimitry Andric //
381ad6265SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
481ad6265SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
581ad6265SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
681ad6265SDimitry Andric //
781ad6265SDimitry Andric //===----------------------------------------------------------------------===//
881ad6265SDimitry Andric 
981ad6265SDimitry Andric #include "ELFObject.h"
1081ad6265SDimitry Andric #include "llvm/ADT/ArrayRef.h"
1181ad6265SDimitry Andric #include "llvm/ADT/STLExtras.h"
1281ad6265SDimitry Andric #include "llvm/ADT/StringRef.h"
1381ad6265SDimitry Andric #include "llvm/ADT/Twine.h"
1481ad6265SDimitry Andric #include "llvm/ADT/iterator_range.h"
1581ad6265SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
1681ad6265SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
1781ad6265SDimitry Andric #include "llvm/Object/ELF.h"
1881ad6265SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
1981ad6265SDimitry Andric #include "llvm/Support/Compression.h"
2081ad6265SDimitry Andric #include "llvm/Support/Endian.h"
2181ad6265SDimitry Andric #include "llvm/Support/ErrorHandling.h"
2281ad6265SDimitry Andric #include "llvm/Support/FileOutputBuffer.h"
2381ad6265SDimitry Andric #include "llvm/Support/Path.h"
2481ad6265SDimitry Andric #include <algorithm>
2581ad6265SDimitry Andric #include <cstddef>
2681ad6265SDimitry Andric #include <cstdint>
2781ad6265SDimitry Andric #include <iterator>
2881ad6265SDimitry Andric #include <unordered_set>
2981ad6265SDimitry Andric #include <utility>
3081ad6265SDimitry Andric #include <vector>
3181ad6265SDimitry Andric 
3281ad6265SDimitry Andric using namespace llvm;
3381ad6265SDimitry Andric using namespace llvm::ELF;
3481ad6265SDimitry Andric using namespace llvm::objcopy::elf;
3581ad6265SDimitry Andric using namespace llvm::object;
3681ad6265SDimitry Andric 
3781ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
3881ad6265SDimitry Andric   uint8_t *B = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
3981ad6265SDimitry Andric                Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
4081ad6265SDimitry Andric   Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
4181ad6265SDimitry Andric   Phdr.p_type = Seg.Type;
4281ad6265SDimitry Andric   Phdr.p_flags = Seg.Flags;
4381ad6265SDimitry Andric   Phdr.p_offset = Seg.Offset;
4481ad6265SDimitry Andric   Phdr.p_vaddr = Seg.VAddr;
4581ad6265SDimitry Andric   Phdr.p_paddr = Seg.PAddr;
4681ad6265SDimitry Andric   Phdr.p_filesz = Seg.FileSize;
4781ad6265SDimitry Andric   Phdr.p_memsz = Seg.MemSize;
4881ad6265SDimitry Andric   Phdr.p_align = Seg.Align;
4981ad6265SDimitry Andric }
5081ad6265SDimitry Andric 
5181ad6265SDimitry Andric Error SectionBase::removeSectionReferences(
5281ad6265SDimitry Andric     bool, function_ref<bool(const SectionBase *)>) {
5381ad6265SDimitry Andric   return Error::success();
5481ad6265SDimitry Andric }
5581ad6265SDimitry Andric 
5681ad6265SDimitry Andric Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)>) {
5781ad6265SDimitry Andric   return Error::success();
5881ad6265SDimitry Andric }
5981ad6265SDimitry Andric 
6081ad6265SDimitry Andric Error SectionBase::initialize(SectionTableRef) { return Error::success(); }
6181ad6265SDimitry Andric void SectionBase::finalize() {}
6281ad6265SDimitry Andric void SectionBase::markSymbols() {}
6381ad6265SDimitry Andric void SectionBase::replaceSectionReferences(
6481ad6265SDimitry Andric     const DenseMap<SectionBase *, SectionBase *> &) {}
6581ad6265SDimitry Andric void SectionBase::onRemove() {}
6681ad6265SDimitry Andric 
6781ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
6881ad6265SDimitry Andric   uint8_t *B =
6981ad6265SDimitry Andric       reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Sec.HeaderOffset;
7081ad6265SDimitry Andric   Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
7181ad6265SDimitry Andric   Shdr.sh_name = Sec.NameIndex;
7281ad6265SDimitry Andric   Shdr.sh_type = Sec.Type;
7381ad6265SDimitry Andric   Shdr.sh_flags = Sec.Flags;
7481ad6265SDimitry Andric   Shdr.sh_addr = Sec.Addr;
7581ad6265SDimitry Andric   Shdr.sh_offset = Sec.Offset;
7681ad6265SDimitry Andric   Shdr.sh_size = Sec.Size;
7781ad6265SDimitry Andric   Shdr.sh_link = Sec.Link;
7881ad6265SDimitry Andric   Shdr.sh_info = Sec.Info;
7981ad6265SDimitry Andric   Shdr.sh_addralign = Sec.Align;
8081ad6265SDimitry Andric   Shdr.sh_entsize = Sec.EntrySize;
8181ad6265SDimitry Andric }
8281ad6265SDimitry Andric 
8381ad6265SDimitry Andric template <class ELFT> Error ELFSectionSizer<ELFT>::visit(Section &) {
8481ad6265SDimitry Andric   return Error::success();
8581ad6265SDimitry Andric }
8681ad6265SDimitry Andric 
8781ad6265SDimitry Andric template <class ELFT> Error ELFSectionSizer<ELFT>::visit(OwnedDataSection &) {
8881ad6265SDimitry Andric   return Error::success();
8981ad6265SDimitry Andric }
9081ad6265SDimitry Andric 
9181ad6265SDimitry Andric template <class ELFT> Error ELFSectionSizer<ELFT>::visit(StringTableSection &) {
9281ad6265SDimitry Andric   return Error::success();
9381ad6265SDimitry Andric }
9481ad6265SDimitry Andric 
9581ad6265SDimitry Andric template <class ELFT>
9681ad6265SDimitry Andric Error ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &) {
9781ad6265SDimitry Andric   return Error::success();
9881ad6265SDimitry Andric }
9981ad6265SDimitry Andric 
10081ad6265SDimitry Andric template <class ELFT>
10181ad6265SDimitry Andric Error ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
10281ad6265SDimitry Andric   Sec.EntrySize = sizeof(Elf_Sym);
10381ad6265SDimitry Andric   Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
10481ad6265SDimitry Andric   // Align to the largest field in Elf_Sym.
10581ad6265SDimitry Andric   Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
10681ad6265SDimitry Andric   return Error::success();
10781ad6265SDimitry Andric }
10881ad6265SDimitry Andric 
10981ad6265SDimitry Andric template <class ELFT>
11081ad6265SDimitry Andric Error ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
11181ad6265SDimitry Andric   Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
11281ad6265SDimitry Andric   Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
11381ad6265SDimitry Andric   // Align to the largest field in Elf_Rel(a).
11481ad6265SDimitry Andric   Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
11581ad6265SDimitry Andric   return Error::success();
11681ad6265SDimitry Andric }
11781ad6265SDimitry Andric 
11881ad6265SDimitry Andric template <class ELFT>
11981ad6265SDimitry Andric Error ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &) {
12081ad6265SDimitry Andric   return Error::success();
12181ad6265SDimitry Andric }
12281ad6265SDimitry Andric 
12381ad6265SDimitry Andric template <class ELFT> Error ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {
12481ad6265SDimitry Andric   Sec.Size = sizeof(Elf_Word) + Sec.GroupMembers.size() * sizeof(Elf_Word);
12581ad6265SDimitry Andric   return Error::success();
12681ad6265SDimitry Andric }
12781ad6265SDimitry Andric 
12881ad6265SDimitry Andric template <class ELFT>
12981ad6265SDimitry Andric Error ELFSectionSizer<ELFT>::visit(SectionIndexSection &) {
13081ad6265SDimitry Andric   return Error::success();
13181ad6265SDimitry Andric }
13281ad6265SDimitry Andric 
13381ad6265SDimitry Andric template <class ELFT> Error ELFSectionSizer<ELFT>::visit(CompressedSection &) {
13481ad6265SDimitry Andric   return Error::success();
13581ad6265SDimitry Andric }
13681ad6265SDimitry Andric 
13781ad6265SDimitry Andric template <class ELFT>
13881ad6265SDimitry Andric Error ELFSectionSizer<ELFT>::visit(DecompressedSection &) {
13981ad6265SDimitry Andric   return Error::success();
14081ad6265SDimitry Andric }
14181ad6265SDimitry Andric 
14281ad6265SDimitry Andric Error BinarySectionWriter::visit(const SectionIndexSection &Sec) {
14381ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
14481ad6265SDimitry Andric                            "cannot write symbol section index table '" +
14581ad6265SDimitry Andric                                Sec.Name + "' ");
14681ad6265SDimitry Andric }
14781ad6265SDimitry Andric 
14881ad6265SDimitry Andric Error BinarySectionWriter::visit(const SymbolTableSection &Sec) {
14981ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
15081ad6265SDimitry Andric                            "cannot write symbol table '" + Sec.Name +
15181ad6265SDimitry Andric                                "' out to binary");
15281ad6265SDimitry Andric }
15381ad6265SDimitry Andric 
15481ad6265SDimitry Andric Error BinarySectionWriter::visit(const RelocationSection &Sec) {
15581ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
15681ad6265SDimitry Andric                            "cannot write relocation section '" + Sec.Name +
15781ad6265SDimitry Andric                                "' out to binary");
15881ad6265SDimitry Andric }
15981ad6265SDimitry Andric 
16081ad6265SDimitry Andric Error BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
16181ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
16281ad6265SDimitry Andric                            "cannot write '" + Sec.Name + "' out to binary");
16381ad6265SDimitry Andric }
16481ad6265SDimitry Andric 
16581ad6265SDimitry Andric Error BinarySectionWriter::visit(const GroupSection &Sec) {
16681ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
16781ad6265SDimitry Andric                            "cannot write '" + Sec.Name + "' out to binary");
16881ad6265SDimitry Andric }
16981ad6265SDimitry Andric 
17081ad6265SDimitry Andric Error SectionWriter::visit(const Section &Sec) {
17181ad6265SDimitry Andric   if (Sec.Type != SHT_NOBITS)
17281ad6265SDimitry Andric     llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
17381ad6265SDimitry Andric 
17481ad6265SDimitry Andric   return Error::success();
17581ad6265SDimitry Andric }
17681ad6265SDimitry Andric 
17781ad6265SDimitry Andric static bool addressOverflows32bit(uint64_t Addr) {
17881ad6265SDimitry Andric   // Sign extended 32 bit addresses (e.g 0xFFFFFFFF80000000) are ok
17981ad6265SDimitry Andric   return Addr > UINT32_MAX && Addr + 0x80000000 > UINT32_MAX;
18081ad6265SDimitry Andric }
18181ad6265SDimitry Andric 
18281ad6265SDimitry Andric template <class T> static T checkedGetHex(StringRef S) {
18381ad6265SDimitry Andric   T Value;
18481ad6265SDimitry Andric   bool Fail = S.getAsInteger(16, Value);
18581ad6265SDimitry Andric   assert(!Fail);
18681ad6265SDimitry Andric   (void)Fail;
18781ad6265SDimitry Andric   return Value;
18881ad6265SDimitry Andric }
18981ad6265SDimitry Andric 
19081ad6265SDimitry Andric // Fills exactly Len bytes of buffer with hexadecimal characters
19181ad6265SDimitry Andric // representing value 'X'
19281ad6265SDimitry Andric template <class T, class Iterator>
19381ad6265SDimitry Andric static Iterator toHexStr(T X, Iterator It, size_t Len) {
19481ad6265SDimitry Andric   // Fill range with '0'
19581ad6265SDimitry Andric   std::fill(It, It + Len, '0');
19681ad6265SDimitry Andric 
19781ad6265SDimitry Andric   for (long I = Len - 1; I >= 0; --I) {
19881ad6265SDimitry Andric     unsigned char Mod = static_cast<unsigned char>(X) & 15;
19981ad6265SDimitry Andric     *(It + I) = hexdigit(Mod, false);
20081ad6265SDimitry Andric     X >>= 4;
20181ad6265SDimitry Andric   }
20281ad6265SDimitry Andric   assert(X == 0);
20381ad6265SDimitry Andric   return It + Len;
20481ad6265SDimitry Andric }
20581ad6265SDimitry Andric 
20681ad6265SDimitry Andric uint8_t IHexRecord::getChecksum(StringRef S) {
20781ad6265SDimitry Andric   assert((S.size() & 1) == 0);
20881ad6265SDimitry Andric   uint8_t Checksum = 0;
20981ad6265SDimitry Andric   while (!S.empty()) {
21081ad6265SDimitry Andric     Checksum += checkedGetHex<uint8_t>(S.take_front(2));
21181ad6265SDimitry Andric     S = S.drop_front(2);
21281ad6265SDimitry Andric   }
21381ad6265SDimitry Andric   return -Checksum;
21481ad6265SDimitry Andric }
21581ad6265SDimitry Andric 
21681ad6265SDimitry Andric IHexLineData IHexRecord::getLine(uint8_t Type, uint16_t Addr,
21781ad6265SDimitry Andric                                  ArrayRef<uint8_t> Data) {
21881ad6265SDimitry Andric   IHexLineData Line(getLineLength(Data.size()));
21981ad6265SDimitry Andric   assert(Line.size());
22081ad6265SDimitry Andric   auto Iter = Line.begin();
22181ad6265SDimitry Andric   *Iter++ = ':';
22281ad6265SDimitry Andric   Iter = toHexStr(Data.size(), Iter, 2);
22381ad6265SDimitry Andric   Iter = toHexStr(Addr, Iter, 4);
22481ad6265SDimitry Andric   Iter = toHexStr(Type, Iter, 2);
22581ad6265SDimitry Andric   for (uint8_t X : Data)
22681ad6265SDimitry Andric     Iter = toHexStr(X, Iter, 2);
22781ad6265SDimitry Andric   StringRef S(Line.data() + 1, std::distance(Line.begin() + 1, Iter));
22881ad6265SDimitry Andric   Iter = toHexStr(getChecksum(S), Iter, 2);
22981ad6265SDimitry Andric   *Iter++ = '\r';
23081ad6265SDimitry Andric   *Iter++ = '\n';
23181ad6265SDimitry Andric   assert(Iter == Line.end());
23281ad6265SDimitry Andric   return Line;
23381ad6265SDimitry Andric }
23481ad6265SDimitry Andric 
23581ad6265SDimitry Andric static Error checkRecord(const IHexRecord &R) {
23681ad6265SDimitry Andric   switch (R.Type) {
23781ad6265SDimitry Andric   case IHexRecord::Data:
23881ad6265SDimitry Andric     if (R.HexData.size() == 0)
23981ad6265SDimitry Andric       return createStringError(
24081ad6265SDimitry Andric           errc::invalid_argument,
24181ad6265SDimitry Andric           "zero data length is not allowed for data records");
24281ad6265SDimitry Andric     break;
24381ad6265SDimitry Andric   case IHexRecord::EndOfFile:
24481ad6265SDimitry Andric     break;
24581ad6265SDimitry Andric   case IHexRecord::SegmentAddr:
24681ad6265SDimitry Andric     // 20-bit segment address. Data length must be 2 bytes
24781ad6265SDimitry Andric     // (4 bytes in hex)
24881ad6265SDimitry Andric     if (R.HexData.size() != 4)
24981ad6265SDimitry Andric       return createStringError(
25081ad6265SDimitry Andric           errc::invalid_argument,
25181ad6265SDimitry Andric           "segment address data should be 2 bytes in size");
25281ad6265SDimitry Andric     break;
25381ad6265SDimitry Andric   case IHexRecord::StartAddr80x86:
25481ad6265SDimitry Andric   case IHexRecord::StartAddr:
25581ad6265SDimitry Andric     if (R.HexData.size() != 8)
25681ad6265SDimitry Andric       return createStringError(errc::invalid_argument,
25781ad6265SDimitry Andric                                "start address data should be 4 bytes in size");
25881ad6265SDimitry Andric     // According to Intel HEX specification '03' record
25981ad6265SDimitry Andric     // only specifies the code address within the 20-bit
26081ad6265SDimitry Andric     // segmented address space of the 8086/80186. This
26181ad6265SDimitry Andric     // means 12 high order bits should be zeroes.
26281ad6265SDimitry Andric     if (R.Type == IHexRecord::StartAddr80x86 &&
26381ad6265SDimitry Andric         R.HexData.take_front(3) != "000")
26481ad6265SDimitry Andric       return createStringError(errc::invalid_argument,
26581ad6265SDimitry Andric                                "start address exceeds 20 bit for 80x86");
26681ad6265SDimitry Andric     break;
26781ad6265SDimitry Andric   case IHexRecord::ExtendedAddr:
26881ad6265SDimitry Andric     // 16-31 bits of linear base address
26981ad6265SDimitry Andric     if (R.HexData.size() != 4)
27081ad6265SDimitry Andric       return createStringError(
27181ad6265SDimitry Andric           errc::invalid_argument,
27281ad6265SDimitry Andric           "extended address data should be 2 bytes in size");
27381ad6265SDimitry Andric     break;
27481ad6265SDimitry Andric   default:
27581ad6265SDimitry Andric     // Unknown record type
27681ad6265SDimitry Andric     return createStringError(errc::invalid_argument, "unknown record type: %u",
27781ad6265SDimitry Andric                              static_cast<unsigned>(R.Type));
27881ad6265SDimitry Andric   }
27981ad6265SDimitry Andric   return Error::success();
28081ad6265SDimitry Andric }
28181ad6265SDimitry Andric 
28281ad6265SDimitry Andric // Checks that IHEX line contains valid characters.
28381ad6265SDimitry Andric // This allows converting hexadecimal data to integers
28481ad6265SDimitry Andric // without extra verification.
28581ad6265SDimitry Andric static Error checkChars(StringRef Line) {
28681ad6265SDimitry Andric   assert(!Line.empty());
28781ad6265SDimitry Andric   if (Line[0] != ':')
28881ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
28981ad6265SDimitry Andric                              "missing ':' in the beginning of line.");
29081ad6265SDimitry Andric 
29181ad6265SDimitry Andric   for (size_t Pos = 1; Pos < Line.size(); ++Pos)
29281ad6265SDimitry Andric     if (hexDigitValue(Line[Pos]) == -1U)
29381ad6265SDimitry Andric       return createStringError(errc::invalid_argument,
29481ad6265SDimitry Andric                                "invalid character at position %zu.", Pos + 1);
29581ad6265SDimitry Andric   return Error::success();
29681ad6265SDimitry Andric }
29781ad6265SDimitry Andric 
29881ad6265SDimitry Andric Expected<IHexRecord> IHexRecord::parse(StringRef Line) {
29981ad6265SDimitry Andric   assert(!Line.empty());
30081ad6265SDimitry Andric 
30181ad6265SDimitry Andric   // ':' + Length + Address + Type + Checksum with empty data ':LLAAAATTCC'
30281ad6265SDimitry Andric   if (Line.size() < 11)
30381ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
30481ad6265SDimitry Andric                              "line is too short: %zu chars.", Line.size());
30581ad6265SDimitry Andric 
30681ad6265SDimitry Andric   if (Error E = checkChars(Line))
30781ad6265SDimitry Andric     return std::move(E);
30881ad6265SDimitry Andric 
30981ad6265SDimitry Andric   IHexRecord Rec;
31081ad6265SDimitry Andric   size_t DataLen = checkedGetHex<uint8_t>(Line.substr(1, 2));
31181ad6265SDimitry Andric   if (Line.size() != getLength(DataLen))
31281ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
31381ad6265SDimitry Andric                              "invalid line length %zu (should be %zu)",
31481ad6265SDimitry Andric                              Line.size(), getLength(DataLen));
31581ad6265SDimitry Andric 
31681ad6265SDimitry Andric   Rec.Addr = checkedGetHex<uint16_t>(Line.substr(3, 4));
31781ad6265SDimitry Andric   Rec.Type = checkedGetHex<uint8_t>(Line.substr(7, 2));
31881ad6265SDimitry Andric   Rec.HexData = Line.substr(9, DataLen * 2);
31981ad6265SDimitry Andric 
32081ad6265SDimitry Andric   if (getChecksum(Line.drop_front(1)) != 0)
32181ad6265SDimitry Andric     return createStringError(errc::invalid_argument, "incorrect checksum.");
32281ad6265SDimitry Andric   if (Error E = checkRecord(Rec))
32381ad6265SDimitry Andric     return std::move(E);
32481ad6265SDimitry Andric   return Rec;
32581ad6265SDimitry Andric }
32681ad6265SDimitry Andric 
32781ad6265SDimitry Andric static uint64_t sectionPhysicalAddr(const SectionBase *Sec) {
32881ad6265SDimitry Andric   Segment *Seg = Sec->ParentSegment;
32981ad6265SDimitry Andric   if (Seg && Seg->Type != ELF::PT_LOAD)
33081ad6265SDimitry Andric     Seg = nullptr;
33181ad6265SDimitry Andric   return Seg ? Seg->PAddr + Sec->OriginalOffset - Seg->OriginalOffset
33281ad6265SDimitry Andric              : Sec->Addr;
33381ad6265SDimitry Andric }
33481ad6265SDimitry Andric 
33581ad6265SDimitry Andric void IHexSectionWriterBase::writeSection(const SectionBase *Sec,
33681ad6265SDimitry Andric                                          ArrayRef<uint8_t> Data) {
33781ad6265SDimitry Andric   assert(Data.size() == Sec->Size);
33881ad6265SDimitry Andric   const uint32_t ChunkSize = 16;
33981ad6265SDimitry Andric   uint32_t Addr = sectionPhysicalAddr(Sec) & 0xFFFFFFFFU;
34081ad6265SDimitry Andric   while (!Data.empty()) {
34181ad6265SDimitry Andric     uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
34281ad6265SDimitry Andric     if (Addr > SegmentAddr + BaseAddr + 0xFFFFU) {
34381ad6265SDimitry Andric       if (Addr > 0xFFFFFU) {
34481ad6265SDimitry Andric         // Write extended address record, zeroing segment address
34581ad6265SDimitry Andric         // if needed.
34681ad6265SDimitry Andric         if (SegmentAddr != 0)
34781ad6265SDimitry Andric           SegmentAddr = writeSegmentAddr(0U);
34881ad6265SDimitry Andric         BaseAddr = writeBaseAddr(Addr);
34981ad6265SDimitry Andric       } else {
35081ad6265SDimitry Andric         // We can still remain 16-bit
35181ad6265SDimitry Andric         SegmentAddr = writeSegmentAddr(Addr);
35281ad6265SDimitry Andric       }
35381ad6265SDimitry Andric     }
35481ad6265SDimitry Andric     uint64_t SegOffset = Addr - BaseAddr - SegmentAddr;
35581ad6265SDimitry Andric     assert(SegOffset <= 0xFFFFU);
35681ad6265SDimitry Andric     DataSize = std::min(DataSize, 0x10000U - SegOffset);
35781ad6265SDimitry Andric     writeData(0, SegOffset, Data.take_front(DataSize));
35881ad6265SDimitry Andric     Addr += DataSize;
35981ad6265SDimitry Andric     Data = Data.drop_front(DataSize);
36081ad6265SDimitry Andric   }
36181ad6265SDimitry Andric }
36281ad6265SDimitry Andric 
36381ad6265SDimitry Andric uint64_t IHexSectionWriterBase::writeSegmentAddr(uint64_t Addr) {
36481ad6265SDimitry Andric   assert(Addr <= 0xFFFFFU);
36581ad6265SDimitry Andric   uint8_t Data[] = {static_cast<uint8_t>((Addr & 0xF0000U) >> 12), 0};
36681ad6265SDimitry Andric   writeData(2, 0, Data);
36781ad6265SDimitry Andric   return Addr & 0xF0000U;
36881ad6265SDimitry Andric }
36981ad6265SDimitry Andric 
37081ad6265SDimitry Andric uint64_t IHexSectionWriterBase::writeBaseAddr(uint64_t Addr) {
37181ad6265SDimitry Andric   assert(Addr <= 0xFFFFFFFFU);
37281ad6265SDimitry Andric   uint64_t Base = Addr & 0xFFFF0000U;
37381ad6265SDimitry Andric   uint8_t Data[] = {static_cast<uint8_t>(Base >> 24),
37481ad6265SDimitry Andric                     static_cast<uint8_t>((Base >> 16) & 0xFF)};
37581ad6265SDimitry Andric   writeData(4, 0, Data);
37681ad6265SDimitry Andric   return Base;
37781ad6265SDimitry Andric }
37881ad6265SDimitry Andric 
37981ad6265SDimitry Andric void IHexSectionWriterBase::writeData(uint8_t, uint16_t,
38081ad6265SDimitry Andric                                       ArrayRef<uint8_t> Data) {
38181ad6265SDimitry Andric   Offset += IHexRecord::getLineLength(Data.size());
38281ad6265SDimitry Andric }
38381ad6265SDimitry Andric 
38481ad6265SDimitry Andric Error IHexSectionWriterBase::visit(const Section &Sec) {
38581ad6265SDimitry Andric   writeSection(&Sec, Sec.Contents);
38681ad6265SDimitry Andric   return Error::success();
38781ad6265SDimitry Andric }
38881ad6265SDimitry Andric 
38981ad6265SDimitry Andric Error IHexSectionWriterBase::visit(const OwnedDataSection &Sec) {
39081ad6265SDimitry Andric   writeSection(&Sec, Sec.Data);
39181ad6265SDimitry Andric   return Error::success();
39281ad6265SDimitry Andric }
39381ad6265SDimitry Andric 
39481ad6265SDimitry Andric Error IHexSectionWriterBase::visit(const StringTableSection &Sec) {
39581ad6265SDimitry Andric   // Check that sizer has already done its work
39681ad6265SDimitry Andric   assert(Sec.Size == Sec.StrTabBuilder.getSize());
39781ad6265SDimitry Andric   // We are free to pass an invalid pointer to writeSection as long
39881ad6265SDimitry Andric   // as we don't actually write any data. The real writer class has
39981ad6265SDimitry Andric   // to override this method .
40081ad6265SDimitry Andric   writeSection(&Sec, {nullptr, static_cast<size_t>(Sec.Size)});
40181ad6265SDimitry Andric   return Error::success();
40281ad6265SDimitry Andric }
40381ad6265SDimitry Andric 
40481ad6265SDimitry Andric Error IHexSectionWriterBase::visit(const DynamicRelocationSection &Sec) {
40581ad6265SDimitry Andric   writeSection(&Sec, Sec.Contents);
40681ad6265SDimitry Andric   return Error::success();
40781ad6265SDimitry Andric }
40881ad6265SDimitry Andric 
40981ad6265SDimitry Andric void IHexSectionWriter::writeData(uint8_t Type, uint16_t Addr,
41081ad6265SDimitry Andric                                   ArrayRef<uint8_t> Data) {
41181ad6265SDimitry Andric   IHexLineData HexData = IHexRecord::getLine(Type, Addr, Data);
41281ad6265SDimitry Andric   memcpy(Out.getBufferStart() + Offset, HexData.data(), HexData.size());
41381ad6265SDimitry Andric   Offset += HexData.size();
41481ad6265SDimitry Andric }
41581ad6265SDimitry Andric 
41681ad6265SDimitry Andric Error IHexSectionWriter::visit(const StringTableSection &Sec) {
41781ad6265SDimitry Andric   assert(Sec.Size == Sec.StrTabBuilder.getSize());
41881ad6265SDimitry Andric   std::vector<uint8_t> Data(Sec.Size);
41981ad6265SDimitry Andric   Sec.StrTabBuilder.write(Data.data());
42081ad6265SDimitry Andric   writeSection(&Sec, Data);
42181ad6265SDimitry Andric   return Error::success();
42281ad6265SDimitry Andric }
42381ad6265SDimitry Andric 
42481ad6265SDimitry Andric Error Section::accept(SectionVisitor &Visitor) const {
42581ad6265SDimitry Andric   return Visitor.visit(*this);
42681ad6265SDimitry Andric }
42781ad6265SDimitry Andric 
42881ad6265SDimitry Andric Error Section::accept(MutableSectionVisitor &Visitor) {
42981ad6265SDimitry Andric   return Visitor.visit(*this);
43081ad6265SDimitry Andric }
43181ad6265SDimitry Andric 
43281ad6265SDimitry Andric Error SectionWriter::visit(const OwnedDataSection &Sec) {
43381ad6265SDimitry Andric   llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
43481ad6265SDimitry Andric   return Error::success();
43581ad6265SDimitry Andric }
43681ad6265SDimitry Andric 
43781ad6265SDimitry Andric template <class ELFT>
43881ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
439*972a253aSDimitry Andric   ArrayRef<uint8_t> Compressed =
440*972a253aSDimitry Andric       Sec.OriginalData.slice(sizeof(Elf_Chdr_Impl<ELFT>));
441753f127fSDimitry Andric   SmallVector<uint8_t, 128> DecompressedContent;
442*972a253aSDimitry Andric   if (Error Err = compression::zlib::uncompress(Compressed, DecompressedContent,
44381ad6265SDimitry Andric                                                 static_cast<size_t>(Sec.Size)))
44481ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
44581ad6265SDimitry Andric                              "'" + Sec.Name + "': " + toString(std::move(Err)));
44681ad6265SDimitry Andric 
44781ad6265SDimitry Andric   uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
44881ad6265SDimitry Andric   std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
44981ad6265SDimitry Andric 
45081ad6265SDimitry Andric   return Error::success();
45181ad6265SDimitry Andric }
45281ad6265SDimitry Andric 
45381ad6265SDimitry Andric Error BinarySectionWriter::visit(const DecompressedSection &Sec) {
45481ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
45581ad6265SDimitry Andric                            "cannot write compressed section '" + Sec.Name +
45681ad6265SDimitry Andric                                "' ");
45781ad6265SDimitry Andric }
45881ad6265SDimitry Andric 
45981ad6265SDimitry Andric Error DecompressedSection::accept(SectionVisitor &Visitor) const {
46081ad6265SDimitry Andric   return Visitor.visit(*this);
46181ad6265SDimitry Andric }
46281ad6265SDimitry Andric 
46381ad6265SDimitry Andric Error DecompressedSection::accept(MutableSectionVisitor &Visitor) {
46481ad6265SDimitry Andric   return Visitor.visit(*this);
46581ad6265SDimitry Andric }
46681ad6265SDimitry Andric 
46781ad6265SDimitry Andric Error OwnedDataSection::accept(SectionVisitor &Visitor) const {
46881ad6265SDimitry Andric   return Visitor.visit(*this);
46981ad6265SDimitry Andric }
47081ad6265SDimitry Andric 
47181ad6265SDimitry Andric Error OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
47281ad6265SDimitry Andric   return Visitor.visit(*this);
47381ad6265SDimitry Andric }
47481ad6265SDimitry Andric 
47581ad6265SDimitry Andric void OwnedDataSection::appendHexData(StringRef HexData) {
47681ad6265SDimitry Andric   assert((HexData.size() & 1) == 0);
47781ad6265SDimitry Andric   while (!HexData.empty()) {
47881ad6265SDimitry Andric     Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2)));
47981ad6265SDimitry Andric     HexData = HexData.drop_front(2);
48081ad6265SDimitry Andric   }
48181ad6265SDimitry Andric   Size = Data.size();
48281ad6265SDimitry Andric }
48381ad6265SDimitry Andric 
48481ad6265SDimitry Andric Error BinarySectionWriter::visit(const CompressedSection &Sec) {
48581ad6265SDimitry Andric   return createStringError(errc::operation_not_permitted,
48681ad6265SDimitry Andric                            "cannot write compressed section '" + Sec.Name +
48781ad6265SDimitry Andric                                "' ");
48881ad6265SDimitry Andric }
48981ad6265SDimitry Andric 
49081ad6265SDimitry Andric template <class ELFT>
49181ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
49281ad6265SDimitry Andric   uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
493*972a253aSDimitry Andric   Elf_Chdr_Impl<ELFT> Chdr = {};
49481ad6265SDimitry Andric   switch (Sec.CompressionType) {
49581ad6265SDimitry Andric   case DebugCompressionType::None:
49681ad6265SDimitry Andric     std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
49781ad6265SDimitry Andric     return Error::success();
49881ad6265SDimitry Andric   case DebugCompressionType::Z:
49981ad6265SDimitry Andric     Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
50081ad6265SDimitry Andric     break;
50181ad6265SDimitry Andric   }
50281ad6265SDimitry Andric   Chdr.ch_size = Sec.DecompressedSize;
50381ad6265SDimitry Andric   Chdr.ch_addralign = Sec.DecompressedAlign;
50481ad6265SDimitry Andric   memcpy(Buf, &Chdr, sizeof(Chdr));
50581ad6265SDimitry Andric   Buf += sizeof(Chdr);
50681ad6265SDimitry Andric 
50781ad6265SDimitry Andric   std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
50881ad6265SDimitry Andric   return Error::success();
50981ad6265SDimitry Andric }
51081ad6265SDimitry Andric 
51181ad6265SDimitry Andric CompressedSection::CompressedSection(const SectionBase &Sec,
51281ad6265SDimitry Andric                                      DebugCompressionType CompressionType)
51381ad6265SDimitry Andric     : SectionBase(Sec), CompressionType(CompressionType),
51481ad6265SDimitry Andric       DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
515753f127fSDimitry Andric   compression::zlib::compress(OriginalData, CompressedData);
51681ad6265SDimitry Andric 
51781ad6265SDimitry Andric   assert(CompressionType != DebugCompressionType::None);
51881ad6265SDimitry Andric   Flags |= ELF::SHF_COMPRESSED;
51981ad6265SDimitry Andric   size_t ChdrSize =
52081ad6265SDimitry Andric       std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
52181ad6265SDimitry Andric                         sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
52281ad6265SDimitry Andric                std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
52381ad6265SDimitry Andric                         sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
52481ad6265SDimitry Andric   Size = ChdrSize + CompressedData.size();
52581ad6265SDimitry Andric   Align = 8;
52681ad6265SDimitry Andric }
52781ad6265SDimitry Andric 
52881ad6265SDimitry Andric CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
52981ad6265SDimitry Andric                                      uint64_t DecompressedSize,
53081ad6265SDimitry Andric                                      uint64_t DecompressedAlign)
53181ad6265SDimitry Andric     : CompressionType(DebugCompressionType::None),
53281ad6265SDimitry Andric       DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
53381ad6265SDimitry Andric   OriginalData = CompressedData;
53481ad6265SDimitry Andric }
53581ad6265SDimitry Andric 
53681ad6265SDimitry Andric Error CompressedSection::accept(SectionVisitor &Visitor) const {
53781ad6265SDimitry Andric   return Visitor.visit(*this);
53881ad6265SDimitry Andric }
53981ad6265SDimitry Andric 
54081ad6265SDimitry Andric Error CompressedSection::accept(MutableSectionVisitor &Visitor) {
54181ad6265SDimitry Andric   return Visitor.visit(*this);
54281ad6265SDimitry Andric }
54381ad6265SDimitry Andric 
54481ad6265SDimitry Andric void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
54581ad6265SDimitry Andric 
54681ad6265SDimitry Andric uint32_t StringTableSection::findIndex(StringRef Name) const {
54781ad6265SDimitry Andric   return StrTabBuilder.getOffset(Name);
54881ad6265SDimitry Andric }
54981ad6265SDimitry Andric 
55081ad6265SDimitry Andric void StringTableSection::prepareForLayout() {
55181ad6265SDimitry Andric   StrTabBuilder.finalize();
55281ad6265SDimitry Andric   Size = StrTabBuilder.getSize();
55381ad6265SDimitry Andric }
55481ad6265SDimitry Andric 
55581ad6265SDimitry Andric Error SectionWriter::visit(const StringTableSection &Sec) {
55681ad6265SDimitry Andric   Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) +
55781ad6265SDimitry Andric                           Sec.Offset);
55881ad6265SDimitry Andric   return Error::success();
55981ad6265SDimitry Andric }
56081ad6265SDimitry Andric 
56181ad6265SDimitry Andric Error StringTableSection::accept(SectionVisitor &Visitor) const {
56281ad6265SDimitry Andric   return Visitor.visit(*this);
56381ad6265SDimitry Andric }
56481ad6265SDimitry Andric 
56581ad6265SDimitry Andric Error StringTableSection::accept(MutableSectionVisitor &Visitor) {
56681ad6265SDimitry Andric   return Visitor.visit(*this);
56781ad6265SDimitry Andric }
56881ad6265SDimitry Andric 
56981ad6265SDimitry Andric template <class ELFT>
57081ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
57181ad6265SDimitry Andric   uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
57281ad6265SDimitry Andric   llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
57381ad6265SDimitry Andric   return Error::success();
57481ad6265SDimitry Andric }
57581ad6265SDimitry Andric 
57681ad6265SDimitry Andric Error SectionIndexSection::initialize(SectionTableRef SecTable) {
57781ad6265SDimitry Andric   Size = 0;
57881ad6265SDimitry Andric   Expected<SymbolTableSection *> Sec =
57981ad6265SDimitry Andric       SecTable.getSectionOfType<SymbolTableSection>(
58081ad6265SDimitry Andric           Link,
58181ad6265SDimitry Andric           "Link field value " + Twine(Link) + " in section " + Name +
58281ad6265SDimitry Andric               " is invalid",
58381ad6265SDimitry Andric           "Link field value " + Twine(Link) + " in section " + Name +
58481ad6265SDimitry Andric               " is not a symbol table");
58581ad6265SDimitry Andric   if (!Sec)
58681ad6265SDimitry Andric     return Sec.takeError();
58781ad6265SDimitry Andric 
58881ad6265SDimitry Andric   setSymTab(*Sec);
58981ad6265SDimitry Andric   Symbols->setShndxTable(this);
59081ad6265SDimitry Andric   return Error::success();
59181ad6265SDimitry Andric }
59281ad6265SDimitry Andric 
59381ad6265SDimitry Andric void SectionIndexSection::finalize() { Link = Symbols->Index; }
59481ad6265SDimitry Andric 
59581ad6265SDimitry Andric Error SectionIndexSection::accept(SectionVisitor &Visitor) const {
59681ad6265SDimitry Andric   return Visitor.visit(*this);
59781ad6265SDimitry Andric }
59881ad6265SDimitry Andric 
59981ad6265SDimitry Andric Error SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
60081ad6265SDimitry Andric   return Visitor.visit(*this);
60181ad6265SDimitry Andric }
60281ad6265SDimitry Andric 
60381ad6265SDimitry Andric static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
60481ad6265SDimitry Andric   switch (Index) {
60581ad6265SDimitry Andric   case SHN_ABS:
60681ad6265SDimitry Andric   case SHN_COMMON:
60781ad6265SDimitry Andric     return true;
60881ad6265SDimitry Andric   }
60981ad6265SDimitry Andric 
61081ad6265SDimitry Andric   if (Machine == EM_AMDGPU) {
61181ad6265SDimitry Andric     return Index == SHN_AMDGPU_LDS;
61281ad6265SDimitry Andric   }
61381ad6265SDimitry Andric 
61481ad6265SDimitry Andric   if (Machine == EM_MIPS) {
61581ad6265SDimitry Andric     switch (Index) {
61681ad6265SDimitry Andric     case SHN_MIPS_ACOMMON:
61781ad6265SDimitry Andric     case SHN_MIPS_SCOMMON:
61881ad6265SDimitry Andric     case SHN_MIPS_SUNDEFINED:
61981ad6265SDimitry Andric       return true;
62081ad6265SDimitry Andric     }
62181ad6265SDimitry Andric   }
62281ad6265SDimitry Andric 
62381ad6265SDimitry Andric   if (Machine == EM_HEXAGON) {
62481ad6265SDimitry Andric     switch (Index) {
62581ad6265SDimitry Andric     case SHN_HEXAGON_SCOMMON:
62681ad6265SDimitry Andric     case SHN_HEXAGON_SCOMMON_1:
62781ad6265SDimitry Andric     case SHN_HEXAGON_SCOMMON_2:
62881ad6265SDimitry Andric     case SHN_HEXAGON_SCOMMON_4:
62981ad6265SDimitry Andric     case SHN_HEXAGON_SCOMMON_8:
63081ad6265SDimitry Andric       return true;
63181ad6265SDimitry Andric     }
63281ad6265SDimitry Andric   }
63381ad6265SDimitry Andric   return false;
63481ad6265SDimitry Andric }
63581ad6265SDimitry Andric 
63681ad6265SDimitry Andric // Large indexes force us to clarify exactly what this function should do. This
63781ad6265SDimitry Andric // function should return the value that will appear in st_shndx when written
63881ad6265SDimitry Andric // out.
63981ad6265SDimitry Andric uint16_t Symbol::getShndx() const {
64081ad6265SDimitry Andric   if (DefinedIn != nullptr) {
64181ad6265SDimitry Andric     if (DefinedIn->Index >= SHN_LORESERVE)
64281ad6265SDimitry Andric       return SHN_XINDEX;
64381ad6265SDimitry Andric     return DefinedIn->Index;
64481ad6265SDimitry Andric   }
64581ad6265SDimitry Andric 
64681ad6265SDimitry Andric   if (ShndxType == SYMBOL_SIMPLE_INDEX) {
64781ad6265SDimitry Andric     // This means that we don't have a defined section but we do need to
64881ad6265SDimitry Andric     // output a legitimate section index.
64981ad6265SDimitry Andric     return SHN_UNDEF;
65081ad6265SDimitry Andric   }
65181ad6265SDimitry Andric 
65281ad6265SDimitry Andric   assert(ShndxType == SYMBOL_ABS || ShndxType == SYMBOL_COMMON ||
65381ad6265SDimitry Andric          (ShndxType >= SYMBOL_LOPROC && ShndxType <= SYMBOL_HIPROC) ||
65481ad6265SDimitry Andric          (ShndxType >= SYMBOL_LOOS && ShndxType <= SYMBOL_HIOS));
65581ad6265SDimitry Andric   return static_cast<uint16_t>(ShndxType);
65681ad6265SDimitry Andric }
65781ad6265SDimitry Andric 
65881ad6265SDimitry Andric bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
65981ad6265SDimitry Andric 
66081ad6265SDimitry Andric void SymbolTableSection::assignIndices() {
66181ad6265SDimitry Andric   uint32_t Index = 0;
66281ad6265SDimitry Andric   for (auto &Sym : Symbols)
66381ad6265SDimitry Andric     Sym->Index = Index++;
66481ad6265SDimitry Andric }
66581ad6265SDimitry Andric 
66681ad6265SDimitry Andric void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
66781ad6265SDimitry Andric                                    SectionBase *DefinedIn, uint64_t Value,
66881ad6265SDimitry Andric                                    uint8_t Visibility, uint16_t Shndx,
66981ad6265SDimitry Andric                                    uint64_t SymbolSize) {
67081ad6265SDimitry Andric   Symbol Sym;
67181ad6265SDimitry Andric   Sym.Name = Name.str();
67281ad6265SDimitry Andric   Sym.Binding = Bind;
67381ad6265SDimitry Andric   Sym.Type = Type;
67481ad6265SDimitry Andric   Sym.DefinedIn = DefinedIn;
67581ad6265SDimitry Andric   if (DefinedIn != nullptr)
67681ad6265SDimitry Andric     DefinedIn->HasSymbol = true;
67781ad6265SDimitry Andric   if (DefinedIn == nullptr) {
67881ad6265SDimitry Andric     if (Shndx >= SHN_LORESERVE)
67981ad6265SDimitry Andric       Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
68081ad6265SDimitry Andric     else
68181ad6265SDimitry Andric       Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
68281ad6265SDimitry Andric   }
68381ad6265SDimitry Andric   Sym.Value = Value;
68481ad6265SDimitry Andric   Sym.Visibility = Visibility;
68581ad6265SDimitry Andric   Sym.Size = SymbolSize;
68681ad6265SDimitry Andric   Sym.Index = Symbols.size();
68781ad6265SDimitry Andric   Symbols.emplace_back(std::make_unique<Symbol>(Sym));
68881ad6265SDimitry Andric   Size += this->EntrySize;
68981ad6265SDimitry Andric }
69081ad6265SDimitry Andric 
69181ad6265SDimitry Andric Error SymbolTableSection::removeSectionReferences(
69281ad6265SDimitry Andric     bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
69381ad6265SDimitry Andric   if (ToRemove(SectionIndexTable))
69481ad6265SDimitry Andric     SectionIndexTable = nullptr;
69581ad6265SDimitry Andric   if (ToRemove(SymbolNames)) {
69681ad6265SDimitry Andric     if (!AllowBrokenLinks)
69781ad6265SDimitry Andric       return createStringError(
69881ad6265SDimitry Andric           llvm::errc::invalid_argument,
69981ad6265SDimitry Andric           "string table '%s' cannot be removed because it is "
70081ad6265SDimitry Andric           "referenced by the symbol table '%s'",
70181ad6265SDimitry Andric           SymbolNames->Name.data(), this->Name.data());
70281ad6265SDimitry Andric     SymbolNames = nullptr;
70381ad6265SDimitry Andric   }
70481ad6265SDimitry Andric   return removeSymbols(
70581ad6265SDimitry Andric       [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
70681ad6265SDimitry Andric }
70781ad6265SDimitry Andric 
70881ad6265SDimitry Andric void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
70981ad6265SDimitry Andric   for (SymPtr &Sym : llvm::drop_begin(Symbols))
71081ad6265SDimitry Andric     Callable(*Sym);
71181ad6265SDimitry Andric   std::stable_partition(
71281ad6265SDimitry Andric       std::begin(Symbols), std::end(Symbols),
71381ad6265SDimitry Andric       [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
71481ad6265SDimitry Andric   assignIndices();
71581ad6265SDimitry Andric }
71681ad6265SDimitry Andric 
71781ad6265SDimitry Andric Error SymbolTableSection::removeSymbols(
71881ad6265SDimitry Andric     function_ref<bool(const Symbol &)> ToRemove) {
71981ad6265SDimitry Andric   Symbols.erase(
72081ad6265SDimitry Andric       std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
72181ad6265SDimitry Andric                      [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
72281ad6265SDimitry Andric       std::end(Symbols));
72381ad6265SDimitry Andric   Size = Symbols.size() * EntrySize;
72481ad6265SDimitry Andric   assignIndices();
72581ad6265SDimitry Andric   return Error::success();
72681ad6265SDimitry Andric }
72781ad6265SDimitry Andric 
72881ad6265SDimitry Andric void SymbolTableSection::replaceSectionReferences(
72981ad6265SDimitry Andric     const DenseMap<SectionBase *, SectionBase *> &FromTo) {
73081ad6265SDimitry Andric   for (std::unique_ptr<Symbol> &Sym : Symbols)
73181ad6265SDimitry Andric     if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
73281ad6265SDimitry Andric       Sym->DefinedIn = To;
73381ad6265SDimitry Andric }
73481ad6265SDimitry Andric 
73581ad6265SDimitry Andric Error SymbolTableSection::initialize(SectionTableRef SecTable) {
73681ad6265SDimitry Andric   Size = 0;
73781ad6265SDimitry Andric   Expected<StringTableSection *> Sec =
73881ad6265SDimitry Andric       SecTable.getSectionOfType<StringTableSection>(
73981ad6265SDimitry Andric           Link,
74081ad6265SDimitry Andric           "Symbol table has link index of " + Twine(Link) +
74181ad6265SDimitry Andric               " which is not a valid index",
74281ad6265SDimitry Andric           "Symbol table has link index of " + Twine(Link) +
74381ad6265SDimitry Andric               " which is not a string table");
74481ad6265SDimitry Andric   if (!Sec)
74581ad6265SDimitry Andric     return Sec.takeError();
74681ad6265SDimitry Andric 
74781ad6265SDimitry Andric   setStrTab(*Sec);
74881ad6265SDimitry Andric   return Error::success();
74981ad6265SDimitry Andric }
75081ad6265SDimitry Andric 
75181ad6265SDimitry Andric void SymbolTableSection::finalize() {
75281ad6265SDimitry Andric   uint32_t MaxLocalIndex = 0;
75381ad6265SDimitry Andric   for (std::unique_ptr<Symbol> &Sym : Symbols) {
75481ad6265SDimitry Andric     Sym->NameIndex =
75581ad6265SDimitry Andric         SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
75681ad6265SDimitry Andric     if (Sym->Binding == STB_LOCAL)
75781ad6265SDimitry Andric       MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
75881ad6265SDimitry Andric   }
75981ad6265SDimitry Andric   // Now we need to set the Link and Info fields.
76081ad6265SDimitry Andric   Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
76181ad6265SDimitry Andric   Info = MaxLocalIndex + 1;
76281ad6265SDimitry Andric }
76381ad6265SDimitry Andric 
76481ad6265SDimitry Andric void SymbolTableSection::prepareForLayout() {
76581ad6265SDimitry Andric   // Reserve proper amount of space in section index table, so we can
76681ad6265SDimitry Andric   // layout sections correctly. We will fill the table with correct
76781ad6265SDimitry Andric   // indexes later in fillShdnxTable.
76881ad6265SDimitry Andric   if (SectionIndexTable)
76981ad6265SDimitry Andric     SectionIndexTable->reserve(Symbols.size());
77081ad6265SDimitry Andric 
77181ad6265SDimitry Andric   // Add all of our strings to SymbolNames so that SymbolNames has the right
77281ad6265SDimitry Andric   // size before layout is decided.
77381ad6265SDimitry Andric   // If the symbol names section has been removed, don't try to add strings to
77481ad6265SDimitry Andric   // the table.
77581ad6265SDimitry Andric   if (SymbolNames != nullptr)
77681ad6265SDimitry Andric     for (std::unique_ptr<Symbol> &Sym : Symbols)
77781ad6265SDimitry Andric       SymbolNames->addString(Sym->Name);
77881ad6265SDimitry Andric }
77981ad6265SDimitry Andric 
78081ad6265SDimitry Andric void SymbolTableSection::fillShndxTable() {
78181ad6265SDimitry Andric   if (SectionIndexTable == nullptr)
78281ad6265SDimitry Andric     return;
78381ad6265SDimitry Andric   // Fill section index table with real section indexes. This function must
78481ad6265SDimitry Andric   // be called after assignOffsets.
78581ad6265SDimitry Andric   for (const std::unique_ptr<Symbol> &Sym : Symbols) {
78681ad6265SDimitry Andric     if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
78781ad6265SDimitry Andric       SectionIndexTable->addIndex(Sym->DefinedIn->Index);
78881ad6265SDimitry Andric     else
78981ad6265SDimitry Andric       SectionIndexTable->addIndex(SHN_UNDEF);
79081ad6265SDimitry Andric   }
79181ad6265SDimitry Andric }
79281ad6265SDimitry Andric 
79381ad6265SDimitry Andric Expected<const Symbol *>
79481ad6265SDimitry Andric SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
79581ad6265SDimitry Andric   if (Symbols.size() <= Index)
79681ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
79781ad6265SDimitry Andric                              "invalid symbol index: " + Twine(Index));
79881ad6265SDimitry Andric   return Symbols[Index].get();
79981ad6265SDimitry Andric }
80081ad6265SDimitry Andric 
80181ad6265SDimitry Andric Expected<Symbol *> SymbolTableSection::getSymbolByIndex(uint32_t Index) {
80281ad6265SDimitry Andric   Expected<const Symbol *> Sym =
80381ad6265SDimitry Andric       static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index);
80481ad6265SDimitry Andric   if (!Sym)
80581ad6265SDimitry Andric     return Sym.takeError();
80681ad6265SDimitry Andric 
80781ad6265SDimitry Andric   return const_cast<Symbol *>(*Sym);
80881ad6265SDimitry Andric }
80981ad6265SDimitry Andric 
81081ad6265SDimitry Andric template <class ELFT>
81181ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
81281ad6265SDimitry Andric   Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
81381ad6265SDimitry Andric   // Loop though symbols setting each entry of the symbol table.
81481ad6265SDimitry Andric   for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
81581ad6265SDimitry Andric     Sym->st_name = Symbol->NameIndex;
81681ad6265SDimitry Andric     Sym->st_value = Symbol->Value;
81781ad6265SDimitry Andric     Sym->st_size = Symbol->Size;
81881ad6265SDimitry Andric     Sym->st_other = Symbol->Visibility;
81981ad6265SDimitry Andric     Sym->setBinding(Symbol->Binding);
82081ad6265SDimitry Andric     Sym->setType(Symbol->Type);
82181ad6265SDimitry Andric     Sym->st_shndx = Symbol->getShndx();
82281ad6265SDimitry Andric     ++Sym;
82381ad6265SDimitry Andric   }
82481ad6265SDimitry Andric   return Error::success();
82581ad6265SDimitry Andric }
82681ad6265SDimitry Andric 
82781ad6265SDimitry Andric Error SymbolTableSection::accept(SectionVisitor &Visitor) const {
82881ad6265SDimitry Andric   return Visitor.visit(*this);
82981ad6265SDimitry Andric }
83081ad6265SDimitry Andric 
83181ad6265SDimitry Andric Error SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
83281ad6265SDimitry Andric   return Visitor.visit(*this);
83381ad6265SDimitry Andric }
83481ad6265SDimitry Andric 
83581ad6265SDimitry Andric StringRef RelocationSectionBase::getNamePrefix() const {
83681ad6265SDimitry Andric   switch (Type) {
83781ad6265SDimitry Andric   case SHT_REL:
83881ad6265SDimitry Andric     return ".rel";
83981ad6265SDimitry Andric   case SHT_RELA:
84081ad6265SDimitry Andric     return ".rela";
84181ad6265SDimitry Andric   default:
84281ad6265SDimitry Andric     llvm_unreachable("not a relocation section");
84381ad6265SDimitry Andric   }
84481ad6265SDimitry Andric }
84581ad6265SDimitry Andric 
84681ad6265SDimitry Andric Error RelocationSection::removeSectionReferences(
84781ad6265SDimitry Andric     bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
84881ad6265SDimitry Andric   if (ToRemove(Symbols)) {
84981ad6265SDimitry Andric     if (!AllowBrokenLinks)
85081ad6265SDimitry Andric       return createStringError(
85181ad6265SDimitry Andric           llvm::errc::invalid_argument,
85281ad6265SDimitry Andric           "symbol table '%s' cannot be removed because it is "
85381ad6265SDimitry Andric           "referenced by the relocation section '%s'",
85481ad6265SDimitry Andric           Symbols->Name.data(), this->Name.data());
85581ad6265SDimitry Andric     Symbols = nullptr;
85681ad6265SDimitry Andric   }
85781ad6265SDimitry Andric 
85881ad6265SDimitry Andric   for (const Relocation &R : Relocations) {
85981ad6265SDimitry Andric     if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn ||
86081ad6265SDimitry Andric         !ToRemove(R.RelocSymbol->DefinedIn))
86181ad6265SDimitry Andric       continue;
86281ad6265SDimitry Andric     return createStringError(llvm::errc::invalid_argument,
86381ad6265SDimitry Andric                              "section '%s' cannot be removed: (%s+0x%" PRIx64
86481ad6265SDimitry Andric                              ") has relocation against symbol '%s'",
86581ad6265SDimitry Andric                              R.RelocSymbol->DefinedIn->Name.data(),
86681ad6265SDimitry Andric                              SecToApplyRel->Name.data(), R.Offset,
86781ad6265SDimitry Andric                              R.RelocSymbol->Name.c_str());
86881ad6265SDimitry Andric   }
86981ad6265SDimitry Andric 
87081ad6265SDimitry Andric   return Error::success();
87181ad6265SDimitry Andric }
87281ad6265SDimitry Andric 
87381ad6265SDimitry Andric template <class SymTabType>
87481ad6265SDimitry Andric Error RelocSectionWithSymtabBase<SymTabType>::initialize(
87581ad6265SDimitry Andric     SectionTableRef SecTable) {
87681ad6265SDimitry Andric   if (Link != SHN_UNDEF) {
87781ad6265SDimitry Andric     Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>(
87881ad6265SDimitry Andric         Link,
87981ad6265SDimitry Andric         "Link field value " + Twine(Link) + " in section " + Name +
88081ad6265SDimitry Andric             " is invalid",
88181ad6265SDimitry Andric         "Link field value " + Twine(Link) + " in section " + Name +
88281ad6265SDimitry Andric             " is not a symbol table");
88381ad6265SDimitry Andric     if (!Sec)
88481ad6265SDimitry Andric       return Sec.takeError();
88581ad6265SDimitry Andric 
88681ad6265SDimitry Andric     setSymTab(*Sec);
88781ad6265SDimitry Andric   }
88881ad6265SDimitry Andric 
88981ad6265SDimitry Andric   if (Info != SHN_UNDEF) {
89081ad6265SDimitry Andric     Expected<SectionBase *> Sec =
89181ad6265SDimitry Andric         SecTable.getSection(Info, "Info field value " + Twine(Info) +
89281ad6265SDimitry Andric                                       " in section " + Name + " is invalid");
89381ad6265SDimitry Andric     if (!Sec)
89481ad6265SDimitry Andric       return Sec.takeError();
89581ad6265SDimitry Andric 
89681ad6265SDimitry Andric     setSection(*Sec);
89781ad6265SDimitry Andric   } else
89881ad6265SDimitry Andric     setSection(nullptr);
89981ad6265SDimitry Andric 
90081ad6265SDimitry Andric   return Error::success();
90181ad6265SDimitry Andric }
90281ad6265SDimitry Andric 
90381ad6265SDimitry Andric template <class SymTabType>
90481ad6265SDimitry Andric void RelocSectionWithSymtabBase<SymTabType>::finalize() {
90581ad6265SDimitry Andric   this->Link = Symbols ? Symbols->Index : 0;
90681ad6265SDimitry Andric 
90781ad6265SDimitry Andric   if (SecToApplyRel != nullptr)
90881ad6265SDimitry Andric     this->Info = SecToApplyRel->Index;
90981ad6265SDimitry Andric }
91081ad6265SDimitry Andric 
91181ad6265SDimitry Andric template <class ELFT>
91281ad6265SDimitry Andric static void setAddend(Elf_Rel_Impl<ELFT, false> &, uint64_t) {}
91381ad6265SDimitry Andric 
91481ad6265SDimitry Andric template <class ELFT>
91581ad6265SDimitry Andric static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
91681ad6265SDimitry Andric   Rela.r_addend = Addend;
91781ad6265SDimitry Andric }
91881ad6265SDimitry Andric 
91981ad6265SDimitry Andric template <class RelRange, class T>
92081ad6265SDimitry Andric static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) {
92181ad6265SDimitry Andric   for (const auto &Reloc : Relocations) {
92281ad6265SDimitry Andric     Buf->r_offset = Reloc.Offset;
92381ad6265SDimitry Andric     setAddend(*Buf, Reloc.Addend);
92481ad6265SDimitry Andric     Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0,
92581ad6265SDimitry Andric                           Reloc.Type, IsMips64EL);
92681ad6265SDimitry Andric     ++Buf;
92781ad6265SDimitry Andric   }
92881ad6265SDimitry Andric }
92981ad6265SDimitry Andric 
93081ad6265SDimitry Andric template <class ELFT>
93181ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
93281ad6265SDimitry Andric   uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
93381ad6265SDimitry Andric   if (Sec.Type == SHT_REL)
93481ad6265SDimitry Andric     writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf),
93581ad6265SDimitry Andric              Sec.getObject().IsMips64EL);
93681ad6265SDimitry Andric   else
93781ad6265SDimitry Andric     writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf),
93881ad6265SDimitry Andric              Sec.getObject().IsMips64EL);
93981ad6265SDimitry Andric   return Error::success();
94081ad6265SDimitry Andric }
94181ad6265SDimitry Andric 
94281ad6265SDimitry Andric Error RelocationSection::accept(SectionVisitor &Visitor) const {
94381ad6265SDimitry Andric   return Visitor.visit(*this);
94481ad6265SDimitry Andric }
94581ad6265SDimitry Andric 
94681ad6265SDimitry Andric Error RelocationSection::accept(MutableSectionVisitor &Visitor) {
94781ad6265SDimitry Andric   return Visitor.visit(*this);
94881ad6265SDimitry Andric }
94981ad6265SDimitry Andric 
95081ad6265SDimitry Andric Error RelocationSection::removeSymbols(
95181ad6265SDimitry Andric     function_ref<bool(const Symbol &)> ToRemove) {
95281ad6265SDimitry Andric   for (const Relocation &Reloc : Relocations)
95381ad6265SDimitry Andric     if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol))
95481ad6265SDimitry Andric       return createStringError(
95581ad6265SDimitry Andric           llvm::errc::invalid_argument,
95681ad6265SDimitry Andric           "not stripping symbol '%s' because it is named in a relocation",
95781ad6265SDimitry Andric           Reloc.RelocSymbol->Name.data());
95881ad6265SDimitry Andric   return Error::success();
95981ad6265SDimitry Andric }
96081ad6265SDimitry Andric 
96181ad6265SDimitry Andric void RelocationSection::markSymbols() {
96281ad6265SDimitry Andric   for (const Relocation &Reloc : Relocations)
96381ad6265SDimitry Andric     if (Reloc.RelocSymbol)
96481ad6265SDimitry Andric       Reloc.RelocSymbol->Referenced = true;
96581ad6265SDimitry Andric }
96681ad6265SDimitry Andric 
96781ad6265SDimitry Andric void RelocationSection::replaceSectionReferences(
96881ad6265SDimitry Andric     const DenseMap<SectionBase *, SectionBase *> &FromTo) {
96981ad6265SDimitry Andric   // Update the target section if it was replaced.
97081ad6265SDimitry Andric   if (SectionBase *To = FromTo.lookup(SecToApplyRel))
97181ad6265SDimitry Andric     SecToApplyRel = To;
97281ad6265SDimitry Andric }
97381ad6265SDimitry Andric 
97481ad6265SDimitry Andric Error SectionWriter::visit(const DynamicRelocationSection &Sec) {
97581ad6265SDimitry Andric   llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
97681ad6265SDimitry Andric   return Error::success();
97781ad6265SDimitry Andric }
97881ad6265SDimitry Andric 
97981ad6265SDimitry Andric Error DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
98081ad6265SDimitry Andric   return Visitor.visit(*this);
98181ad6265SDimitry Andric }
98281ad6265SDimitry Andric 
98381ad6265SDimitry Andric Error DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
98481ad6265SDimitry Andric   return Visitor.visit(*this);
98581ad6265SDimitry Andric }
98681ad6265SDimitry Andric 
98781ad6265SDimitry Andric Error DynamicRelocationSection::removeSectionReferences(
98881ad6265SDimitry Andric     bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
98981ad6265SDimitry Andric   if (ToRemove(Symbols)) {
99081ad6265SDimitry Andric     if (!AllowBrokenLinks)
99181ad6265SDimitry Andric       return createStringError(
99281ad6265SDimitry Andric           llvm::errc::invalid_argument,
99381ad6265SDimitry Andric           "symbol table '%s' cannot be removed because it is "
99481ad6265SDimitry Andric           "referenced by the relocation section '%s'",
99581ad6265SDimitry Andric           Symbols->Name.data(), this->Name.data());
99681ad6265SDimitry Andric     Symbols = nullptr;
99781ad6265SDimitry Andric   }
99881ad6265SDimitry Andric 
99981ad6265SDimitry Andric   // SecToApplyRel contains a section referenced by sh_info field. It keeps
100081ad6265SDimitry Andric   // a section to which the relocation section applies. When we remove any
100181ad6265SDimitry Andric   // sections we also remove their relocation sections. Since we do that much
100281ad6265SDimitry Andric   // earlier, this assert should never be triggered.
100381ad6265SDimitry Andric   assert(!SecToApplyRel || !ToRemove(SecToApplyRel));
100481ad6265SDimitry Andric   return Error::success();
100581ad6265SDimitry Andric }
100681ad6265SDimitry Andric 
100781ad6265SDimitry Andric Error Section::removeSectionReferences(
100881ad6265SDimitry Andric     bool AllowBrokenDependency,
100981ad6265SDimitry Andric     function_ref<bool(const SectionBase *)> ToRemove) {
101081ad6265SDimitry Andric   if (ToRemove(LinkSection)) {
101181ad6265SDimitry Andric     if (!AllowBrokenDependency)
101281ad6265SDimitry Andric       return createStringError(llvm::errc::invalid_argument,
101381ad6265SDimitry Andric                                "section '%s' cannot be removed because it is "
101481ad6265SDimitry Andric                                "referenced by the section '%s'",
101581ad6265SDimitry Andric                                LinkSection->Name.data(), this->Name.data());
101681ad6265SDimitry Andric     LinkSection = nullptr;
101781ad6265SDimitry Andric   }
101881ad6265SDimitry Andric   return Error::success();
101981ad6265SDimitry Andric }
102081ad6265SDimitry Andric 
102181ad6265SDimitry Andric void GroupSection::finalize() {
102281ad6265SDimitry Andric   this->Info = Sym ? Sym->Index : 0;
102381ad6265SDimitry Andric   this->Link = SymTab ? SymTab->Index : 0;
102481ad6265SDimitry Andric   // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global
102581ad6265SDimitry Andric   // status is not part of the equation. If Sym is localized, the intention is
102681ad6265SDimitry Andric   // likely to make the group fully localized. Drop GRP_COMDAT to suppress
102781ad6265SDimitry Andric   // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc
102881ad6265SDimitry Andric   if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL)
102981ad6265SDimitry Andric     this->FlagWord &= ~GRP_COMDAT;
103081ad6265SDimitry Andric }
103181ad6265SDimitry Andric 
103281ad6265SDimitry Andric Error GroupSection::removeSectionReferences(
103381ad6265SDimitry Andric     bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
103481ad6265SDimitry Andric   if (ToRemove(SymTab)) {
103581ad6265SDimitry Andric     if (!AllowBrokenLinks)
103681ad6265SDimitry Andric       return createStringError(
103781ad6265SDimitry Andric           llvm::errc::invalid_argument,
103881ad6265SDimitry Andric           "section '.symtab' cannot be removed because it is "
103981ad6265SDimitry Andric           "referenced by the group section '%s'",
104081ad6265SDimitry Andric           this->Name.data());
104181ad6265SDimitry Andric     SymTab = nullptr;
104281ad6265SDimitry Andric     Sym = nullptr;
104381ad6265SDimitry Andric   }
104481ad6265SDimitry Andric   llvm::erase_if(GroupMembers, ToRemove);
104581ad6265SDimitry Andric   return Error::success();
104681ad6265SDimitry Andric }
104781ad6265SDimitry Andric 
104881ad6265SDimitry Andric Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
104981ad6265SDimitry Andric   if (ToRemove(*Sym))
105081ad6265SDimitry Andric     return createStringError(llvm::errc::invalid_argument,
105181ad6265SDimitry Andric                              "symbol '%s' cannot be removed because it is "
105281ad6265SDimitry Andric                              "referenced by the section '%s[%d]'",
105381ad6265SDimitry Andric                              Sym->Name.data(), this->Name.data(), this->Index);
105481ad6265SDimitry Andric   return Error::success();
105581ad6265SDimitry Andric }
105681ad6265SDimitry Andric 
105781ad6265SDimitry Andric void GroupSection::markSymbols() {
105881ad6265SDimitry Andric   if (Sym)
105981ad6265SDimitry Andric     Sym->Referenced = true;
106081ad6265SDimitry Andric }
106181ad6265SDimitry Andric 
106281ad6265SDimitry Andric void GroupSection::replaceSectionReferences(
106381ad6265SDimitry Andric     const DenseMap<SectionBase *, SectionBase *> &FromTo) {
106481ad6265SDimitry Andric   for (SectionBase *&Sec : GroupMembers)
106581ad6265SDimitry Andric     if (SectionBase *To = FromTo.lookup(Sec))
106681ad6265SDimitry Andric       Sec = To;
106781ad6265SDimitry Andric }
106881ad6265SDimitry Andric 
106981ad6265SDimitry Andric void GroupSection::onRemove() {
107081ad6265SDimitry Andric   // As the header section of the group is removed, drop the Group flag in its
107181ad6265SDimitry Andric   // former members.
107281ad6265SDimitry Andric   for (SectionBase *Sec : GroupMembers)
107381ad6265SDimitry Andric     Sec->Flags &= ~SHF_GROUP;
107481ad6265SDimitry Andric }
107581ad6265SDimitry Andric 
107681ad6265SDimitry Andric Error Section::initialize(SectionTableRef SecTable) {
107781ad6265SDimitry Andric   if (Link == ELF::SHN_UNDEF)
107881ad6265SDimitry Andric     return Error::success();
107981ad6265SDimitry Andric 
108081ad6265SDimitry Andric   Expected<SectionBase *> Sec =
108181ad6265SDimitry Andric       SecTable.getSection(Link, "Link field value " + Twine(Link) +
108281ad6265SDimitry Andric                                     " in section " + Name + " is invalid");
108381ad6265SDimitry Andric   if (!Sec)
108481ad6265SDimitry Andric     return Sec.takeError();
108581ad6265SDimitry Andric 
108681ad6265SDimitry Andric   LinkSection = *Sec;
108781ad6265SDimitry Andric 
108881ad6265SDimitry Andric   if (LinkSection->Type == ELF::SHT_SYMTAB)
108981ad6265SDimitry Andric     LinkSection = nullptr;
109081ad6265SDimitry Andric 
109181ad6265SDimitry Andric   return Error::success();
109281ad6265SDimitry Andric }
109381ad6265SDimitry Andric 
109481ad6265SDimitry Andric void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
109581ad6265SDimitry Andric 
109681ad6265SDimitry Andric void GnuDebugLinkSection::init(StringRef File) {
109781ad6265SDimitry Andric   FileName = sys::path::filename(File);
109881ad6265SDimitry Andric   // The format for the .gnu_debuglink starts with the file name and is
109981ad6265SDimitry Andric   // followed by a null terminator and then the CRC32 of the file. The CRC32
110081ad6265SDimitry Andric   // should be 4 byte aligned. So we add the FileName size, a 1 for the null
110181ad6265SDimitry Andric   // byte, and then finally push the size to alignment and add 4.
110281ad6265SDimitry Andric   Size = alignTo(FileName.size() + 1, 4) + 4;
110381ad6265SDimitry Andric   // The CRC32 will only be aligned if we align the whole section.
110481ad6265SDimitry Andric   Align = 4;
110581ad6265SDimitry Andric   Type = OriginalType = ELF::SHT_PROGBITS;
110681ad6265SDimitry Andric   Name = ".gnu_debuglink";
110781ad6265SDimitry Andric   // For sections not found in segments, OriginalOffset is only used to
110881ad6265SDimitry Andric   // establish the order that sections should go in. By using the maximum
110981ad6265SDimitry Andric   // possible offset we cause this section to wind up at the end.
111081ad6265SDimitry Andric   OriginalOffset = std::numeric_limits<uint64_t>::max();
111181ad6265SDimitry Andric }
111281ad6265SDimitry Andric 
111381ad6265SDimitry Andric GnuDebugLinkSection::GnuDebugLinkSection(StringRef File,
111481ad6265SDimitry Andric                                          uint32_t PrecomputedCRC)
111581ad6265SDimitry Andric     : FileName(File), CRC32(PrecomputedCRC) {
111681ad6265SDimitry Andric   init(File);
111781ad6265SDimitry Andric }
111881ad6265SDimitry Andric 
111981ad6265SDimitry Andric template <class ELFT>
112081ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
112181ad6265SDimitry Andric   unsigned char *Buf =
112281ad6265SDimitry Andric       reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
112381ad6265SDimitry Andric   Elf_Word *CRC =
112481ad6265SDimitry Andric       reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
112581ad6265SDimitry Andric   *CRC = Sec.CRC32;
112681ad6265SDimitry Andric   llvm::copy(Sec.FileName, Buf);
112781ad6265SDimitry Andric   return Error::success();
112881ad6265SDimitry Andric }
112981ad6265SDimitry Andric 
113081ad6265SDimitry Andric Error GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
113181ad6265SDimitry Andric   return Visitor.visit(*this);
113281ad6265SDimitry Andric }
113381ad6265SDimitry Andric 
113481ad6265SDimitry Andric Error GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
113581ad6265SDimitry Andric   return Visitor.visit(*this);
113681ad6265SDimitry Andric }
113781ad6265SDimitry Andric 
113881ad6265SDimitry Andric template <class ELFT>
113981ad6265SDimitry Andric Error ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
114081ad6265SDimitry Andric   ELF::Elf32_Word *Buf =
114181ad6265SDimitry Andric       reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
114281ad6265SDimitry Andric   support::endian::write32<ELFT::TargetEndianness>(Buf++, Sec.FlagWord);
114381ad6265SDimitry Andric   for (SectionBase *S : Sec.GroupMembers)
114481ad6265SDimitry Andric     support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
114581ad6265SDimitry Andric   return Error::success();
114681ad6265SDimitry Andric }
114781ad6265SDimitry Andric 
114881ad6265SDimitry Andric Error GroupSection::accept(SectionVisitor &Visitor) const {
114981ad6265SDimitry Andric   return Visitor.visit(*this);
115081ad6265SDimitry Andric }
115181ad6265SDimitry Andric 
115281ad6265SDimitry Andric Error GroupSection::accept(MutableSectionVisitor &Visitor) {
115381ad6265SDimitry Andric   return Visitor.visit(*this);
115481ad6265SDimitry Andric }
115581ad6265SDimitry Andric 
115681ad6265SDimitry Andric // Returns true IFF a section is wholly inside the range of a segment
115781ad6265SDimitry Andric static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) {
115881ad6265SDimitry Andric   // If a section is empty it should be treated like it has a size of 1. This is
115981ad6265SDimitry Andric   // to clarify the case when an empty section lies on a boundary between two
116081ad6265SDimitry Andric   // segments and ensures that the section "belongs" to the second segment and
116181ad6265SDimitry Andric   // not the first.
116281ad6265SDimitry Andric   uint64_t SecSize = Sec.Size ? Sec.Size : 1;
116381ad6265SDimitry Andric 
116481ad6265SDimitry Andric   // Ignore just added sections.
116581ad6265SDimitry Andric   if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max())
116681ad6265SDimitry Andric     return false;
116781ad6265SDimitry Andric 
116881ad6265SDimitry Andric   if (Sec.Type == SHT_NOBITS) {
116981ad6265SDimitry Andric     if (!(Sec.Flags & SHF_ALLOC))
117081ad6265SDimitry Andric       return false;
117181ad6265SDimitry Andric 
117281ad6265SDimitry Andric     bool SectionIsTLS = Sec.Flags & SHF_TLS;
117381ad6265SDimitry Andric     bool SegmentIsTLS = Seg.Type == PT_TLS;
117481ad6265SDimitry Andric     if (SectionIsTLS != SegmentIsTLS)
117581ad6265SDimitry Andric       return false;
117681ad6265SDimitry Andric 
117781ad6265SDimitry Andric     return Seg.VAddr <= Sec.Addr &&
117881ad6265SDimitry Andric            Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize;
117981ad6265SDimitry Andric   }
118081ad6265SDimitry Andric 
118181ad6265SDimitry Andric   return Seg.Offset <= Sec.OriginalOffset &&
118281ad6265SDimitry Andric          Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize;
118381ad6265SDimitry Andric }
118481ad6265SDimitry Andric 
118581ad6265SDimitry Andric // Returns true IFF a segment's original offset is inside of another segment's
118681ad6265SDimitry Andric // range.
118781ad6265SDimitry Andric static bool segmentOverlapsSegment(const Segment &Child,
118881ad6265SDimitry Andric                                    const Segment &Parent) {
118981ad6265SDimitry Andric 
119081ad6265SDimitry Andric   return Parent.OriginalOffset <= Child.OriginalOffset &&
119181ad6265SDimitry Andric          Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
119281ad6265SDimitry Andric }
119381ad6265SDimitry Andric 
119481ad6265SDimitry Andric static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
119581ad6265SDimitry Andric   // Any segment without a parent segment should come before a segment
119681ad6265SDimitry Andric   // that has a parent segment.
119781ad6265SDimitry Andric   if (A->OriginalOffset < B->OriginalOffset)
119881ad6265SDimitry Andric     return true;
119981ad6265SDimitry Andric   if (A->OriginalOffset > B->OriginalOffset)
120081ad6265SDimitry Andric     return false;
120181ad6265SDimitry Andric   return A->Index < B->Index;
120281ad6265SDimitry Andric }
120381ad6265SDimitry Andric 
120481ad6265SDimitry Andric void BasicELFBuilder::initFileHeader() {
120581ad6265SDimitry Andric   Obj->Flags = 0x0;
120681ad6265SDimitry Andric   Obj->Type = ET_REL;
120781ad6265SDimitry Andric   Obj->OSABI = ELFOSABI_NONE;
120881ad6265SDimitry Andric   Obj->ABIVersion = 0;
120981ad6265SDimitry Andric   Obj->Entry = 0x0;
121081ad6265SDimitry Andric   Obj->Machine = EM_NONE;
121181ad6265SDimitry Andric   Obj->Version = 1;
121281ad6265SDimitry Andric }
121381ad6265SDimitry Andric 
121481ad6265SDimitry Andric void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
121581ad6265SDimitry Andric 
121681ad6265SDimitry Andric StringTableSection *BasicELFBuilder::addStrTab() {
121781ad6265SDimitry Andric   auto &StrTab = Obj->addSection<StringTableSection>();
121881ad6265SDimitry Andric   StrTab.Name = ".strtab";
121981ad6265SDimitry Andric 
122081ad6265SDimitry Andric   Obj->SectionNames = &StrTab;
122181ad6265SDimitry Andric   return &StrTab;
122281ad6265SDimitry Andric }
122381ad6265SDimitry Andric 
122481ad6265SDimitry Andric SymbolTableSection *BasicELFBuilder::addSymTab(StringTableSection *StrTab) {
122581ad6265SDimitry Andric   auto &SymTab = Obj->addSection<SymbolTableSection>();
122681ad6265SDimitry Andric 
122781ad6265SDimitry Andric   SymTab.Name = ".symtab";
122881ad6265SDimitry Andric   SymTab.Link = StrTab->Index;
122981ad6265SDimitry Andric 
123081ad6265SDimitry Andric   // The symbol table always needs a null symbol
123181ad6265SDimitry Andric   SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
123281ad6265SDimitry Andric 
123381ad6265SDimitry Andric   Obj->SymbolTable = &SymTab;
123481ad6265SDimitry Andric   return &SymTab;
123581ad6265SDimitry Andric }
123681ad6265SDimitry Andric 
123781ad6265SDimitry Andric Error BasicELFBuilder::initSections() {
123881ad6265SDimitry Andric   for (SectionBase &Sec : Obj->sections())
123981ad6265SDimitry Andric     if (Error Err = Sec.initialize(Obj->sections()))
124081ad6265SDimitry Andric       return Err;
124181ad6265SDimitry Andric 
124281ad6265SDimitry Andric   return Error::success();
124381ad6265SDimitry Andric }
124481ad6265SDimitry Andric 
124581ad6265SDimitry Andric void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
124681ad6265SDimitry Andric   auto Data = ArrayRef<uint8_t>(
124781ad6265SDimitry Andric       reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
124881ad6265SDimitry Andric       MemBuf->getBufferSize());
124981ad6265SDimitry Andric   auto &DataSection = Obj->addSection<Section>(Data);
125081ad6265SDimitry Andric   DataSection.Name = ".data";
125181ad6265SDimitry Andric   DataSection.Type = ELF::SHT_PROGBITS;
125281ad6265SDimitry Andric   DataSection.Size = Data.size();
125381ad6265SDimitry Andric   DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
125481ad6265SDimitry Andric 
125581ad6265SDimitry Andric   std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
125681ad6265SDimitry Andric   std::replace_if(
125781ad6265SDimitry Andric       std::begin(SanitizedFilename), std::end(SanitizedFilename),
125881ad6265SDimitry Andric       [](char C) { return !isAlnum(C); }, '_');
125981ad6265SDimitry Andric   Twine Prefix = Twine("_binary_") + SanitizedFilename;
126081ad6265SDimitry Andric 
126181ad6265SDimitry Andric   SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
126281ad6265SDimitry Andric                     /*Value=*/0, NewSymbolVisibility, 0, 0);
126381ad6265SDimitry Andric   SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
126481ad6265SDimitry Andric                     /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
126581ad6265SDimitry Andric   SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
126681ad6265SDimitry Andric                     /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
126781ad6265SDimitry Andric                     0);
126881ad6265SDimitry Andric }
126981ad6265SDimitry Andric 
127081ad6265SDimitry Andric Expected<std::unique_ptr<Object>> BinaryELFBuilder::build() {
127181ad6265SDimitry Andric   initFileHeader();
127281ad6265SDimitry Andric   initHeaderSegment();
127381ad6265SDimitry Andric 
127481ad6265SDimitry Andric   SymbolTableSection *SymTab = addSymTab(addStrTab());
127581ad6265SDimitry Andric   if (Error Err = initSections())
127681ad6265SDimitry Andric     return std::move(Err);
127781ad6265SDimitry Andric   addData(SymTab);
127881ad6265SDimitry Andric 
127981ad6265SDimitry Andric   return std::move(Obj);
128081ad6265SDimitry Andric }
128181ad6265SDimitry Andric 
128281ad6265SDimitry Andric // Adds sections from IHEX data file. Data should have been
128381ad6265SDimitry Andric // fully validated by this time.
128481ad6265SDimitry Andric void IHexELFBuilder::addDataSections() {
128581ad6265SDimitry Andric   OwnedDataSection *Section = nullptr;
128681ad6265SDimitry Andric   uint64_t SegmentAddr = 0, BaseAddr = 0;
128781ad6265SDimitry Andric   uint32_t SecNo = 1;
128881ad6265SDimitry Andric 
128981ad6265SDimitry Andric   for (const IHexRecord &R : Records) {
129081ad6265SDimitry Andric     uint64_t RecAddr;
129181ad6265SDimitry Andric     switch (R.Type) {
129281ad6265SDimitry Andric     case IHexRecord::Data:
129381ad6265SDimitry Andric       // Ignore empty data records
129481ad6265SDimitry Andric       if (R.HexData.empty())
129581ad6265SDimitry Andric         continue;
129681ad6265SDimitry Andric       RecAddr = R.Addr + SegmentAddr + BaseAddr;
129781ad6265SDimitry Andric       if (!Section || Section->Addr + Section->Size != RecAddr) {
129881ad6265SDimitry Andric         // OriginalOffset field is only used to sort sections before layout, so
129981ad6265SDimitry Andric         // instead of keeping track of real offsets in IHEX file, and as
130081ad6265SDimitry Andric         // layoutSections() and layoutSectionsForOnlyKeepDebug() use
130181ad6265SDimitry Andric         // llvm::stable_sort(), we can just set it to a constant (zero).
130281ad6265SDimitry Andric         Section = &Obj->addSection<OwnedDataSection>(
130381ad6265SDimitry Andric             ".sec" + std::to_string(SecNo), RecAddr,
130481ad6265SDimitry Andric             ELF::SHF_ALLOC | ELF::SHF_WRITE, 0);
130581ad6265SDimitry Andric         SecNo++;
130681ad6265SDimitry Andric       }
130781ad6265SDimitry Andric       Section->appendHexData(R.HexData);
130881ad6265SDimitry Andric       break;
130981ad6265SDimitry Andric     case IHexRecord::EndOfFile:
131081ad6265SDimitry Andric       break;
131181ad6265SDimitry Andric     case IHexRecord::SegmentAddr:
131281ad6265SDimitry Andric       // 20-bit segment address.
131381ad6265SDimitry Andric       SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
131481ad6265SDimitry Andric       break;
131581ad6265SDimitry Andric     case IHexRecord::StartAddr80x86:
131681ad6265SDimitry Andric     case IHexRecord::StartAddr:
131781ad6265SDimitry Andric       Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
131881ad6265SDimitry Andric       assert(Obj->Entry <= 0xFFFFFU);
131981ad6265SDimitry Andric       break;
132081ad6265SDimitry Andric     case IHexRecord::ExtendedAddr:
132181ad6265SDimitry Andric       // 16-31 bits of linear base address
132281ad6265SDimitry Andric       BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
132381ad6265SDimitry Andric       break;
132481ad6265SDimitry Andric     default:
132581ad6265SDimitry Andric       llvm_unreachable("unknown record type");
132681ad6265SDimitry Andric     }
132781ad6265SDimitry Andric   }
132881ad6265SDimitry Andric }
132981ad6265SDimitry Andric 
133081ad6265SDimitry Andric Expected<std::unique_ptr<Object>> IHexELFBuilder::build() {
133181ad6265SDimitry Andric   initFileHeader();
133281ad6265SDimitry Andric   initHeaderSegment();
133381ad6265SDimitry Andric   StringTableSection *StrTab = addStrTab();
133481ad6265SDimitry Andric   addSymTab(StrTab);
133581ad6265SDimitry Andric   if (Error Err = initSections())
133681ad6265SDimitry Andric     return std::move(Err);
133781ad6265SDimitry Andric   addDataSections();
133881ad6265SDimitry Andric 
133981ad6265SDimitry Andric   return std::move(Obj);
134081ad6265SDimitry Andric }
134181ad6265SDimitry Andric 
134281ad6265SDimitry Andric template <class ELFT>
134381ad6265SDimitry Andric ELFBuilder<ELFT>::ELFBuilder(const ELFObjectFile<ELFT> &ElfObj, Object &Obj,
134481ad6265SDimitry Andric                              Optional<StringRef> ExtractPartition)
134581ad6265SDimitry Andric     : ElfFile(ElfObj.getELFFile()), Obj(Obj),
134681ad6265SDimitry Andric       ExtractPartition(ExtractPartition) {
134781ad6265SDimitry Andric   Obj.IsMips64EL = ElfFile.isMips64EL();
134881ad6265SDimitry Andric }
134981ad6265SDimitry Andric 
135081ad6265SDimitry Andric template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
135181ad6265SDimitry Andric   for (Segment &Parent : Obj.segments()) {
135281ad6265SDimitry Andric     // Every segment will overlap with itself but we don't want a segment to
135381ad6265SDimitry Andric     // be its own parent so we avoid that situation.
135481ad6265SDimitry Andric     if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
135581ad6265SDimitry Andric       // We want a canonical "most parental" segment but this requires
135681ad6265SDimitry Andric       // inspecting the ParentSegment.
135781ad6265SDimitry Andric       if (compareSegmentsByOffset(&Parent, &Child))
135881ad6265SDimitry Andric         if (Child.ParentSegment == nullptr ||
135981ad6265SDimitry Andric             compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
136081ad6265SDimitry Andric           Child.ParentSegment = &Parent;
136181ad6265SDimitry Andric         }
136281ad6265SDimitry Andric     }
136381ad6265SDimitry Andric   }
136481ad6265SDimitry Andric }
136581ad6265SDimitry Andric 
136681ad6265SDimitry Andric template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
136781ad6265SDimitry Andric   if (!ExtractPartition)
136881ad6265SDimitry Andric     return Error::success();
136981ad6265SDimitry Andric 
137081ad6265SDimitry Andric   for (const SectionBase &Sec : Obj.sections()) {
137181ad6265SDimitry Andric     if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
137281ad6265SDimitry Andric       EhdrOffset = Sec.Offset;
137381ad6265SDimitry Andric       return Error::success();
137481ad6265SDimitry Andric     }
137581ad6265SDimitry Andric   }
137681ad6265SDimitry Andric   return createStringError(errc::invalid_argument,
137781ad6265SDimitry Andric                            "could not find partition named '" +
137881ad6265SDimitry Andric                                *ExtractPartition + "'");
137981ad6265SDimitry Andric }
138081ad6265SDimitry Andric 
138181ad6265SDimitry Andric template <class ELFT>
138281ad6265SDimitry Andric Error ELFBuilder<ELFT>::readProgramHeaders(const ELFFile<ELFT> &HeadersFile) {
138381ad6265SDimitry Andric   uint32_t Index = 0;
138481ad6265SDimitry Andric 
138581ad6265SDimitry Andric   Expected<typename ELFFile<ELFT>::Elf_Phdr_Range> Headers =
138681ad6265SDimitry Andric       HeadersFile.program_headers();
138781ad6265SDimitry Andric   if (!Headers)
138881ad6265SDimitry Andric     return Headers.takeError();
138981ad6265SDimitry Andric 
139081ad6265SDimitry Andric   for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
139181ad6265SDimitry Andric     if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
139281ad6265SDimitry Andric       return createStringError(
139381ad6265SDimitry Andric           errc::invalid_argument,
139481ad6265SDimitry Andric           "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
139581ad6265SDimitry Andric               " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
139681ad6265SDimitry Andric               " goes past the end of the file");
139781ad6265SDimitry Andric 
139881ad6265SDimitry Andric     ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
139981ad6265SDimitry Andric                            (size_t)Phdr.p_filesz};
140081ad6265SDimitry Andric     Segment &Seg = Obj.addSegment(Data);
140181ad6265SDimitry Andric     Seg.Type = Phdr.p_type;
140281ad6265SDimitry Andric     Seg.Flags = Phdr.p_flags;
140381ad6265SDimitry Andric     Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
140481ad6265SDimitry Andric     Seg.Offset = Phdr.p_offset + EhdrOffset;
140581ad6265SDimitry Andric     Seg.VAddr = Phdr.p_vaddr;
140681ad6265SDimitry Andric     Seg.PAddr = Phdr.p_paddr;
140781ad6265SDimitry Andric     Seg.FileSize = Phdr.p_filesz;
140881ad6265SDimitry Andric     Seg.MemSize = Phdr.p_memsz;
140981ad6265SDimitry Andric     Seg.Align = Phdr.p_align;
141081ad6265SDimitry Andric     Seg.Index = Index++;
141181ad6265SDimitry Andric     for (SectionBase &Sec : Obj.sections())
141281ad6265SDimitry Andric       if (sectionWithinSegment(Sec, Seg)) {
141381ad6265SDimitry Andric         Seg.addSection(&Sec);
141481ad6265SDimitry Andric         if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
141581ad6265SDimitry Andric           Sec.ParentSegment = &Seg;
141681ad6265SDimitry Andric       }
141781ad6265SDimitry Andric   }
141881ad6265SDimitry Andric 
141981ad6265SDimitry Andric   auto &ElfHdr = Obj.ElfHdrSegment;
142081ad6265SDimitry Andric   ElfHdr.Index = Index++;
142181ad6265SDimitry Andric   ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
142281ad6265SDimitry Andric 
142381ad6265SDimitry Andric   const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
142481ad6265SDimitry Andric   auto &PrHdr = Obj.ProgramHdrSegment;
142581ad6265SDimitry Andric   PrHdr.Type = PT_PHDR;
142681ad6265SDimitry Andric   PrHdr.Flags = 0;
142781ad6265SDimitry Andric   // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
142881ad6265SDimitry Andric   // Whereas this works automatically for ElfHdr, here OriginalOffset is
142981ad6265SDimitry Andric   // always non-zero and to ensure the equation we assign the same value to
143081ad6265SDimitry Andric   // VAddr as well.
143181ad6265SDimitry Andric   PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
143281ad6265SDimitry Andric   PrHdr.PAddr = 0;
143381ad6265SDimitry Andric   PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
143481ad6265SDimitry Andric   // The spec requires us to naturally align all the fields.
143581ad6265SDimitry Andric   PrHdr.Align = sizeof(Elf_Addr);
143681ad6265SDimitry Andric   PrHdr.Index = Index++;
143781ad6265SDimitry Andric 
143881ad6265SDimitry Andric   // Now we do an O(n^2) loop through the segments in order to match up
143981ad6265SDimitry Andric   // segments.
144081ad6265SDimitry Andric   for (Segment &Child : Obj.segments())
144181ad6265SDimitry Andric     setParentSegment(Child);
144281ad6265SDimitry Andric   setParentSegment(ElfHdr);
144381ad6265SDimitry Andric   setParentSegment(PrHdr);
144481ad6265SDimitry Andric 
144581ad6265SDimitry Andric   return Error::success();
144681ad6265SDimitry Andric }
144781ad6265SDimitry Andric 
144881ad6265SDimitry Andric template <class ELFT>
144981ad6265SDimitry Andric Error ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
145081ad6265SDimitry Andric   if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
145181ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
145281ad6265SDimitry Andric                              "invalid alignment " + Twine(GroupSec->Align) +
145381ad6265SDimitry Andric                                  " of group section '" + GroupSec->Name + "'");
145481ad6265SDimitry Andric   SectionTableRef SecTable = Obj.sections();
145581ad6265SDimitry Andric   if (GroupSec->Link != SHN_UNDEF) {
145681ad6265SDimitry Andric     auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
145781ad6265SDimitry Andric         GroupSec->Link,
145881ad6265SDimitry Andric         "link field value '" + Twine(GroupSec->Link) + "' in section '" +
145981ad6265SDimitry Andric             GroupSec->Name + "' is invalid",
146081ad6265SDimitry Andric         "link field value '" + Twine(GroupSec->Link) + "' in section '" +
146181ad6265SDimitry Andric             GroupSec->Name + "' is not a symbol table");
146281ad6265SDimitry Andric     if (!SymTab)
146381ad6265SDimitry Andric       return SymTab.takeError();
146481ad6265SDimitry Andric 
146581ad6265SDimitry Andric     Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
146681ad6265SDimitry Andric     if (!Sym)
146781ad6265SDimitry Andric       return createStringError(errc::invalid_argument,
146881ad6265SDimitry Andric                                "info field value '" + Twine(GroupSec->Info) +
146981ad6265SDimitry Andric                                    "' in section '" + GroupSec->Name +
147081ad6265SDimitry Andric                                    "' is not a valid symbol index");
147181ad6265SDimitry Andric     GroupSec->setSymTab(*SymTab);
147281ad6265SDimitry Andric     GroupSec->setSymbol(*Sym);
147381ad6265SDimitry Andric   }
147481ad6265SDimitry Andric   if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
147581ad6265SDimitry Andric       GroupSec->Contents.empty())
147681ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
147781ad6265SDimitry Andric                              "the content of the section " + GroupSec->Name +
147881ad6265SDimitry Andric                                  " is malformed");
147981ad6265SDimitry Andric   const ELF::Elf32_Word *Word =
148081ad6265SDimitry Andric       reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
148181ad6265SDimitry Andric   const ELF::Elf32_Word *End =
148281ad6265SDimitry Andric       Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
148381ad6265SDimitry Andric   GroupSec->setFlagWord(
148481ad6265SDimitry Andric       support::endian::read32<ELFT::TargetEndianness>(Word++));
148581ad6265SDimitry Andric   for (; Word != End; ++Word) {
148681ad6265SDimitry Andric     uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
148781ad6265SDimitry Andric     Expected<SectionBase *> Sec = SecTable.getSection(
148881ad6265SDimitry Andric         Index, "group member index " + Twine(Index) + " in section '" +
148981ad6265SDimitry Andric                    GroupSec->Name + "' is invalid");
149081ad6265SDimitry Andric     if (!Sec)
149181ad6265SDimitry Andric       return Sec.takeError();
149281ad6265SDimitry Andric 
149381ad6265SDimitry Andric     GroupSec->addMember(*Sec);
149481ad6265SDimitry Andric   }
149581ad6265SDimitry Andric 
149681ad6265SDimitry Andric   return Error::success();
149781ad6265SDimitry Andric }
149881ad6265SDimitry Andric 
149981ad6265SDimitry Andric template <class ELFT>
150081ad6265SDimitry Andric Error ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
150181ad6265SDimitry Andric   Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
150281ad6265SDimitry Andric   if (!Shdr)
150381ad6265SDimitry Andric     return Shdr.takeError();
150481ad6265SDimitry Andric 
150581ad6265SDimitry Andric   Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
150681ad6265SDimitry Andric   if (!StrTabData)
150781ad6265SDimitry Andric     return StrTabData.takeError();
150881ad6265SDimitry Andric 
150981ad6265SDimitry Andric   ArrayRef<Elf_Word> ShndxData;
151081ad6265SDimitry Andric 
151181ad6265SDimitry Andric   Expected<typename ELFFile<ELFT>::Elf_Sym_Range> Symbols =
151281ad6265SDimitry Andric       ElfFile.symbols(*Shdr);
151381ad6265SDimitry Andric   if (!Symbols)
151481ad6265SDimitry Andric     return Symbols.takeError();
151581ad6265SDimitry Andric 
151681ad6265SDimitry Andric   for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
151781ad6265SDimitry Andric     SectionBase *DefSection = nullptr;
151881ad6265SDimitry Andric 
151981ad6265SDimitry Andric     Expected<StringRef> Name = Sym.getName(*StrTabData);
152081ad6265SDimitry Andric     if (!Name)
152181ad6265SDimitry Andric       return Name.takeError();
152281ad6265SDimitry Andric 
152381ad6265SDimitry Andric     if (Sym.st_shndx == SHN_XINDEX) {
152481ad6265SDimitry Andric       if (SymTab->getShndxTable() == nullptr)
152581ad6265SDimitry Andric         return createStringError(errc::invalid_argument,
152681ad6265SDimitry Andric                                  "symbol '" + *Name +
152781ad6265SDimitry Andric                                      "' has index SHN_XINDEX but no "
152881ad6265SDimitry Andric                                      "SHT_SYMTAB_SHNDX section exists");
152981ad6265SDimitry Andric       if (ShndxData.data() == nullptr) {
153081ad6265SDimitry Andric         Expected<const Elf_Shdr *> ShndxSec =
153181ad6265SDimitry Andric             ElfFile.getSection(SymTab->getShndxTable()->Index);
153281ad6265SDimitry Andric         if (!ShndxSec)
153381ad6265SDimitry Andric           return ShndxSec.takeError();
153481ad6265SDimitry Andric 
153581ad6265SDimitry Andric         Expected<ArrayRef<Elf_Word>> Data =
153681ad6265SDimitry Andric             ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
153781ad6265SDimitry Andric         if (!Data)
153881ad6265SDimitry Andric           return Data.takeError();
153981ad6265SDimitry Andric 
154081ad6265SDimitry Andric         ShndxData = *Data;
154181ad6265SDimitry Andric         if (ShndxData.size() != Symbols->size())
154281ad6265SDimitry Andric           return createStringError(
154381ad6265SDimitry Andric               errc::invalid_argument,
154481ad6265SDimitry Andric               "symbol section index table does not have the same number of "
154581ad6265SDimitry Andric               "entries as the symbol table");
154681ad6265SDimitry Andric       }
154781ad6265SDimitry Andric       Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
154881ad6265SDimitry Andric       Expected<SectionBase *> Sec = Obj.sections().getSection(
154981ad6265SDimitry Andric           Index,
155081ad6265SDimitry Andric           "symbol '" + *Name + "' has invalid section index " + Twine(Index));
155181ad6265SDimitry Andric       if (!Sec)
155281ad6265SDimitry Andric         return Sec.takeError();
155381ad6265SDimitry Andric 
155481ad6265SDimitry Andric       DefSection = *Sec;
155581ad6265SDimitry Andric     } else if (Sym.st_shndx >= SHN_LORESERVE) {
155681ad6265SDimitry Andric       if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
155781ad6265SDimitry Andric         return createStringError(
155881ad6265SDimitry Andric             errc::invalid_argument,
155981ad6265SDimitry Andric             "symbol '" + *Name +
156081ad6265SDimitry Andric                 "' has unsupported value greater than or equal "
156181ad6265SDimitry Andric                 "to SHN_LORESERVE: " +
156281ad6265SDimitry Andric                 Twine(Sym.st_shndx));
156381ad6265SDimitry Andric       }
156481ad6265SDimitry Andric     } else if (Sym.st_shndx != SHN_UNDEF) {
156581ad6265SDimitry Andric       Expected<SectionBase *> Sec = Obj.sections().getSection(
156681ad6265SDimitry Andric           Sym.st_shndx, "symbol '" + *Name +
156781ad6265SDimitry Andric                             "' is defined has invalid section index " +
156881ad6265SDimitry Andric                             Twine(Sym.st_shndx));
156981ad6265SDimitry Andric       if (!Sec)
157081ad6265SDimitry Andric         return Sec.takeError();
157181ad6265SDimitry Andric 
157281ad6265SDimitry Andric       DefSection = *Sec;
157381ad6265SDimitry Andric     }
157481ad6265SDimitry Andric 
157581ad6265SDimitry Andric     SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
157681ad6265SDimitry Andric                       Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
157781ad6265SDimitry Andric   }
157881ad6265SDimitry Andric 
157981ad6265SDimitry Andric   return Error::success();
158081ad6265SDimitry Andric }
158181ad6265SDimitry Andric 
158281ad6265SDimitry Andric template <class ELFT>
158381ad6265SDimitry Andric static void getAddend(uint64_t &, const Elf_Rel_Impl<ELFT, false> &) {}
158481ad6265SDimitry Andric 
158581ad6265SDimitry Andric template <class ELFT>
158681ad6265SDimitry Andric static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
158781ad6265SDimitry Andric   ToSet = Rela.r_addend;
158881ad6265SDimitry Andric }
158981ad6265SDimitry Andric 
159081ad6265SDimitry Andric template <class T>
159181ad6265SDimitry Andric static Error initRelocations(RelocationSection *Relocs, T RelRange) {
159281ad6265SDimitry Andric   for (const auto &Rel : RelRange) {
159381ad6265SDimitry Andric     Relocation ToAdd;
159481ad6265SDimitry Andric     ToAdd.Offset = Rel.r_offset;
159581ad6265SDimitry Andric     getAddend(ToAdd.Addend, Rel);
159681ad6265SDimitry Andric     ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
159781ad6265SDimitry Andric 
159881ad6265SDimitry Andric     if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
159981ad6265SDimitry Andric       if (!Relocs->getObject().SymbolTable)
160081ad6265SDimitry Andric         return createStringError(
160181ad6265SDimitry Andric             errc::invalid_argument,
160281ad6265SDimitry Andric             "'" + Relocs->Name + "': relocation references symbol with index " +
160381ad6265SDimitry Andric                 Twine(Sym) + ", but there is no symbol table");
160481ad6265SDimitry Andric       Expected<Symbol *> SymByIndex =
160581ad6265SDimitry Andric           Relocs->getObject().SymbolTable->getSymbolByIndex(Sym);
160681ad6265SDimitry Andric       if (!SymByIndex)
160781ad6265SDimitry Andric         return SymByIndex.takeError();
160881ad6265SDimitry Andric 
160981ad6265SDimitry Andric       ToAdd.RelocSymbol = *SymByIndex;
161081ad6265SDimitry Andric     }
161181ad6265SDimitry Andric 
161281ad6265SDimitry Andric     Relocs->addRelocation(ToAdd);
161381ad6265SDimitry Andric   }
161481ad6265SDimitry Andric 
161581ad6265SDimitry Andric   return Error::success();
161681ad6265SDimitry Andric }
161781ad6265SDimitry Andric 
161881ad6265SDimitry Andric Expected<SectionBase *> SectionTableRef::getSection(uint32_t Index,
161981ad6265SDimitry Andric                                                     Twine ErrMsg) {
162081ad6265SDimitry Andric   if (Index == SHN_UNDEF || Index > Sections.size())
162181ad6265SDimitry Andric     return createStringError(errc::invalid_argument, ErrMsg);
162281ad6265SDimitry Andric   return Sections[Index - 1].get();
162381ad6265SDimitry Andric }
162481ad6265SDimitry Andric 
162581ad6265SDimitry Andric template <class T>
162681ad6265SDimitry Andric Expected<T *> SectionTableRef::getSectionOfType(uint32_t Index,
162781ad6265SDimitry Andric                                                 Twine IndexErrMsg,
162881ad6265SDimitry Andric                                                 Twine TypeErrMsg) {
162981ad6265SDimitry Andric   Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
163081ad6265SDimitry Andric   if (!BaseSec)
163181ad6265SDimitry Andric     return BaseSec.takeError();
163281ad6265SDimitry Andric 
163381ad6265SDimitry Andric   if (T *Sec = dyn_cast<T>(*BaseSec))
163481ad6265SDimitry Andric     return Sec;
163581ad6265SDimitry Andric 
163681ad6265SDimitry Andric   return createStringError(errc::invalid_argument, TypeErrMsg);
163781ad6265SDimitry Andric }
163881ad6265SDimitry Andric 
163981ad6265SDimitry Andric template <class ELFT>
164081ad6265SDimitry Andric Expected<SectionBase &> ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
164181ad6265SDimitry Andric   switch (Shdr.sh_type) {
164281ad6265SDimitry Andric   case SHT_REL:
164381ad6265SDimitry Andric   case SHT_RELA:
164481ad6265SDimitry Andric     if (Shdr.sh_flags & SHF_ALLOC) {
164581ad6265SDimitry Andric       if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
164681ad6265SDimitry Andric         return Obj.addSection<DynamicRelocationSection>(*Data);
164781ad6265SDimitry Andric       else
164881ad6265SDimitry Andric         return Data.takeError();
164981ad6265SDimitry Andric     }
165081ad6265SDimitry Andric     return Obj.addSection<RelocationSection>(Obj);
165181ad6265SDimitry Andric   case SHT_STRTAB:
165281ad6265SDimitry Andric     // If a string table is allocated we don't want to mess with it. That would
165381ad6265SDimitry Andric     // mean altering the memory image. There are no special link types or
165481ad6265SDimitry Andric     // anything so we can just use a Section.
165581ad6265SDimitry Andric     if (Shdr.sh_flags & SHF_ALLOC) {
165681ad6265SDimitry Andric       if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
165781ad6265SDimitry Andric         return Obj.addSection<Section>(*Data);
165881ad6265SDimitry Andric       else
165981ad6265SDimitry Andric         return Data.takeError();
166081ad6265SDimitry Andric     }
166181ad6265SDimitry Andric     return Obj.addSection<StringTableSection>();
166281ad6265SDimitry Andric   case SHT_HASH:
166381ad6265SDimitry Andric   case SHT_GNU_HASH:
166481ad6265SDimitry Andric     // Hash tables should refer to SHT_DYNSYM which we're not going to change.
166581ad6265SDimitry Andric     // Because of this we don't need to mess with the hash tables either.
166681ad6265SDimitry Andric     if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
166781ad6265SDimitry Andric       return Obj.addSection<Section>(*Data);
166881ad6265SDimitry Andric     else
166981ad6265SDimitry Andric       return Data.takeError();
167081ad6265SDimitry Andric   case SHT_GROUP:
167181ad6265SDimitry Andric     if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
167281ad6265SDimitry Andric       return Obj.addSection<GroupSection>(*Data);
167381ad6265SDimitry Andric     else
167481ad6265SDimitry Andric       return Data.takeError();
167581ad6265SDimitry Andric   case SHT_DYNSYM:
167681ad6265SDimitry Andric     if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
167781ad6265SDimitry Andric       return Obj.addSection<DynamicSymbolTableSection>(*Data);
167881ad6265SDimitry Andric     else
167981ad6265SDimitry Andric       return Data.takeError();
168081ad6265SDimitry Andric   case SHT_DYNAMIC:
168181ad6265SDimitry Andric     if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
168281ad6265SDimitry Andric       return Obj.addSection<DynamicSection>(*Data);
168381ad6265SDimitry Andric     else
168481ad6265SDimitry Andric       return Data.takeError();
168581ad6265SDimitry Andric   case SHT_SYMTAB: {
168681ad6265SDimitry Andric     auto &SymTab = Obj.addSection<SymbolTableSection>();
168781ad6265SDimitry Andric     Obj.SymbolTable = &SymTab;
168881ad6265SDimitry Andric     return SymTab;
168981ad6265SDimitry Andric   }
169081ad6265SDimitry Andric   case SHT_SYMTAB_SHNDX: {
169181ad6265SDimitry Andric     auto &ShndxSection = Obj.addSection<SectionIndexSection>();
169281ad6265SDimitry Andric     Obj.SectionIndexTable = &ShndxSection;
169381ad6265SDimitry Andric     return ShndxSection;
169481ad6265SDimitry Andric   }
169581ad6265SDimitry Andric   case SHT_NOBITS:
169681ad6265SDimitry Andric     return Obj.addSection<Section>(ArrayRef<uint8_t>());
169781ad6265SDimitry Andric   default: {
169881ad6265SDimitry Andric     Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
169981ad6265SDimitry Andric     if (!Data)
170081ad6265SDimitry Andric       return Data.takeError();
170181ad6265SDimitry Andric 
170281ad6265SDimitry Andric     Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
170381ad6265SDimitry Andric     if (!Name)
170481ad6265SDimitry Andric       return Name.takeError();
170581ad6265SDimitry Andric 
1706*972a253aSDimitry Andric     if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
170781ad6265SDimitry Andric       return Obj.addSection<Section>(*Data);
1708*972a253aSDimitry Andric     auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
1709*972a253aSDimitry Andric     return Obj.addSection<CompressedSection>(
1710*972a253aSDimitry Andric         CompressedSection(*Data, Chdr->ch_size, Chdr->ch_addralign));
171181ad6265SDimitry Andric   }
171281ad6265SDimitry Andric   }
171381ad6265SDimitry Andric }
171481ad6265SDimitry Andric 
171581ad6265SDimitry Andric template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
171681ad6265SDimitry Andric   uint32_t Index = 0;
171781ad6265SDimitry Andric   Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections =
171881ad6265SDimitry Andric       ElfFile.sections();
171981ad6265SDimitry Andric   if (!Sections)
172081ad6265SDimitry Andric     return Sections.takeError();
172181ad6265SDimitry Andric 
172281ad6265SDimitry Andric   for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
172381ad6265SDimitry Andric     if (Index == 0) {
172481ad6265SDimitry Andric       ++Index;
172581ad6265SDimitry Andric       continue;
172681ad6265SDimitry Andric     }
172781ad6265SDimitry Andric     Expected<SectionBase &> Sec = makeSection(Shdr);
172881ad6265SDimitry Andric     if (!Sec)
172981ad6265SDimitry Andric       return Sec.takeError();
173081ad6265SDimitry Andric 
173181ad6265SDimitry Andric     Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
173281ad6265SDimitry Andric     if (!SecName)
173381ad6265SDimitry Andric       return SecName.takeError();
173481ad6265SDimitry Andric     Sec->Name = SecName->str();
173581ad6265SDimitry Andric     Sec->Type = Sec->OriginalType = Shdr.sh_type;
173681ad6265SDimitry Andric     Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
173781ad6265SDimitry Andric     Sec->Addr = Shdr.sh_addr;
173881ad6265SDimitry Andric     Sec->Offset = Shdr.sh_offset;
173981ad6265SDimitry Andric     Sec->OriginalOffset = Shdr.sh_offset;
174081ad6265SDimitry Andric     Sec->Size = Shdr.sh_size;
174181ad6265SDimitry Andric     Sec->Link = Shdr.sh_link;
174281ad6265SDimitry Andric     Sec->Info = Shdr.sh_info;
174381ad6265SDimitry Andric     Sec->Align = Shdr.sh_addralign;
174481ad6265SDimitry Andric     Sec->EntrySize = Shdr.sh_entsize;
174581ad6265SDimitry Andric     Sec->Index = Index++;
174681ad6265SDimitry Andric     Sec->OriginalIndex = Sec->Index;
174781ad6265SDimitry Andric     Sec->OriginalData = ArrayRef<uint8_t>(
174881ad6265SDimitry Andric         ElfFile.base() + Shdr.sh_offset,
174981ad6265SDimitry Andric         (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
175081ad6265SDimitry Andric   }
175181ad6265SDimitry Andric 
175281ad6265SDimitry Andric   return Error::success();
175381ad6265SDimitry Andric }
175481ad6265SDimitry Andric 
175581ad6265SDimitry Andric template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
175681ad6265SDimitry Andric   uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
175781ad6265SDimitry Andric   if (ShstrIndex == SHN_XINDEX) {
175881ad6265SDimitry Andric     Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
175981ad6265SDimitry Andric     if (!Sec)
176081ad6265SDimitry Andric       return Sec.takeError();
176181ad6265SDimitry Andric 
176281ad6265SDimitry Andric     ShstrIndex = (*Sec)->sh_link;
176381ad6265SDimitry Andric   }
176481ad6265SDimitry Andric 
176581ad6265SDimitry Andric   if (ShstrIndex == SHN_UNDEF)
176681ad6265SDimitry Andric     Obj.HadShdrs = false;
176781ad6265SDimitry Andric   else {
176881ad6265SDimitry Andric     Expected<StringTableSection *> Sec =
176981ad6265SDimitry Andric         Obj.sections().template getSectionOfType<StringTableSection>(
177081ad6265SDimitry Andric             ShstrIndex,
177181ad6265SDimitry Andric             "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
177281ad6265SDimitry Andric                 " is invalid",
177381ad6265SDimitry Andric             "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
177481ad6265SDimitry Andric                 " does not reference a string table");
177581ad6265SDimitry Andric     if (!Sec)
177681ad6265SDimitry Andric       return Sec.takeError();
177781ad6265SDimitry Andric 
177881ad6265SDimitry Andric     Obj.SectionNames = *Sec;
177981ad6265SDimitry Andric   }
178081ad6265SDimitry Andric 
178181ad6265SDimitry Andric   // If a section index table exists we'll need to initialize it before we
178281ad6265SDimitry Andric   // initialize the symbol table because the symbol table might need to
178381ad6265SDimitry Andric   // reference it.
178481ad6265SDimitry Andric   if (Obj.SectionIndexTable)
178581ad6265SDimitry Andric     if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
178681ad6265SDimitry Andric       return Err;
178781ad6265SDimitry Andric 
178881ad6265SDimitry Andric   // Now that all of the sections have been added we can fill out some extra
178981ad6265SDimitry Andric   // details about symbol tables. We need the symbol table filled out before
179081ad6265SDimitry Andric   // any relocations.
179181ad6265SDimitry Andric   if (Obj.SymbolTable) {
179281ad6265SDimitry Andric     if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
179381ad6265SDimitry Andric       return Err;
179481ad6265SDimitry Andric     if (Error Err = initSymbolTable(Obj.SymbolTable))
179581ad6265SDimitry Andric       return Err;
179681ad6265SDimitry Andric   } else if (EnsureSymtab) {
179781ad6265SDimitry Andric     if (Error Err = Obj.addNewSymbolTable())
179881ad6265SDimitry Andric       return Err;
179981ad6265SDimitry Andric   }
180081ad6265SDimitry Andric 
180181ad6265SDimitry Andric   // Now that all sections and symbols have been added we can add
180281ad6265SDimitry Andric   // relocations that reference symbols and set the link and info fields for
180381ad6265SDimitry Andric   // relocation sections.
180481ad6265SDimitry Andric   for (SectionBase &Sec : Obj.sections()) {
180581ad6265SDimitry Andric     if (&Sec == Obj.SymbolTable)
180681ad6265SDimitry Andric       continue;
180781ad6265SDimitry Andric     if (Error Err = Sec.initialize(Obj.sections()))
180881ad6265SDimitry Andric       return Err;
180981ad6265SDimitry Andric     if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
181081ad6265SDimitry Andric       Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections =
181181ad6265SDimitry Andric           ElfFile.sections();
181281ad6265SDimitry Andric       if (!Sections)
181381ad6265SDimitry Andric         return Sections.takeError();
181481ad6265SDimitry Andric 
181581ad6265SDimitry Andric       const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
181681ad6265SDimitry Andric           Sections->begin() + RelSec->Index;
181781ad6265SDimitry Andric       if (RelSec->Type == SHT_REL) {
181881ad6265SDimitry Andric         Expected<typename ELFFile<ELFT>::Elf_Rel_Range> Rels =
181981ad6265SDimitry Andric             ElfFile.rels(*Shdr);
182081ad6265SDimitry Andric         if (!Rels)
182181ad6265SDimitry Andric           return Rels.takeError();
182281ad6265SDimitry Andric 
182381ad6265SDimitry Andric         if (Error Err = initRelocations(RelSec, *Rels))
182481ad6265SDimitry Andric           return Err;
182581ad6265SDimitry Andric       } else {
182681ad6265SDimitry Andric         Expected<typename ELFFile<ELFT>::Elf_Rela_Range> Relas =
182781ad6265SDimitry Andric             ElfFile.relas(*Shdr);
182881ad6265SDimitry Andric         if (!Relas)
182981ad6265SDimitry Andric           return Relas.takeError();
183081ad6265SDimitry Andric 
183181ad6265SDimitry Andric         if (Error Err = initRelocations(RelSec, *Relas))
183281ad6265SDimitry Andric           return Err;
183381ad6265SDimitry Andric       }
183481ad6265SDimitry Andric     } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
183581ad6265SDimitry Andric       if (Error Err = initGroupSection(GroupSec))
183681ad6265SDimitry Andric         return Err;
183781ad6265SDimitry Andric     }
183881ad6265SDimitry Andric   }
183981ad6265SDimitry Andric 
184081ad6265SDimitry Andric   return Error::success();
184181ad6265SDimitry Andric }
184281ad6265SDimitry Andric 
184381ad6265SDimitry Andric template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
184481ad6265SDimitry Andric   if (Error E = readSectionHeaders())
184581ad6265SDimitry Andric     return E;
184681ad6265SDimitry Andric   if (Error E = findEhdrOffset())
184781ad6265SDimitry Andric     return E;
184881ad6265SDimitry Andric 
184981ad6265SDimitry Andric   // The ELFFile whose ELF headers and program headers are copied into the
185081ad6265SDimitry Andric   // output file. Normally the same as ElfFile, but if we're extracting a
185181ad6265SDimitry Andric   // loadable partition it will point to the partition's headers.
185281ad6265SDimitry Andric   Expected<ELFFile<ELFT>> HeadersFile = ELFFile<ELFT>::create(toStringRef(
185381ad6265SDimitry Andric       {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
185481ad6265SDimitry Andric   if (!HeadersFile)
185581ad6265SDimitry Andric     return HeadersFile.takeError();
185681ad6265SDimitry Andric 
185781ad6265SDimitry Andric   const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
185881ad6265SDimitry Andric   Obj.OSABI = Ehdr.e_ident[EI_OSABI];
185981ad6265SDimitry Andric   Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
186081ad6265SDimitry Andric   Obj.Type = Ehdr.e_type;
186181ad6265SDimitry Andric   Obj.Machine = Ehdr.e_machine;
186281ad6265SDimitry Andric   Obj.Version = Ehdr.e_version;
186381ad6265SDimitry Andric   Obj.Entry = Ehdr.e_entry;
186481ad6265SDimitry Andric   Obj.Flags = Ehdr.e_flags;
186581ad6265SDimitry Andric 
186681ad6265SDimitry Andric   if (Error E = readSections(EnsureSymtab))
186781ad6265SDimitry Andric     return E;
186881ad6265SDimitry Andric   return readProgramHeaders(*HeadersFile);
186981ad6265SDimitry Andric }
187081ad6265SDimitry Andric 
187181ad6265SDimitry Andric Writer::~Writer() = default;
187281ad6265SDimitry Andric 
187381ad6265SDimitry Andric Reader::~Reader() = default;
187481ad6265SDimitry Andric 
187581ad6265SDimitry Andric Expected<std::unique_ptr<Object>>
187681ad6265SDimitry Andric BinaryReader::create(bool /*EnsureSymtab*/) const {
187781ad6265SDimitry Andric   return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
187881ad6265SDimitry Andric }
187981ad6265SDimitry Andric 
188081ad6265SDimitry Andric Expected<std::vector<IHexRecord>> IHexReader::parse() const {
188181ad6265SDimitry Andric   SmallVector<StringRef, 16> Lines;
188281ad6265SDimitry Andric   std::vector<IHexRecord> Records;
188381ad6265SDimitry Andric   bool HasSections = false;
188481ad6265SDimitry Andric 
188581ad6265SDimitry Andric   MemBuf->getBuffer().split(Lines, '\n');
188681ad6265SDimitry Andric   Records.reserve(Lines.size());
188781ad6265SDimitry Andric   for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
188881ad6265SDimitry Andric     StringRef Line = Lines[LineNo - 1].trim();
188981ad6265SDimitry Andric     if (Line.empty())
189081ad6265SDimitry Andric       continue;
189181ad6265SDimitry Andric 
189281ad6265SDimitry Andric     Expected<IHexRecord> R = IHexRecord::parse(Line);
189381ad6265SDimitry Andric     if (!R)
189481ad6265SDimitry Andric       return parseError(LineNo, R.takeError());
189581ad6265SDimitry Andric     if (R->Type == IHexRecord::EndOfFile)
189681ad6265SDimitry Andric       break;
189781ad6265SDimitry Andric     HasSections |= (R->Type == IHexRecord::Data);
189881ad6265SDimitry Andric     Records.push_back(*R);
189981ad6265SDimitry Andric   }
190081ad6265SDimitry Andric   if (!HasSections)
190181ad6265SDimitry Andric     return parseError(-1U, "no sections");
190281ad6265SDimitry Andric 
190381ad6265SDimitry Andric   return std::move(Records);
190481ad6265SDimitry Andric }
190581ad6265SDimitry Andric 
190681ad6265SDimitry Andric Expected<std::unique_ptr<Object>>
190781ad6265SDimitry Andric IHexReader::create(bool /*EnsureSymtab*/) const {
190881ad6265SDimitry Andric   Expected<std::vector<IHexRecord>> Records = parse();
190981ad6265SDimitry Andric   if (!Records)
191081ad6265SDimitry Andric     return Records.takeError();
191181ad6265SDimitry Andric 
191281ad6265SDimitry Andric   return IHexELFBuilder(*Records).build();
191381ad6265SDimitry Andric }
191481ad6265SDimitry Andric 
191581ad6265SDimitry Andric Expected<std::unique_ptr<Object>> ELFReader::create(bool EnsureSymtab) const {
191681ad6265SDimitry Andric   auto Obj = std::make_unique<Object>();
191781ad6265SDimitry Andric   if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
191881ad6265SDimitry Andric     ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
191981ad6265SDimitry Andric     if (Error Err = Builder.build(EnsureSymtab))
192081ad6265SDimitry Andric       return std::move(Err);
192181ad6265SDimitry Andric     return std::move(Obj);
192281ad6265SDimitry Andric   } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
192381ad6265SDimitry Andric     ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
192481ad6265SDimitry Andric     if (Error Err = Builder.build(EnsureSymtab))
192581ad6265SDimitry Andric       return std::move(Err);
192681ad6265SDimitry Andric     return std::move(Obj);
192781ad6265SDimitry Andric   } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
192881ad6265SDimitry Andric     ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
192981ad6265SDimitry Andric     if (Error Err = Builder.build(EnsureSymtab))
193081ad6265SDimitry Andric       return std::move(Err);
193181ad6265SDimitry Andric     return std::move(Obj);
193281ad6265SDimitry Andric   } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
193381ad6265SDimitry Andric     ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
193481ad6265SDimitry Andric     if (Error Err = Builder.build(EnsureSymtab))
193581ad6265SDimitry Andric       return std::move(Err);
193681ad6265SDimitry Andric     return std::move(Obj);
193781ad6265SDimitry Andric   }
193881ad6265SDimitry Andric   return createStringError(errc::invalid_argument, "invalid file type");
193981ad6265SDimitry Andric }
194081ad6265SDimitry Andric 
194181ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
194281ad6265SDimitry Andric   Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
194381ad6265SDimitry Andric   std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
194481ad6265SDimitry Andric   Ehdr.e_ident[EI_MAG0] = 0x7f;
194581ad6265SDimitry Andric   Ehdr.e_ident[EI_MAG1] = 'E';
194681ad6265SDimitry Andric   Ehdr.e_ident[EI_MAG2] = 'L';
194781ad6265SDimitry Andric   Ehdr.e_ident[EI_MAG3] = 'F';
194881ad6265SDimitry Andric   Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
194981ad6265SDimitry Andric   Ehdr.e_ident[EI_DATA] =
195081ad6265SDimitry Andric       ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
195181ad6265SDimitry Andric   Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
195281ad6265SDimitry Andric   Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
195381ad6265SDimitry Andric   Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
195481ad6265SDimitry Andric 
195581ad6265SDimitry Andric   Ehdr.e_type = Obj.Type;
195681ad6265SDimitry Andric   Ehdr.e_machine = Obj.Machine;
195781ad6265SDimitry Andric   Ehdr.e_version = Obj.Version;
195881ad6265SDimitry Andric   Ehdr.e_entry = Obj.Entry;
195981ad6265SDimitry Andric   // We have to use the fully-qualified name llvm::size
196081ad6265SDimitry Andric   // since some compilers complain on ambiguous resolution.
196181ad6265SDimitry Andric   Ehdr.e_phnum = llvm::size(Obj.segments());
196281ad6265SDimitry Andric   Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
196381ad6265SDimitry Andric   Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
196481ad6265SDimitry Andric   Ehdr.e_flags = Obj.Flags;
196581ad6265SDimitry Andric   Ehdr.e_ehsize = sizeof(Elf_Ehdr);
196681ad6265SDimitry Andric   if (WriteSectionHeaders && Obj.sections().size() != 0) {
196781ad6265SDimitry Andric     Ehdr.e_shentsize = sizeof(Elf_Shdr);
196881ad6265SDimitry Andric     Ehdr.e_shoff = Obj.SHOff;
196981ad6265SDimitry Andric     // """
197081ad6265SDimitry Andric     // If the number of sections is greater than or equal to
197181ad6265SDimitry Andric     // SHN_LORESERVE (0xff00), this member has the value zero and the actual
197281ad6265SDimitry Andric     // number of section header table entries is contained in the sh_size field
197381ad6265SDimitry Andric     // of the section header at index 0.
197481ad6265SDimitry Andric     // """
197581ad6265SDimitry Andric     auto Shnum = Obj.sections().size() + 1;
197681ad6265SDimitry Andric     if (Shnum >= SHN_LORESERVE)
197781ad6265SDimitry Andric       Ehdr.e_shnum = 0;
197881ad6265SDimitry Andric     else
197981ad6265SDimitry Andric       Ehdr.e_shnum = Shnum;
198081ad6265SDimitry Andric     // """
198181ad6265SDimitry Andric     // If the section name string table section index is greater than or equal
198281ad6265SDimitry Andric     // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
198381ad6265SDimitry Andric     // and the actual index of the section name string table section is
198481ad6265SDimitry Andric     // contained in the sh_link field of the section header at index 0.
198581ad6265SDimitry Andric     // """
198681ad6265SDimitry Andric     if (Obj.SectionNames->Index >= SHN_LORESERVE)
198781ad6265SDimitry Andric       Ehdr.e_shstrndx = SHN_XINDEX;
198881ad6265SDimitry Andric     else
198981ad6265SDimitry Andric       Ehdr.e_shstrndx = Obj.SectionNames->Index;
199081ad6265SDimitry Andric   } else {
199181ad6265SDimitry Andric     Ehdr.e_shentsize = 0;
199281ad6265SDimitry Andric     Ehdr.e_shoff = 0;
199381ad6265SDimitry Andric     Ehdr.e_shnum = 0;
199481ad6265SDimitry Andric     Ehdr.e_shstrndx = 0;
199581ad6265SDimitry Andric   }
199681ad6265SDimitry Andric }
199781ad6265SDimitry Andric 
199881ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
199981ad6265SDimitry Andric   for (auto &Seg : Obj.segments())
200081ad6265SDimitry Andric     writePhdr(Seg);
200181ad6265SDimitry Andric }
200281ad6265SDimitry Andric 
200381ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
200481ad6265SDimitry Andric   // This reference serves to write the dummy section header at the begining
200581ad6265SDimitry Andric   // of the file. It is not used for anything else
200681ad6265SDimitry Andric   Elf_Shdr &Shdr =
200781ad6265SDimitry Andric       *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
200881ad6265SDimitry Andric   Shdr.sh_name = 0;
200981ad6265SDimitry Andric   Shdr.sh_type = SHT_NULL;
201081ad6265SDimitry Andric   Shdr.sh_flags = 0;
201181ad6265SDimitry Andric   Shdr.sh_addr = 0;
201281ad6265SDimitry Andric   Shdr.sh_offset = 0;
201381ad6265SDimitry Andric   // See writeEhdr for why we do this.
201481ad6265SDimitry Andric   uint64_t Shnum = Obj.sections().size() + 1;
201581ad6265SDimitry Andric   if (Shnum >= SHN_LORESERVE)
201681ad6265SDimitry Andric     Shdr.sh_size = Shnum;
201781ad6265SDimitry Andric   else
201881ad6265SDimitry Andric     Shdr.sh_size = 0;
201981ad6265SDimitry Andric   // See writeEhdr for why we do this.
202081ad6265SDimitry Andric   if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
202181ad6265SDimitry Andric     Shdr.sh_link = Obj.SectionNames->Index;
202281ad6265SDimitry Andric   else
202381ad6265SDimitry Andric     Shdr.sh_link = 0;
202481ad6265SDimitry Andric   Shdr.sh_info = 0;
202581ad6265SDimitry Andric   Shdr.sh_addralign = 0;
202681ad6265SDimitry Andric   Shdr.sh_entsize = 0;
202781ad6265SDimitry Andric 
202881ad6265SDimitry Andric   for (SectionBase &Sec : Obj.sections())
202981ad6265SDimitry Andric     writeShdr(Sec);
203081ad6265SDimitry Andric }
203181ad6265SDimitry Andric 
203281ad6265SDimitry Andric template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
203381ad6265SDimitry Andric   for (SectionBase &Sec : Obj.sections())
203481ad6265SDimitry Andric     // Segments are responsible for writing their contents, so only write the
203581ad6265SDimitry Andric     // section data if the section is not in a segment. Note that this renders
203681ad6265SDimitry Andric     // sections in segments effectively immutable.
203781ad6265SDimitry Andric     if (Sec.ParentSegment == nullptr)
203881ad6265SDimitry Andric       if (Error Err = Sec.accept(*SecWriter))
203981ad6265SDimitry Andric         return Err;
204081ad6265SDimitry Andric 
204181ad6265SDimitry Andric   return Error::success();
204281ad6265SDimitry Andric }
204381ad6265SDimitry Andric 
204481ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
204581ad6265SDimitry Andric   for (Segment &Seg : Obj.segments()) {
204681ad6265SDimitry Andric     size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
204781ad6265SDimitry Andric     std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
204881ad6265SDimitry Andric                 Size);
204981ad6265SDimitry Andric   }
205081ad6265SDimitry Andric 
205181ad6265SDimitry Andric   for (auto it : Obj.getUpdatedSections()) {
205281ad6265SDimitry Andric     SectionBase *Sec = it.first;
205381ad6265SDimitry Andric     ArrayRef<uint8_t> Data = it.second;
205481ad6265SDimitry Andric 
205581ad6265SDimitry Andric     auto *Parent = Sec->ParentSegment;
205681ad6265SDimitry Andric     assert(Parent && "This section should've been part of a segment.");
205781ad6265SDimitry Andric     uint64_t Offset =
205881ad6265SDimitry Andric         Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
205981ad6265SDimitry Andric     llvm::copy(Data, Buf->getBufferStart() + Offset);
206081ad6265SDimitry Andric   }
206181ad6265SDimitry Andric 
206281ad6265SDimitry Andric   // Iterate over removed sections and overwrite their old data with zeroes.
206381ad6265SDimitry Andric   for (auto &Sec : Obj.removedSections()) {
206481ad6265SDimitry Andric     Segment *Parent = Sec.ParentSegment;
206581ad6265SDimitry Andric     if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
206681ad6265SDimitry Andric       continue;
206781ad6265SDimitry Andric     uint64_t Offset =
206881ad6265SDimitry Andric         Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
206981ad6265SDimitry Andric     std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
207081ad6265SDimitry Andric   }
207181ad6265SDimitry Andric }
207281ad6265SDimitry Andric 
207381ad6265SDimitry Andric template <class ELFT>
207481ad6265SDimitry Andric ELFWriter<ELFT>::ELFWriter(Object &Obj, raw_ostream &Buf, bool WSH,
207581ad6265SDimitry Andric                            bool OnlyKeepDebug)
207681ad6265SDimitry Andric     : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
207781ad6265SDimitry Andric       OnlyKeepDebug(OnlyKeepDebug) {}
207881ad6265SDimitry Andric 
207981ad6265SDimitry Andric Error Object::updateSection(StringRef Name, ArrayRef<uint8_t> Data) {
208081ad6265SDimitry Andric   auto It = llvm::find_if(Sections,
208181ad6265SDimitry Andric                           [&](const SecPtr &Sec) { return Sec->Name == Name; });
208281ad6265SDimitry Andric   if (It == Sections.end())
208381ad6265SDimitry Andric     return createStringError(errc::invalid_argument, "section '%s' not found",
208481ad6265SDimitry Andric                              Name.str().c_str());
208581ad6265SDimitry Andric 
208681ad6265SDimitry Andric   auto *OldSec = It->get();
208781ad6265SDimitry Andric   if (!OldSec->hasContents())
208881ad6265SDimitry Andric     return createStringError(
208981ad6265SDimitry Andric         errc::invalid_argument,
209081ad6265SDimitry Andric         "section '%s' cannot be updated because it does not have contents",
209181ad6265SDimitry Andric         Name.str().c_str());
209281ad6265SDimitry Andric 
209381ad6265SDimitry Andric   if (Data.size() > OldSec->Size && OldSec->ParentSegment)
209481ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
209581ad6265SDimitry Andric                              "cannot fit data of size %zu into section '%s' "
209681ad6265SDimitry Andric                              "with size %zu that is part of a segment",
209781ad6265SDimitry Andric                              Data.size(), Name.str().c_str(), OldSec->Size);
209881ad6265SDimitry Andric 
209981ad6265SDimitry Andric   if (!OldSec->ParentSegment) {
210081ad6265SDimitry Andric     *It = std::make_unique<OwnedDataSection>(*OldSec, Data);
210181ad6265SDimitry Andric   } else {
210281ad6265SDimitry Andric     // The segment writer will be in charge of updating these contents.
210381ad6265SDimitry Andric     OldSec->Size = Data.size();
210481ad6265SDimitry Andric     UpdatedSections[OldSec] = Data;
210581ad6265SDimitry Andric   }
210681ad6265SDimitry Andric 
210781ad6265SDimitry Andric   return Error::success();
210881ad6265SDimitry Andric }
210981ad6265SDimitry Andric 
211081ad6265SDimitry Andric Error Object::removeSections(
211181ad6265SDimitry Andric     bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
211281ad6265SDimitry Andric 
211381ad6265SDimitry Andric   auto Iter = std::stable_partition(
211481ad6265SDimitry Andric       std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
211581ad6265SDimitry Andric         if (ToRemove(*Sec))
211681ad6265SDimitry Andric           return false;
211781ad6265SDimitry Andric         if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
211881ad6265SDimitry Andric           if (auto ToRelSec = RelSec->getSection())
211981ad6265SDimitry Andric             return !ToRemove(*ToRelSec);
212081ad6265SDimitry Andric         }
212181ad6265SDimitry Andric         return true;
212281ad6265SDimitry Andric       });
212381ad6265SDimitry Andric   if (SymbolTable != nullptr && ToRemove(*SymbolTable))
212481ad6265SDimitry Andric     SymbolTable = nullptr;
212581ad6265SDimitry Andric   if (SectionNames != nullptr && ToRemove(*SectionNames))
212681ad6265SDimitry Andric     SectionNames = nullptr;
212781ad6265SDimitry Andric   if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
212881ad6265SDimitry Andric     SectionIndexTable = nullptr;
212981ad6265SDimitry Andric   // Now make sure there are no remaining references to the sections that will
213081ad6265SDimitry Andric   // be removed. Sometimes it is impossible to remove a reference so we emit
213181ad6265SDimitry Andric   // an error here instead.
213281ad6265SDimitry Andric   std::unordered_set<const SectionBase *> RemoveSections;
213381ad6265SDimitry Andric   RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
213481ad6265SDimitry Andric   for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
213581ad6265SDimitry Andric     for (auto &Segment : Segments)
213681ad6265SDimitry Andric       Segment->removeSection(RemoveSec.get());
213781ad6265SDimitry Andric     RemoveSec->onRemove();
213881ad6265SDimitry Andric     RemoveSections.insert(RemoveSec.get());
213981ad6265SDimitry Andric   }
214081ad6265SDimitry Andric 
214181ad6265SDimitry Andric   // For each section that remains alive, we want to remove the dead references.
214281ad6265SDimitry Andric   // This either might update the content of the section (e.g. remove symbols
214381ad6265SDimitry Andric   // from symbol table that belongs to removed section) or trigger an error if
214481ad6265SDimitry Andric   // a live section critically depends on a section being removed somehow
214581ad6265SDimitry Andric   // (e.g. the removed section is referenced by a relocation).
214681ad6265SDimitry Andric   for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
214781ad6265SDimitry Andric     if (Error E = KeepSec->removeSectionReferences(
214881ad6265SDimitry Andric             AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
214981ad6265SDimitry Andric               return RemoveSections.find(Sec) != RemoveSections.end();
215081ad6265SDimitry Andric             }))
215181ad6265SDimitry Andric       return E;
215281ad6265SDimitry Andric   }
215381ad6265SDimitry Andric 
215481ad6265SDimitry Andric   // Transfer removed sections into the Object RemovedSections container for use
215581ad6265SDimitry Andric   // later.
215681ad6265SDimitry Andric   std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
215781ad6265SDimitry Andric   // Now finally get rid of them all together.
215881ad6265SDimitry Andric   Sections.erase(Iter, std::end(Sections));
215981ad6265SDimitry Andric   return Error::success();
216081ad6265SDimitry Andric }
216181ad6265SDimitry Andric 
216281ad6265SDimitry Andric Error Object::replaceSections(
216381ad6265SDimitry Andric     const DenseMap<SectionBase *, SectionBase *> &FromTo) {
216481ad6265SDimitry Andric   auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
216581ad6265SDimitry Andric     return Lhs->Index < Rhs->Index;
216681ad6265SDimitry Andric   };
216781ad6265SDimitry Andric   assert(llvm::is_sorted(Sections, SectionIndexLess) &&
216881ad6265SDimitry Andric          "Sections are expected to be sorted by Index");
216981ad6265SDimitry Andric   // Set indices of new sections so that they can be later sorted into positions
217081ad6265SDimitry Andric   // of removed ones.
217181ad6265SDimitry Andric   for (auto &I : FromTo)
217281ad6265SDimitry Andric     I.second->Index = I.first->Index;
217381ad6265SDimitry Andric 
217481ad6265SDimitry Andric   // Notify all sections about the replacement.
217581ad6265SDimitry Andric   for (auto &Sec : Sections)
217681ad6265SDimitry Andric     Sec->replaceSectionReferences(FromTo);
217781ad6265SDimitry Andric 
217881ad6265SDimitry Andric   if (Error E = removeSections(
217981ad6265SDimitry Andric           /*AllowBrokenLinks=*/false,
218081ad6265SDimitry Andric           [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
218181ad6265SDimitry Andric     return E;
218281ad6265SDimitry Andric   llvm::sort(Sections, SectionIndexLess);
218381ad6265SDimitry Andric   return Error::success();
218481ad6265SDimitry Andric }
218581ad6265SDimitry Andric 
218681ad6265SDimitry Andric Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
218781ad6265SDimitry Andric   if (SymbolTable)
218881ad6265SDimitry Andric     for (const SecPtr &Sec : Sections)
218981ad6265SDimitry Andric       if (Error E = Sec->removeSymbols(ToRemove))
219081ad6265SDimitry Andric         return E;
219181ad6265SDimitry Andric   return Error::success();
219281ad6265SDimitry Andric }
219381ad6265SDimitry Andric 
219481ad6265SDimitry Andric Error Object::addNewSymbolTable() {
219581ad6265SDimitry Andric   assert(!SymbolTable && "Object must not has a SymbolTable.");
219681ad6265SDimitry Andric 
219781ad6265SDimitry Andric   // Reuse an existing SHT_STRTAB section if it exists.
219881ad6265SDimitry Andric   StringTableSection *StrTab = nullptr;
219981ad6265SDimitry Andric   for (SectionBase &Sec : sections()) {
220081ad6265SDimitry Andric     if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
220181ad6265SDimitry Andric       StrTab = static_cast<StringTableSection *>(&Sec);
220281ad6265SDimitry Andric 
220381ad6265SDimitry Andric       // Prefer a string table that is not the section header string table, if
220481ad6265SDimitry Andric       // such a table exists.
220581ad6265SDimitry Andric       if (SectionNames != &Sec)
220681ad6265SDimitry Andric         break;
220781ad6265SDimitry Andric     }
220881ad6265SDimitry Andric   }
220981ad6265SDimitry Andric   if (!StrTab)
221081ad6265SDimitry Andric     StrTab = &addSection<StringTableSection>();
221181ad6265SDimitry Andric 
221281ad6265SDimitry Andric   SymbolTableSection &SymTab = addSection<SymbolTableSection>();
221381ad6265SDimitry Andric   SymTab.Name = ".symtab";
221481ad6265SDimitry Andric   SymTab.Link = StrTab->Index;
221581ad6265SDimitry Andric   if (Error Err = SymTab.initialize(sections()))
221681ad6265SDimitry Andric     return Err;
221781ad6265SDimitry Andric   SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
221881ad6265SDimitry Andric 
221981ad6265SDimitry Andric   SymbolTable = &SymTab;
222081ad6265SDimitry Andric 
222181ad6265SDimitry Andric   return Error::success();
222281ad6265SDimitry Andric }
222381ad6265SDimitry Andric 
222481ad6265SDimitry Andric // Orders segments such that if x = y->ParentSegment then y comes before x.
222581ad6265SDimitry Andric static void orderSegments(std::vector<Segment *> &Segments) {
222681ad6265SDimitry Andric   llvm::stable_sort(Segments, compareSegmentsByOffset);
222781ad6265SDimitry Andric }
222881ad6265SDimitry Andric 
222981ad6265SDimitry Andric // This function finds a consistent layout for a list of segments starting from
223081ad6265SDimitry Andric // an Offset. It assumes that Segments have been sorted by orderSegments and
223181ad6265SDimitry Andric // returns an Offset one past the end of the last segment.
223281ad6265SDimitry Andric static uint64_t layoutSegments(std::vector<Segment *> &Segments,
223381ad6265SDimitry Andric                                uint64_t Offset) {
223481ad6265SDimitry Andric   assert(llvm::is_sorted(Segments, compareSegmentsByOffset));
223581ad6265SDimitry Andric   // The only way a segment should move is if a section was between two
223681ad6265SDimitry Andric   // segments and that section was removed. If that section isn't in a segment
223781ad6265SDimitry Andric   // then it's acceptable, but not ideal, to simply move it to after the
223881ad6265SDimitry Andric   // segments. So we can simply layout segments one after the other accounting
223981ad6265SDimitry Andric   // for alignment.
224081ad6265SDimitry Andric   for (Segment *Seg : Segments) {
224181ad6265SDimitry Andric     // We assume that segments have been ordered by OriginalOffset and Index
224281ad6265SDimitry Andric     // such that a parent segment will always come before a child segment in
224381ad6265SDimitry Andric     // OrderedSegments. This means that the Offset of the ParentSegment should
224481ad6265SDimitry Andric     // already be set and we can set our offset relative to it.
224581ad6265SDimitry Andric     if (Seg->ParentSegment != nullptr) {
224681ad6265SDimitry Andric       Segment *Parent = Seg->ParentSegment;
224781ad6265SDimitry Andric       Seg->Offset =
224881ad6265SDimitry Andric           Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
224981ad6265SDimitry Andric     } else {
225081ad6265SDimitry Andric       Seg->Offset =
225181ad6265SDimitry Andric           alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
225281ad6265SDimitry Andric     }
225381ad6265SDimitry Andric     Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
225481ad6265SDimitry Andric   }
225581ad6265SDimitry Andric   return Offset;
225681ad6265SDimitry Andric }
225781ad6265SDimitry Andric 
225881ad6265SDimitry Andric // This function finds a consistent layout for a list of sections. It assumes
225981ad6265SDimitry Andric // that the ->ParentSegment of each section has already been laid out. The
226081ad6265SDimitry Andric // supplied starting Offset is used for the starting offset of any section that
226181ad6265SDimitry Andric // does not have a ParentSegment. It returns either the offset given if all
226281ad6265SDimitry Andric // sections had a ParentSegment or an offset one past the last section if there
226381ad6265SDimitry Andric // was a section that didn't have a ParentSegment.
226481ad6265SDimitry Andric template <class Range>
226581ad6265SDimitry Andric static uint64_t layoutSections(Range Sections, uint64_t Offset) {
226681ad6265SDimitry Andric   // Now the offset of every segment has been set we can assign the offsets
226781ad6265SDimitry Andric   // of each section. For sections that are covered by a segment we should use
226881ad6265SDimitry Andric   // the segment's original offset and the section's original offset to compute
226981ad6265SDimitry Andric   // the offset from the start of the segment. Using the offset from the start
227081ad6265SDimitry Andric   // of the segment we can assign a new offset to the section. For sections not
227181ad6265SDimitry Andric   // covered by segments we can just bump Offset to the next valid location.
227281ad6265SDimitry Andric   // While it is not necessary, layout the sections in the order based on their
227381ad6265SDimitry Andric   // original offsets to resemble the input file as close as possible.
227481ad6265SDimitry Andric   std::vector<SectionBase *> OutOfSegmentSections;
227581ad6265SDimitry Andric   uint32_t Index = 1;
227681ad6265SDimitry Andric   for (auto &Sec : Sections) {
227781ad6265SDimitry Andric     Sec.Index = Index++;
227881ad6265SDimitry Andric     if (Sec.ParentSegment != nullptr) {
227981ad6265SDimitry Andric       auto Segment = *Sec.ParentSegment;
228081ad6265SDimitry Andric       Sec.Offset =
228181ad6265SDimitry Andric           Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
228281ad6265SDimitry Andric     } else
228381ad6265SDimitry Andric       OutOfSegmentSections.push_back(&Sec);
228481ad6265SDimitry Andric   }
228581ad6265SDimitry Andric 
228681ad6265SDimitry Andric   llvm::stable_sort(OutOfSegmentSections,
228781ad6265SDimitry Andric                     [](const SectionBase *Lhs, const SectionBase *Rhs) {
228881ad6265SDimitry Andric                       return Lhs->OriginalOffset < Rhs->OriginalOffset;
228981ad6265SDimitry Andric                     });
229081ad6265SDimitry Andric   for (auto *Sec : OutOfSegmentSections) {
229181ad6265SDimitry Andric     Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
229281ad6265SDimitry Andric     Sec->Offset = Offset;
229381ad6265SDimitry Andric     if (Sec->Type != SHT_NOBITS)
229481ad6265SDimitry Andric       Offset += Sec->Size;
229581ad6265SDimitry Andric   }
229681ad6265SDimitry Andric   return Offset;
229781ad6265SDimitry Andric }
229881ad6265SDimitry Andric 
229981ad6265SDimitry Andric // Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
230081ad6265SDimitry Andric // occupy no space in the file.
230181ad6265SDimitry Andric static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off) {
230281ad6265SDimitry Andric   // The layout algorithm requires the sections to be handled in the order of
230381ad6265SDimitry Andric   // their offsets in the input file, at least inside segments.
230481ad6265SDimitry Andric   std::vector<SectionBase *> Sections;
230581ad6265SDimitry Andric   Sections.reserve(Obj.sections().size());
230681ad6265SDimitry Andric   uint32_t Index = 1;
230781ad6265SDimitry Andric   for (auto &Sec : Obj.sections()) {
230881ad6265SDimitry Andric     Sec.Index = Index++;
230981ad6265SDimitry Andric     Sections.push_back(&Sec);
231081ad6265SDimitry Andric   }
231181ad6265SDimitry Andric   llvm::stable_sort(Sections,
231281ad6265SDimitry Andric                     [](const SectionBase *Lhs, const SectionBase *Rhs) {
231381ad6265SDimitry Andric                       return Lhs->OriginalOffset < Rhs->OriginalOffset;
231481ad6265SDimitry Andric                     });
231581ad6265SDimitry Andric 
231681ad6265SDimitry Andric   for (auto *Sec : Sections) {
231781ad6265SDimitry Andric     auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
231881ad6265SDimitry Andric                          ? Sec->ParentSegment->firstSection()
231981ad6265SDimitry Andric                          : nullptr;
232081ad6265SDimitry Andric 
232181ad6265SDimitry Andric     // The first section in a PT_LOAD has to have congruent offset and address
232281ad6265SDimitry Andric     // modulo the alignment, which usually equals the maximum page size.
232381ad6265SDimitry Andric     if (FirstSec && FirstSec == Sec)
232481ad6265SDimitry Andric       Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
232581ad6265SDimitry Andric 
232681ad6265SDimitry Andric     // sh_offset is not significant for SHT_NOBITS sections, but the congruence
232781ad6265SDimitry Andric     // rule must be followed if it is the first section in a PT_LOAD. Do not
232881ad6265SDimitry Andric     // advance Off.
232981ad6265SDimitry Andric     if (Sec->Type == SHT_NOBITS) {
233081ad6265SDimitry Andric       Sec->Offset = Off;
233181ad6265SDimitry Andric       continue;
233281ad6265SDimitry Andric     }
233381ad6265SDimitry Andric 
233481ad6265SDimitry Andric     if (!FirstSec) {
233581ad6265SDimitry Andric       // FirstSec being nullptr generally means that Sec does not have the
233681ad6265SDimitry Andric       // SHF_ALLOC flag.
233781ad6265SDimitry Andric       Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
233881ad6265SDimitry Andric     } else if (FirstSec != Sec) {
233981ad6265SDimitry Andric       // The offset is relative to the first section in the PT_LOAD segment. Use
234081ad6265SDimitry Andric       // sh_offset for non-SHF_ALLOC sections.
234181ad6265SDimitry Andric       Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
234281ad6265SDimitry Andric     }
234381ad6265SDimitry Andric     Sec->Offset = Off;
234481ad6265SDimitry Andric     Off += Sec->Size;
234581ad6265SDimitry Andric   }
234681ad6265SDimitry Andric   return Off;
234781ad6265SDimitry Andric }
234881ad6265SDimitry Andric 
234981ad6265SDimitry Andric // Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
235081ad6265SDimitry Andric // have been updated.
235181ad6265SDimitry Andric static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
235281ad6265SDimitry Andric                                                uint64_t HdrEnd) {
235381ad6265SDimitry Andric   uint64_t MaxOffset = 0;
235481ad6265SDimitry Andric   for (Segment *Seg : Segments) {
235581ad6265SDimitry Andric     if (Seg->Type == PT_PHDR)
235681ad6265SDimitry Andric       continue;
235781ad6265SDimitry Andric 
235881ad6265SDimitry Andric     // The segment offset is generally the offset of the first section.
235981ad6265SDimitry Andric     //
236081ad6265SDimitry Andric     // For a segment containing no section (see sectionWithinSegment), if it has
236181ad6265SDimitry Andric     // a parent segment, copy the parent segment's offset field. This works for
236281ad6265SDimitry Andric     // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
236381ad6265SDimitry Andric     // debugging anyway.
236481ad6265SDimitry Andric     const SectionBase *FirstSec = Seg->firstSection();
236581ad6265SDimitry Andric     uint64_t Offset =
236681ad6265SDimitry Andric         FirstSec ? FirstSec->Offset
236781ad6265SDimitry Andric                  : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
236881ad6265SDimitry Andric     uint64_t FileSize = 0;
236981ad6265SDimitry Andric     for (const SectionBase *Sec : Seg->Sections) {
237081ad6265SDimitry Andric       uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
237181ad6265SDimitry Andric       if (Sec->Offset + Size > Offset)
237281ad6265SDimitry Andric         FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
237381ad6265SDimitry Andric     }
237481ad6265SDimitry Andric 
237581ad6265SDimitry Andric     // If the segment includes EHDR and program headers, don't make it smaller
237681ad6265SDimitry Andric     // than the headers.
237781ad6265SDimitry Andric     if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
237881ad6265SDimitry Andric       FileSize += Offset - Seg->Offset;
237981ad6265SDimitry Andric       Offset = Seg->Offset;
238081ad6265SDimitry Andric       FileSize = std::max(FileSize, HdrEnd - Offset);
238181ad6265SDimitry Andric     }
238281ad6265SDimitry Andric 
238381ad6265SDimitry Andric     Seg->Offset = Offset;
238481ad6265SDimitry Andric     Seg->FileSize = FileSize;
238581ad6265SDimitry Andric     MaxOffset = std::max(MaxOffset, Offset + FileSize);
238681ad6265SDimitry Andric   }
238781ad6265SDimitry Andric   return MaxOffset;
238881ad6265SDimitry Andric }
238981ad6265SDimitry Andric 
239081ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
239181ad6265SDimitry Andric   Segment &ElfHdr = Obj.ElfHdrSegment;
239281ad6265SDimitry Andric   ElfHdr.Type = PT_PHDR;
239381ad6265SDimitry Andric   ElfHdr.Flags = 0;
239481ad6265SDimitry Andric   ElfHdr.VAddr = 0;
239581ad6265SDimitry Andric   ElfHdr.PAddr = 0;
239681ad6265SDimitry Andric   ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
239781ad6265SDimitry Andric   ElfHdr.Align = 0;
239881ad6265SDimitry Andric }
239981ad6265SDimitry Andric 
240081ad6265SDimitry Andric template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
240181ad6265SDimitry Andric   // We need a temporary list of segments that has a special order to it
240281ad6265SDimitry Andric   // so that we know that anytime ->ParentSegment is set that segment has
240381ad6265SDimitry Andric   // already had its offset properly set.
240481ad6265SDimitry Andric   std::vector<Segment *> OrderedSegments;
240581ad6265SDimitry Andric   for (Segment &Segment : Obj.segments())
240681ad6265SDimitry Andric     OrderedSegments.push_back(&Segment);
240781ad6265SDimitry Andric   OrderedSegments.push_back(&Obj.ElfHdrSegment);
240881ad6265SDimitry Andric   OrderedSegments.push_back(&Obj.ProgramHdrSegment);
240981ad6265SDimitry Andric   orderSegments(OrderedSegments);
241081ad6265SDimitry Andric 
241181ad6265SDimitry Andric   uint64_t Offset;
241281ad6265SDimitry Andric   if (OnlyKeepDebug) {
241381ad6265SDimitry Andric     // For --only-keep-debug, the sections that did not preserve contents were
241481ad6265SDimitry Andric     // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
241581ad6265SDimitry Andric     // then rewrite p_offset/p_filesz of program headers.
241681ad6265SDimitry Andric     uint64_t HdrEnd =
241781ad6265SDimitry Andric         sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
241881ad6265SDimitry Andric     Offset = layoutSectionsForOnlyKeepDebug(Obj, HdrEnd);
241981ad6265SDimitry Andric     Offset = std::max(Offset,
242081ad6265SDimitry Andric                       layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
242181ad6265SDimitry Andric   } else {
242281ad6265SDimitry Andric     // Offset is used as the start offset of the first segment to be laid out.
242381ad6265SDimitry Andric     // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
242481ad6265SDimitry Andric     // we start at offset 0.
242581ad6265SDimitry Andric     Offset = layoutSegments(OrderedSegments, 0);
242681ad6265SDimitry Andric     Offset = layoutSections(Obj.sections(), Offset);
242781ad6265SDimitry Andric   }
242881ad6265SDimitry Andric   // If we need to write the section header table out then we need to align the
242981ad6265SDimitry Andric   // Offset so that SHOffset is valid.
243081ad6265SDimitry Andric   if (WriteSectionHeaders)
243181ad6265SDimitry Andric     Offset = alignTo(Offset, sizeof(Elf_Addr));
243281ad6265SDimitry Andric   Obj.SHOff = Offset;
243381ad6265SDimitry Andric }
243481ad6265SDimitry Andric 
243581ad6265SDimitry Andric template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
243681ad6265SDimitry Andric   // We already have the section header offset so we can calculate the total
243781ad6265SDimitry Andric   // size by just adding up the size of each section header.
243881ad6265SDimitry Andric   if (!WriteSectionHeaders)
243981ad6265SDimitry Andric     return Obj.SHOff;
244081ad6265SDimitry Andric   size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
244181ad6265SDimitry Andric   return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
244281ad6265SDimitry Andric }
244381ad6265SDimitry Andric 
244481ad6265SDimitry Andric template <class ELFT> Error ELFWriter<ELFT>::write() {
244581ad6265SDimitry Andric   // Segment data must be written first, so that the ELF header and program
244681ad6265SDimitry Andric   // header tables can overwrite it, if covered by a segment.
244781ad6265SDimitry Andric   writeSegmentData();
244881ad6265SDimitry Andric   writeEhdr();
244981ad6265SDimitry Andric   writePhdrs();
245081ad6265SDimitry Andric   if (Error E = writeSectionData())
245181ad6265SDimitry Andric     return E;
245281ad6265SDimitry Andric   if (WriteSectionHeaders)
245381ad6265SDimitry Andric     writeShdrs();
245481ad6265SDimitry Andric 
245581ad6265SDimitry Andric   // TODO: Implement direct writing to the output stream (without intermediate
245681ad6265SDimitry Andric   // memory buffer Buf).
245781ad6265SDimitry Andric   Out.write(Buf->getBufferStart(), Buf->getBufferSize());
245881ad6265SDimitry Andric   return Error::success();
245981ad6265SDimitry Andric }
246081ad6265SDimitry Andric 
246181ad6265SDimitry Andric static Error removeUnneededSections(Object &Obj) {
246281ad6265SDimitry Andric   // We can remove an empty symbol table from non-relocatable objects.
246381ad6265SDimitry Andric   // Relocatable objects typically have relocation sections whose
246481ad6265SDimitry Andric   // sh_link field points to .symtab, so we can't remove .symtab
246581ad6265SDimitry Andric   // even if it is empty.
246681ad6265SDimitry Andric   if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
246781ad6265SDimitry Andric       !Obj.SymbolTable->empty())
246881ad6265SDimitry Andric     return Error::success();
246981ad6265SDimitry Andric 
247081ad6265SDimitry Andric   // .strtab can be used for section names. In such a case we shouldn't
247181ad6265SDimitry Andric   // remove it.
247281ad6265SDimitry Andric   auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
247381ad6265SDimitry Andric                      ? nullptr
247481ad6265SDimitry Andric                      : Obj.SymbolTable->getStrTab();
247581ad6265SDimitry Andric   return Obj.removeSections(false, [&](const SectionBase &Sec) {
247681ad6265SDimitry Andric     return &Sec == Obj.SymbolTable || &Sec == StrTab;
247781ad6265SDimitry Andric   });
247881ad6265SDimitry Andric }
247981ad6265SDimitry Andric 
248081ad6265SDimitry Andric template <class ELFT> Error ELFWriter<ELFT>::finalize() {
248181ad6265SDimitry Andric   // It could happen that SectionNames has been removed and yet the user wants
248281ad6265SDimitry Andric   // a section header table output. We need to throw an error if a user tries
248381ad6265SDimitry Andric   // to do that.
248481ad6265SDimitry Andric   if (Obj.SectionNames == nullptr && WriteSectionHeaders)
248581ad6265SDimitry Andric     return createStringError(llvm::errc::invalid_argument,
248681ad6265SDimitry Andric                              "cannot write section header table because "
248781ad6265SDimitry Andric                              "section header string table was removed");
248881ad6265SDimitry Andric 
248981ad6265SDimitry Andric   if (Error E = removeUnneededSections(Obj))
249081ad6265SDimitry Andric     return E;
249181ad6265SDimitry Andric 
249281ad6265SDimitry Andric   // We need to assign indexes before we perform layout because we need to know
249381ad6265SDimitry Andric   // if we need large indexes or not. We can assign indexes first and check as
249481ad6265SDimitry Andric   // we go to see if we will actully need large indexes.
249581ad6265SDimitry Andric   bool NeedsLargeIndexes = false;
249681ad6265SDimitry Andric   if (Obj.sections().size() >= SHN_LORESERVE) {
249781ad6265SDimitry Andric     SectionTableRef Sections = Obj.sections();
249881ad6265SDimitry Andric     // Sections doesn't include the null section header, so account for this
249981ad6265SDimitry Andric     // when skipping the first N sections.
250081ad6265SDimitry Andric     NeedsLargeIndexes =
250181ad6265SDimitry Andric         any_of(drop_begin(Sections, SHN_LORESERVE - 1),
250281ad6265SDimitry Andric                [](const SectionBase &Sec) { return Sec.HasSymbol; });
250381ad6265SDimitry Andric     // TODO: handle case where only one section needs the large index table but
250481ad6265SDimitry Andric     // only needs it because the large index table hasn't been removed yet.
250581ad6265SDimitry Andric   }
250681ad6265SDimitry Andric 
250781ad6265SDimitry Andric   if (NeedsLargeIndexes) {
250881ad6265SDimitry Andric     // This means we definitely need to have a section index table but if we
250981ad6265SDimitry Andric     // already have one then we should use it instead of making a new one.
251081ad6265SDimitry Andric     if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
251181ad6265SDimitry Andric       // Addition of a section to the end does not invalidate the indexes of
251281ad6265SDimitry Andric       // other sections and assigns the correct index to the new section.
251381ad6265SDimitry Andric       auto &Shndx = Obj.addSection<SectionIndexSection>();
251481ad6265SDimitry Andric       Obj.SymbolTable->setShndxTable(&Shndx);
251581ad6265SDimitry Andric       Shndx.setSymTab(Obj.SymbolTable);
251681ad6265SDimitry Andric     }
251781ad6265SDimitry Andric   } else {
251881ad6265SDimitry Andric     // Since we don't need SectionIndexTable we should remove it and all
251981ad6265SDimitry Andric     // references to it.
252081ad6265SDimitry Andric     if (Obj.SectionIndexTable != nullptr) {
252181ad6265SDimitry Andric       // We do not support sections referring to the section index table.
252281ad6265SDimitry Andric       if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
252381ad6265SDimitry Andric                                        [this](const SectionBase &Sec) {
252481ad6265SDimitry Andric                                          return &Sec == Obj.SectionIndexTable;
252581ad6265SDimitry Andric                                        }))
252681ad6265SDimitry Andric         return E;
252781ad6265SDimitry Andric     }
252881ad6265SDimitry Andric   }
252981ad6265SDimitry Andric 
253081ad6265SDimitry Andric   // Make sure we add the names of all the sections. Importantly this must be
253181ad6265SDimitry Andric   // done after we decide to add or remove SectionIndexes.
253281ad6265SDimitry Andric   if (Obj.SectionNames != nullptr)
253381ad6265SDimitry Andric     for (const SectionBase &Sec : Obj.sections())
253481ad6265SDimitry Andric       Obj.SectionNames->addString(Sec.Name);
253581ad6265SDimitry Andric 
253681ad6265SDimitry Andric   initEhdrSegment();
253781ad6265SDimitry Andric 
253881ad6265SDimitry Andric   // Before we can prepare for layout the indexes need to be finalized.
253981ad6265SDimitry Andric   // Also, the output arch may not be the same as the input arch, so fix up
254081ad6265SDimitry Andric   // size-related fields before doing layout calculations.
254181ad6265SDimitry Andric   uint64_t Index = 0;
254281ad6265SDimitry Andric   auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
254381ad6265SDimitry Andric   for (SectionBase &Sec : Obj.sections()) {
254481ad6265SDimitry Andric     Sec.Index = Index++;
254581ad6265SDimitry Andric     if (Error Err = Sec.accept(*SecSizer))
254681ad6265SDimitry Andric       return Err;
254781ad6265SDimitry Andric   }
254881ad6265SDimitry Andric 
254981ad6265SDimitry Andric   // The symbol table does not update all other sections on update. For
255081ad6265SDimitry Andric   // instance, symbol names are not added as new symbols are added. This means
255181ad6265SDimitry Andric   // that some sections, like .strtab, don't yet have their final size.
255281ad6265SDimitry Andric   if (Obj.SymbolTable != nullptr)
255381ad6265SDimitry Andric     Obj.SymbolTable->prepareForLayout();
255481ad6265SDimitry Andric 
255581ad6265SDimitry Andric   // Now that all strings are added we want to finalize string table builders,
255681ad6265SDimitry Andric   // because that affects section sizes which in turn affects section offsets.
255781ad6265SDimitry Andric   for (SectionBase &Sec : Obj.sections())
255881ad6265SDimitry Andric     if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
255981ad6265SDimitry Andric       StrTab->prepareForLayout();
256081ad6265SDimitry Andric 
256181ad6265SDimitry Andric   assignOffsets();
256281ad6265SDimitry Andric 
256381ad6265SDimitry Andric   // layoutSections could have modified section indexes, so we need
256481ad6265SDimitry Andric   // to fill the index table after assignOffsets.
256581ad6265SDimitry Andric   if (Obj.SymbolTable != nullptr)
256681ad6265SDimitry Andric     Obj.SymbolTable->fillShndxTable();
256781ad6265SDimitry Andric 
256881ad6265SDimitry Andric   // Finally now that all offsets and indexes have been set we can finalize any
256981ad6265SDimitry Andric   // remaining issues.
257081ad6265SDimitry Andric   uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
257181ad6265SDimitry Andric   for (SectionBase &Sec : Obj.sections()) {
257281ad6265SDimitry Andric     Sec.HeaderOffset = Offset;
257381ad6265SDimitry Andric     Offset += sizeof(Elf_Shdr);
257481ad6265SDimitry Andric     if (WriteSectionHeaders)
257581ad6265SDimitry Andric       Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
257681ad6265SDimitry Andric     Sec.finalize();
257781ad6265SDimitry Andric   }
257881ad6265SDimitry Andric 
257981ad6265SDimitry Andric   size_t TotalSize = totalSize();
258081ad6265SDimitry Andric   Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
258181ad6265SDimitry Andric   if (!Buf)
258281ad6265SDimitry Andric     return createStringError(errc::not_enough_memory,
258381ad6265SDimitry Andric                              "failed to allocate memory buffer of " +
258481ad6265SDimitry Andric                                  Twine::utohexstr(TotalSize) + " bytes");
258581ad6265SDimitry Andric 
258681ad6265SDimitry Andric   SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
258781ad6265SDimitry Andric   return Error::success();
258881ad6265SDimitry Andric }
258981ad6265SDimitry Andric 
259081ad6265SDimitry Andric Error BinaryWriter::write() {
259181ad6265SDimitry Andric   for (const SectionBase &Sec : Obj.allocSections())
259281ad6265SDimitry Andric     if (Error Err = Sec.accept(*SecWriter))
259381ad6265SDimitry Andric       return Err;
259481ad6265SDimitry Andric 
259581ad6265SDimitry Andric   // TODO: Implement direct writing to the output stream (without intermediate
259681ad6265SDimitry Andric   // memory buffer Buf).
259781ad6265SDimitry Andric   Out.write(Buf->getBufferStart(), Buf->getBufferSize());
259881ad6265SDimitry Andric   return Error::success();
259981ad6265SDimitry Andric }
260081ad6265SDimitry Andric 
260181ad6265SDimitry Andric Error BinaryWriter::finalize() {
260281ad6265SDimitry Andric   // Compute the section LMA based on its sh_offset and the containing segment's
260381ad6265SDimitry Andric   // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
260481ad6265SDimitry Andric   // sections as MinAddr. In the output, the contents between address 0 and
260581ad6265SDimitry Andric   // MinAddr will be skipped.
260681ad6265SDimitry Andric   uint64_t MinAddr = UINT64_MAX;
260781ad6265SDimitry Andric   for (SectionBase &Sec : Obj.allocSections()) {
2608753f127fSDimitry Andric     // If Sec's type is changed from SHT_NOBITS due to --set-section-flags,
2609753f127fSDimitry Andric     // Offset may not be aligned. Align it to max(Align, 1).
261081ad6265SDimitry Andric     if (Sec.ParentSegment != nullptr)
2611753f127fSDimitry Andric       Sec.Addr = alignTo(Sec.Offset - Sec.ParentSegment->Offset +
2612753f127fSDimitry Andric                              Sec.ParentSegment->PAddr,
2613753f127fSDimitry Andric                          std::max(Sec.Align, uint64_t(1)));
261481ad6265SDimitry Andric     if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
261581ad6265SDimitry Andric       MinAddr = std::min(MinAddr, Sec.Addr);
261681ad6265SDimitry Andric   }
261781ad6265SDimitry Andric 
261881ad6265SDimitry Andric   // Now that every section has been laid out we just need to compute the total
261981ad6265SDimitry Andric   // file size. This might not be the same as the offset returned by
262081ad6265SDimitry Andric   // layoutSections, because we want to truncate the last segment to the end of
262181ad6265SDimitry Andric   // its last non-empty section, to match GNU objcopy's behaviour.
262281ad6265SDimitry Andric   TotalSize = 0;
262381ad6265SDimitry Andric   for (SectionBase &Sec : Obj.allocSections())
262481ad6265SDimitry Andric     if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
262581ad6265SDimitry Andric       Sec.Offset = Sec.Addr - MinAddr;
262681ad6265SDimitry Andric       TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
262781ad6265SDimitry Andric     }
262881ad6265SDimitry Andric 
262981ad6265SDimitry Andric   Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
263081ad6265SDimitry Andric   if (!Buf)
263181ad6265SDimitry Andric     return createStringError(errc::not_enough_memory,
263281ad6265SDimitry Andric                              "failed to allocate memory buffer of " +
263381ad6265SDimitry Andric                                  Twine::utohexstr(TotalSize) + " bytes");
263481ad6265SDimitry Andric   SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
263581ad6265SDimitry Andric   return Error::success();
263681ad6265SDimitry Andric }
263781ad6265SDimitry Andric 
263881ad6265SDimitry Andric bool IHexWriter::SectionCompare::operator()(const SectionBase *Lhs,
263981ad6265SDimitry Andric                                             const SectionBase *Rhs) const {
264081ad6265SDimitry Andric   return (sectionPhysicalAddr(Lhs) & 0xFFFFFFFFU) <
264181ad6265SDimitry Andric          (sectionPhysicalAddr(Rhs) & 0xFFFFFFFFU);
264281ad6265SDimitry Andric }
264381ad6265SDimitry Andric 
264481ad6265SDimitry Andric uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
264581ad6265SDimitry Andric   IHexLineData HexData;
264681ad6265SDimitry Andric   uint8_t Data[4] = {};
264781ad6265SDimitry Andric   // We don't write entry point record if entry is zero.
264881ad6265SDimitry Andric   if (Obj.Entry == 0)
264981ad6265SDimitry Andric     return 0;
265081ad6265SDimitry Andric 
265181ad6265SDimitry Andric   if (Obj.Entry <= 0xFFFFFU) {
265281ad6265SDimitry Andric     Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
265381ad6265SDimitry Andric     support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
265481ad6265SDimitry Andric                            support::big);
265581ad6265SDimitry Andric     HexData = IHexRecord::getLine(IHexRecord::StartAddr80x86, 0, Data);
265681ad6265SDimitry Andric   } else {
265781ad6265SDimitry Andric     support::endian::write(Data, static_cast<uint32_t>(Obj.Entry),
265881ad6265SDimitry Andric                            support::big);
265981ad6265SDimitry Andric     HexData = IHexRecord::getLine(IHexRecord::StartAddr, 0, Data);
266081ad6265SDimitry Andric   }
266181ad6265SDimitry Andric   memcpy(Buf, HexData.data(), HexData.size());
266281ad6265SDimitry Andric   return HexData.size();
266381ad6265SDimitry Andric }
266481ad6265SDimitry Andric 
266581ad6265SDimitry Andric uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
266681ad6265SDimitry Andric   IHexLineData HexData = IHexRecord::getLine(IHexRecord::EndOfFile, 0, {});
266781ad6265SDimitry Andric   memcpy(Buf, HexData.data(), HexData.size());
266881ad6265SDimitry Andric   return HexData.size();
266981ad6265SDimitry Andric }
267081ad6265SDimitry Andric 
267181ad6265SDimitry Andric Error IHexWriter::write() {
267281ad6265SDimitry Andric   IHexSectionWriter Writer(*Buf);
267381ad6265SDimitry Andric   // Write sections.
267481ad6265SDimitry Andric   for (const SectionBase *Sec : Sections)
267581ad6265SDimitry Andric     if (Error Err = Sec->accept(Writer))
267681ad6265SDimitry Andric       return Err;
267781ad6265SDimitry Andric 
267881ad6265SDimitry Andric   uint64_t Offset = Writer.getBufferOffset();
267981ad6265SDimitry Andric   // Write entry point address.
268081ad6265SDimitry Andric   Offset += writeEntryPointRecord(
268181ad6265SDimitry Andric       reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
268281ad6265SDimitry Andric   // Write EOF.
268381ad6265SDimitry Andric   Offset += writeEndOfFileRecord(
268481ad6265SDimitry Andric       reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
268581ad6265SDimitry Andric   assert(Offset == TotalSize);
268681ad6265SDimitry Andric 
268781ad6265SDimitry Andric   // TODO: Implement direct writing to the output stream (without intermediate
268881ad6265SDimitry Andric   // memory buffer Buf).
268981ad6265SDimitry Andric   Out.write(Buf->getBufferStart(), Buf->getBufferSize());
269081ad6265SDimitry Andric   return Error::success();
269181ad6265SDimitry Andric }
269281ad6265SDimitry Andric 
269381ad6265SDimitry Andric Error IHexWriter::checkSection(const SectionBase &Sec) {
269481ad6265SDimitry Andric   uint64_t Addr = sectionPhysicalAddr(&Sec);
269581ad6265SDimitry Andric   if (addressOverflows32bit(Addr) || addressOverflows32bit(Addr + Sec.Size - 1))
269681ad6265SDimitry Andric     return createStringError(
269781ad6265SDimitry Andric         errc::invalid_argument,
269881ad6265SDimitry Andric         "Section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
269981ad6265SDimitry Andric         Sec.Name.c_str(), Addr, Addr + Sec.Size - 1);
270081ad6265SDimitry Andric   return Error::success();
270181ad6265SDimitry Andric }
270281ad6265SDimitry Andric 
270381ad6265SDimitry Andric Error IHexWriter::finalize() {
270481ad6265SDimitry Andric   // We can't write 64-bit addresses.
270581ad6265SDimitry Andric   if (addressOverflows32bit(Obj.Entry))
270681ad6265SDimitry Andric     return createStringError(errc::invalid_argument,
270781ad6265SDimitry Andric                              "Entry point address 0x%llx overflows 32 bits",
270881ad6265SDimitry Andric                              Obj.Entry);
270981ad6265SDimitry Andric 
271081ad6265SDimitry Andric   for (const SectionBase &Sec : Obj.sections())
271181ad6265SDimitry Andric     if ((Sec.Flags & ELF::SHF_ALLOC) && Sec.Type != ELF::SHT_NOBITS &&
271281ad6265SDimitry Andric         Sec.Size > 0) {
271381ad6265SDimitry Andric       if (Error E = checkSection(Sec))
271481ad6265SDimitry Andric         return E;
271581ad6265SDimitry Andric       Sections.insert(&Sec);
271681ad6265SDimitry Andric     }
271781ad6265SDimitry Andric 
271881ad6265SDimitry Andric   std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
271981ad6265SDimitry Andric       WritableMemoryBuffer::getNewMemBuffer(0);
272081ad6265SDimitry Andric   if (!EmptyBuffer)
272181ad6265SDimitry Andric     return createStringError(errc::not_enough_memory,
272281ad6265SDimitry Andric                              "failed to allocate memory buffer of 0 bytes");
272381ad6265SDimitry Andric 
272481ad6265SDimitry Andric   IHexSectionWriterBase LengthCalc(*EmptyBuffer);
272581ad6265SDimitry Andric   for (const SectionBase *Sec : Sections)
272681ad6265SDimitry Andric     if (Error Err = Sec->accept(LengthCalc))
272781ad6265SDimitry Andric       return Err;
272881ad6265SDimitry Andric 
272981ad6265SDimitry Andric   // We need space to write section records + StartAddress record
273081ad6265SDimitry Andric   // (if start adress is not zero) + EndOfFile record.
273181ad6265SDimitry Andric   TotalSize = LengthCalc.getBufferOffset() +
273281ad6265SDimitry Andric               (Obj.Entry ? IHexRecord::getLineLength(4) : 0) +
273381ad6265SDimitry Andric               IHexRecord::getLineLength(0);
273481ad6265SDimitry Andric 
273581ad6265SDimitry Andric   Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
273681ad6265SDimitry Andric   if (!Buf)
273781ad6265SDimitry Andric     return createStringError(errc::not_enough_memory,
273881ad6265SDimitry Andric                              "failed to allocate memory buffer of " +
273981ad6265SDimitry Andric                                  Twine::utohexstr(TotalSize) + " bytes");
274081ad6265SDimitry Andric 
274181ad6265SDimitry Andric   return Error::success();
274281ad6265SDimitry Andric }
274381ad6265SDimitry Andric 
274481ad6265SDimitry Andric namespace llvm {
274581ad6265SDimitry Andric namespace objcopy {
274681ad6265SDimitry Andric namespace elf {
274781ad6265SDimitry Andric 
274881ad6265SDimitry Andric template class ELFBuilder<ELF64LE>;
274981ad6265SDimitry Andric template class ELFBuilder<ELF64BE>;
275081ad6265SDimitry Andric template class ELFBuilder<ELF32LE>;
275181ad6265SDimitry Andric template class ELFBuilder<ELF32BE>;
275281ad6265SDimitry Andric 
275381ad6265SDimitry Andric template class ELFWriter<ELF64LE>;
275481ad6265SDimitry Andric template class ELFWriter<ELF64BE>;
275581ad6265SDimitry Andric template class ELFWriter<ELF32LE>;
275681ad6265SDimitry Andric template class ELFWriter<ELF32BE>;
275781ad6265SDimitry Andric 
275881ad6265SDimitry Andric } // end namespace elf
275981ad6265SDimitry Andric } // end namespace objcopy
276081ad6265SDimitry Andric } // end namespace llvm
2761