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