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