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