blob: 9e82448187eafc9e784203dcef5bff3b2ad3a271 [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 Ehrlichf5a43772017-09-25 20:37:28 +0000178void SymbolTableSection::initialize(SectionTableRef SecTable) {
179 Size = 0;
180 setStrTab(SecTable.getSectionOfType<StringTableSection>(
181 Link,
182 "Symbol table has link index of " + Twine(Link) +
183 " which is not a valid index",
184 "Symbol table has link index of " + Twine(Link) +
185 " which is not a string table"));
186}
187
Petr Hosek79cee9e2017-08-29 02:12:03 +0000188void SymbolTableSection::finalize() {
189 // Make sure SymbolNames is finalized before getting name indexes.
190 SymbolNames->finalize();
191
192 uint32_t MaxLocalIndex = 0;
193 for (auto &Sym : Symbols) {
194 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
195 if (Sym->Binding == STB_LOCAL)
196 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
197 }
198 // Now we need to set the Link and Info fields.
199 Link = SymbolNames->Index;
200 Info = MaxLocalIndex + 1;
201}
202
203void SymbolTableSection::addSymbolNames() {
204 // Add all of our strings to SymbolNames so that SymbolNames has the right
205 // size before layout is decided.
206 for (auto &Sym : Symbols)
207 SymbolNames->addString(Sym->Name);
208}
209
210const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
211 if (Symbols.size() <= Index)
212 error("Invalid symbol index: " + Twine(Index));
213 return Symbols[Index].get();
214}
215
216template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000217void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000218 uint8_t *Buf = Out.getBufferStart();
219 Buf += Offset;
220 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
221 // Loop though symbols setting each entry of the symbol table.
222 for (auto &Symbol : Symbols) {
223 Sym->st_name = Symbol->NameIndex;
224 Sym->st_value = Symbol->Value;
225 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000226 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000227 Sym->setBinding(Symbol->Binding);
228 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000229 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000230 ++Sym;
231 }
232}
233
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000234template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000235void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
236 const SectionBase *Sec) {
237 if (Symbols == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000238 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
239 "referenced by the relocation "
240 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000241 this->Name);
242 }
243}
244
245template <class SymTabType>
246void RelocSectionWithSymtabBase<SymTabType>::initialize(
247 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000248 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000249 Link,
250 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
251 "Link field value " + Twine(Link) + " in section " + Name +
252 " is not a symbol table"));
253
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000254 if (Info != SHN_UNDEF)
Jake Ehrlich777fb002017-12-15 20:17:55 +0000255 setSection(SecTable.getSection(Info,
256 "Info field value " + Twine(Info) +
257 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000258 else
259 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000260}
261
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000262template <class SymTabType>
263void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000264 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000265 if (SecToApplyRel != nullptr)
266 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000267}
268
269template <class ELFT>
270void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
271
272template <class ELFT>
273void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
274 Rela.r_addend = Addend;
275}
276
277template <class ELFT>
278template <class T>
279void RelocationSection<ELFT>::writeRel(T *Buf) const {
280 for (const auto &Reloc : Relocations) {
281 Buf->r_offset = Reloc.Offset;
282 setAddend(*Buf, Reloc.Addend);
283 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
284 ++Buf;
285 }
286}
287
288template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000289void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000290 uint8_t *Buf = Out.getBufferStart() + Offset;
291 if (Type == SHT_REL)
292 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
293 else
294 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
295}
296
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000297void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000298 std::copy(std::begin(Contents), std::end(Contents),
299 Out.getBufferStart() + Offset);
300}
301
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000302void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
303 if (StrTab == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000304 error("String table " + StrTab->Name + " cannot be removed because it is "
305 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000306 this->Name);
307 }
308}
309
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000310bool SectionWithStrTab::classof(const SectionBase *S) {
311 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
312}
313
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000314void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000315 auto StrTab = SecTable.getSection(Link,
316 "Link field value " + Twine(Link) +
317 " in section " + Name + " is invalid");
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000318 if (StrTab->Type != SHT_STRTAB) {
319 error("Link field value " + Twine(Link) + " in section " + Name +
320 " is not a string table");
321 }
322 setStrTab(StrTab);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000323}
324
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000325void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
326
Petr Hosek05a04cb2017-08-01 00:33:58 +0000327// Returns true IFF a section is wholly inside the range of a segment
328static bool sectionWithinSegment(const SectionBase &Section,
329 const Segment &Segment) {
330 // If a section is empty it should be treated like it has a size of 1. This is
331 // to clarify the case when an empty section lies on a boundary between two
332 // segments and ensures that the section "belongs" to the second segment and
333 // not the first.
334 uint64_t SecSize = Section.Size ? Section.Size : 1;
335 return Segment.Offset <= Section.OriginalOffset &&
336 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
337}
338
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000339// Returns true IFF a segment's original offset is inside of another segment's
340// range.
341static bool segmentOverlapsSegment(const Segment &Child,
342 const Segment &Parent) {
343
344 return Parent.OriginalOffset <= Child.OriginalOffset &&
345 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
346}
347
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000348static bool compareSegments(const Segment *A, const Segment *B) {
349 // Any segment without a parent segment should come before a segment
350 // that has a parent segment.
351 if (A->OriginalOffset < B->OriginalOffset)
352 return true;
353 if (A->OriginalOffset > B->OriginalOffset)
354 return false;
355 return A->Index < B->Index;
356}
357
Petr Hosek05a04cb2017-08-01 00:33:58 +0000358template <class ELFT>
359void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
360 uint32_t Index = 0;
361 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000362 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
363 (size_t)Phdr.p_filesz};
364 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000365 Segment &Seg = *Segments.back();
366 Seg.Type = Phdr.p_type;
367 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000368 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000369 Seg.Offset = Phdr.p_offset;
370 Seg.VAddr = Phdr.p_vaddr;
371 Seg.PAddr = Phdr.p_paddr;
372 Seg.FileSize = Phdr.p_filesz;
373 Seg.MemSize = Phdr.p_memsz;
374 Seg.Align = Phdr.p_align;
375 Seg.Index = Index++;
376 for (auto &Section : Sections) {
377 if (sectionWithinSegment(*Section, Seg)) {
378 Seg.addSection(&*Section);
379 if (!Section->ParentSegment ||
380 Section->ParentSegment->Offset > Seg.Offset) {
381 Section->ParentSegment = &Seg;
382 }
383 }
384 }
385 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000386 // Now we do an O(n^2) loop through the segments in order to match up
387 // segments.
388 for (auto &Child : Segments) {
389 for (auto &Parent : Segments) {
390 // Every segment will overlap with itself but we don't want a segment to
391 // be it's own parent so we avoid that situation.
392 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
393 // We want a canonical "most parental" segment but this requires
394 // inspecting the ParentSegment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000395 if (compareSegments(Parent.get(), Child.get()))
396 if (Child->ParentSegment == nullptr ||
397 compareSegments(Parent.get(), Child->ParentSegment)) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000398 Child->ParentSegment = Parent.get();
399 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000400 }
401 }
402 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000403}
404
405template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000406void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000407 SymbolTableSection *SymTab,
408 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000409 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
410 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
411
412 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
413 SectionBase *DefSection = nullptr;
414 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000415
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000416 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000417 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000418 error(
419 "Symbol '" + Name +
420 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
421 Twine(Sym.st_shndx));
422 }
423 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000424 DefSection = SecTable.getSection(
Jake Ehrlich777fb002017-12-15 20:17:55 +0000425 Sym.st_shndx,
426 "Symbol '" + Name + "' is defined in invalid section with index " +
427 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000428 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000429
Petr Hosek79cee9e2017-08-29 02:12:03 +0000430 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000431 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000432 }
433}
434
435template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000436static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
437
438template <class ELFT>
439static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
440 ToSet = Rela.r_addend;
441}
442
443template <class ELFT, class T>
444void initRelocations(RelocationSection<ELFT> *Relocs,
445 SymbolTableSection *SymbolTable, T RelRange) {
446 for (const auto &Rel : RelRange) {
447 Relocation ToAdd;
448 ToAdd.Offset = Rel.r_offset;
449 getAddend(ToAdd.Addend, Rel);
450 ToAdd.Type = Rel.getType(false);
451 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
452 Relocs->addRelocation(ToAdd);
453 }
454}
455
Zachary Turner41a9ee92017-10-11 23:54:34 +0000456SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000457 if (Index == SHN_UNDEF || Index > Sections.size())
458 error(ErrMsg);
459 return Sections[Index - 1].get();
460}
461
462template <class T>
Zachary Turner41a9ee92017-10-11 23:54:34 +0000463T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
464 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000465 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000466 return Sec;
467 error(TypeErrMsg);
468}
469
Petr Hosekd7df9b22017-09-06 23:41:02 +0000470template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000471std::unique_ptr<SectionBase>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000472Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
Petr Hosek05a04cb2017-08-01 00:33:58 +0000473 const Elf_Shdr &Shdr) {
474 ArrayRef<uint8_t> Data;
475 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000476 case SHT_REL:
477 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000478 if (Shdr.sh_flags & SHF_ALLOC) {
479 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
480 return llvm::make_unique<DynamicRelocationSection>(Data);
481 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000482 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000483 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000484 // If a string table is allocated we don't want to mess with it. That would
485 // mean altering the memory image. There are no special link types or
486 // anything so we can just use a Section.
487 if (Shdr.sh_flags & SHF_ALLOC) {
488 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
489 return llvm::make_unique<Section>(Data);
490 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000491 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000492 case SHT_HASH:
493 case SHT_GNU_HASH:
494 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
495 // Because of this we don't need to mess with the hash tables either.
496 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
497 return llvm::make_unique<Section>(Data);
498 case SHT_DYNSYM:
499 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
500 return llvm::make_unique<DynamicSymbolTableSection>(Data);
501 case SHT_DYNAMIC:
502 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
503 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000504 case SHT_SYMTAB: {
505 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
506 SymbolTable = SymTab.get();
507 return std::move(SymTab);
508 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000509 case SHT_NOBITS:
510 return llvm::make_unique<Section>(Data);
511 default:
512 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
513 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000514 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000515}
516
517template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000518SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000519 uint32_t Index = 0;
520 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
521 if (Index == 0) {
522 ++Index;
523 continue;
524 }
525 SecPtr Sec = makeSection(ElfFile, Shdr);
526 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
527 Sec->Type = Shdr.sh_type;
528 Sec->Flags = Shdr.sh_flags;
529 Sec->Addr = Shdr.sh_addr;
530 Sec->Offset = Shdr.sh_offset;
531 Sec->OriginalOffset = Shdr.sh_offset;
532 Sec->Size = Shdr.sh_size;
533 Sec->Link = Shdr.sh_link;
534 Sec->Info = Shdr.sh_info;
535 Sec->Align = Shdr.sh_addralign;
536 Sec->EntrySize = Shdr.sh_entsize;
537 Sec->Index = Index++;
538 Sections.push_back(std::move(Sec));
539 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000540
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000541 SectionTableRef SecTable(Sections);
542
Petr Hosek79cee9e2017-08-29 02:12:03 +0000543 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000544 // details about symbol tables. We need the symbol table filled out before
545 // any relocations.
546 if (SymbolTable) {
547 SymbolTable->initialize(SecTable);
548 initSymbolTable(ElfFile, SymbolTable, SecTable);
549 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000550
551 // Now that all sections and symbols have been added we can add
552 // relocations that reference symbols and set the link and info fields for
553 // relocation sections.
554 for (auto &Section : Sections) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000555 if (Section.get() == SymbolTable)
556 continue;
557 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000558 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000559 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
560 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000561 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000562 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000563 initRelocations(RelSec, SymbolTable,
564 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000565 }
566 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000567
568 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000569}
570
Petr Hosek05a04cb2017-08-01 00:33:58 +0000571template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
572 const auto &ElfFile = *Obj.getELFFile();
573 const auto &Ehdr = *ElfFile.getHeader();
574
575 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
576 Type = Ehdr.e_type;
577 Machine = Ehdr.e_machine;
578 Version = Ehdr.e_version;
579 Entry = Ehdr.e_entry;
580 Flags = Ehdr.e_flags;
581
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000582 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000583 readProgramHeaders(ElfFile);
584
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000585 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000586 Ehdr.e_shstrndx,
587 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
588 " is invalid",
589 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
590 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000591}
592
Petr Hosek05a04cb2017-08-01 00:33:58 +0000593template <class ELFT>
594void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
595 uint8_t *Buf = Out.getBufferStart();
596 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
597 std::copy(Ident, Ident + 16, Ehdr.e_ident);
598 Ehdr.e_type = Type;
599 Ehdr.e_machine = Machine;
600 Ehdr.e_version = Version;
601 Ehdr.e_entry = Entry;
602 Ehdr.e_phoff = sizeof(Elf_Ehdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000603 Ehdr.e_flags = Flags;
604 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
605 Ehdr.e_phentsize = sizeof(Elf_Phdr);
606 Ehdr.e_phnum = Segments.size();
607 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000608 if (WriteSectionHeaders) {
609 Ehdr.e_shoff = SHOffset;
610 Ehdr.e_shnum = Sections.size() + 1;
611 Ehdr.e_shstrndx = SectionNames->Index;
612 } else {
613 Ehdr.e_shoff = 0;
614 Ehdr.e_shnum = 0;
615 Ehdr.e_shstrndx = 0;
616 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000617}
618
619template <class ELFT>
620void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
621 for (auto &Phdr : Segments)
622 Phdr->template writeHeader<ELFT>(Out);
623}
624
625template <class ELFT>
626void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
627 uint8_t *Buf = Out.getBufferStart() + SHOffset;
628 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000629 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000630 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
631 Shdr.sh_name = 0;
632 Shdr.sh_type = SHT_NULL;
633 Shdr.sh_flags = 0;
634 Shdr.sh_addr = 0;
635 Shdr.sh_offset = 0;
636 Shdr.sh_size = 0;
637 Shdr.sh_link = 0;
638 Shdr.sh_info = 0;
639 Shdr.sh_addralign = 0;
640 Shdr.sh_entsize = 0;
641
642 for (auto &Section : Sections)
643 Section->template writeHeader<ELFT>(Out);
644}
645
646template <class ELFT>
647void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
648 for (auto &Section : Sections)
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000649 Section->writeSection(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000650}
651
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000652template <class ELFT>
653void Object<ELFT>::removeSections(
654 std::function<bool(const SectionBase &)> ToRemove) {
655
656 auto Iter = std::stable_partition(
657 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
658 if (ToRemove(*Sec))
659 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000660 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
661 if (auto ToRelSec = RelSec->getSection())
662 return !ToRemove(*ToRelSec);
663 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000664 return true;
665 });
666 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
667 SymbolTable = nullptr;
668 if (ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000669 if (WriteSectionHeaders)
670 error("Cannot remove " + SectionNames->Name +
671 " because it is the section header string table.");
672 SectionNames = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000673 }
674 // Now make sure there are no remaining references to the sections that will
675 // be removed. Sometimes it is impossible to remove a reference so we emit
676 // an error here instead.
677 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
678 for (auto &Segment : Segments)
679 Segment->removeSection(RemoveSec.get());
680 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
681 KeepSec->removeSectionReferences(RemoveSec.get());
682 }
683 // Now finally get rid of them all togethor.
684 Sections.erase(Iter, std::end(Sections));
685}
686
Jake Ehrliche8437de2017-12-19 00:47:30 +0000687template <class ELFT>
688void Object<ELFT>::addSection(StringRef SecName, ArrayRef<uint8_t> Data) {
689 auto Sec = llvm::make_unique<OwnedDataSection>(SecName, Data);
690 Sec->OriginalOffset = ~0ULL;
691 Sections.push_back(std::move(Sec));
692}
693
Petr Hosekc4df10e2017-08-04 21:09:26 +0000694template <class ELFT> void ELFObject<ELFT>::sortSections() {
695 // Put all sections in offset order. Maintain the ordering as closely as
696 // possible while meeting that demand however.
697 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
698 return A->OriginalOffset < B->OriginalOffset;
699 };
700 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
701 CompareSections);
702}
703
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000704static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
705 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
706 if (Align == 0)
707 Align = 1;
708 auto Diff =
709 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
710 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
711 // (Offset + Diff) & -Align == Addr & -Align will still hold.
712 if (Diff < 0)
713 Diff += Align;
714 return Offset + Diff;
715}
716
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000717// Orders segments such that if x = y->ParentSegment then y comes before x.
718static void OrderSegments(std::vector<Segment *> &Segments) {
719 std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
720}
721
722// This function finds a consistent layout for a list of segments starting from
723// an Offset. It assumes that Segments have been sorted by OrderSegments and
724// returns an Offset one past the end of the last segment.
725static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
726 uint64_t Offset) {
727 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
728 compareSegments));
Petr Hosek3f383832017-08-26 01:32:20 +0000729 // The only way a segment should move is if a section was between two
730 // segments and that section was removed. If that section isn't in a segment
731 // then it's acceptable, but not ideal, to simply move it to after the
732 // segments. So we can simply layout segments one after the other accounting
733 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000734 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000735 // We assume that segments have been ordered by OriginalOffset and Index
736 // such that a parent segment will always come before a child segment in
737 // OrderedSegments. This means that the Offset of the ParentSegment should
738 // already be set and we can set our offset relative to it.
739 if (Segment->ParentSegment != nullptr) {
740 auto Parent = Segment->ParentSegment;
741 Segment->Offset =
742 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
743 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000744 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000745 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000746 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000747 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000748 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000749 return Offset;
750}
751
752// This function finds a consistent layout for a list of sections. It assumes
753// that the ->ParentSegment of each section has already been laid out. The
754// supplied starting Offset is used for the starting offset of any section that
755// does not have a ParentSegment. It returns either the offset given if all
756// sections had a ParentSegment or an offset one past the last section if there
757// was a section that didn't have a ParentSegment.
758template <class SecPtr>
759static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000760 // Now the offset of every segment has been set we can assign the offsets
761 // of each section. For sections that are covered by a segment we should use
762 // the segment's original offset and the section's original offset to compute
763 // the offset from the start of the segment. Using the offset from the start
764 // of the segment we can assign a new offset to the section. For sections not
765 // covered by segments we can just bump Offset to the next valid location.
766 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000767 for (auto &Section : Sections) {
Petr Hosek3f383832017-08-26 01:32:20 +0000768 Section->Index = Index++;
769 if (Section->ParentSegment != nullptr) {
770 auto Segment = Section->ParentSegment;
771 Section->Offset =
772 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
773 } else {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000774 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000775 Section->Offset = Offset;
776 if (Section->Type != SHT_NOBITS)
777 Offset += Section->Size;
778 }
779 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000780 return Offset;
781}
Petr Hosek3f383832017-08-26 01:32:20 +0000782
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000783template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
784 // We need a temporary list of segments that has a special order to it
785 // so that we know that anytime ->ParentSegment is set that segment has
786 // already had its offset properly set.
787 std::vector<Segment *> OrderedSegments;
788 for (auto &Segment : this->Segments)
789 OrderedSegments.push_back(Segment.get());
790 OrderSegments(OrderedSegments);
791 // The size of ELF + program headers will not change so it is ok to assume
792 // that the first offset of the first segment is a good place to start
793 // outputting sections. This covers both the standard case and the PT_PHDR
794 // case.
795 uint64_t Offset;
796 if (!OrderedSegments.empty()) {
797 Offset = OrderedSegments[0]->Offset;
798 } else {
799 Offset = sizeof(Elf_Ehdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000800 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000801 Offset = LayoutSegments(OrderedSegments, Offset);
802 Offset = LayoutSections(this->Sections, Offset);
803 // If we need to write the section header table out then we need to align the
804 // Offset so that SHOffset is valid.
805 if (this->WriteSectionHeaders)
806 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Petr Hosekc4df10e2017-08-04 21:09:26 +0000807 this->SHOffset = Offset;
808}
809
810template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
811 // We already have the section header offset so we can calculate the total
812 // size by just adding up the size of each section header.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000813 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000814 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000815 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000816}
817
818template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
819 this->writeHeader(Out);
820 this->writeProgramHeaders(Out);
821 this->writeSectionData(Out);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000822 if (this->WriteSectionHeaders)
823 this->writeSectionHeaders(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000824}
825
826template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000827 // Make sure we add the names of all the sections.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000828 if (this->SectionNames != nullptr)
829 for (const auto &Section : this->Sections) {
830 this->SectionNames->addString(Section->Name);
831 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000832 // Make sure we add the names of all the symbols.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000833 if (this->SymbolTable != nullptr)
834 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000835
836 sortSections();
837 assignOffsets();
838
839 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000840 if (this->SectionNames != nullptr)
841 this->SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000842 // Finally now that all offsets and indexes have been set we can finalize any
843 // remaining issues.
844 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
845 for (auto &Section : this->Sections) {
846 Section->HeaderOffset = Offset;
847 Offset += sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000848 if (this->WriteSectionHeaders)
849 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000850 Section->finalize();
851 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000852}
853
854template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
855 return TotalSize;
856}
857
858template <class ELFT>
859void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000860 for (auto &Section : this->Sections) {
861 if ((Section->Flags & SHF_ALLOC) == 0)
862 continue;
863 Section->writeSection(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000864 }
865}
866
867template <class ELFT> void BinaryObject<ELFT>::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000868 // TODO: Create a filter range to construct OrderedSegments from so that this
869 // code can be deduped with assignOffsets above. This should also solve the
870 // todo below for LayoutSections.
871 // We need a temporary list of segments that has a special order to it
872 // so that we know that anytime ->ParentSegment is set that segment has
873 // already had it's offset properly set. We only want to consider the segments
874 // that will affect layout of allocated sections so we only add those.
875 std::vector<Segment *> OrderedSegments;
876 for (auto &Section : this->Sections) {
877 if ((Section->Flags & SHF_ALLOC) != 0 &&
878 Section->ParentSegment != nullptr) {
879 OrderedSegments.push_back(Section->ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000880 }
881 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000882 OrderSegments(OrderedSegments);
883 // Because we add a ParentSegment for each section we might have duplicate
884 // segments in OrderedSegments. If there were duplicates then LayoutSegments
885 // would do very strange things.
886 auto End =
887 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
888 OrderedSegments.erase(End, std::end(OrderedSegments));
889
890 // Modify the first segment so that there is no gap at the start. This allows
891 // our layout algorithm to proceed as expected while not out writing out the
892 // gap at the start.
893 if (!OrderedSegments.empty()) {
894 auto Seg = OrderedSegments[0];
895 auto Sec = Seg->firstSection();
896 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
897 Seg->OriginalOffset += Diff;
898 // The size needs to be shrunk as well
899 Seg->FileSize -= Diff;
900 Seg->MemSize -= Diff;
901 // The VAddr needs to be adjusted so that the alignment is correct as well
902 Seg->VAddr += Diff;
903 Seg->PAddr = Seg->VAddr;
904 // We don't want this to be shifted by alignment so we need to set the
905 // alignment to zero.
906 Seg->Align = 0;
907 }
908
909 uint64_t Offset = LayoutSegments(OrderedSegments, 0);
910
911 // TODO: generalize LayoutSections to take a range. Pass a special range
912 // constructed from an iterator that skips values for which a predicate does
913 // not hold. Then pass such a range to LayoutSections instead of constructing
914 // AllocatedSections here.
915 std::vector<SectionBase *> AllocatedSections;
916 for (auto &Section : this->Sections) {
917 if ((Section->Flags & SHF_ALLOC) == 0)
918 continue;
919 AllocatedSections.push_back(Section.get());
920 }
921 LayoutSections(AllocatedSections, Offset);
922
923 // Now that every section has been laid out we just need to compute the total
924 // file size. This might not be the same as the offset returned by
925 // LayoutSections, because we want to truncate the last segment to the end of
926 // its last section, to match GNU objcopy's behaviour.
927 TotalSize = 0;
928 for (const auto &Section : AllocatedSections) {
929 if (Section->Type != SHT_NOBITS)
930 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
931 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000932}
933
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000934namespace llvm {
935
Petr Hosek35fdbd52017-08-01 05:31:50 +0000936template class Object<ELF64LE>;
937template class Object<ELF64BE>;
938template class Object<ELF32LE>;
939template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000940
941template class ELFObject<ELF64LE>;
942template class ELFObject<ELF64BE>;
943template class ELFObject<ELF32LE>;
944template class ELFObject<ELF32BE>;
945
946template class BinaryObject<ELF64LE>;
947template class BinaryObject<ELF64BE>;
948template class BinaryObject<ELF32LE>;
949template class BinaryObject<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000950
951} // end namespace llvm