OSDN Git Service

[llvm-objcopy] Add --globalize-symbol option
[android-x86/external-llvm.git] / tools / llvm-objcopy / Object.cpp
1 //===- Object.cpp ---------------------------------------------------------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Object.h"
11 #include "llvm-objcopy.h"
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/FileOutputBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include <algorithm>
23 #include <cstddef>
24 #include <cstdint>
25 #include <iterator>
26 #include <utility>
27 #include <vector>
28
29 using namespace llvm;
30 using namespace object;
31 using namespace ELF;
32
33 template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
34   using Elf_Phdr = typename ELFT::Phdr;
35
36   uint8_t *Buf = BufPtr->getBufferStart();
37   Buf += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
38   Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
39   Phdr.p_type = Seg.Type;
40   Phdr.p_flags = Seg.Flags;
41   Phdr.p_offset = Seg.Offset;
42   Phdr.p_vaddr = Seg.VAddr;
43   Phdr.p_paddr = Seg.PAddr;
44   Phdr.p_filesz = Seg.FileSize;
45   Phdr.p_memsz = Seg.MemSize;
46   Phdr.p_align = Seg.Align;
47 }
48
49 void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
50 void SectionBase::initialize(SectionTableRef SecTable) {}
51 void SectionBase::finalize() {}
52
53 template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
54   uint8_t *Buf = BufPtr->getBufferStart();
55   Buf += Sec.HeaderOffset;
56   typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
57   Shdr.sh_name = Sec.NameIndex;
58   Shdr.sh_type = Sec.Type;
59   Shdr.sh_flags = Sec.Flags;
60   Shdr.sh_addr = Sec.Addr;
61   Shdr.sh_offset = Sec.Offset;
62   Shdr.sh_size = Sec.Size;
63   Shdr.sh_link = Sec.Link;
64   Shdr.sh_info = Sec.Info;
65   Shdr.sh_addralign = Sec.Align;
66   Shdr.sh_entsize = Sec.EntrySize;
67 }
68
69 SectionVisitor::~SectionVisitor() {}
70
71 void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
72   error("Cannot write symbol table '" + Sec.Name + "' out to binary");
73 }
74
75 void BinarySectionWriter::visit(const RelocationSection &Sec) {
76   error("Cannot write relocation section '" + Sec.Name + "' out to binary");
77 }
78
79 void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
80   error("Cannot write '" + Sec.Name + "' out to binary");
81 }
82
83 void BinarySectionWriter::visit(const GroupSection &Sec) {
84   error("Cannot write '" + Sec.Name + "' out to binary");
85 }
86
87 void SectionWriter::visit(const Section &Sec) {
88   if (Sec.Type == SHT_NOBITS)
89     return;
90   uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
91   std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
92 }
93
94 void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
95
96 void SectionWriter::visit(const OwnedDataSection &Sec) {
97   uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
98   std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
99 }
100
101 void OwnedDataSection::accept(SectionVisitor &Visitor) const {
102   Visitor.visit(*this);
103 }
104
105 void StringTableSection::addString(StringRef Name) {
106   StrTabBuilder.add(Name);
107   Size = StrTabBuilder.getSize();
108 }
109
110 uint32_t StringTableSection::findIndex(StringRef Name) const {
111   return StrTabBuilder.getOffset(Name);
112 }
113
114 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
115
116 void SectionWriter::visit(const StringTableSection &Sec) {
117   Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
118 }
119
120 void StringTableSection::accept(SectionVisitor &Visitor) const {
121   Visitor.visit(*this);
122 }
123
124 static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
125   switch (Index) {
126   case SHN_ABS:
127   case SHN_COMMON:
128     return true;
129   }
130   if (Machine == EM_HEXAGON) {
131     switch (Index) {
132     case SHN_HEXAGON_SCOMMON:
133     case SHN_HEXAGON_SCOMMON_2:
134     case SHN_HEXAGON_SCOMMON_4:
135     case SHN_HEXAGON_SCOMMON_8:
136       return true;
137     }
138   }
139   return false;
140 }
141
142 uint16_t Symbol::getShndx() const {
143   if (DefinedIn != nullptr) {
144     return DefinedIn->Index;
145   }
146   switch (ShndxType) {
147   // This means that we don't have a defined section but we do need to
148   // output a legitimate section index.
149   case SYMBOL_SIMPLE_INDEX:
150     return SHN_UNDEF;
151   case SYMBOL_ABS:
152   case SYMBOL_COMMON:
153   case SYMBOL_HEXAGON_SCOMMON:
154   case SYMBOL_HEXAGON_SCOMMON_2:
155   case SYMBOL_HEXAGON_SCOMMON_4:
156   case SYMBOL_HEXAGON_SCOMMON_8:
157     return static_cast<uint16_t>(ShndxType);
158   }
159   llvm_unreachable("Symbol with invalid ShndxType encountered");
160 }
161
162 void SymbolTableSection::assignIndices() {
163   uint32_t Index = 0;
164   for (auto &Sym : Symbols)
165     Sym->Index = Index++;
166 }
167
168 void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
169                                    SectionBase *DefinedIn, uint64_t Value,
170                                    uint8_t Visibility, uint16_t Shndx,
171                                    uint64_t Sz) {
172   Symbol Sym;
173   Sym.Name = Name;
174   Sym.Binding = Bind;
175   Sym.Type = Type;
176   Sym.DefinedIn = DefinedIn;
177   if (DefinedIn == nullptr) {
178     if (Shndx >= SHN_LORESERVE)
179       Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
180     else
181       Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
182   }
183   Sym.Value = Value;
184   Sym.Visibility = Visibility;
185   Sym.Size = Sz;
186   Sym.Index = Symbols.size();
187   Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
188   Size += this->EntrySize;
189 }
190
191 void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
192   if (SymbolNames == Sec) {
193     error("String table " + SymbolNames->Name +
194           " cannot be removed because it is referenced by the symbol table " +
195           this->Name);
196   }
197   auto Iter =
198       std::remove_if(std::begin(Symbols), std::end(Symbols),
199                      [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
200   Size -= (std::end(Symbols) - Iter) * this->EntrySize;
201   Symbols.erase(Iter, std::end(Symbols));
202   assignIndices();
203 }
204
205 void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
206   for (auto &Sym : Symbols)
207     Callable(*Sym);
208   std::stable_partition(
209       std::begin(Symbols), std::end(Symbols),
210       [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
211   assignIndices();
212 }
213
214 void SymbolTableSection::initialize(SectionTableRef SecTable) {
215   Size = 0;
216   setStrTab(SecTable.getSectionOfType<StringTableSection>(
217       Link,
218       "Symbol table has link index of " + Twine(Link) +
219           " which is not a valid index",
220       "Symbol table has link index of " + Twine(Link) +
221           " which is not a string table"));
222 }
223
224 void SymbolTableSection::finalize() {
225   // Make sure SymbolNames is finalized before getting name indexes.
226   SymbolNames->finalize();
227
228   uint32_t MaxLocalIndex = 0;
229   for (auto &Sym : Symbols) {
230     Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
231     if (Sym->Binding == STB_LOCAL)
232       MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
233   }
234   // Now we need to set the Link and Info fields.
235   Link = SymbolNames->Index;
236   Info = MaxLocalIndex + 1;
237 }
238
239 void SymbolTableSection::addSymbolNames() {
240   // Add all of our strings to SymbolNames so that SymbolNames has the right
241   // size before layout is decided.
242   for (auto &Sym : Symbols)
243     SymbolNames->addString(Sym->Name);
244 }
245
246 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
247   if (Symbols.size() <= Index)
248     error("Invalid symbol index: " + Twine(Index));
249   return Symbols[Index].get();
250 }
251
252 template <class ELFT>
253 void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
254   uint8_t *Buf = Out.getBufferStart();
255   Buf += Sec.Offset;
256   typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
257   // Loop though symbols setting each entry of the symbol table.
258   for (auto &Symbol : Sec.Symbols) {
259     Sym->st_name = Symbol->NameIndex;
260     Sym->st_value = Symbol->Value;
261     Sym->st_size = Symbol->Size;
262     Sym->st_other = Symbol->Visibility;
263     Sym->setBinding(Symbol->Binding);
264     Sym->setType(Symbol->Type);
265     Sym->st_shndx = Symbol->getShndx();
266     ++Sym;
267   }
268 }
269
270 void SymbolTableSection::accept(SectionVisitor &Visitor) const {
271   Visitor.visit(*this);
272 }
273
274 template <class SymTabType>
275 void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
276     const SectionBase *Sec) {
277   if (Symbols == Sec) {
278     error("Symbol table " + Symbols->Name +
279           " cannot be removed because it is "
280           "referenced by the relocation "
281           "section " +
282           this->Name);
283   }
284 }
285
286 template <class SymTabType>
287 void RelocSectionWithSymtabBase<SymTabType>::initialize(
288     SectionTableRef SecTable) {
289   setSymTab(SecTable.getSectionOfType<SymTabType>(
290       Link,
291       "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
292       "Link field value " + Twine(Link) + " in section " + Name +
293           " is not a symbol table"));
294
295   if (Info != SHN_UNDEF)
296     setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
297                                              " in section " + Name +
298                                              " is invalid"));
299   else
300     setSection(nullptr);
301 }
302
303 template <class SymTabType>
304 void RelocSectionWithSymtabBase<SymTabType>::finalize() {
305   this->Link = Symbols->Index;
306   if (SecToApplyRel != nullptr)
307     this->Info = SecToApplyRel->Index;
308 }
309
310 template <class ELFT>
311 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
312
313 template <class ELFT>
314 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
315   Rela.r_addend = Addend;
316 }
317
318 template <class RelRange, class T>
319 void writeRel(const RelRange &Relocations, T *Buf) {
320   for (const auto &Reloc : Relocations) {
321     Buf->r_offset = Reloc.Offset;
322     setAddend(*Buf, Reloc.Addend);
323     Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
324     ++Buf;
325   }
326 }
327
328 template <class ELFT>
329 void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
330   uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
331   if (Sec.Type == SHT_REL)
332     writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
333   else
334     writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
335 }
336
337 void RelocationSection::accept(SectionVisitor &Visitor) const {
338   Visitor.visit(*this);
339 }
340
341 void SectionWriter::visit(const DynamicRelocationSection &Sec) {
342   std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
343             Out.getBufferStart() + Sec.Offset);
344 }
345
346 void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
347   Visitor.visit(*this);
348 }
349
350 void Section::removeSectionReferences(const SectionBase *Sec) {
351   if (LinkSection == Sec) {
352     error("Section " + LinkSection->Name +
353           " cannot be removed because it is "
354           "referenced by the section " +
355           this->Name);
356   }
357 }
358
359 void GroupSection::finalize() {
360   this->Info = Sym->Index;
361   this->Link = SymTab->Index;
362 }
363
364 void Section::initialize(SectionTableRef SecTable) {
365   if (Link != ELF::SHN_UNDEF)
366     LinkSection =
367         SecTable.getSection(Link, "Link field value " + Twine(Link) +
368                                       " in section " + Name + " is invalid");
369 }
370
371 void Section::finalize() {
372   if (LinkSection)
373     this->Link = LinkSection->Index;
374 }
375
376 void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
377   FileName = sys::path::filename(File);
378   // The format for the .gnu_debuglink starts with the file name and is
379   // followed by a null terminator and then the CRC32 of the file. The CRC32
380   // should be 4 byte aligned. So we add the FileName size, a 1 for the null
381   // byte, and then finally push the size to alignment and add 4.
382   Size = alignTo(FileName.size() + 1, 4) + 4;
383   // The CRC32 will only be aligned if we align the whole section.
384   Align = 4;
385   Type = ELF::SHT_PROGBITS;
386   Name = ".gnu_debuglink";
387   // For sections not found in segments, OriginalOffset is only used to
388   // establish the order that sections should go in. By using the maximum
389   // possible offset we cause this section to wind up at the end.
390   OriginalOffset = std::numeric_limits<uint64_t>::max();
391   JamCRC crc;
392   crc.update(ArrayRef<char>(Data.data(), Data.size()));
393   // The CRC32 value needs to be complemented because the JamCRC dosn't
394   // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
395   // but it starts by default at 0xFFFFFFFF which is the complement of zero.
396   CRC32 = ~crc.getCRC();
397 }
398
399 GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
400   // Read in the file to compute the CRC of it.
401   auto DebugOrErr = MemoryBuffer::getFile(File);
402   if (!DebugOrErr)
403     error("'" + File + "': " + DebugOrErr.getError().message());
404   auto Debug = std::move(*DebugOrErr);
405   init(File, Debug->getBuffer());
406 }
407
408 template <class ELFT>
409 void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
410   auto Buf = Out.getBufferStart() + Sec.Offset;
411   char *File = reinterpret_cast<char *>(Buf);
412   Elf_Word *CRC =
413       reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
414   *CRC = Sec.CRC32;
415   std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
416 }
417
418 void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
419   Visitor.visit(*this);
420 }
421
422 template <class ELFT>
423 void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
424   ELF::Elf32_Word *Buf =
425       reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
426   *Buf++ = Sec.FlagWord;
427   for (const auto *S : Sec.GroupMembers)
428     support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
429 }
430
431 void GroupSection::accept(SectionVisitor &Visitor) const {
432   Visitor.visit(*this);
433 }
434
435 // Returns true IFF a section is wholly inside the range of a segment
436 static bool sectionWithinSegment(const SectionBase &Section,
437                                  const Segment &Segment) {
438   // If a section is empty it should be treated like it has a size of 1. This is
439   // to clarify the case when an empty section lies on a boundary between two
440   // segments and ensures that the section "belongs" to the second segment and
441   // not the first.
442   uint64_t SecSize = Section.Size ? Section.Size : 1;
443   return Segment.Offset <= Section.OriginalOffset &&
444          Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
445 }
446
447 // Returns true IFF a segment's original offset is inside of another segment's
448 // range.
449 static bool segmentOverlapsSegment(const Segment &Child,
450                                    const Segment &Parent) {
451
452   return Parent.OriginalOffset <= Child.OriginalOffset &&
453          Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
454 }
455
456 static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
457   // Any segment without a parent segment should come before a segment
458   // that has a parent segment.
459   if (A->OriginalOffset < B->OriginalOffset)
460     return true;
461   if (A->OriginalOffset > B->OriginalOffset)
462     return false;
463   return A->Index < B->Index;
464 }
465
466 static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
467   if (A->PAddr < B->PAddr)
468     return true;
469   if (A->PAddr > B->PAddr)
470     return false;
471   return A->Index < B->Index;
472 }
473
474 template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
475   for (auto &Parent : Obj.segments()) {
476     // Every segment will overlap with itself but we don't want a segment to
477     // be it's own parent so we avoid that situation.
478     if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
479       // We want a canonical "most parental" segment but this requires
480       // inspecting the ParentSegment.
481       if (compareSegmentsByOffset(&Parent, &Child))
482         if (Child.ParentSegment == nullptr ||
483             compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
484           Child.ParentSegment = &Parent;
485         }
486     }
487   }
488 }
489
490 template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
491   uint32_t Index = 0;
492   for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
493     ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
494                            (size_t)Phdr.p_filesz};
495     Segment &Seg = Obj.addSegment(Data);
496     Seg.Type = Phdr.p_type;
497     Seg.Flags = Phdr.p_flags;
498     Seg.OriginalOffset = Phdr.p_offset;
499     Seg.Offset = Phdr.p_offset;
500     Seg.VAddr = Phdr.p_vaddr;
501     Seg.PAddr = Phdr.p_paddr;
502     Seg.FileSize = Phdr.p_filesz;
503     Seg.MemSize = Phdr.p_memsz;
504     Seg.Align = Phdr.p_align;
505     Seg.Index = Index++;
506     for (auto &Section : Obj.sections()) {
507       if (sectionWithinSegment(Section, Seg)) {
508         Seg.addSection(&Section);
509         if (!Section.ParentSegment ||
510             Section.ParentSegment->Offset > Seg.Offset) {
511           Section.ParentSegment = &Seg;
512         }
513       }
514     }
515   }
516
517   auto &ElfHdr = Obj.ElfHdrSegment;
518   // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
519   // segments must not overlap, and other types fit even less.
520   ElfHdr.Type = PT_PHDR;
521   ElfHdr.Flags = 0;
522   ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
523   ElfHdr.VAddr = 0;
524   ElfHdr.PAddr = 0;
525   ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
526   ElfHdr.Align = 0;
527   ElfHdr.Index = Index++;
528
529   const auto &Ehdr = *ElfFile.getHeader();
530   auto &PrHdr = Obj.ProgramHdrSegment;
531   PrHdr.Type = PT_PHDR;
532   PrHdr.Flags = 0;
533   // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
534   // Whereas this works automatically for ElfHdr, here OriginalOffset is
535   // always non-zero and to ensure the equation we assign the same value to
536   // VAddr as well.
537   PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
538   PrHdr.PAddr = 0;
539   PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
540   // The spec requires us to naturally align all the fields.
541   PrHdr.Align = sizeof(Elf_Addr);
542   PrHdr.Index = Index++;
543
544   // Now we do an O(n^2) loop through the segments in order to match up
545   // segments.
546   for (auto &Child : Obj.segments())
547     setParentSegment(Child);
548   setParentSegment(ElfHdr);
549   setParentSegment(PrHdr);
550 }
551
552 template <class ELFT>
553 void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
554   auto SecTable = Obj.sections();
555   auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
556       GroupSec->Link,
557       "Link field value " + Twine(GroupSec->Link) + " in section " +
558           GroupSec->Name + " is invalid",
559       "Link field value " + Twine(GroupSec->Link) + " in section " +
560           GroupSec->Name + " is not a symbol table");
561   auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
562   if (!Sym)
563     error("Info field value " + Twine(GroupSec->Info) + " in section " +
564           GroupSec->Name + " is not a valid symbol index");
565   GroupSec->setSymTab(SymTab);
566   GroupSec->setSymbol(Sym);
567   if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
568       GroupSec->Contents.empty())
569     error("The content of the section " + GroupSec->Name + " is malformed");
570   const ELF::Elf32_Word *Word =
571       reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
572   const ELF::Elf32_Word *End =
573       Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
574   GroupSec->setFlagWord(*Word++);
575   for (; Word != End; ++Word) {
576     uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
577     GroupSec->addMember(SecTable.getSection(
578         Index, "Group member index " + Twine(Index) + " in section " +
579                    GroupSec->Name + " is invalid"));
580   }
581 }
582
583 template <class ELFT>
584 void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
585   const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
586   StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
587
588   for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
589     SectionBase *DefSection = nullptr;
590     StringRef Name = unwrapOrError(Sym.getName(StrTabData));
591
592     if (Sym.st_shndx >= SHN_LORESERVE) {
593       if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
594         error(
595             "Symbol '" + Name +
596             "' has unsupported value greater than or equal to SHN_LORESERVE: " +
597             Twine(Sym.st_shndx));
598       }
599     } else if (Sym.st_shndx != SHN_UNDEF) {
600       DefSection = Obj.sections().getSection(
601           Sym.st_shndx, "Symbol '" + Name +
602                             "' is defined in invalid section with index " +
603                             Twine(Sym.st_shndx));
604     }
605
606     SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
607                       Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
608   }
609 }
610
611 template <class ELFT>
612 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
613
614 template <class ELFT>
615 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
616   ToSet = Rela.r_addend;
617 }
618
619 template <class T>
620 void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
621                      T RelRange) {
622   for (const auto &Rel : RelRange) {
623     Relocation ToAdd;
624     ToAdd.Offset = Rel.r_offset;
625     getAddend(ToAdd.Addend, Rel);
626     ToAdd.Type = Rel.getType(false);
627     ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
628     Relocs->addRelocation(ToAdd);
629   }
630 }
631
632 SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
633   if (Index == SHN_UNDEF || Index > Sections.size())
634     error(ErrMsg);
635   return Sections[Index - 1].get();
636 }
637
638 template <class T>
639 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
640                                      Twine TypeErrMsg) {
641   if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
642     return Sec;
643   error(TypeErrMsg);
644 }
645
646 template <class ELFT>
647 SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
648   ArrayRef<uint8_t> Data;
649   switch (Shdr.sh_type) {
650   case SHT_REL:
651   case SHT_RELA:
652     if (Shdr.sh_flags & SHF_ALLOC) {
653       Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
654       return Obj.addSection<DynamicRelocationSection>(Data);
655     }
656     return Obj.addSection<RelocationSection>();
657   case SHT_STRTAB:
658     // If a string table is allocated we don't want to mess with it. That would
659     // mean altering the memory image. There are no special link types or
660     // anything so we can just use a Section.
661     if (Shdr.sh_flags & SHF_ALLOC) {
662       Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
663       return Obj.addSection<Section>(Data);
664     }
665     return Obj.addSection<StringTableSection>();
666   case SHT_HASH:
667   case SHT_GNU_HASH:
668     // Hash tables should refer to SHT_DYNSYM which we're not going to change.
669     // Because of this we don't need to mess with the hash tables either.
670     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
671     return Obj.addSection<Section>(Data);
672   case SHT_GROUP:
673     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
674     return Obj.addSection<GroupSection>(Data);
675   case SHT_DYNSYM:
676     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
677     return Obj.addSection<DynamicSymbolTableSection>(Data);
678   case SHT_DYNAMIC:
679     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
680     return Obj.addSection<DynamicSection>(Data);
681   case SHT_SYMTAB: {
682     auto &SymTab = Obj.addSection<SymbolTableSection>();
683     Obj.SymbolTable = &SymTab;
684     return SymTab;
685   }
686   case SHT_NOBITS:
687     return Obj.addSection<Section>(Data);
688   default:
689     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
690     return Obj.addSection<Section>(Data);
691   }
692 }
693
694 template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
695   uint32_t Index = 0;
696   for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
697     if (Index == 0) {
698       ++Index;
699       continue;
700     }
701     auto &Sec = makeSection(Shdr);
702     Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
703     Sec.Type = Shdr.sh_type;
704     Sec.Flags = Shdr.sh_flags;
705     Sec.Addr = Shdr.sh_addr;
706     Sec.Offset = Shdr.sh_offset;
707     Sec.OriginalOffset = Shdr.sh_offset;
708     Sec.Size = Shdr.sh_size;
709     Sec.Link = Shdr.sh_link;
710     Sec.Info = Shdr.sh_info;
711     Sec.Align = Shdr.sh_addralign;
712     Sec.EntrySize = Shdr.sh_entsize;
713     Sec.Index = Index++;
714   }
715
716   // Now that all of the sections have been added we can fill out some extra
717   // details about symbol tables. We need the symbol table filled out before
718   // any relocations.
719   if (Obj.SymbolTable) {
720     Obj.SymbolTable->initialize(Obj.sections());
721     initSymbolTable(Obj.SymbolTable);
722   }
723
724   // Now that all sections and symbols have been added we can add
725   // relocations that reference symbols and set the link and info fields for
726   // relocation sections.
727   for (auto &Section : Obj.sections()) {
728     if (&Section == Obj.SymbolTable)
729       continue;
730     Section.initialize(Obj.sections());
731     if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
732       auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
733       if (RelSec->Type == SHT_REL)
734         initRelocations(RelSec, Obj.SymbolTable,
735                         unwrapOrError(ElfFile.rels(Shdr)));
736       else
737         initRelocations(RelSec, Obj.SymbolTable,
738                         unwrapOrError(ElfFile.relas(Shdr)));
739     } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
740       initGroupSection(GroupSec);
741     }
742   }
743 }
744
745 template <class ELFT> void ELFBuilder<ELFT>::build() {
746   const auto &Ehdr = *ElfFile.getHeader();
747
748   std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
749   Obj.Type = Ehdr.e_type;
750   Obj.Machine = Ehdr.e_machine;
751   Obj.Version = Ehdr.e_version;
752   Obj.Entry = Ehdr.e_entry;
753   Obj.Flags = Ehdr.e_flags;
754
755   readSectionHeaders();
756   readProgramHeaders();
757
758   Obj.SectionNames =
759       Obj.sections().template getSectionOfType<StringTableSection>(
760           Ehdr.e_shstrndx,
761           "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
762               " in elf header " + " is invalid",
763           "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
764               " in elf header " + " is not a string table");
765 }
766
767 // A generic size function which computes sizes of any random access range.
768 template <class R> size_t size(R &&Range) {
769   return static_cast<size_t>(std::end(Range) - std::begin(Range));
770 }
771
772 Writer::~Writer() {}
773
774 Reader::~Reader() {}
775
776 ELFReader::ELFReader(StringRef File) {
777   auto BinaryOrErr = createBinary(File);
778   if (!BinaryOrErr)
779     reportError(File, BinaryOrErr.takeError());
780   auto OwnedBin = std::move(BinaryOrErr.get());
781   std::tie(Bin, Data) = OwnedBin.takeBinary();
782 }
783
784 ElfType ELFReader::getElfType() const {
785   if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
786     return ELFT_ELF32LE;
787   if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
788     return ELFT_ELF64LE;
789   if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
790     return ELFT_ELF32BE;
791   if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
792     return ELFT_ELF64BE;
793   llvm_unreachable("Invalid ELFType");
794 }
795
796 std::unique_ptr<Object> ELFReader::create() const {
797   auto Obj = llvm::make_unique<Object>(Data);
798   if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
799     ELFBuilder<ELF32LE> Builder(*o, *Obj);
800     Builder.build();
801     return Obj;
802   } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
803     ELFBuilder<ELF64LE> Builder(*o, *Obj);
804     Builder.build();
805     return Obj;
806   } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
807     ELFBuilder<ELF32BE> Builder(*o, *Obj);
808     Builder.build();
809     return Obj;
810   } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
811     ELFBuilder<ELF64BE> Builder(*o, *Obj);
812     Builder.build();
813     return Obj;
814   }
815   error("Invalid file type");
816 }
817
818 template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
819   uint8_t *Buf = BufPtr->getBufferStart();
820   Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
821   std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
822   Ehdr.e_type = Obj.Type;
823   Ehdr.e_machine = Obj.Machine;
824   Ehdr.e_version = Obj.Version;
825   Ehdr.e_entry = Obj.Entry;
826   Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
827   Ehdr.e_flags = Obj.Flags;
828   Ehdr.e_ehsize = sizeof(Elf_Ehdr);
829   Ehdr.e_phentsize = sizeof(Elf_Phdr);
830   Ehdr.e_phnum = size(Obj.segments());
831   Ehdr.e_shentsize = sizeof(Elf_Shdr);
832   if (WriteSectionHeaders) {
833     Ehdr.e_shoff = Obj.SHOffset;
834     Ehdr.e_shnum = size(Obj.sections()) + 1;
835     Ehdr.e_shstrndx = Obj.SectionNames->Index;
836   } else {
837     Ehdr.e_shoff = 0;
838     Ehdr.e_shnum = 0;
839     Ehdr.e_shstrndx = 0;
840   }
841 }
842
843 template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
844   for (auto &Seg : Obj.segments())
845     writePhdr(Seg);
846 }
847
848 template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
849   uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
850   // This reference serves to write the dummy section header at the begining
851   // of the file. It is not used for anything else
852   Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
853   Shdr.sh_name = 0;
854   Shdr.sh_type = SHT_NULL;
855   Shdr.sh_flags = 0;
856   Shdr.sh_addr = 0;
857   Shdr.sh_offset = 0;
858   Shdr.sh_size = 0;
859   Shdr.sh_link = 0;
860   Shdr.sh_info = 0;
861   Shdr.sh_addralign = 0;
862   Shdr.sh_entsize = 0;
863
864   for (auto &Sec : Obj.sections())
865     writeShdr(Sec);
866 }
867
868 template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
869   for (auto &Sec : Obj.sections())
870     Sec.accept(*SecWriter);
871 }
872
873 void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
874
875   auto Iter = std::stable_partition(
876       std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
877         if (ToRemove(*Sec))
878           return false;
879         if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
880           if (auto ToRelSec = RelSec->getSection())
881             return !ToRemove(*ToRelSec);
882         }
883         return true;
884       });
885   if (SymbolTable != nullptr && ToRemove(*SymbolTable))
886     SymbolTable = nullptr;
887   if (SectionNames != nullptr && ToRemove(*SectionNames)) {
888     SectionNames = nullptr;
889   }
890   // Now make sure there are no remaining references to the sections that will
891   // be removed. Sometimes it is impossible to remove a reference so we emit
892   // an error here instead.
893   for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
894     for (auto &Segment : Segments)
895       Segment->removeSection(RemoveSec.get());
896     for (auto &KeepSec : make_range(std::begin(Sections), Iter))
897       KeepSec->removeSectionReferences(RemoveSec.get());
898   }
899   // Now finally get rid of them all togethor.
900   Sections.erase(Iter, std::end(Sections));
901 }
902
903 void Object::sortSections() {
904   // Put all sections in offset order. Maintain the ordering as closely as
905   // possible while meeting that demand however.
906   auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
907     return A->OriginalOffset < B->OriginalOffset;
908   };
909   std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
910                    CompareSections);
911 }
912
913 static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
914   // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
915   if (Align == 0)
916     Align = 1;
917   auto Diff =
918       static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
919   // We only want to add to Offset, however, so if Diff < 0 we can add Align and
920   // (Offset + Diff) & -Align == Addr & -Align will still hold.
921   if (Diff < 0)
922     Diff += Align;
923   return Offset + Diff;
924 }
925
926 // Orders segments such that if x = y->ParentSegment then y comes before x.
927 static void OrderSegments(std::vector<Segment *> &Segments) {
928   std::stable_sort(std::begin(Segments), std::end(Segments),
929                    compareSegmentsByOffset);
930 }
931
932 // This function finds a consistent layout for a list of segments starting from
933 // an Offset. It assumes that Segments have been sorted by OrderSegments and
934 // returns an Offset one past the end of the last segment.
935 static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
936                                uint64_t Offset) {
937   assert(std::is_sorted(std::begin(Segments), std::end(Segments),
938                         compareSegmentsByOffset));
939   // The only way a segment should move is if a section was between two
940   // segments and that section was removed. If that section isn't in a segment
941   // then it's acceptable, but not ideal, to simply move it to after the
942   // segments. So we can simply layout segments one after the other accounting
943   // for alignment.
944   for (auto &Segment : Segments) {
945     // We assume that segments have been ordered by OriginalOffset and Index
946     // such that a parent segment will always come before a child segment in
947     // OrderedSegments. This means that the Offset of the ParentSegment should
948     // already be set and we can set our offset relative to it.
949     if (Segment->ParentSegment != nullptr) {
950       auto Parent = Segment->ParentSegment;
951       Segment->Offset =
952           Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
953     } else {
954       Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
955       Segment->Offset = Offset;
956     }
957     Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
958   }
959   return Offset;
960 }
961
962 // This function finds a consistent layout for a list of sections. It assumes
963 // that the ->ParentSegment of each section has already been laid out. The
964 // supplied starting Offset is used for the starting offset of any section that
965 // does not have a ParentSegment. It returns either the offset given if all
966 // sections had a ParentSegment or an offset one past the last section if there
967 // was a section that didn't have a ParentSegment.
968 template <class Range>
969 static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
970   // Now the offset of every segment has been set we can assign the offsets
971   // of each section. For sections that are covered by a segment we should use
972   // the segment's original offset and the section's original offset to compute
973   // the offset from the start of the segment. Using the offset from the start
974   // of the segment we can assign a new offset to the section. For sections not
975   // covered by segments we can just bump Offset to the next valid location.
976   uint32_t Index = 1;
977   for (auto &Section : Sections) {
978     Section.Index = Index++;
979     if (Section.ParentSegment != nullptr) {
980       auto Segment = *Section.ParentSegment;
981       Section.Offset =
982           Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
983     } else {
984       Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
985       Section.Offset = Offset;
986       if (Section.Type != SHT_NOBITS)
987         Offset += Section.Size;
988     }
989   }
990   return Offset;
991 }
992
993 template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
994   // We need a temporary list of segments that has a special order to it
995   // so that we know that anytime ->ParentSegment is set that segment has
996   // already had its offset properly set.
997   std::vector<Segment *> OrderedSegments;
998   for (auto &Segment : Obj.segments())
999     OrderedSegments.push_back(&Segment);
1000   OrderedSegments.push_back(&Obj.ElfHdrSegment);
1001   OrderedSegments.push_back(&Obj.ProgramHdrSegment);
1002   OrderSegments(OrderedSegments);
1003   // Offset is used as the start offset of the first segment to be laid out.
1004   // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1005   // we start at offset 0.
1006   uint64_t Offset = 0;
1007   Offset = LayoutSegments(OrderedSegments, Offset);
1008   Offset = LayoutSections(Obj.sections(), Offset);
1009   // If we need to write the section header table out then we need to align the
1010   // Offset so that SHOffset is valid.
1011   if (WriteSectionHeaders)
1012     Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
1013   Obj.SHOffset = Offset;
1014 }
1015
1016 template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
1017   // We already have the section header offset so we can calculate the total
1018   // size by just adding up the size of each section header.
1019   auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1020   return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
1021          NullSectionSize;
1022 }
1023
1024 template <class ELFT> void ELFWriter<ELFT>::write() {
1025   writeEhdr();
1026   writePhdrs();
1027   writeSectionData();
1028   if (WriteSectionHeaders)
1029     writeShdrs();
1030   if (auto E = BufPtr->commit())
1031     reportError(File, errorToErrorCode(std::move(E)));
1032 }
1033
1034 void Writer::createBuffer(uint64_t Size) {
1035   auto BufferOrErr =
1036       FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
1037   handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
1038     error("failed to open " + File);
1039   });
1040   BufPtr = std::move(*BufferOrErr);
1041 }
1042
1043 template <class ELFT> void ELFWriter<ELFT>::finalize() {
1044   // It could happen that SectionNames has been removed and yet the user wants
1045   // a section header table output. We need to throw an error if a user tries
1046   // to do that.
1047   if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1048     error("Cannot write section header table because section header string "
1049           "table was removed.");
1050
1051   // Make sure we add the names of all the sections.
1052   if (Obj.SectionNames != nullptr)
1053     for (const auto &Section : Obj.sections()) {
1054       Obj.SectionNames->addString(Section.Name);
1055     }
1056   // Make sure we add the names of all the symbols.
1057   if (Obj.SymbolTable != nullptr)
1058     Obj.SymbolTable->addSymbolNames();
1059
1060   Obj.sortSections();
1061   assignOffsets();
1062
1063   // Finalize SectionNames first so that we can assign name indexes.
1064   if (Obj.SectionNames != nullptr)
1065     Obj.SectionNames->finalize();
1066   // Finally now that all offsets and indexes have been set we can finalize any
1067   // remaining issues.
1068   uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1069   for (auto &Section : Obj.sections()) {
1070     Section.HeaderOffset = Offset;
1071     Offset += sizeof(Elf_Shdr);
1072     if (WriteSectionHeaders)
1073       Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1074     Section.finalize();
1075   }
1076
1077   createBuffer(totalSize());
1078   SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
1079 }
1080
1081 void BinaryWriter::write() {
1082   for (auto &Section : Obj.sections()) {
1083     if ((Section.Flags & SHF_ALLOC) == 0)
1084       continue;
1085     Section.accept(*SecWriter);
1086   }
1087   if (auto E = BufPtr->commit())
1088     reportError(File, errorToErrorCode(std::move(E)));
1089 }
1090
1091 void BinaryWriter::finalize() {
1092   // TODO: Create a filter range to construct OrderedSegments from so that this
1093   // code can be deduped with assignOffsets above. This should also solve the
1094   // todo below for LayoutSections.
1095   // We need a temporary list of segments that has a special order to it
1096   // so that we know that anytime ->ParentSegment is set that segment has
1097   // already had it's offset properly set. We only want to consider the segments
1098   // that will affect layout of allocated sections so we only add those.
1099   std::vector<Segment *> OrderedSegments;
1100   for (auto &Section : Obj.sections()) {
1101     if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1102       OrderedSegments.push_back(Section.ParentSegment);
1103     }
1104   }
1105
1106   // For binary output, we're going to use physical addresses instead of
1107   // virtual addresses, since a binary output is used for cases like ROM
1108   // loading and physical addresses are intended for ROM loading.
1109   // However, if no segment has a physical address, we'll fallback to using
1110   // virtual addresses for all.
1111   if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1112                   [](const Segment *Segment) { return Segment->PAddr == 0; }))
1113     for (const auto &Segment : OrderedSegments)
1114       Segment->PAddr = Segment->VAddr;
1115
1116   std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1117                    compareSegmentsByPAddr);
1118
1119   // Because we add a ParentSegment for each section we might have duplicate
1120   // segments in OrderedSegments. If there were duplicates then LayoutSegments
1121   // would do very strange things.
1122   auto End =
1123       std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1124   OrderedSegments.erase(End, std::end(OrderedSegments));
1125
1126   uint64_t Offset = 0;
1127
1128   // Modify the first segment so that there is no gap at the start. This allows
1129   // our layout algorithm to proceed as expected while not out writing out the
1130   // gap at the start.
1131   if (!OrderedSegments.empty()) {
1132     auto Seg = OrderedSegments[0];
1133     auto Sec = Seg->firstSection();
1134     auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1135     Seg->OriginalOffset += Diff;
1136     // The size needs to be shrunk as well.
1137     Seg->FileSize -= Diff;
1138     // The PAddr needs to be increased to remove the gap before the first
1139     // section.
1140     Seg->PAddr += Diff;
1141     uint64_t LowestPAddr = Seg->PAddr;
1142     for (auto &Segment : OrderedSegments) {
1143       Segment->Offset = Segment->PAddr - LowestPAddr;
1144       Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1145     }
1146   }
1147
1148   // TODO: generalize LayoutSections to take a range. Pass a special range
1149   // constructed from an iterator that skips values for which a predicate does
1150   // not hold. Then pass such a range to LayoutSections instead of constructing
1151   // AllocatedSections here.
1152   std::vector<SectionBase *> AllocatedSections;
1153   for (auto &Section : Obj.sections()) {
1154     if ((Section.Flags & SHF_ALLOC) == 0)
1155       continue;
1156     AllocatedSections.push_back(&Section);
1157   }
1158   LayoutSections(make_pointee_range(AllocatedSections), Offset);
1159
1160   // Now that every section has been laid out we just need to compute the total
1161   // file size. This might not be the same as the offset returned by
1162   // LayoutSections, because we want to truncate the last segment to the end of
1163   // its last section, to match GNU objcopy's behaviour.
1164   TotalSize = 0;
1165   for (const auto &Section : AllocatedSections) {
1166     if (Section->Type != SHT_NOBITS)
1167       TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1168   }
1169
1170   createBuffer(TotalSize);
1171   SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
1172 }
1173
1174 namespace llvm {
1175
1176 template class ELFBuilder<ELF64LE>;
1177 template class ELFBuilder<ELF64BE>;
1178 template class ELFBuilder<ELF32LE>;
1179 template class ELFBuilder<ELF32BE>;
1180
1181 template class ELFWriter<ELF64LE>;
1182 template class ELFWriter<ELF64BE>;
1183 template class ELFWriter<ELF32LE>;
1184 template class ELFWriter<ELF32BE>;
1185 } // end namespace llvm