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