OSDN Git Service

cad97b93c3fee0460af5ede7681a856a3b8dfed3
[android-x86/external-llvm.git] / tools / llvm-objcopy / Object.cpp
1 //===- Object.cpp -----------------------------------------------*- C++ -*-===//
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 #include "Object.h"
10 #include "llvm-objcopy.h"
11
12 using namespace llvm;
13 using namespace object;
14 using namespace ELF;
15
16 template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
17   typedef typename ELFT::Ehdr Elf_Ehdr;
18   typedef typename ELFT::Phdr Elf_Phdr;
19
20   uint8_t *Buf = Out.getBufferStart();
21   Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
22   Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
23   Phdr.p_type = Type;
24   Phdr.p_flags = Flags;
25   Phdr.p_offset = Offset;
26   Phdr.p_vaddr = VAddr;
27   Phdr.p_paddr = PAddr;
28   Phdr.p_filesz = FileSize;
29   Phdr.p_memsz = MemSize;
30   Phdr.p_align = Align;
31 }
32
33 void Segment::finalize() {
34   auto FirstSec = firstSection();
35   if (FirstSec) {
36     // It is possible for a gap to be at the begining of a segment. Because of
37     // this we need to compute the new offset based on how large this gap was
38     // in the source file. Section layout should have already ensured that this
39     // space is not used for something else.
40     uint64_t OriginalOffset = Offset;
41     Offset = FirstSec->Offset - (FirstSec->OriginalOffset - OriginalOffset);
42   }
43 }
44
45 void Segment::writeSegment(FileOutputBuffer &Out) const {
46   uint8_t *Buf = Out.getBufferStart() + Offset;
47   // We want to maintain segments' interstitial data and contents exactly.
48   // This lets us just copy segments directly.
49   std::copy(std::begin(Contents), std::end(Contents), Buf);
50 }
51
52 void SectionBase::finalize() {}
53
54 template <class ELFT>
55 void SectionBase::writeHeader(FileOutputBuffer &Out) const {
56   uint8_t *Buf = Out.getBufferStart();
57   Buf += HeaderOffset;
58   typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
59   Shdr.sh_name = NameIndex;
60   Shdr.sh_type = Type;
61   Shdr.sh_flags = Flags;
62   Shdr.sh_addr = Addr;
63   Shdr.sh_offset = Offset;
64   Shdr.sh_size = Size;
65   Shdr.sh_link = Link;
66   Shdr.sh_info = Info;
67   Shdr.sh_addralign = Align;
68   Shdr.sh_entsize = EntrySize;
69 }
70
71 void Section::writeSection(FileOutputBuffer &Out) const {
72   if (Type == SHT_NOBITS)
73     return;
74   uint8_t *Buf = Out.getBufferStart() + Offset;
75   std::copy(std::begin(Contents), std::end(Contents), Buf);
76 }
77
78 void StringTableSection::addString(StringRef Name) {
79   StrTabBuilder.add(Name);
80   Size = StrTabBuilder.getSize();
81 }
82
83 uint32_t StringTableSection::findIndex(StringRef Name) const {
84   return StrTabBuilder.getOffset(Name);
85 }
86
87 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
88
89 void StringTableSection::writeSection(FileOutputBuffer &Out) const {
90   StrTabBuilder.write(Out.getBufferStart() + Offset);
91 }
92
93 static bool isValidReservedSectionIndex(uint16_t Index) {
94   switch (Index) {
95   case SHN_ABS:
96   case SHN_COMMON:
97   case SHN_HEXAGON_SCOMMON:
98   case SHN_HEXAGON_SCOMMON_2:
99   case SHN_HEXAGON_SCOMMON_4:
100   case SHN_HEXAGON_SCOMMON_8:
101     return true;
102   default:
103     return false;
104   }
105 }
106
107 uint16_t Symbol::getShndx() const {
108   if (DefinedIn != nullptr) {
109     return DefinedIn->Index;
110   }
111   switch (ShndxType) {
112   // This means that we don't have a defined section but we do need to
113   // output a legitimate section index.
114   case SYMBOL_SIMPLE_INDEX:
115     return SHN_UNDEF;
116   case SYMBOL_ABS:
117   case SYMBOL_COMMON:
118   case SYMBOL_HEXAGON_SCOMMON:
119   case SYMBOL_HEXAGON_SCOMMON_2:
120   case SYMBOL_HEXAGON_SCOMMON_4:
121   case SYMBOL_HEXAGON_SCOMMON_8:
122     return static_cast<uint16_t>(ShndxType);
123   }
124   llvm_unreachable("Symbol with invalid ShndxType encountered");
125 }
126
127 void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
128                                    SectionBase *DefinedIn, uint64_t Value,
129                                    uint16_t Shndx, uint64_t Sz) {
130   Symbol Sym;
131   Sym.Name = Name;
132   Sym.Binding = Bind;
133   Sym.Type = Type;
134   Sym.DefinedIn = DefinedIn;
135   if (DefinedIn == nullptr) {
136     if (isValidReservedSectionIndex(Shndx))
137       Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
138     else
139       Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
140   }
141   Sym.Value = Value;
142   Sym.Size = Sz;
143   Sym.Index = Symbols.size();
144   Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
145   Size += this->EntrySize;
146 }
147
148 void SymbolTableSection::finalize() {
149   // Make sure SymbolNames is finalized before getting name indexes.
150   SymbolNames->finalize();
151
152   uint32_t MaxLocalIndex = 0;
153   for (auto &Sym : Symbols) {
154     Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
155     if (Sym->Binding == STB_LOCAL)
156       MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
157   }
158   // Now we need to set the Link and Info fields.
159   Link = SymbolNames->Index;
160   Info = MaxLocalIndex + 1;
161 }
162
163 void SymbolTableSection::addSymbolNames() {
164   // Add all of our strings to SymbolNames so that SymbolNames has the right
165   // size before layout is decided.
166   for (auto &Sym : Symbols)
167     SymbolNames->addString(Sym->Name);
168 }
169
170 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
171   if (Symbols.size() <= Index)
172     error("Invalid symbol index: " + Twine(Index));
173   return Symbols[Index].get();
174 }
175
176 template <class ELFT>
177 void SymbolTableSectionImpl<ELFT>::writeSection(
178     llvm::FileOutputBuffer &Out) const {
179   uint8_t *Buf = Out.getBufferStart();
180   Buf += Offset;
181   typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
182   // Loop though symbols setting each entry of the symbol table.
183   for (auto &Symbol : Symbols) {
184     Sym->st_name = Symbol->NameIndex;
185     Sym->st_value = Symbol->Value;
186     Sym->st_size = Symbol->Size;
187     Sym->setBinding(Symbol->Binding);
188     Sym->setType(Symbol->Type);
189     Sym->st_shndx = Symbol->getShndx();
190     ++Sym;
191   }
192 }
193
194 template <class ELFT> void RelocationSection<ELFT>::finalize() {
195   this->Link = Symbols->Index;
196   this->Info = SecToApplyRel->Index;
197 }
198
199 template <class ELFT>
200 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
201
202 template <class ELFT>
203 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
204   Rela.r_addend = Addend;
205 }
206
207 template <class ELFT>
208 template <class T>
209 void RelocationSection<ELFT>::writeRel(T *Buf) const {
210   for (const auto &Reloc : Relocations) {
211     Buf->r_offset = Reloc.Offset;
212     setAddend(*Buf, Reloc.Addend);
213     Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
214     ++Buf;
215   }
216 }
217
218 template <class ELFT>
219 void RelocationSection<ELFT>::writeSection(llvm::FileOutputBuffer &Out) const {
220   uint8_t *Buf = Out.getBufferStart() + Offset;
221   if (Type == SHT_REL)
222     writeRel(reinterpret_cast<Elf_Rel *>(Buf));
223   else
224     writeRel(reinterpret_cast<Elf_Rela *>(Buf));
225 }
226
227 // Returns true IFF a section is wholly inside the range of a segment
228 static bool sectionWithinSegment(const SectionBase &Section,
229                                  const Segment &Segment) {
230   // If a section is empty it should be treated like it has a size of 1. This is
231   // to clarify the case when an empty section lies on a boundary between two
232   // segments and ensures that the section "belongs" to the second segment and
233   // not the first.
234   uint64_t SecSize = Section.Size ? Section.Size : 1;
235   return Segment.Offset <= Section.OriginalOffset &&
236          Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
237 }
238
239 template <class ELFT>
240 void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
241   uint32_t Index = 0;
242   for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
243     ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
244                            (size_t)Phdr.p_filesz};
245     Segments.emplace_back(llvm::make_unique<Segment>(Data));
246     Segment &Seg = *Segments.back();
247     Seg.Type = Phdr.p_type;
248     Seg.Flags = Phdr.p_flags;
249     Seg.OriginalOffset = Phdr.p_offset;
250     Seg.Offset = Phdr.p_offset;
251     Seg.VAddr = Phdr.p_vaddr;
252     Seg.PAddr = Phdr.p_paddr;
253     Seg.FileSize = Phdr.p_filesz;
254     Seg.MemSize = Phdr.p_memsz;
255     Seg.Align = Phdr.p_align;
256     Seg.Index = Index++;
257     for (auto &Section : Sections) {
258       if (sectionWithinSegment(*Section, Seg)) {
259         Seg.addSection(&*Section);
260         if (!Section->ParentSegment ||
261             Section->ParentSegment->Offset > Seg.Offset) {
262           Section->ParentSegment = &Seg;
263         }
264       }
265     }
266   }
267 }
268
269 template <class ELFT>
270 void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
271                                    SymbolTableSection *SymTab) {
272
273   SymTab->Size = 0;
274   if (SymbolTable->Link - 1 >= Sections.size())
275     error("Symbol table has link index of " + Twine(SymbolTable->Link) +
276           " which is not a valid index");
277
278   if (auto StrTab =
279           dyn_cast<StringTableSection>(Sections[SymbolTable->Link - 1].get()))
280     SymTab->setStrTab(StrTab);
281   else
282     error("Symbol table has link index of " + Twine(SymbolTable->Link) +
283           "which is not a string table");
284
285   const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
286   StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
287
288   for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
289     SectionBase *DefSection = nullptr;
290     StringRef Name = unwrapOrError(Sym.getName(StrTabData));
291     if (Sym.st_shndx >= SHN_LORESERVE) {
292       if (!isValidReservedSectionIndex(Sym.st_shndx)) {
293         error(
294             "Symbol '" + Name +
295             "' has unsupported value greater than or equal to SHN_LORESERVE: " +
296             Twine(Sym.st_shndx));
297       }
298     } else if (Sym.st_shndx != SHN_UNDEF) {
299       if (Sym.st_shndx >= Sections.size())
300         error("Symbol '" + Name +
301               "' is defined in invalid section with index " +
302               Twine(Sym.st_shndx));
303       DefSection = Sections[Sym.st_shndx - 1].get();
304     }
305     SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
306                       Sym.getValue(), Sym.st_shndx, Sym.st_size);
307   }
308 }
309
310 template <class ELFT>
311 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
312
313 template <class ELFT>
314 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
315   ToSet = Rela.r_addend;
316 }
317
318 template <class ELFT, class T>
319 void initRelocations(RelocationSection<ELFT> *Relocs,
320                      SymbolTableSection *SymbolTable, T RelRange) {
321   for (const auto &Rel : RelRange) {
322     Relocation ToAdd;
323     ToAdd.Offset = Rel.r_offset;
324     getAddend(ToAdd.Addend, Rel);
325     ToAdd.Type = Rel.getType(false);
326     ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
327     Relocs->addRelocation(ToAdd);
328   }
329 }
330
331 template <class ELFT>
332 std::unique_ptr<SectionBase>
333 Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
334                           const Elf_Shdr &Shdr) {
335   ArrayRef<uint8_t> Data;
336   switch (Shdr.sh_type) {
337   case SHT_REL:
338   case SHT_RELA:
339     return llvm::make_unique<RelocationSection<ELFT>>();
340   case SHT_STRTAB:
341     return llvm::make_unique<StringTableSection>();
342   case SHT_SYMTAB: {
343     auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
344     SymbolTable = SymTab.get();
345     return std::move(SymTab);
346   }
347   case SHT_NOBITS:
348     return llvm::make_unique<Section>(Data);
349   default:
350     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
351     return llvm::make_unique<Section>(Data);
352   }
353 }
354
355 template <class ELFT>
356 void Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
357   uint32_t Index = 0;
358   for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
359     if (Index == 0) {
360       ++Index;
361       continue;
362     }
363     SecPtr Sec = makeSection(ElfFile, Shdr);
364     Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
365     Sec->Type = Shdr.sh_type;
366     Sec->Flags = Shdr.sh_flags;
367     Sec->Addr = Shdr.sh_addr;
368     Sec->Offset = Shdr.sh_offset;
369     Sec->OriginalOffset = Shdr.sh_offset;
370     Sec->Size = Shdr.sh_size;
371     Sec->Link = Shdr.sh_link;
372     Sec->Info = Shdr.sh_info;
373     Sec->Align = Shdr.sh_addralign;
374     Sec->EntrySize = Shdr.sh_entsize;
375     Sec->Index = Index++;
376     Sections.push_back(std::move(Sec));
377   }
378
379   // Now that all of the sections have been added we can fill out some extra
380   // details about symbol tables.
381   if (SymbolTable)
382     initSymbolTable(ElfFile, SymbolTable);
383
384   // Now that all sections and symbols have been added we can add
385   // relocations that reference symbols and set the link and info fields for
386   // relocation sections.
387   for (auto &Section : Sections) {
388     if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
389       if (RelSec->Link - 1 >= Sections.size() || RelSec->Link == 0) {
390         error("Link field value " + Twine(RelSec->Link) + " in section " +
391               RelSec->Name + " is invalid");
392       }
393       if (RelSec->Info - 1 >= Sections.size() || RelSec->Info == 0) {
394         error("Info field value " + Twine(RelSec->Link) + " in section " +
395               RelSec->Name + " is invalid");
396       }
397       auto SymTab =
398           dyn_cast<SymbolTableSection>(Sections[RelSec->Link - 1].get());
399       if (SymTab == nullptr) {
400         error("Link field of relocation section " + RelSec->Name +
401               " is not a symbol table");
402       }
403       RelSec->setSymTab(SymTab);
404       RelSec->setSection(Sections[RelSec->Info - 1].get());
405       auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
406       if (RelSec->Type == SHT_REL)
407         initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.rels(Shdr)));
408       else
409         initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.relas(Shdr)));
410     }
411   }
412 }
413
414 template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
415   const auto &ElfFile = *Obj.getELFFile();
416   const auto &Ehdr = *ElfFile.getHeader();
417
418   std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
419   Type = Ehdr.e_type;
420   Machine = Ehdr.e_machine;
421   Version = Ehdr.e_version;
422   Entry = Ehdr.e_entry;
423   Flags = Ehdr.e_flags;
424
425   readSectionHeaders(ElfFile);
426   readProgramHeaders(ElfFile);
427
428   SectionNames =
429       dyn_cast<StringTableSection>(Sections[Ehdr.e_shstrndx - 1].get());
430 }
431
432 template <class ELFT>
433 void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
434   uint8_t *Buf = Out.getBufferStart();
435   Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
436   std::copy(Ident, Ident + 16, Ehdr.e_ident);
437   Ehdr.e_type = Type;
438   Ehdr.e_machine = Machine;
439   Ehdr.e_version = Version;
440   Ehdr.e_entry = Entry;
441   Ehdr.e_phoff = sizeof(Elf_Ehdr);
442   Ehdr.e_shoff = SHOffset;
443   Ehdr.e_flags = Flags;
444   Ehdr.e_ehsize = sizeof(Elf_Ehdr);
445   Ehdr.e_phentsize = sizeof(Elf_Phdr);
446   Ehdr.e_phnum = Segments.size();
447   Ehdr.e_shentsize = sizeof(Elf_Shdr);
448   Ehdr.e_shnum = Sections.size() + 1;
449   Ehdr.e_shstrndx = SectionNames->Index;
450 }
451
452 template <class ELFT>
453 void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
454   for (auto &Phdr : Segments)
455     Phdr->template writeHeader<ELFT>(Out);
456 }
457
458 template <class ELFT>
459 void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
460   uint8_t *Buf = Out.getBufferStart() + SHOffset;
461   // This reference serves to write the dummy section header at the begining
462   // of the file.
463   Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
464   Shdr.sh_name = 0;
465   Shdr.sh_type = SHT_NULL;
466   Shdr.sh_flags = 0;
467   Shdr.sh_addr = 0;
468   Shdr.sh_offset = 0;
469   Shdr.sh_size = 0;
470   Shdr.sh_link = 0;
471   Shdr.sh_info = 0;
472   Shdr.sh_addralign = 0;
473   Shdr.sh_entsize = 0;
474
475   for (auto &Section : Sections)
476     Section->template writeHeader<ELFT>(Out);
477 }
478
479 template <class ELFT>
480 void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
481   for (auto &Section : Sections)
482     Section->writeSection(Out);
483 }
484
485 template <class ELFT> void ELFObject<ELFT>::sortSections() {
486   // Put all sections in offset order. Maintain the ordering as closely as
487   // possible while meeting that demand however.
488   auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
489     return A->OriginalOffset < B->OriginalOffset;
490   };
491   std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
492                    CompareSections);
493 }
494
495 template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
496   // The size of ELF + program headers will not change so it is ok to assume
497   // that the first offset of the first segment is a good place to start
498   // outputting sections. This covers both the standard case and the PT_PHDR
499   // case.
500   uint64_t Offset;
501   if (!this->Segments.empty()) {
502     Offset = this->Segments[0]->Offset;
503   } else {
504     Offset = sizeof(Elf_Ehdr);
505   }
506   // The only way a segment should move is if a section was between two
507   // segments and that section was removed. If that section isn't in a segment
508   // then it's acceptable, but not ideal, to simply move it to after the
509   // segments. So we can simply layout segments one after the other accounting
510   // for alignment.
511   for (auto &Segment : this->Segments) {
512     Offset = alignTo(Offset, Segment->Align);
513     Segment->Offset = Offset;
514     Offset += Segment->FileSize;
515   }
516   // Now the offset of every segment has been set we can assign the offsets
517   // of each section. For sections that are covered by a segment we should use
518   // the segment's original offset and the section's original offset to compute
519   // the offset from the start of the segment. Using the offset from the start
520   // of the segment we can assign a new offset to the section. For sections not
521   // covered by segments we can just bump Offset to the next valid location.
522   uint32_t Index = 1;
523   for (auto &Section : this->Sections) {
524     Section->Index = Index++;
525     if (Section->ParentSegment != nullptr) {
526       auto Segment = Section->ParentSegment;
527       Section->Offset =
528           Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
529     } else {
530       Offset = alignTo(Offset, Section->Offset);
531       Section->Offset = Offset;
532       if (Section->Type != SHT_NOBITS)
533         Offset += Section->Size;
534     }
535   }
536
537   Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
538   this->SHOffset = Offset;
539 }
540
541 template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
542   // We already have the section header offset so we can calculate the total
543   // size by just adding up the size of each section header.
544   return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
545          sizeof(Elf_Shdr);
546 }
547
548 template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
549   this->writeHeader(Out);
550   this->writeProgramHeaders(Out);
551   this->writeSectionData(Out);
552   this->writeSectionHeaders(Out);
553 }
554
555 template <class ELFT> void ELFObject<ELFT>::finalize() {
556   // Make sure we add the names of all the sections.
557   for (const auto &Section : this->Sections) {
558     this->SectionNames->addString(Section->Name);
559   }
560   // Make sure we add the names of all the symbols.
561   this->SymbolTable->addSymbolNames();
562
563   sortSections();
564   assignOffsets();
565
566   // Finalize SectionNames first so that we can assign name indexes.
567   this->SectionNames->finalize();
568   // Finally now that all offsets and indexes have been set we can finalize any
569   // remaining issues.
570   uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
571   for (auto &Section : this->Sections) {
572     Section->HeaderOffset = Offset;
573     Offset += sizeof(Elf_Shdr);
574     Section->NameIndex = this->SectionNames->findIndex(Section->Name);
575     Section->finalize();
576   }
577
578   for (auto &Segment : this->Segments)
579     Segment->finalize();
580 }
581
582 template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
583   return TotalSize;
584 }
585
586 template <class ELFT>
587 void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
588   for (auto &Segment : this->Segments) {
589     // GNU objcopy does not output segments that do not cover a section. Such
590     // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
591     if (Segment->Type == llvm::ELF::PT_LOAD &&
592         Segment->firstSection() != nullptr) {
593       Segment->writeSegment(Out);
594     }
595   }
596 }
597
598 template <class ELFT> void BinaryObject<ELFT>::finalize() {
599   for (auto &Segment : this->Segments)
600     Segment->finalize();
601
602   // Put all segments in offset order.
603   auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
604     return A->Offset < B->Offset;
605   };
606   std::sort(std::begin(this->Segments), std::end(this->Segments),
607             CompareSegments);
608
609   uint64_t Offset = 0;
610   for (auto &Segment : this->Segments) {
611     if (Segment->Type == llvm::ELF::PT_LOAD &&
612         Segment->firstSection() != nullptr) {
613       Offset = alignTo(Offset, Segment->Align);
614       Segment->Offset = Offset;
615       Offset += Segment->FileSize;
616     }
617   }
618   TotalSize = Offset;
619 }
620
621 template class Object<ELF64LE>;
622 template class Object<ELF64BE>;
623 template class Object<ELF32LE>;
624 template class Object<ELF32BE>;
625
626 template class ELFObject<ELF64LE>;
627 template class ELFObject<ELF64BE>;
628 template class ELFObject<ELF32LE>;
629 template class ELFObject<ELF32BE>;
630
631 template class BinaryObject<ELF64LE>;
632 template class BinaryObject<ELF64BE>;
633 template class BinaryObject<ELF32LE>;
634 template class BinaryObject<ELF32BE>;