]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-objcopy/Object.cpp
MFV r329718: 8520 7198 lzc_rollback_to should support rolling back to origin
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 <algorithm>
22 #include <cstddef>
23 #include <cstdint>
24 #include <iterator>
25 #include <utility>
26 #include <vector>
27
28 using namespace llvm;
29 using namespace object;
30 using namespace ELF;
31
32 template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
33   using Elf_Ehdr = typename ELFT::Ehdr;
34   using Elf_Phdr = typename ELFT::Phdr;
35
36   uint8_t *Buf = Out.getBufferStart();
37   Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
38   Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
39   Phdr.p_type = Type;
40   Phdr.p_flags = Flags;
41   Phdr.p_offset = Offset;
42   Phdr.p_vaddr = VAddr;
43   Phdr.p_paddr = PAddr;
44   Phdr.p_filesz = FileSize;
45   Phdr.p_memsz = MemSize;
46   Phdr.p_align = Align;
47 }
48
49 void Segment::writeSegment(FileOutputBuffer &Out) const {
50   uint8_t *Buf = Out.getBufferStart() + Offset;
51   // We want to maintain segments' interstitial data and contents exactly.
52   // This lets us just copy segments directly.
53   std::copy(std::begin(Contents), std::end(Contents), Buf);
54 }
55
56 void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
57 void SectionBase::initialize(SectionTableRef SecTable) {}
58 void SectionBase::finalize() {}
59
60 template <class ELFT>
61 void SectionBase::writeHeader(FileOutputBuffer &Out) const {
62   uint8_t *Buf = Out.getBufferStart();
63   Buf += HeaderOffset;
64   typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
65   Shdr.sh_name = NameIndex;
66   Shdr.sh_type = Type;
67   Shdr.sh_flags = Flags;
68   Shdr.sh_addr = Addr;
69   Shdr.sh_offset = Offset;
70   Shdr.sh_size = Size;
71   Shdr.sh_link = Link;
72   Shdr.sh_info = Info;
73   Shdr.sh_addralign = Align;
74   Shdr.sh_entsize = EntrySize;
75 }
76
77 void Section::writeSection(FileOutputBuffer &Out) const {
78   if (Type == SHT_NOBITS)
79     return;
80   uint8_t *Buf = Out.getBufferStart() + Offset;
81   std::copy(std::begin(Contents), std::end(Contents), Buf);
82 }
83
84 void OwnedDataSection::writeSection(FileOutputBuffer &Out) const {
85   uint8_t *Buf = Out.getBufferStart() + Offset;
86   std::copy(std::begin(Data), std::end(Data), Buf);
87 }
88
89 void StringTableSection::addString(StringRef Name) {
90   StrTabBuilder.add(Name);
91   Size = StrTabBuilder.getSize();
92 }
93
94 uint32_t StringTableSection::findIndex(StringRef Name) const {
95   return StrTabBuilder.getOffset(Name);
96 }
97
98 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
99
100 void StringTableSection::writeSection(FileOutputBuffer &Out) const {
101   StrTabBuilder.write(Out.getBufferStart() + Offset);
102 }
103
104 static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
105   switch (Index) {
106   case SHN_ABS:
107   case SHN_COMMON:
108     return true;
109   }
110   if (Machine == EM_HEXAGON) {
111     switch (Index) {
112     case SHN_HEXAGON_SCOMMON:
113     case SHN_HEXAGON_SCOMMON_2:
114     case SHN_HEXAGON_SCOMMON_4:
115     case SHN_HEXAGON_SCOMMON_8:
116       return true;
117     }
118   }
119   return false;
120 }
121
122 uint16_t Symbol::getShndx() const {
123   if (DefinedIn != nullptr) {
124     return DefinedIn->Index;
125   }
126   switch (ShndxType) {
127   // This means that we don't have a defined section but we do need to
128   // output a legitimate section index.
129   case SYMBOL_SIMPLE_INDEX:
130     return SHN_UNDEF;
131   case SYMBOL_ABS:
132   case SYMBOL_COMMON:
133   case SYMBOL_HEXAGON_SCOMMON:
134   case SYMBOL_HEXAGON_SCOMMON_2:
135   case SYMBOL_HEXAGON_SCOMMON_4:
136   case SYMBOL_HEXAGON_SCOMMON_8:
137     return static_cast<uint16_t>(ShndxType);
138   }
139   llvm_unreachable("Symbol with invalid ShndxType encountered");
140 }
141
142 void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
143                                    SectionBase *DefinedIn, uint64_t Value,
144                                    uint8_t Visibility, uint16_t Shndx,
145                                    uint64_t Sz) {
146   Symbol Sym;
147   Sym.Name = Name;
148   Sym.Binding = Bind;
149   Sym.Type = Type;
150   Sym.DefinedIn = DefinedIn;
151   if (DefinedIn == nullptr) {
152     if (Shndx >= SHN_LORESERVE)
153       Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
154     else
155       Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
156   }
157   Sym.Value = Value;
158   Sym.Visibility = Visibility;
159   Sym.Size = Sz;
160   Sym.Index = Symbols.size();
161   Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
162   Size += this->EntrySize;
163 }
164
165 void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
166   if (SymbolNames == Sec) {
167     error("String table " + SymbolNames->Name +
168           " cannot be removed because it is referenced by the symbol table " +
169           this->Name);
170   }
171   auto Iter =
172       std::remove_if(std::begin(Symbols), std::end(Symbols),
173                      [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
174   Size -= (std::end(Symbols) - Iter) * this->EntrySize;
175   Symbols.erase(Iter, std::end(Symbols));
176 }
177
178 void SymbolTableSection::initialize(SectionTableRef SecTable) {
179   Size = 0;
180   setStrTab(SecTable.getSectionOfType<StringTableSection>(
181       Link,
182       "Symbol table has link index of " + Twine(Link) +
183           " which is not a valid index",
184       "Symbol table has link index of " + Twine(Link) +
185           " which is not a string table"));
186 }
187
188 void SymbolTableSection::finalize() {
189   // Make sure SymbolNames is finalized before getting name indexes.
190   SymbolNames->finalize();
191
192   uint32_t MaxLocalIndex = 0;
193   for (auto &Sym : Symbols) {
194     Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
195     if (Sym->Binding == STB_LOCAL)
196       MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
197   }
198   // Now we need to set the Link and Info fields.
199   Link = SymbolNames->Index;
200   Info = MaxLocalIndex + 1;
201 }
202
203 void SymbolTableSection::addSymbolNames() {
204   // Add all of our strings to SymbolNames so that SymbolNames has the right
205   // size before layout is decided.
206   for (auto &Sym : Symbols)
207     SymbolNames->addString(Sym->Name);
208 }
209
210 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
211   if (Symbols.size() <= Index)
212     error("Invalid symbol index: " + Twine(Index));
213   return Symbols[Index].get();
214 }
215
216 template <class ELFT>
217 void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
218   uint8_t *Buf = Out.getBufferStart();
219   Buf += Offset;
220   typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
221   // Loop though symbols setting each entry of the symbol table.
222   for (auto &Symbol : Symbols) {
223     Sym->st_name = Symbol->NameIndex;
224     Sym->st_value = Symbol->Value;
225     Sym->st_size = Symbol->Size;
226     Sym->st_other = Symbol->Visibility;
227     Sym->setBinding(Symbol->Binding);
228     Sym->setType(Symbol->Type);
229     Sym->st_shndx = Symbol->getShndx();
230     ++Sym;
231   }
232 }
233
234 template <class SymTabType>
235 void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
236     const SectionBase *Sec) {
237   if (Symbols == Sec) {
238     error("Symbol table " + Symbols->Name + " cannot be removed because it is "
239                                             "referenced by the relocation "
240                                             "section " +
241           this->Name);
242   }
243 }
244
245 template <class SymTabType>
246 void RelocSectionWithSymtabBase<SymTabType>::initialize(
247     SectionTableRef SecTable) {
248   setSymTab(SecTable.getSectionOfType<SymTabType>(
249       Link,
250       "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
251       "Link field value " + Twine(Link) + " in section " + Name +
252           " is not a symbol table"));
253
254   if (Info != SHN_UNDEF)
255     setSection(SecTable.getSection(Info,
256                                    "Info field value " + Twine(Info) +
257                                        " in section " + Name + " is invalid"));
258   else
259     setSection(nullptr);
260 }
261
262 template <class SymTabType>
263 void RelocSectionWithSymtabBase<SymTabType>::finalize() {
264   this->Link = Symbols->Index;
265   if (SecToApplyRel != nullptr)
266     this->Info = SecToApplyRel->Index;
267 }
268
269 template <class ELFT>
270 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
271
272 template <class ELFT>
273 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
274   Rela.r_addend = Addend;
275 }
276
277 template <class ELFT>
278 template <class T>
279 void RelocationSection<ELFT>::writeRel(T *Buf) const {
280   for (const auto &Reloc : Relocations) {
281     Buf->r_offset = Reloc.Offset;
282     setAddend(*Buf, Reloc.Addend);
283     Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
284     ++Buf;
285   }
286 }
287
288 template <class ELFT>
289 void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
290   uint8_t *Buf = Out.getBufferStart() + Offset;
291   if (Type == SHT_REL)
292     writeRel(reinterpret_cast<Elf_Rel *>(Buf));
293   else
294     writeRel(reinterpret_cast<Elf_Rela *>(Buf));
295 }
296
297 void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
298   std::copy(std::begin(Contents), std::end(Contents),
299             Out.getBufferStart() + Offset);
300 }
301
302 void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
303   if (StrTab == Sec) {
304     error("String table " + StrTab->Name + " cannot be removed because it is "
305                                            "referenced by the section " +
306           this->Name);
307   }
308 }
309
310 bool SectionWithStrTab::classof(const SectionBase *S) {
311   return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
312 }
313
314 void SectionWithStrTab::initialize(SectionTableRef SecTable) {
315   auto StrTab = SecTable.getSection(Link,
316                                     "Link field value " + Twine(Link) +
317                                         " in section " + Name + " is invalid");
318   if (StrTab->Type != SHT_STRTAB) {
319     error("Link field value " + Twine(Link) + " in section " + Name +
320           " is not a string table");
321   }
322   setStrTab(StrTab);
323 }
324
325 void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
326
327 // Returns true IFF a section is wholly inside the range of a segment
328 static bool sectionWithinSegment(const SectionBase &Section,
329                                  const Segment &Segment) {
330   // If a section is empty it should be treated like it has a size of 1. This is
331   // to clarify the case when an empty section lies on a boundary between two
332   // segments and ensures that the section "belongs" to the second segment and
333   // not the first.
334   uint64_t SecSize = Section.Size ? Section.Size : 1;
335   return Segment.Offset <= Section.OriginalOffset &&
336          Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
337 }
338
339 // Returns true IFF a segment's original offset is inside of another segment's
340 // range.
341 static bool segmentOverlapsSegment(const Segment &Child,
342                                    const Segment &Parent) {
343
344   return Parent.OriginalOffset <= Child.OriginalOffset &&
345          Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
346 }
347
348 static bool compareSegments(const Segment *A, const Segment *B) {
349   // Any segment without a parent segment should come before a segment
350   // that has a parent segment.
351   if (A->OriginalOffset < B->OriginalOffset)
352     return true;
353   if (A->OriginalOffset > B->OriginalOffset)
354     return false;
355   return A->Index < B->Index;
356 }
357
358 template <class ELFT>
359 void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
360   uint32_t Index = 0;
361   for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
362     ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
363                            (size_t)Phdr.p_filesz};
364     Segments.emplace_back(llvm::make_unique<Segment>(Data));
365     Segment &Seg = *Segments.back();
366     Seg.Type = Phdr.p_type;
367     Seg.Flags = Phdr.p_flags;
368     Seg.OriginalOffset = Phdr.p_offset;
369     Seg.Offset = Phdr.p_offset;
370     Seg.VAddr = Phdr.p_vaddr;
371     Seg.PAddr = Phdr.p_paddr;
372     Seg.FileSize = Phdr.p_filesz;
373     Seg.MemSize = Phdr.p_memsz;
374     Seg.Align = Phdr.p_align;
375     Seg.Index = Index++;
376     for (auto &Section : Sections) {
377       if (sectionWithinSegment(*Section, Seg)) {
378         Seg.addSection(&*Section);
379         if (!Section->ParentSegment ||
380             Section->ParentSegment->Offset > Seg.Offset) {
381           Section->ParentSegment = &Seg;
382         }
383       }
384     }
385   }
386   // Now we do an O(n^2) loop through the segments in order to match up
387   // segments.
388   for (auto &Child : Segments) {
389     for (auto &Parent : Segments) {
390       // Every segment will overlap with itself but we don't want a segment to
391       // be it's own parent so we avoid that situation.
392       if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
393         // We want a canonical "most parental" segment but this requires
394         // inspecting the ParentSegment.
395         if (compareSegments(Parent.get(), Child.get()))
396           if (Child->ParentSegment == nullptr ||
397               compareSegments(Parent.get(), Child->ParentSegment)) {
398             Child->ParentSegment = Parent.get();
399           }
400       }
401     }
402   }
403 }
404
405 template <class ELFT>
406 void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
407                                    SymbolTableSection *SymTab,
408                                    SectionTableRef SecTable) {
409   const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
410   StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
411
412   for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
413     SectionBase *DefSection = nullptr;
414     StringRef Name = unwrapOrError(Sym.getName(StrTabData));
415
416     if (Sym.st_shndx >= SHN_LORESERVE) {
417       if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
418         error(
419             "Symbol '" + Name +
420             "' has unsupported value greater than or equal to SHN_LORESERVE: " +
421             Twine(Sym.st_shndx));
422       }
423     } else if (Sym.st_shndx != SHN_UNDEF) {
424       DefSection = SecTable.getSection(
425           Sym.st_shndx,
426           "Symbol '" + Name + "' is defined in invalid section with index " +
427               Twine(Sym.st_shndx));
428     }
429
430     SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
431                       Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
432   }
433 }
434
435 template <class ELFT>
436 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
437
438 template <class ELFT>
439 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
440   ToSet = Rela.r_addend;
441 }
442
443 template <class ELFT, class T>
444 void initRelocations(RelocationSection<ELFT> *Relocs,
445                      SymbolTableSection *SymbolTable, T RelRange) {
446   for (const auto &Rel : RelRange) {
447     Relocation ToAdd;
448     ToAdd.Offset = Rel.r_offset;
449     getAddend(ToAdd.Addend, Rel);
450     ToAdd.Type = Rel.getType(false);
451     ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
452     Relocs->addRelocation(ToAdd);
453   }
454 }
455
456 SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
457   if (Index == SHN_UNDEF || Index > Sections.size())
458     error(ErrMsg);
459   return Sections[Index - 1].get();
460 }
461
462 template <class T>
463 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
464                                      Twine TypeErrMsg) {
465   if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
466     return Sec;
467   error(TypeErrMsg);
468 }
469
470 template <class ELFT>
471 std::unique_ptr<SectionBase>
472 Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
473                           const Elf_Shdr &Shdr) {
474   ArrayRef<uint8_t> Data;
475   switch (Shdr.sh_type) {
476   case SHT_REL:
477   case SHT_RELA:
478     if (Shdr.sh_flags & SHF_ALLOC) {
479       Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
480       return llvm::make_unique<DynamicRelocationSection>(Data);
481     }
482     return llvm::make_unique<RelocationSection<ELFT>>();
483   case SHT_STRTAB:
484     // If a string table is allocated we don't want to mess with it. That would
485     // mean altering the memory image. There are no special link types or
486     // anything so we can just use a Section.
487     if (Shdr.sh_flags & SHF_ALLOC) {
488       Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
489       return llvm::make_unique<Section>(Data);
490     }
491     return llvm::make_unique<StringTableSection>();
492   case SHT_HASH:
493   case SHT_GNU_HASH:
494     // Hash tables should refer to SHT_DYNSYM which we're not going to change.
495     // Because of this we don't need to mess with the hash tables either.
496     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
497     return llvm::make_unique<Section>(Data);
498   case SHT_DYNSYM:
499     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
500     return llvm::make_unique<DynamicSymbolTableSection>(Data);
501   case SHT_DYNAMIC:
502     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
503     return llvm::make_unique<DynamicSection>(Data);
504   case SHT_SYMTAB: {
505     auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
506     SymbolTable = SymTab.get();
507     return std::move(SymTab);
508   }
509   case SHT_NOBITS:
510     return llvm::make_unique<Section>(Data);
511   default:
512     Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
513     return llvm::make_unique<Section>(Data);
514   }
515 }
516
517 template <class ELFT>
518 SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
519   uint32_t Index = 0;
520   for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
521     if (Index == 0) {
522       ++Index;
523       continue;
524     }
525     SecPtr Sec = makeSection(ElfFile, Shdr);
526     Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
527     Sec->Type = Shdr.sh_type;
528     Sec->Flags = Shdr.sh_flags;
529     Sec->Addr = Shdr.sh_addr;
530     Sec->Offset = Shdr.sh_offset;
531     Sec->OriginalOffset = Shdr.sh_offset;
532     Sec->Size = Shdr.sh_size;
533     Sec->Link = Shdr.sh_link;
534     Sec->Info = Shdr.sh_info;
535     Sec->Align = Shdr.sh_addralign;
536     Sec->EntrySize = Shdr.sh_entsize;
537     Sec->Index = Index++;
538     Sections.push_back(std::move(Sec));
539   }
540
541   SectionTableRef SecTable(Sections);
542
543   // Now that all of the sections have been added we can fill out some extra
544   // details about symbol tables. We need the symbol table filled out before
545   // any relocations.
546   if (SymbolTable) {
547     SymbolTable->initialize(SecTable);
548     initSymbolTable(ElfFile, SymbolTable, SecTable);
549   }
550
551   // Now that all sections and symbols have been added we can add
552   // relocations that reference symbols and set the link and info fields for
553   // relocation sections.
554   for (auto &Section : Sections) {
555     if (Section.get() == SymbolTable)
556       continue;
557     Section->initialize(SecTable);
558     if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
559       auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
560       if (RelSec->Type == SHT_REL)
561         initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
562       else
563         initRelocations(RelSec, SymbolTable,
564                         unwrapOrError(ElfFile.relas(Shdr)));
565     }
566   }
567
568   return SecTable;
569 }
570
571 template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
572   const auto &ElfFile = *Obj.getELFFile();
573   const auto &Ehdr = *ElfFile.getHeader();
574
575   std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
576   Type = Ehdr.e_type;
577   Machine = Ehdr.e_machine;
578   Version = Ehdr.e_version;
579   Entry = Ehdr.e_entry;
580   Flags = Ehdr.e_flags;
581
582   SectionTableRef SecTable = readSectionHeaders(ElfFile);
583   readProgramHeaders(ElfFile);
584
585   SectionNames = SecTable.getSectionOfType<StringTableSection>(
586       Ehdr.e_shstrndx,
587       "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
588           " is invalid",
589       "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
590           " is not a string table");
591 }
592
593 template <class ELFT>
594 void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
595   uint8_t *Buf = Out.getBufferStart();
596   Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
597   std::copy(Ident, Ident + 16, Ehdr.e_ident);
598   Ehdr.e_type = Type;
599   Ehdr.e_machine = Machine;
600   Ehdr.e_version = Version;
601   Ehdr.e_entry = Entry;
602   Ehdr.e_phoff = sizeof(Elf_Ehdr);
603   Ehdr.e_flags = Flags;
604   Ehdr.e_ehsize = sizeof(Elf_Ehdr);
605   Ehdr.e_phentsize = sizeof(Elf_Phdr);
606   Ehdr.e_phnum = Segments.size();
607   Ehdr.e_shentsize = sizeof(Elf_Shdr);
608   if (WriteSectionHeaders) {
609     Ehdr.e_shoff = SHOffset;
610     Ehdr.e_shnum = Sections.size() + 1;
611     Ehdr.e_shstrndx = SectionNames->Index;
612   } else {
613     Ehdr.e_shoff = 0;
614     Ehdr.e_shnum = 0;
615     Ehdr.e_shstrndx = 0;
616   }
617 }
618
619 template <class ELFT>
620 void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
621   for (auto &Phdr : Segments)
622     Phdr->template writeHeader<ELFT>(Out);
623 }
624
625 template <class ELFT>
626 void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
627   uint8_t *Buf = Out.getBufferStart() + SHOffset;
628   // This reference serves to write the dummy section header at the begining
629   // of the file. It is not used for anything else
630   Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
631   Shdr.sh_name = 0;
632   Shdr.sh_type = SHT_NULL;
633   Shdr.sh_flags = 0;
634   Shdr.sh_addr = 0;
635   Shdr.sh_offset = 0;
636   Shdr.sh_size = 0;
637   Shdr.sh_link = 0;
638   Shdr.sh_info = 0;
639   Shdr.sh_addralign = 0;
640   Shdr.sh_entsize = 0;
641
642   for (auto &Section : Sections)
643     Section->template writeHeader<ELFT>(Out);
644 }
645
646 template <class ELFT>
647 void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
648   for (auto &Section : Sections)
649     Section->writeSection(Out);
650 }
651
652 template <class ELFT>
653 void Object<ELFT>::removeSections(
654     std::function<bool(const SectionBase &)> ToRemove) {
655
656   auto Iter = std::stable_partition(
657       std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
658         if (ToRemove(*Sec))
659           return false;
660         if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
661           if (auto ToRelSec = RelSec->getSection())
662             return !ToRemove(*ToRelSec);
663         }
664         return true;
665       });
666   if (SymbolTable != nullptr && ToRemove(*SymbolTable))
667     SymbolTable = nullptr;
668   if (ToRemove(*SectionNames)) {
669     if (WriteSectionHeaders)
670       error("Cannot remove " + SectionNames->Name +
671             " because it is the section header string table.");
672     SectionNames = nullptr;
673   }
674   // Now make sure there are no remaining references to the sections that will
675   // be removed. Sometimes it is impossible to remove a reference so we emit
676   // an error here instead.
677   for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
678     for (auto &Segment : Segments)
679       Segment->removeSection(RemoveSec.get());
680     for (auto &KeepSec : make_range(std::begin(Sections), Iter))
681       KeepSec->removeSectionReferences(RemoveSec.get());
682   }
683   // Now finally get rid of them all togethor.
684   Sections.erase(Iter, std::end(Sections));
685 }
686
687 template <class ELFT>
688 void Object<ELFT>::addSection(StringRef SecName, ArrayRef<uint8_t> Data) {
689   auto Sec = llvm::make_unique<OwnedDataSection>(SecName, Data);
690   Sec->OriginalOffset = ~0ULL;
691   Sections.push_back(std::move(Sec));
692 }
693
694 template <class ELFT> void ELFObject<ELFT>::sortSections() {
695   // Put all sections in offset order. Maintain the ordering as closely as
696   // possible while meeting that demand however.
697   auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
698     return A->OriginalOffset < B->OriginalOffset;
699   };
700   std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
701                    CompareSections);
702 }
703
704 static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
705   // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
706   if (Align == 0)
707     Align = 1;
708   auto Diff =
709       static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
710   // We only want to add to Offset, however, so if Diff < 0 we can add Align and
711   // (Offset + Diff) & -Align == Addr & -Align will still hold.
712   if (Diff < 0)
713     Diff += Align;
714   return Offset + Diff;
715 }
716
717 // Orders segments such that if x = y->ParentSegment then y comes before x.
718 static void OrderSegments(std::vector<Segment *> &Segments) {
719   std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
720 }
721
722 // This function finds a consistent layout for a list of segments starting from
723 // an Offset. It assumes that Segments have been sorted by OrderSegments and
724 // returns an Offset one past the end of the last segment.
725 static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
726                                uint64_t Offset) {
727   assert(std::is_sorted(std::begin(Segments), std::end(Segments),
728                         compareSegments));
729   // The only way a segment should move is if a section was between two
730   // segments and that section was removed. If that section isn't in a segment
731   // then it's acceptable, but not ideal, to simply move it to after the
732   // segments. So we can simply layout segments one after the other accounting
733   // for alignment.
734   for (auto &Segment : Segments) {
735     // We assume that segments have been ordered by OriginalOffset and Index
736     // such that a parent segment will always come before a child segment in
737     // OrderedSegments. This means that the Offset of the ParentSegment should
738     // already be set and we can set our offset relative to it.
739     if (Segment->ParentSegment != nullptr) {
740       auto Parent = Segment->ParentSegment;
741       Segment->Offset =
742           Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
743     } else {
744       Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
745       Segment->Offset = Offset;
746     }
747     Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
748   }
749   return Offset;
750 }
751
752 // This function finds a consistent layout for a list of sections. It assumes
753 // that the ->ParentSegment of each section has already been laid out. The
754 // supplied starting Offset is used for the starting offset of any section that
755 // does not have a ParentSegment. It returns either the offset given if all
756 // sections had a ParentSegment or an offset one past the last section if there
757 // was a section that didn't have a ParentSegment.
758 template <class SecPtr>
759 static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
760   // Now the offset of every segment has been set we can assign the offsets
761   // of each section. For sections that are covered by a segment we should use
762   // the segment's original offset and the section's original offset to compute
763   // the offset from the start of the segment. Using the offset from the start
764   // of the segment we can assign a new offset to the section. For sections not
765   // covered by segments we can just bump Offset to the next valid location.
766   uint32_t Index = 1;
767   for (auto &Section : Sections) {
768     Section->Index = Index++;
769     if (Section->ParentSegment != nullptr) {
770       auto Segment = Section->ParentSegment;
771       Section->Offset =
772           Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
773     } else {
774       Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
775       Section->Offset = Offset;
776       if (Section->Type != SHT_NOBITS)
777         Offset += Section->Size;
778     }
779   }
780   return Offset;
781 }
782
783 template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
784   // We need a temporary list of segments that has a special order to it
785   // so that we know that anytime ->ParentSegment is set that segment has
786   // already had its offset properly set.
787   std::vector<Segment *> OrderedSegments;
788   for (auto &Segment : this->Segments)
789     OrderedSegments.push_back(Segment.get());
790   OrderSegments(OrderedSegments);
791   // The size of ELF + program headers will not change so it is ok to assume
792   // that the first offset of the first segment is a good place to start
793   // outputting sections. This covers both the standard case and the PT_PHDR
794   // case.
795   uint64_t Offset;
796   if (!OrderedSegments.empty()) {
797     Offset = OrderedSegments[0]->Offset;
798   } else {
799     Offset = sizeof(Elf_Ehdr);
800   }
801   Offset = LayoutSegments(OrderedSegments, Offset);
802   Offset = LayoutSections(this->Sections, Offset);
803   // If we need to write the section header table out then we need to align the
804   // Offset so that SHOffset is valid.
805   if (this->WriteSectionHeaders)
806     Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
807   this->SHOffset = Offset;
808 }
809
810 template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
811   // We already have the section header offset so we can calculate the total
812   // size by just adding up the size of each section header.
813   auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
814   return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
815          NullSectionSize;
816 }
817
818 template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
819   this->writeHeader(Out);
820   this->writeProgramHeaders(Out);
821   this->writeSectionData(Out);
822   if (this->WriteSectionHeaders)
823     this->writeSectionHeaders(Out);
824 }
825
826 template <class ELFT> void ELFObject<ELFT>::finalize() {
827   // Make sure we add the names of all the sections.
828   if (this->SectionNames != nullptr)
829     for (const auto &Section : this->Sections) {
830       this->SectionNames->addString(Section->Name);
831     }
832   // Make sure we add the names of all the symbols.
833   if (this->SymbolTable != nullptr)
834     this->SymbolTable->addSymbolNames();
835
836   sortSections();
837   assignOffsets();
838
839   // Finalize SectionNames first so that we can assign name indexes.
840   if (this->SectionNames != nullptr)
841     this->SectionNames->finalize();
842   // Finally now that all offsets and indexes have been set we can finalize any
843   // remaining issues.
844   uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
845   for (auto &Section : this->Sections) {
846     Section->HeaderOffset = Offset;
847     Offset += sizeof(Elf_Shdr);
848     if (this->WriteSectionHeaders)
849       Section->NameIndex = this->SectionNames->findIndex(Section->Name);
850     Section->finalize();
851   }
852 }
853
854 template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
855   return TotalSize;
856 }
857
858 template <class ELFT>
859 void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
860   for (auto &Section : this->Sections) {
861     if ((Section->Flags & SHF_ALLOC) == 0)
862       continue;
863     Section->writeSection(Out);
864   }
865 }
866
867 template <class ELFT> void BinaryObject<ELFT>::finalize() {
868   // TODO: Create a filter range to construct OrderedSegments from so that this
869   // code can be deduped with assignOffsets above. This should also solve the
870   // todo below for LayoutSections.
871   // We need a temporary list of segments that has a special order to it
872   // so that we know that anytime ->ParentSegment is set that segment has
873   // already had it's offset properly set. We only want to consider the segments
874   // that will affect layout of allocated sections so we only add those.
875   std::vector<Segment *> OrderedSegments;
876   for (auto &Section : this->Sections) {
877     if ((Section->Flags & SHF_ALLOC) != 0 &&
878         Section->ParentSegment != nullptr) {
879       OrderedSegments.push_back(Section->ParentSegment);
880     }
881   }
882   OrderSegments(OrderedSegments);
883   // Because we add a ParentSegment for each section we might have duplicate
884   // segments in OrderedSegments. If there were duplicates then LayoutSegments
885   // would do very strange things.
886   auto End =
887       std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
888   OrderedSegments.erase(End, std::end(OrderedSegments));
889
890   // Modify the first segment so that there is no gap at the start. This allows
891   // our layout algorithm to proceed as expected while not out writing out the
892   // gap at the start.
893   if (!OrderedSegments.empty()) {
894     auto Seg = OrderedSegments[0];
895     auto Sec = Seg->firstSection();
896     auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
897     Seg->OriginalOffset += Diff;
898     // The size needs to be shrunk as well
899     Seg->FileSize -= Diff;
900     Seg->MemSize -= Diff;
901     // The VAddr needs to be adjusted so that the alignment is correct as well
902     Seg->VAddr += Diff;
903     Seg->PAddr = Seg->VAddr;
904     // We don't want this to be shifted by alignment so we need to set the
905     // alignment to zero.
906     Seg->Align = 0;
907   }
908
909   uint64_t Offset = LayoutSegments(OrderedSegments, 0);
910
911   // TODO: generalize LayoutSections to take a range. Pass a special range
912   // constructed from an iterator that skips values for which a predicate does
913   // not hold. Then pass such a range to LayoutSections instead of constructing
914   // AllocatedSections here.
915   std::vector<SectionBase *> AllocatedSections;
916   for (auto &Section : this->Sections) {
917     if ((Section->Flags & SHF_ALLOC) == 0)
918       continue;
919     AllocatedSections.push_back(Section.get());
920   }
921   LayoutSections(AllocatedSections, Offset);
922
923   // Now that every section has been laid out we just need to compute the total
924   // file size. This might not be the same as the offset returned by
925   // LayoutSections, because we want to truncate the last segment to the end of
926   // its last section, to match GNU objcopy's behaviour.
927   TotalSize = 0;
928   for (const auto &Section : AllocatedSections) {
929     if (Section->Type != SHT_NOBITS)
930       TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
931   }
932 }
933
934 namespace llvm {
935
936 template class Object<ELF64LE>;
937 template class Object<ELF64BE>;
938 template class Object<ELF32LE>;
939 template class Object<ELF32BE>;
940
941 template class ELFObject<ELF64LE>;
942 template class ELFObject<ELF64BE>;
943 template class ELFObject<ELF32LE>;
944 template class ELFObject<ELF32BE>;
945
946 template class BinaryObject<ELF64LE>;
947 template class BinaryObject<ELF64BE>;
948 template class BinaryObject<ELF32LE>;
949 template class BinaryObject<ELF32BE>;
950
951 } // end namespace llvm