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