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