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