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