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