blob: a0708ed59b4869c76c1213562ed132f9acdd6080 [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
Jake Ehrliche8437de2017-12-19 00:47:30 +000084void OwnedDataSection::writeSection(FileOutputBuffer &Out) const {
85 uint8_t *Buf = Out.getBufferStart() + Offset;
86 std::copy(std::begin(Data), std::end(Data), Buf);
87}
88
Petr Hosek05a04cb2017-08-01 00:33:58 +000089void StringTableSection::addString(StringRef Name) {
90 StrTabBuilder.add(Name);
91 Size = StrTabBuilder.getSize();
92}
93
94uint32_t StringTableSection::findIndex(StringRef Name) const {
95 return StrTabBuilder.getOffset(Name);
96}
97
98void StringTableSection::finalize() { StrTabBuilder.finalize(); }
99
100void StringTableSection::writeSection(FileOutputBuffer &Out) const {
101 StrTabBuilder.write(Out.getBufferStart() + Offset);
102}
103
Petr Hosekc1135772017-09-13 03:04:50 +0000104static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000105 switch (Index) {
106 case SHN_ABS:
107 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000108 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000109 }
Petr Hosekc1135772017-09-13 03:04:50 +0000110 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;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000120}
121
122uint16_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
Petr Hosek79cee9e2017-08-29 02:12:03 +0000142void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
143 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000144 uint8_t Visibility, uint16_t Shndx,
145 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000146 Symbol Sym;
147 Sym.Name = Name;
148 Sym.Binding = Bind;
149 Sym.Type = Type;
150 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000151 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000152 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000153 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
154 else
155 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
156 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000157 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000158 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000159 Sym.Size = Sz;
160 Sym.Index = Symbols.size();
161 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
162 Size += this->EntrySize;
163}
164
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000165void 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
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000178void SymbolTableSection::localize(
179 std::function<bool(const Symbol &)> ToLocalize) {
180 for (const auto &Sym : Symbols) {
181 if (ToLocalize(*Sym))
182 Sym->Binding = STB_LOCAL;
183 }
184
185 // Now that the local symbols aren't grouped at the start we have to reorder
186 // the symbols to respect this property.
187 std::stable_partition(
188 std::begin(Symbols), std::end(Symbols),
189 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
190
191 // Lastly we fix the symbol indexes.
192 uint32_t Index = 0;
193 for (auto &Sym : Symbols)
194 Sym->Index = Index++;
195}
196
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000197void SymbolTableSection::initialize(SectionTableRef SecTable) {
198 Size = 0;
199 setStrTab(SecTable.getSectionOfType<StringTableSection>(
200 Link,
201 "Symbol table has link index of " + Twine(Link) +
202 " which is not a valid index",
203 "Symbol table has link index of " + Twine(Link) +
204 " which is not a string table"));
205}
206
Petr Hosek79cee9e2017-08-29 02:12:03 +0000207void SymbolTableSection::finalize() {
208 // Make sure SymbolNames is finalized before getting name indexes.
209 SymbolNames->finalize();
210
211 uint32_t MaxLocalIndex = 0;
212 for (auto &Sym : Symbols) {
213 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
214 if (Sym->Binding == STB_LOCAL)
215 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
216 }
217 // Now we need to set the Link and Info fields.
218 Link = SymbolNames->Index;
219 Info = MaxLocalIndex + 1;
220}
221
222void SymbolTableSection::addSymbolNames() {
223 // Add all of our strings to SymbolNames so that SymbolNames has the right
224 // size before layout is decided.
225 for (auto &Sym : Symbols)
226 SymbolNames->addString(Sym->Name);
227}
228
229const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
230 if (Symbols.size() <= Index)
231 error("Invalid symbol index: " + Twine(Index));
232 return Symbols[Index].get();
233}
234
235template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000236void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000237 uint8_t *Buf = Out.getBufferStart();
238 Buf += Offset;
239 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
240 // Loop though symbols setting each entry of the symbol table.
241 for (auto &Symbol : Symbols) {
242 Sym->st_name = Symbol->NameIndex;
243 Sym->st_value = Symbol->Value;
244 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000245 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000246 Sym->setBinding(Symbol->Binding);
247 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000248 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000249 ++Sym;
250 }
251}
252
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000253template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000254void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
255 const SectionBase *Sec) {
256 if (Symbols == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000257 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
258 "referenced by the relocation "
259 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000260 this->Name);
261 }
262}
263
264template <class SymTabType>
265void RelocSectionWithSymtabBase<SymTabType>::initialize(
266 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000267 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000268 Link,
269 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
270 "Link field value " + Twine(Link) + " in section " + Name +
271 " is not a symbol table"));
272
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000273 if (Info != SHN_UNDEF)
Jake Ehrlich777fb002017-12-15 20:17:55 +0000274 setSection(SecTable.getSection(Info,
275 "Info field value " + Twine(Info) +
276 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000277 else
278 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000279}
280
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000281template <class SymTabType>
282void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000283 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000284 if (SecToApplyRel != nullptr)
285 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000286}
287
288template <class ELFT>
289void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
290
291template <class ELFT>
292void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
293 Rela.r_addend = Addend;
294}
295
296template <class ELFT>
297template <class T>
298void RelocationSection<ELFT>::writeRel(T *Buf) const {
299 for (const auto &Reloc : Relocations) {
300 Buf->r_offset = Reloc.Offset;
301 setAddend(*Buf, Reloc.Addend);
302 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
303 ++Buf;
304 }
305}
306
307template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000308void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000309 uint8_t *Buf = Out.getBufferStart() + Offset;
310 if (Type == SHT_REL)
311 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
312 else
313 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
314}
315
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000316void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000317 std::copy(std::begin(Contents), std::end(Contents),
318 Out.getBufferStart() + Offset);
319}
320
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000321void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
322 if (StrTab == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000323 error("String table " + StrTab->Name + " cannot be removed because it is "
324 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000325 this->Name);
326 }
327}
328
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000329bool SectionWithStrTab::classof(const SectionBase *S) {
330 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
331}
332
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000333void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000334 auto StrTab = SecTable.getSection(Link,
335 "Link field value " + Twine(Link) +
336 " in section " + Name + " is invalid");
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000337 if (StrTab->Type != SHT_STRTAB) {
338 error("Link field value " + Twine(Link) + " in section " + Name +
339 " is not a string table");
340 }
341 setStrTab(StrTab);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000342}
343
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000344void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
345
Petr Hosek05a04cb2017-08-01 00:33:58 +0000346// Returns true IFF a section is wholly inside the range of a segment
347static bool sectionWithinSegment(const SectionBase &Section,
348 const Segment &Segment) {
349 // If a section is empty it should be treated like it has a size of 1. This is
350 // to clarify the case when an empty section lies on a boundary between two
351 // segments and ensures that the section "belongs" to the second segment and
352 // not the first.
353 uint64_t SecSize = Section.Size ? Section.Size : 1;
354 return Segment.Offset <= Section.OriginalOffset &&
355 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
356}
357
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000358// Returns true IFF a segment's original offset is inside of another segment's
359// range.
360static bool segmentOverlapsSegment(const Segment &Child,
361 const Segment &Parent) {
362
363 return Parent.OriginalOffset <= Child.OriginalOffset &&
364 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
365}
366
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000367static bool compareSegments(const Segment *A, const Segment *B) {
368 // Any segment without a parent segment should come before a segment
369 // that has a parent segment.
370 if (A->OriginalOffset < B->OriginalOffset)
371 return true;
372 if (A->OriginalOffset > B->OriginalOffset)
373 return false;
374 return A->Index < B->Index;
375}
376
Petr Hosek05a04cb2017-08-01 00:33:58 +0000377template <class ELFT>
378void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
379 uint32_t Index = 0;
380 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000381 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
382 (size_t)Phdr.p_filesz};
383 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000384 Segment &Seg = *Segments.back();
385 Seg.Type = Phdr.p_type;
386 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000387 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000388 Seg.Offset = Phdr.p_offset;
389 Seg.VAddr = Phdr.p_vaddr;
390 Seg.PAddr = Phdr.p_paddr;
391 Seg.FileSize = Phdr.p_filesz;
392 Seg.MemSize = Phdr.p_memsz;
393 Seg.Align = Phdr.p_align;
394 Seg.Index = Index++;
395 for (auto &Section : Sections) {
396 if (sectionWithinSegment(*Section, Seg)) {
397 Seg.addSection(&*Section);
398 if (!Section->ParentSegment ||
399 Section->ParentSegment->Offset > Seg.Offset) {
400 Section->ParentSegment = &Seg;
401 }
402 }
403 }
404 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000405 // Now we do an O(n^2) loop through the segments in order to match up
406 // segments.
407 for (auto &Child : Segments) {
408 for (auto &Parent : Segments) {
409 // Every segment will overlap with itself but we don't want a segment to
410 // be it's own parent so we avoid that situation.
411 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
412 // We want a canonical "most parental" segment but this requires
413 // inspecting the ParentSegment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000414 if (compareSegments(Parent.get(), Child.get()))
415 if (Child->ParentSegment == nullptr ||
416 compareSegments(Parent.get(), Child->ParentSegment)) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000417 Child->ParentSegment = Parent.get();
418 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000419 }
420 }
421 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000422}
423
424template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000425void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000426 SymbolTableSection *SymTab,
427 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000428 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
429 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
430
431 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
432 SectionBase *DefSection = nullptr;
433 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000434
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000435 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000436 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000437 error(
438 "Symbol '" + Name +
439 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
440 Twine(Sym.st_shndx));
441 }
442 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000443 DefSection = SecTable.getSection(
Jake Ehrlich777fb002017-12-15 20:17:55 +0000444 Sym.st_shndx,
445 "Symbol '" + Name + "' is defined in invalid section with index " +
446 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000447 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000448
Petr Hosek79cee9e2017-08-29 02:12:03 +0000449 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000450 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000451 }
452}
453
454template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000455static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
456
457template <class ELFT>
458static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
459 ToSet = Rela.r_addend;
460}
461
462template <class ELFT, class T>
463void initRelocations(RelocationSection<ELFT> *Relocs,
464 SymbolTableSection *SymbolTable, T RelRange) {
465 for (const auto &Rel : RelRange) {
466 Relocation ToAdd;
467 ToAdd.Offset = Rel.r_offset;
468 getAddend(ToAdd.Addend, Rel);
469 ToAdd.Type = Rel.getType(false);
470 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
471 Relocs->addRelocation(ToAdd);
472 }
473}
474
Zachary Turner41a9ee92017-10-11 23:54:34 +0000475SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000476 if (Index == SHN_UNDEF || Index > Sections.size())
477 error(ErrMsg);
478 return Sections[Index - 1].get();
479}
480
481template <class T>
Zachary Turner41a9ee92017-10-11 23:54:34 +0000482T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
483 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000484 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000485 return Sec;
486 error(TypeErrMsg);
487}
488
Petr Hosekd7df9b22017-09-06 23:41:02 +0000489template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000490std::unique_ptr<SectionBase>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000491Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
Petr Hosek05a04cb2017-08-01 00:33:58 +0000492 const Elf_Shdr &Shdr) {
493 ArrayRef<uint8_t> Data;
494 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000495 case SHT_REL:
496 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000497 if (Shdr.sh_flags & SHF_ALLOC) {
498 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
499 return llvm::make_unique<DynamicRelocationSection>(Data);
500 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000501 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000502 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000503 // If a string table is allocated we don't want to mess with it. That would
504 // mean altering the memory image. There are no special link types or
505 // anything so we can just use a Section.
506 if (Shdr.sh_flags & SHF_ALLOC) {
507 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
508 return llvm::make_unique<Section>(Data);
509 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000510 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000511 case SHT_HASH:
512 case SHT_GNU_HASH:
513 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
514 // Because of this we don't need to mess with the hash tables either.
515 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
516 return llvm::make_unique<Section>(Data);
517 case SHT_DYNSYM:
518 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
519 return llvm::make_unique<DynamicSymbolTableSection>(Data);
520 case SHT_DYNAMIC:
521 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
522 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000523 case SHT_SYMTAB: {
524 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
525 SymbolTable = SymTab.get();
526 return std::move(SymTab);
527 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000528 case SHT_NOBITS:
529 return llvm::make_unique<Section>(Data);
530 default:
531 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
532 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000533 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000534}
535
536template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000537SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000538 uint32_t Index = 0;
539 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
540 if (Index == 0) {
541 ++Index;
542 continue;
543 }
544 SecPtr Sec = makeSection(ElfFile, Shdr);
545 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
546 Sec->Type = Shdr.sh_type;
547 Sec->Flags = Shdr.sh_flags;
548 Sec->Addr = Shdr.sh_addr;
549 Sec->Offset = Shdr.sh_offset;
550 Sec->OriginalOffset = Shdr.sh_offset;
551 Sec->Size = Shdr.sh_size;
552 Sec->Link = Shdr.sh_link;
553 Sec->Info = Shdr.sh_info;
554 Sec->Align = Shdr.sh_addralign;
555 Sec->EntrySize = Shdr.sh_entsize;
556 Sec->Index = Index++;
557 Sections.push_back(std::move(Sec));
558 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000559
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000560 SectionTableRef SecTable(Sections);
561
Petr Hosek79cee9e2017-08-29 02:12:03 +0000562 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000563 // details about symbol tables. We need the symbol table filled out before
564 // any relocations.
565 if (SymbolTable) {
566 SymbolTable->initialize(SecTable);
567 initSymbolTable(ElfFile, SymbolTable, SecTable);
568 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000569
570 // Now that all sections and symbols have been added we can add
571 // relocations that reference symbols and set the link and info fields for
572 // relocation sections.
573 for (auto &Section : Sections) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000574 if (Section.get() == SymbolTable)
575 continue;
576 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000577 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000578 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
579 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000580 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000581 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000582 initRelocations(RelSec, SymbolTable,
583 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000584 }
585 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000586
587 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000588}
589
Petr Hosek05a04cb2017-08-01 00:33:58 +0000590template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
591 const auto &ElfFile = *Obj.getELFFile();
592 const auto &Ehdr = *ElfFile.getHeader();
593
594 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
595 Type = Ehdr.e_type;
596 Machine = Ehdr.e_machine;
597 Version = Ehdr.e_version;
598 Entry = Ehdr.e_entry;
599 Flags = Ehdr.e_flags;
600
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000601 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000602 readProgramHeaders(ElfFile);
603
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000604 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000605 Ehdr.e_shstrndx,
606 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
607 " is invalid",
608 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
609 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000610}
611
Petr Hosek05a04cb2017-08-01 00:33:58 +0000612template <class ELFT>
613void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
614 uint8_t *Buf = Out.getBufferStart();
615 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
616 std::copy(Ident, Ident + 16, Ehdr.e_ident);
617 Ehdr.e_type = Type;
618 Ehdr.e_machine = Machine;
619 Ehdr.e_version = Version;
620 Ehdr.e_entry = Entry;
621 Ehdr.e_phoff = sizeof(Elf_Ehdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000622 Ehdr.e_flags = Flags;
623 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
624 Ehdr.e_phentsize = sizeof(Elf_Phdr);
625 Ehdr.e_phnum = Segments.size();
626 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000627 if (WriteSectionHeaders) {
628 Ehdr.e_shoff = SHOffset;
629 Ehdr.e_shnum = Sections.size() + 1;
630 Ehdr.e_shstrndx = SectionNames->Index;
631 } else {
632 Ehdr.e_shoff = 0;
633 Ehdr.e_shnum = 0;
634 Ehdr.e_shstrndx = 0;
635 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000636}
637
638template <class ELFT>
639void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
640 for (auto &Phdr : Segments)
641 Phdr->template writeHeader<ELFT>(Out);
642}
643
644template <class ELFT>
645void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
646 uint8_t *Buf = Out.getBufferStart() + SHOffset;
647 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000648 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000649 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
650 Shdr.sh_name = 0;
651 Shdr.sh_type = SHT_NULL;
652 Shdr.sh_flags = 0;
653 Shdr.sh_addr = 0;
654 Shdr.sh_offset = 0;
655 Shdr.sh_size = 0;
656 Shdr.sh_link = 0;
657 Shdr.sh_info = 0;
658 Shdr.sh_addralign = 0;
659 Shdr.sh_entsize = 0;
660
661 for (auto &Section : Sections)
662 Section->template writeHeader<ELFT>(Out);
663}
664
665template <class ELFT>
666void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
667 for (auto &Section : Sections)
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000668 Section->writeSection(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000669}
670
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000671template <class ELFT>
672void Object<ELFT>::removeSections(
673 std::function<bool(const SectionBase &)> ToRemove) {
674
675 auto Iter = std::stable_partition(
676 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
677 if (ToRemove(*Sec))
678 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000679 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
680 if (auto ToRelSec = RelSec->getSection())
681 return !ToRemove(*ToRelSec);
682 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000683 return true;
684 });
685 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
686 SymbolTable = nullptr;
687 if (ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000688 if (WriteSectionHeaders)
689 error("Cannot remove " + SectionNames->Name +
690 " because it is the section header string table.");
691 SectionNames = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000692 }
693 // Now make sure there are no remaining references to the sections that will
694 // be removed. Sometimes it is impossible to remove a reference so we emit
695 // an error here instead.
696 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
697 for (auto &Segment : Segments)
698 Segment->removeSection(RemoveSec.get());
699 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
700 KeepSec->removeSectionReferences(RemoveSec.get());
701 }
702 // Now finally get rid of them all togethor.
703 Sections.erase(Iter, std::end(Sections));
704}
705
Jake Ehrliche8437de2017-12-19 00:47:30 +0000706template <class ELFT>
707void Object<ELFT>::addSection(StringRef SecName, ArrayRef<uint8_t> Data) {
708 auto Sec = llvm::make_unique<OwnedDataSection>(SecName, Data);
709 Sec->OriginalOffset = ~0ULL;
710 Sections.push_back(std::move(Sec));
711}
712
Petr Hosekc4df10e2017-08-04 21:09:26 +0000713template <class ELFT> void ELFObject<ELFT>::sortSections() {
714 // Put all sections in offset order. Maintain the ordering as closely as
715 // possible while meeting that demand however.
716 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
717 return A->OriginalOffset < B->OriginalOffset;
718 };
719 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
720 CompareSections);
721}
722
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000723static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
724 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
725 if (Align == 0)
726 Align = 1;
727 auto Diff =
728 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
729 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
730 // (Offset + Diff) & -Align == Addr & -Align will still hold.
731 if (Diff < 0)
732 Diff += Align;
733 return Offset + Diff;
734}
735
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000736// Orders segments such that if x = y->ParentSegment then y comes before x.
737static void OrderSegments(std::vector<Segment *> &Segments) {
738 std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
739}
740
741// This function finds a consistent layout for a list of segments starting from
742// an Offset. It assumes that Segments have been sorted by OrderSegments and
743// returns an Offset one past the end of the last segment.
744static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
745 uint64_t Offset) {
746 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
747 compareSegments));
Petr Hosek3f383832017-08-26 01:32:20 +0000748 // The only way a segment should move is if a section was between two
749 // segments and that section was removed. If that section isn't in a segment
750 // then it's acceptable, but not ideal, to simply move it to after the
751 // segments. So we can simply layout segments one after the other accounting
752 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000753 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000754 // We assume that segments have been ordered by OriginalOffset and Index
755 // such that a parent segment will always come before a child segment in
756 // OrderedSegments. This means that the Offset of the ParentSegment should
757 // already be set and we can set our offset relative to it.
758 if (Segment->ParentSegment != nullptr) {
759 auto Parent = Segment->ParentSegment;
760 Segment->Offset =
761 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
762 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000763 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000764 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000765 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000766 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000767 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000768 return Offset;
769}
770
771// This function finds a consistent layout for a list of sections. It assumes
772// that the ->ParentSegment of each section has already been laid out. The
773// supplied starting Offset is used for the starting offset of any section that
774// does not have a ParentSegment. It returns either the offset given if all
775// sections had a ParentSegment or an offset one past the last section if there
776// was a section that didn't have a ParentSegment.
777template <class SecPtr>
778static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000779 // Now the offset of every segment has been set we can assign the offsets
780 // of each section. For sections that are covered by a segment we should use
781 // the segment's original offset and the section's original offset to compute
782 // the offset from the start of the segment. Using the offset from the start
783 // of the segment we can assign a new offset to the section. For sections not
784 // covered by segments we can just bump Offset to the next valid location.
785 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000786 for (auto &Section : Sections) {
Petr Hosek3f383832017-08-26 01:32:20 +0000787 Section->Index = Index++;
788 if (Section->ParentSegment != nullptr) {
789 auto Segment = Section->ParentSegment;
790 Section->Offset =
791 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
792 } else {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000793 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000794 Section->Offset = Offset;
795 if (Section->Type != SHT_NOBITS)
796 Offset += Section->Size;
797 }
798 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000799 return Offset;
800}
Petr Hosek3f383832017-08-26 01:32:20 +0000801
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000802template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
803 // We need a temporary list of segments that has a special order to it
804 // so that we know that anytime ->ParentSegment is set that segment has
805 // already had its offset properly set.
806 std::vector<Segment *> OrderedSegments;
807 for (auto &Segment : this->Segments)
808 OrderedSegments.push_back(Segment.get());
809 OrderSegments(OrderedSegments);
810 // The size of ELF + program headers will not change so it is ok to assume
811 // that the first offset of the first segment is a good place to start
812 // outputting sections. This covers both the standard case and the PT_PHDR
813 // case.
814 uint64_t Offset;
815 if (!OrderedSegments.empty()) {
816 Offset = OrderedSegments[0]->Offset;
817 } else {
818 Offset = sizeof(Elf_Ehdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000819 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000820 Offset = LayoutSegments(OrderedSegments, Offset);
821 Offset = LayoutSections(this->Sections, Offset);
822 // If we need to write the section header table out then we need to align the
823 // Offset so that SHOffset is valid.
824 if (this->WriteSectionHeaders)
825 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Petr Hosekc4df10e2017-08-04 21:09:26 +0000826 this->SHOffset = Offset;
827}
828
829template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
830 // We already have the section header offset so we can calculate the total
831 // size by just adding up the size of each section header.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000832 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000833 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000834 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000835}
836
837template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
838 this->writeHeader(Out);
839 this->writeProgramHeaders(Out);
840 this->writeSectionData(Out);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000841 if (this->WriteSectionHeaders)
842 this->writeSectionHeaders(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000843}
844
845template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000846 // Make sure we add the names of all the sections.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000847 if (this->SectionNames != nullptr)
848 for (const auto &Section : this->Sections) {
849 this->SectionNames->addString(Section->Name);
850 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000851 // Make sure we add the names of all the symbols.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000852 if (this->SymbolTable != nullptr)
853 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000854
855 sortSections();
856 assignOffsets();
857
858 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000859 if (this->SectionNames != nullptr)
860 this->SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000861 // Finally now that all offsets and indexes have been set we can finalize any
862 // remaining issues.
863 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
864 for (auto &Section : this->Sections) {
865 Section->HeaderOffset = Offset;
866 Offset += sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000867 if (this->WriteSectionHeaders)
868 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000869 Section->finalize();
870 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000871}
872
873template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
874 return TotalSize;
875}
876
877template <class ELFT>
878void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000879 for (auto &Section : this->Sections) {
880 if ((Section->Flags & SHF_ALLOC) == 0)
881 continue;
882 Section->writeSection(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000883 }
884}
885
886template <class ELFT> void BinaryObject<ELFT>::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000887 // TODO: Create a filter range to construct OrderedSegments from so that this
888 // code can be deduped with assignOffsets above. This should also solve the
889 // todo below for LayoutSections.
890 // We need a temporary list of segments that has a special order to it
891 // so that we know that anytime ->ParentSegment is set that segment has
892 // already had it's offset properly set. We only want to consider the segments
893 // that will affect layout of allocated sections so we only add those.
894 std::vector<Segment *> OrderedSegments;
895 for (auto &Section : this->Sections) {
896 if ((Section->Flags & SHF_ALLOC) != 0 &&
897 Section->ParentSegment != nullptr) {
898 OrderedSegments.push_back(Section->ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000899 }
900 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000901 OrderSegments(OrderedSegments);
902 // Because we add a ParentSegment for each section we might have duplicate
903 // segments in OrderedSegments. If there were duplicates then LayoutSegments
904 // would do very strange things.
905 auto End =
906 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
907 OrderedSegments.erase(End, std::end(OrderedSegments));
908
909 // Modify the first segment so that there is no gap at the start. This allows
910 // our layout algorithm to proceed as expected while not out writing out the
911 // gap at the start.
912 if (!OrderedSegments.empty()) {
913 auto Seg = OrderedSegments[0];
914 auto Sec = Seg->firstSection();
915 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
916 Seg->OriginalOffset += Diff;
917 // The size needs to be shrunk as well
918 Seg->FileSize -= Diff;
919 Seg->MemSize -= Diff;
920 // The VAddr needs to be adjusted so that the alignment is correct as well
921 Seg->VAddr += Diff;
922 Seg->PAddr = Seg->VAddr;
923 // We don't want this to be shifted by alignment so we need to set the
924 // alignment to zero.
925 Seg->Align = 0;
926 }
927
928 uint64_t Offset = LayoutSegments(OrderedSegments, 0);
929
930 // TODO: generalize LayoutSections to take a range. Pass a special range
931 // constructed from an iterator that skips values for which a predicate does
932 // not hold. Then pass such a range to LayoutSections instead of constructing
933 // AllocatedSections here.
934 std::vector<SectionBase *> AllocatedSections;
935 for (auto &Section : this->Sections) {
936 if ((Section->Flags & SHF_ALLOC) == 0)
937 continue;
938 AllocatedSections.push_back(Section.get());
939 }
940 LayoutSections(AllocatedSections, Offset);
941
942 // Now that every section has been laid out we just need to compute the total
943 // file size. This might not be the same as the offset returned by
944 // LayoutSections, because we want to truncate the last segment to the end of
945 // its last section, to match GNU objcopy's behaviour.
946 TotalSize = 0;
947 for (const auto &Section : AllocatedSections) {
948 if (Section->Type != SHT_NOBITS)
949 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
950 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000951}
952
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000953namespace llvm {
954
Petr Hosek35fdbd52017-08-01 05:31:50 +0000955template class Object<ELF64LE>;
956template class Object<ELF64BE>;
957template class Object<ELF32LE>;
958template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000959
960template class ELFObject<ELF64LE>;
961template class ELFObject<ELF64BE>;
962template class ELFObject<ELF32LE>;
963template class ELFObject<ELF32BE>;
964
965template class BinaryObject<ELF64LE>;
966template class BinaryObject<ELF64BE>;
967template class BinaryObject<ELF32LE>;
968template class BinaryObject<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000969
970} // end namespace llvm