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