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