blob: bd5bcd7fc1889f77a8b9c93b1b582ac6cccd353a [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "Object.h"
11#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000012#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>
Petr Hosek05a04cb2017-08-01 00:33:58 +000027
28using namespace llvm;
29using namespace object;
30using namespace ELF;
31
32template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000033 using Elf_Ehdr = typename ELFT::Ehdr;
34 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000035
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
Petr Hosekc4df10e2017-08-04 21:09:26 +000049void 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
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000056void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000057void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000058void SectionBase::finalize() {}
59
60template <class ELFT>
61void 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
77void 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
84void StringTableSection::addString(StringRef Name) {
85 StrTabBuilder.add(Name);
86 Size = StrTabBuilder.getSize();
87}
88
89uint32_t StringTableSection::findIndex(StringRef Name) const {
90 return StrTabBuilder.getOffset(Name);
91}
92
93void StringTableSection::finalize() { StrTabBuilder.finalize(); }
94
95void StringTableSection::writeSection(FileOutputBuffer &Out) const {
96 StrTabBuilder.write(Out.getBufferStart() + Offset);
97}
98
Petr Hosekc1135772017-09-13 03:04:50 +000099static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000100 switch (Index) {
101 case SHN_ABS:
102 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000103 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000104 }
Petr Hosekc1135772017-09-13 03:04:50 +0000105 if (Machine == EM_HEXAGON) {
106 switch (Index) {
107 case SHN_HEXAGON_SCOMMON:
108 case SHN_HEXAGON_SCOMMON_2:
109 case SHN_HEXAGON_SCOMMON_4:
110 case SHN_HEXAGON_SCOMMON_8:
111 return true;
112 }
113 }
114 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000115}
116
117uint16_t Symbol::getShndx() const {
118 if (DefinedIn != nullptr) {
119 return DefinedIn->Index;
120 }
121 switch (ShndxType) {
122 // This means that we don't have a defined section but we do need to
123 // output a legitimate section index.
124 case SYMBOL_SIMPLE_INDEX:
125 return SHN_UNDEF;
126 case SYMBOL_ABS:
127 case SYMBOL_COMMON:
128 case SYMBOL_HEXAGON_SCOMMON:
129 case SYMBOL_HEXAGON_SCOMMON_2:
130 case SYMBOL_HEXAGON_SCOMMON_4:
131 case SYMBOL_HEXAGON_SCOMMON_8:
132 return static_cast<uint16_t>(ShndxType);
133 }
134 llvm_unreachable("Symbol with invalid ShndxType encountered");
135}
136
Petr Hosek79cee9e2017-08-29 02:12:03 +0000137void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
138 SectionBase *DefinedIn, uint64_t Value,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000139 uint16_t Shndx, uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000140 Symbol Sym;
141 Sym.Name = Name;
142 Sym.Binding = Bind;
143 Sym.Type = Type;
144 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000145 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000146 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000147 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
148 else
149 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
150 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000151 Sym.Value = Value;
152 Sym.Size = Sz;
153 Sym.Index = Symbols.size();
154 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
155 Size += this->EntrySize;
156}
157
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000158void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
159 if (SymbolNames == Sec) {
160 error("String table " + SymbolNames->Name +
161 " cannot be removed because it is referenced by the symbol table " +
162 this->Name);
163 }
164 auto Iter =
165 std::remove_if(std::begin(Symbols), std::end(Symbols),
166 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
167 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
168 Symbols.erase(Iter, std::end(Symbols));
169}
170
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000171void SymbolTableSection::initialize(SectionTableRef SecTable) {
172 Size = 0;
173 setStrTab(SecTable.getSectionOfType<StringTableSection>(
174 Link,
175 "Symbol table has link index of " + Twine(Link) +
176 " which is not a valid index",
177 "Symbol table has link index of " + Twine(Link) +
178 " which is not a string table"));
179}
180
Petr Hosek79cee9e2017-08-29 02:12:03 +0000181void SymbolTableSection::finalize() {
182 // Make sure SymbolNames is finalized before getting name indexes.
183 SymbolNames->finalize();
184
185 uint32_t MaxLocalIndex = 0;
186 for (auto &Sym : Symbols) {
187 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
188 if (Sym->Binding == STB_LOCAL)
189 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
190 }
191 // Now we need to set the Link and Info fields.
192 Link = SymbolNames->Index;
193 Info = MaxLocalIndex + 1;
194}
195
196void SymbolTableSection::addSymbolNames() {
197 // Add all of our strings to SymbolNames so that SymbolNames has the right
198 // size before layout is decided.
199 for (auto &Sym : Symbols)
200 SymbolNames->addString(Sym->Name);
201}
202
203const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
204 if (Symbols.size() <= Index)
205 error("Invalid symbol index: " + Twine(Index));
206 return Symbols[Index].get();
207}
208
209template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000210void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000211 uint8_t *Buf = Out.getBufferStart();
212 Buf += Offset;
213 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
214 // Loop though symbols setting each entry of the symbol table.
215 for (auto &Symbol : Symbols) {
216 Sym->st_name = Symbol->NameIndex;
217 Sym->st_value = Symbol->Value;
218 Sym->st_size = Symbol->Size;
219 Sym->setBinding(Symbol->Binding);
220 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000221 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000222 ++Sym;
223 }
224}
225
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000226template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000227void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
228 const SectionBase *Sec) {
229 if (Symbols == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000230 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
231 "referenced by the relocation "
232 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000233 this->Name);
234 }
235}
236
237template <class SymTabType>
238void RelocSectionWithSymtabBase<SymTabType>::initialize(
239 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000240 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000241 Link,
242 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
243 "Link field value " + Twine(Link) + " in section " + Name +
244 " is not a symbol table"));
245
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000246 if (Info != SHN_UNDEF)
Jake Ehrlich777fb002017-12-15 20:17:55 +0000247 setSection(SecTable.getSection(Info,
248 "Info field value " + Twine(Info) +
249 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000250 else
251 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000252}
253
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000254template <class SymTabType>
255void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000256 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000257 if (SecToApplyRel != nullptr)
258 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000259}
260
261template <class ELFT>
262void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
263
264template <class ELFT>
265void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
266 Rela.r_addend = Addend;
267}
268
269template <class ELFT>
270template <class T>
271void RelocationSection<ELFT>::writeRel(T *Buf) const {
272 for (const auto &Reloc : Relocations) {
273 Buf->r_offset = Reloc.Offset;
274 setAddend(*Buf, Reloc.Addend);
275 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
276 ++Buf;
277 }
278}
279
280template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000281void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000282 uint8_t *Buf = Out.getBufferStart() + Offset;
283 if (Type == SHT_REL)
284 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
285 else
286 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
287}
288
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000289void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000290 std::copy(std::begin(Contents), std::end(Contents),
291 Out.getBufferStart() + Offset);
292}
293
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000294void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
295 if (StrTab == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000296 error("String table " + StrTab->Name + " cannot be removed because it is "
297 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000298 this->Name);
299 }
300}
301
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000302bool SectionWithStrTab::classof(const SectionBase *S) {
303 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
304}
305
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000306void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000307 auto StrTab = SecTable.getSection(Link,
308 "Link field value " + Twine(Link) +
309 " in section " + Name + " is invalid");
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000310 if (StrTab->Type != SHT_STRTAB) {
311 error("Link field value " + Twine(Link) + " in section " + Name +
312 " is not a string table");
313 }
314 setStrTab(StrTab);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000315}
316
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000317void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
318
Petr Hosek05a04cb2017-08-01 00:33:58 +0000319// Returns true IFF a section is wholly inside the range of a segment
320static bool sectionWithinSegment(const SectionBase &Section,
321 const Segment &Segment) {
322 // If a section is empty it should be treated like it has a size of 1. This is
323 // to clarify the case when an empty section lies on a boundary between two
324 // segments and ensures that the section "belongs" to the second segment and
325 // not the first.
326 uint64_t SecSize = Section.Size ? Section.Size : 1;
327 return Segment.Offset <= Section.OriginalOffset &&
328 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
329}
330
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000331// Returns true IFF a segment's original offset is inside of another segment's
332// range.
333static bool segmentOverlapsSegment(const Segment &Child,
334 const Segment &Parent) {
335
336 return Parent.OriginalOffset <= Child.OriginalOffset &&
337 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
338}
339
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000340static bool compareSegments(const Segment *A, const Segment *B) {
341 // Any segment without a parent segment should come before a segment
342 // that has a parent segment.
343 if (A->OriginalOffset < B->OriginalOffset)
344 return true;
345 if (A->OriginalOffset > B->OriginalOffset)
346 return false;
347 return A->Index < B->Index;
348}
349
Petr Hosek05a04cb2017-08-01 00:33:58 +0000350template <class ELFT>
351void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
352 uint32_t Index = 0;
353 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000354 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
355 (size_t)Phdr.p_filesz};
356 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000357 Segment &Seg = *Segments.back();
358 Seg.Type = Phdr.p_type;
359 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000360 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000361 Seg.Offset = Phdr.p_offset;
362 Seg.VAddr = Phdr.p_vaddr;
363 Seg.PAddr = Phdr.p_paddr;
364 Seg.FileSize = Phdr.p_filesz;
365 Seg.MemSize = Phdr.p_memsz;
366 Seg.Align = Phdr.p_align;
367 Seg.Index = Index++;
368 for (auto &Section : Sections) {
369 if (sectionWithinSegment(*Section, Seg)) {
370 Seg.addSection(&*Section);
371 if (!Section->ParentSegment ||
372 Section->ParentSegment->Offset > Seg.Offset) {
373 Section->ParentSegment = &Seg;
374 }
375 }
376 }
377 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000378 // Now we do an O(n^2) loop through the segments in order to match up
379 // segments.
380 for (auto &Child : Segments) {
381 for (auto &Parent : Segments) {
382 // Every segment will overlap with itself but we don't want a segment to
383 // be it's own parent so we avoid that situation.
384 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
385 // We want a canonical "most parental" segment but this requires
386 // inspecting the ParentSegment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000387 if (compareSegments(Parent.get(), Child.get()))
388 if (Child->ParentSegment == nullptr ||
389 compareSegments(Parent.get(), Child->ParentSegment)) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000390 Child->ParentSegment = Parent.get();
391 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000392 }
393 }
394 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000395}
396
397template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000398void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000399 SymbolTableSection *SymTab,
400 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000401 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
402 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
403
404 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
405 SectionBase *DefSection = nullptr;
406 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000407
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000408 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000409 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000410 error(
411 "Symbol '" + Name +
412 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
413 Twine(Sym.st_shndx));
414 }
415 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000416 DefSection = SecTable.getSection(
Jake Ehrlich777fb002017-12-15 20:17:55 +0000417 Sym.st_shndx,
418 "Symbol '" + Name + "' is defined in invalid section with index " +
419 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000420 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000421
Petr Hosek79cee9e2017-08-29 02:12:03 +0000422 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000423 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000424 }
425}
426
427template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000428static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
429
430template <class ELFT>
431static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
432 ToSet = Rela.r_addend;
433}
434
435template <class ELFT, class T>
436void initRelocations(RelocationSection<ELFT> *Relocs,
437 SymbolTableSection *SymbolTable, T RelRange) {
438 for (const auto &Rel : RelRange) {
439 Relocation ToAdd;
440 ToAdd.Offset = Rel.r_offset;
441 getAddend(ToAdd.Addend, Rel);
442 ToAdd.Type = Rel.getType(false);
443 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
444 Relocs->addRelocation(ToAdd);
445 }
446}
447
Zachary Turner41a9ee92017-10-11 23:54:34 +0000448SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000449 if (Index == SHN_UNDEF || Index > Sections.size())
450 error(ErrMsg);
451 return Sections[Index - 1].get();
452}
453
454template <class T>
Zachary Turner41a9ee92017-10-11 23:54:34 +0000455T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
456 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000457 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000458 return Sec;
459 error(TypeErrMsg);
460}
461
Petr Hosekd7df9b22017-09-06 23:41:02 +0000462template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000463std::unique_ptr<SectionBase>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000464Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
Petr Hosek05a04cb2017-08-01 00:33:58 +0000465 const Elf_Shdr &Shdr) {
466 ArrayRef<uint8_t> Data;
467 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000468 case SHT_REL:
469 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000470 if (Shdr.sh_flags & SHF_ALLOC) {
471 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
472 return llvm::make_unique<DynamicRelocationSection>(Data);
473 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000474 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000475 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000476 // If a string table is allocated we don't want to mess with it. That would
477 // mean altering the memory image. There are no special link types or
478 // anything so we can just use a Section.
479 if (Shdr.sh_flags & SHF_ALLOC) {
480 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
481 return llvm::make_unique<Section>(Data);
482 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000483 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000484 case SHT_HASH:
485 case SHT_GNU_HASH:
486 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
487 // Because of this we don't need to mess with the hash tables either.
488 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
489 return llvm::make_unique<Section>(Data);
490 case SHT_DYNSYM:
491 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
492 return llvm::make_unique<DynamicSymbolTableSection>(Data);
493 case SHT_DYNAMIC:
494 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
495 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000496 case SHT_SYMTAB: {
497 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
498 SymbolTable = SymTab.get();
499 return std::move(SymTab);
500 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000501 case SHT_NOBITS:
502 return llvm::make_unique<Section>(Data);
503 default:
504 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
505 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000506 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000507}
508
509template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000510SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000511 uint32_t Index = 0;
512 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
513 if (Index == 0) {
514 ++Index;
515 continue;
516 }
517 SecPtr Sec = makeSection(ElfFile, Shdr);
518 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
519 Sec->Type = Shdr.sh_type;
520 Sec->Flags = Shdr.sh_flags;
521 Sec->Addr = Shdr.sh_addr;
522 Sec->Offset = Shdr.sh_offset;
523 Sec->OriginalOffset = Shdr.sh_offset;
524 Sec->Size = Shdr.sh_size;
525 Sec->Link = Shdr.sh_link;
526 Sec->Info = Shdr.sh_info;
527 Sec->Align = Shdr.sh_addralign;
528 Sec->EntrySize = Shdr.sh_entsize;
529 Sec->Index = Index++;
530 Sections.push_back(std::move(Sec));
531 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000532
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000533 SectionTableRef SecTable(Sections);
534
Petr Hosek79cee9e2017-08-29 02:12:03 +0000535 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000536 // details about symbol tables. We need the symbol table filled out before
537 // any relocations.
538 if (SymbolTable) {
539 SymbolTable->initialize(SecTable);
540 initSymbolTable(ElfFile, SymbolTable, SecTable);
541 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000542
543 // Now that all sections and symbols have been added we can add
544 // relocations that reference symbols and set the link and info fields for
545 // relocation sections.
546 for (auto &Section : Sections) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000547 if (Section.get() == SymbolTable)
548 continue;
549 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000550 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000551 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
552 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000553 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000554 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000555 initRelocations(RelSec, SymbolTable,
556 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000557 }
558 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000559
560 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000561}
562
Petr Hosek05a04cb2017-08-01 00:33:58 +0000563template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
564 const auto &ElfFile = *Obj.getELFFile();
565 const auto &Ehdr = *ElfFile.getHeader();
566
567 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
568 Type = Ehdr.e_type;
569 Machine = Ehdr.e_machine;
570 Version = Ehdr.e_version;
571 Entry = Ehdr.e_entry;
572 Flags = Ehdr.e_flags;
573
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000574 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000575 readProgramHeaders(ElfFile);
576
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000577 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000578 Ehdr.e_shstrndx,
579 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
580 " is invalid",
581 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
582 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000583}
584
Petr Hosek05a04cb2017-08-01 00:33:58 +0000585template <class ELFT>
586void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
587 uint8_t *Buf = Out.getBufferStart();
588 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
589 std::copy(Ident, Ident + 16, Ehdr.e_ident);
590 Ehdr.e_type = Type;
591 Ehdr.e_machine = Machine;
592 Ehdr.e_version = Version;
593 Ehdr.e_entry = Entry;
594 Ehdr.e_phoff = sizeof(Elf_Ehdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000595 Ehdr.e_flags = Flags;
596 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
597 Ehdr.e_phentsize = sizeof(Elf_Phdr);
598 Ehdr.e_phnum = Segments.size();
599 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000600 if (WriteSectionHeaders) {
601 Ehdr.e_shoff = SHOffset;
602 Ehdr.e_shnum = Sections.size() + 1;
603 Ehdr.e_shstrndx = SectionNames->Index;
604 } else {
605 Ehdr.e_shoff = 0;
606 Ehdr.e_shnum = 0;
607 Ehdr.e_shstrndx = 0;
608 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000609}
610
611template <class ELFT>
612void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
613 for (auto &Phdr : Segments)
614 Phdr->template writeHeader<ELFT>(Out);
615}
616
617template <class ELFT>
618void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
619 uint8_t *Buf = Out.getBufferStart() + SHOffset;
620 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000621 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000622 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
623 Shdr.sh_name = 0;
624 Shdr.sh_type = SHT_NULL;
625 Shdr.sh_flags = 0;
626 Shdr.sh_addr = 0;
627 Shdr.sh_offset = 0;
628 Shdr.sh_size = 0;
629 Shdr.sh_link = 0;
630 Shdr.sh_info = 0;
631 Shdr.sh_addralign = 0;
632 Shdr.sh_entsize = 0;
633
634 for (auto &Section : Sections)
635 Section->template writeHeader<ELFT>(Out);
636}
637
638template <class ELFT>
639void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
640 for (auto &Section : Sections)
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000641 Section->writeSection(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000642}
643
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000644template <class ELFT>
645void Object<ELFT>::removeSections(
646 std::function<bool(const SectionBase &)> ToRemove) {
647
648 auto Iter = std::stable_partition(
649 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
650 if (ToRemove(*Sec))
651 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000652 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
653 if (auto ToRelSec = RelSec->getSection())
654 return !ToRemove(*ToRelSec);
655 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000656 return true;
657 });
658 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
659 SymbolTable = nullptr;
660 if (ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000661 if (WriteSectionHeaders)
662 error("Cannot remove " + SectionNames->Name +
663 " because it is the section header string table.");
664 SectionNames = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000665 }
666 // Now make sure there are no remaining references to the sections that will
667 // be removed. Sometimes it is impossible to remove a reference so we emit
668 // an error here instead.
669 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
670 for (auto &Segment : Segments)
671 Segment->removeSection(RemoveSec.get());
672 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
673 KeepSec->removeSectionReferences(RemoveSec.get());
674 }
675 // Now finally get rid of them all togethor.
676 Sections.erase(Iter, std::end(Sections));
677}
678
Petr Hosekc4df10e2017-08-04 21:09:26 +0000679template <class ELFT> void ELFObject<ELFT>::sortSections() {
680 // Put all sections in offset order. Maintain the ordering as closely as
681 // possible while meeting that demand however.
682 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
683 return A->OriginalOffset < B->OriginalOffset;
684 };
685 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
686 CompareSections);
687}
688
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000689static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
690 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
691 if (Align == 0)
692 Align = 1;
693 auto Diff =
694 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
695 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
696 // (Offset + Diff) & -Align == Addr & -Align will still hold.
697 if (Diff < 0)
698 Diff += Align;
699 return Offset + Diff;
700}
701
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000702// Orders segments such that if x = y->ParentSegment then y comes before x.
703static void OrderSegments(std::vector<Segment *> &Segments) {
704 std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
705}
706
707// This function finds a consistent layout for a list of segments starting from
708// an Offset. It assumes that Segments have been sorted by OrderSegments and
709// returns an Offset one past the end of the last segment.
710static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
711 uint64_t Offset) {
712 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
713 compareSegments));
Petr Hosek3f383832017-08-26 01:32:20 +0000714 // The only way a segment should move is if a section was between two
715 // segments and that section was removed. If that section isn't in a segment
716 // then it's acceptable, but not ideal, to simply move it to after the
717 // segments. So we can simply layout segments one after the other accounting
718 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000719 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000720 // We assume that segments have been ordered by OriginalOffset and Index
721 // such that a parent segment will always come before a child segment in
722 // OrderedSegments. This means that the Offset of the ParentSegment should
723 // already be set and we can set our offset relative to it.
724 if (Segment->ParentSegment != nullptr) {
725 auto Parent = Segment->ParentSegment;
726 Segment->Offset =
727 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
728 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000729 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000730 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000731 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000732 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000733 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000734 return Offset;
735}
736
737// This function finds a consistent layout for a list of sections. It assumes
738// that the ->ParentSegment of each section has already been laid out. The
739// supplied starting Offset is used for the starting offset of any section that
740// does not have a ParentSegment. It returns either the offset given if all
741// sections had a ParentSegment or an offset one past the last section if there
742// was a section that didn't have a ParentSegment.
743template <class SecPtr>
744static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000745 // Now the offset of every segment has been set we can assign the offsets
746 // of each section. For sections that are covered by a segment we should use
747 // the segment's original offset and the section's original offset to compute
748 // the offset from the start of the segment. Using the offset from the start
749 // of the segment we can assign a new offset to the section. For sections not
750 // covered by segments we can just bump Offset to the next valid location.
751 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000752 for (auto &Section : Sections) {
Petr Hosek3f383832017-08-26 01:32:20 +0000753 Section->Index = Index++;
754 if (Section->ParentSegment != nullptr) {
755 auto Segment = Section->ParentSegment;
756 Section->Offset =
757 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
758 } else {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000759 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000760 Section->Offset = Offset;
761 if (Section->Type != SHT_NOBITS)
762 Offset += Section->Size;
763 }
764 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000765 return Offset;
766}
Petr Hosek3f383832017-08-26 01:32:20 +0000767
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000768template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
769 // We need a temporary list of segments that has a special order to it
770 // so that we know that anytime ->ParentSegment is set that segment has
771 // already had its offset properly set.
772 std::vector<Segment *> OrderedSegments;
773 for (auto &Segment : this->Segments)
774 OrderedSegments.push_back(Segment.get());
775 OrderSegments(OrderedSegments);
776 // The size of ELF + program headers will not change so it is ok to assume
777 // that the first offset of the first segment is a good place to start
778 // outputting sections. This covers both the standard case and the PT_PHDR
779 // case.
780 uint64_t Offset;
781 if (!OrderedSegments.empty()) {
782 Offset = OrderedSegments[0]->Offset;
783 } else {
784 Offset = sizeof(Elf_Ehdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000785 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000786 Offset = LayoutSegments(OrderedSegments, Offset);
787 Offset = LayoutSections(this->Sections, Offset);
788 // If we need to write the section header table out then we need to align the
789 // Offset so that SHOffset is valid.
790 if (this->WriteSectionHeaders)
791 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Petr Hosekc4df10e2017-08-04 21:09:26 +0000792 this->SHOffset = Offset;
793}
794
795template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
796 // We already have the section header offset so we can calculate the total
797 // size by just adding up the size of each section header.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000798 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000799 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000800 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000801}
802
803template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
804 this->writeHeader(Out);
805 this->writeProgramHeaders(Out);
806 this->writeSectionData(Out);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000807 if (this->WriteSectionHeaders)
808 this->writeSectionHeaders(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000809}
810
811template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000812 // Make sure we add the names of all the sections.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000813 if (this->SectionNames != nullptr)
814 for (const auto &Section : this->Sections) {
815 this->SectionNames->addString(Section->Name);
816 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000817 // Make sure we add the names of all the symbols.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000818 if (this->SymbolTable != nullptr)
819 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000820
821 sortSections();
822 assignOffsets();
823
824 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000825 if (this->SectionNames != nullptr)
826 this->SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000827 // Finally now that all offsets and indexes have been set we can finalize any
828 // remaining issues.
829 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
830 for (auto &Section : this->Sections) {
831 Section->HeaderOffset = Offset;
832 Offset += sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000833 if (this->WriteSectionHeaders)
834 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000835 Section->finalize();
836 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000837}
838
839template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
840 return TotalSize;
841}
842
843template <class ELFT>
844void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000845 for (auto &Section : this->Sections) {
846 if ((Section->Flags & SHF_ALLOC) == 0)
847 continue;
848 Section->writeSection(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000849 }
850}
851
852template <class ELFT> void BinaryObject<ELFT>::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000853 // TODO: Create a filter range to construct OrderedSegments from so that this
854 // code can be deduped with assignOffsets above. This should also solve the
855 // todo below for LayoutSections.
856 // We need a temporary list of segments that has a special order to it
857 // so that we know that anytime ->ParentSegment is set that segment has
858 // already had it's offset properly set. We only want to consider the segments
859 // that will affect layout of allocated sections so we only add those.
860 std::vector<Segment *> OrderedSegments;
861 for (auto &Section : this->Sections) {
862 if ((Section->Flags & SHF_ALLOC) != 0 &&
863 Section->ParentSegment != nullptr) {
864 OrderedSegments.push_back(Section->ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000865 }
866 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000867 OrderSegments(OrderedSegments);
868 // Because we add a ParentSegment for each section we might have duplicate
869 // segments in OrderedSegments. If there were duplicates then LayoutSegments
870 // would do very strange things.
871 auto End =
872 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
873 OrderedSegments.erase(End, std::end(OrderedSegments));
874
875 // Modify the first segment so that there is no gap at the start. This allows
876 // our layout algorithm to proceed as expected while not out writing out the
877 // gap at the start.
878 if (!OrderedSegments.empty()) {
879 auto Seg = OrderedSegments[0];
880 auto Sec = Seg->firstSection();
881 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
882 Seg->OriginalOffset += Diff;
883 // The size needs to be shrunk as well
884 Seg->FileSize -= Diff;
885 Seg->MemSize -= Diff;
886 // The VAddr needs to be adjusted so that the alignment is correct as well
887 Seg->VAddr += Diff;
888 Seg->PAddr = Seg->VAddr;
889 // We don't want this to be shifted by alignment so we need to set the
890 // alignment to zero.
891 Seg->Align = 0;
892 }
893
894 uint64_t Offset = LayoutSegments(OrderedSegments, 0);
895
896 // TODO: generalize LayoutSections to take a range. Pass a special range
897 // constructed from an iterator that skips values for which a predicate does
898 // not hold. Then pass such a range to LayoutSections instead of constructing
899 // AllocatedSections here.
900 std::vector<SectionBase *> AllocatedSections;
901 for (auto &Section : this->Sections) {
902 if ((Section->Flags & SHF_ALLOC) == 0)
903 continue;
904 AllocatedSections.push_back(Section.get());
905 }
906 LayoutSections(AllocatedSections, Offset);
907
908 // Now that every section has been laid out we just need to compute the total
909 // file size. This might not be the same as the offset returned by
910 // LayoutSections, because we want to truncate the last segment to the end of
911 // its last section, to match GNU objcopy's behaviour.
912 TotalSize = 0;
913 for (const auto &Section : AllocatedSections) {
914 if (Section->Type != SHT_NOBITS)
915 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
916 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000917}
918
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000919namespace llvm {
920
Petr Hosek35fdbd52017-08-01 05:31:50 +0000921template class Object<ELF64LE>;
922template class Object<ELF64BE>;
923template class Object<ELF32LE>;
924template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000925
926template class ELFObject<ELF64LE>;
927template class ELFObject<ELF64BE>;
928template class ELFObject<ELF32LE>;
929template class ELFObject<ELF32BE>;
930
931template class BinaryObject<ELF64LE>;
932template class BinaryObject<ELF64BE>;
933template class BinaryObject<ELF32LE>;
934template class BinaryObject<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000935
936} // end namespace llvm