blob: d5dfcac40e4e4680046c2e335d7466eb90bffc6d [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,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000144 uint16_t Shndx, uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000145 Symbol Sym;
146 Sym.Name = Name;
147 Sym.Binding = Bind;
148 Sym.Type = Type;
149 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000150 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000151 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000152 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
153 else
154 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
155 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000156 Sym.Value = Value;
157 Sym.Size = Sz;
158 Sym.Index = Symbols.size();
159 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
160 Size += this->EntrySize;
161}
162
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000163void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
164 if (SymbolNames == Sec) {
165 error("String table " + SymbolNames->Name +
166 " cannot be removed because it is referenced by the symbol table " +
167 this->Name);
168 }
169 auto Iter =
170 std::remove_if(std::begin(Symbols), std::end(Symbols),
171 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
172 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
173 Symbols.erase(Iter, std::end(Symbols));
174}
175
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000176void SymbolTableSection::initialize(SectionTableRef SecTable) {
177 Size = 0;
178 setStrTab(SecTable.getSectionOfType<StringTableSection>(
179 Link,
180 "Symbol table has link index of " + Twine(Link) +
181 " which is not a valid index",
182 "Symbol table has link index of " + Twine(Link) +
183 " which is not a string table"));
184}
185
Petr Hosek79cee9e2017-08-29 02:12:03 +0000186void SymbolTableSection::finalize() {
187 // Make sure SymbolNames is finalized before getting name indexes.
188 SymbolNames->finalize();
189
190 uint32_t MaxLocalIndex = 0;
191 for (auto &Sym : Symbols) {
192 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
193 if (Sym->Binding == STB_LOCAL)
194 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
195 }
196 // Now we need to set the Link and Info fields.
197 Link = SymbolNames->Index;
198 Info = MaxLocalIndex + 1;
199}
200
201void SymbolTableSection::addSymbolNames() {
202 // Add all of our strings to SymbolNames so that SymbolNames has the right
203 // size before layout is decided.
204 for (auto &Sym : Symbols)
205 SymbolNames->addString(Sym->Name);
206}
207
208const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
209 if (Symbols.size() <= Index)
210 error("Invalid symbol index: " + Twine(Index));
211 return Symbols[Index].get();
212}
213
214template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000215void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000216 uint8_t *Buf = Out.getBufferStart();
217 Buf += Offset;
218 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
219 // Loop though symbols setting each entry of the symbol table.
220 for (auto &Symbol : Symbols) {
221 Sym->st_name = Symbol->NameIndex;
222 Sym->st_value = Symbol->Value;
223 Sym->st_size = Symbol->Size;
224 Sym->setBinding(Symbol->Binding);
225 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000226 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000227 ++Sym;
228 }
229}
230
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000231template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000232void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
233 const SectionBase *Sec) {
234 if (Symbols == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000235 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
236 "referenced by the relocation "
237 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000238 this->Name);
239 }
240}
241
242template <class SymTabType>
243void RelocSectionWithSymtabBase<SymTabType>::initialize(
244 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000245 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000246 Link,
247 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
248 "Link field value " + Twine(Link) + " in section " + Name +
249 " is not a symbol table"));
250
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000251 if (Info != SHN_UNDEF)
Jake Ehrlich777fb002017-12-15 20:17:55 +0000252 setSection(SecTable.getSection(Info,
253 "Info field value " + Twine(Info) +
254 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000255 else
256 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000257}
258
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000259template <class SymTabType>
260void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000261 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000262 if (SecToApplyRel != nullptr)
263 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000264}
265
266template <class ELFT>
267void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
268
269template <class ELFT>
270void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
271 Rela.r_addend = Addend;
272}
273
274template <class ELFT>
275template <class T>
276void RelocationSection<ELFT>::writeRel(T *Buf) const {
277 for (const auto &Reloc : Relocations) {
278 Buf->r_offset = Reloc.Offset;
279 setAddend(*Buf, Reloc.Addend);
280 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
281 ++Buf;
282 }
283}
284
285template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000286void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000287 uint8_t *Buf = Out.getBufferStart() + Offset;
288 if (Type == SHT_REL)
289 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
290 else
291 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
292}
293
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000294void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000295 std::copy(std::begin(Contents), std::end(Contents),
296 Out.getBufferStart() + Offset);
297}
298
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000299void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
300 if (StrTab == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000301 error("String table " + StrTab->Name + " cannot be removed because it is "
302 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000303 this->Name);
304 }
305}
306
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000307bool SectionWithStrTab::classof(const SectionBase *S) {
308 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
309}
310
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000311void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000312 auto StrTab = SecTable.getSection(Link,
313 "Link field value " + Twine(Link) +
314 " in section " + Name + " is invalid");
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000315 if (StrTab->Type != SHT_STRTAB) {
316 error("Link field value " + Twine(Link) + " in section " + Name +
317 " is not a string table");
318 }
319 setStrTab(StrTab);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000320}
321
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000322void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
323
Petr Hosek05a04cb2017-08-01 00:33:58 +0000324// Returns true IFF a section is wholly inside the range of a segment
325static bool sectionWithinSegment(const SectionBase &Section,
326 const Segment &Segment) {
327 // If a section is empty it should be treated like it has a size of 1. This is
328 // to clarify the case when an empty section lies on a boundary between two
329 // segments and ensures that the section "belongs" to the second segment and
330 // not the first.
331 uint64_t SecSize = Section.Size ? Section.Size : 1;
332 return Segment.Offset <= Section.OriginalOffset &&
333 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
334}
335
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000336// Returns true IFF a segment's original offset is inside of another segment's
337// range.
338static bool segmentOverlapsSegment(const Segment &Child,
339 const Segment &Parent) {
340
341 return Parent.OriginalOffset <= Child.OriginalOffset &&
342 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
343}
344
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000345static bool compareSegments(const Segment *A, const Segment *B) {
346 // Any segment without a parent segment should come before a segment
347 // that has a parent segment.
348 if (A->OriginalOffset < B->OriginalOffset)
349 return true;
350 if (A->OriginalOffset > B->OriginalOffset)
351 return false;
352 return A->Index < B->Index;
353}
354
Petr Hosek05a04cb2017-08-01 00:33:58 +0000355template <class ELFT>
356void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
357 uint32_t Index = 0;
358 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000359 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
360 (size_t)Phdr.p_filesz};
361 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000362 Segment &Seg = *Segments.back();
363 Seg.Type = Phdr.p_type;
364 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000365 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000366 Seg.Offset = Phdr.p_offset;
367 Seg.VAddr = Phdr.p_vaddr;
368 Seg.PAddr = Phdr.p_paddr;
369 Seg.FileSize = Phdr.p_filesz;
370 Seg.MemSize = Phdr.p_memsz;
371 Seg.Align = Phdr.p_align;
372 Seg.Index = Index++;
373 for (auto &Section : Sections) {
374 if (sectionWithinSegment(*Section, Seg)) {
375 Seg.addSection(&*Section);
376 if (!Section->ParentSegment ||
377 Section->ParentSegment->Offset > Seg.Offset) {
378 Section->ParentSegment = &Seg;
379 }
380 }
381 }
382 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000383 // Now we do an O(n^2) loop through the segments in order to match up
384 // segments.
385 for (auto &Child : Segments) {
386 for (auto &Parent : Segments) {
387 // Every segment will overlap with itself but we don't want a segment to
388 // be it's own parent so we avoid that situation.
389 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
390 // We want a canonical "most parental" segment but this requires
391 // inspecting the ParentSegment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000392 if (compareSegments(Parent.get(), Child.get()))
393 if (Child->ParentSegment == nullptr ||
394 compareSegments(Parent.get(), Child->ParentSegment)) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000395 Child->ParentSegment = Parent.get();
396 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000397 }
398 }
399 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000400}
401
402template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000403void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000404 SymbolTableSection *SymTab,
405 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000406 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
407 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
408
409 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
410 SectionBase *DefSection = nullptr;
411 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000412
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000413 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000414 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000415 error(
416 "Symbol '" + Name +
417 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
418 Twine(Sym.st_shndx));
419 }
420 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000421 DefSection = SecTable.getSection(
Jake Ehrlich777fb002017-12-15 20:17:55 +0000422 Sym.st_shndx,
423 "Symbol '" + Name + "' is defined in invalid section with index " +
424 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000425 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000426
Petr Hosek79cee9e2017-08-29 02:12:03 +0000427 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000428 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000429 }
430}
431
432template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000433static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
434
435template <class ELFT>
436static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
437 ToSet = Rela.r_addend;
438}
439
440template <class ELFT, class T>
441void initRelocations(RelocationSection<ELFT> *Relocs,
442 SymbolTableSection *SymbolTable, T RelRange) {
443 for (const auto &Rel : RelRange) {
444 Relocation ToAdd;
445 ToAdd.Offset = Rel.r_offset;
446 getAddend(ToAdd.Addend, Rel);
447 ToAdd.Type = Rel.getType(false);
448 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
449 Relocs->addRelocation(ToAdd);
450 }
451}
452
Zachary Turner41a9ee92017-10-11 23:54:34 +0000453SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000454 if (Index == SHN_UNDEF || Index > Sections.size())
455 error(ErrMsg);
456 return Sections[Index - 1].get();
457}
458
459template <class T>
Zachary Turner41a9ee92017-10-11 23:54:34 +0000460T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
461 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000462 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000463 return Sec;
464 error(TypeErrMsg);
465}
466
Petr Hosekd7df9b22017-09-06 23:41:02 +0000467template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000468std::unique_ptr<SectionBase>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000469Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
Petr Hosek05a04cb2017-08-01 00:33:58 +0000470 const Elf_Shdr &Shdr) {
471 ArrayRef<uint8_t> Data;
472 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000473 case SHT_REL:
474 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000475 if (Shdr.sh_flags & SHF_ALLOC) {
476 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
477 return llvm::make_unique<DynamicRelocationSection>(Data);
478 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000479 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000480 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000481 // If a string table is allocated we don't want to mess with it. That would
482 // mean altering the memory image. There are no special link types or
483 // anything so we can just use a Section.
484 if (Shdr.sh_flags & SHF_ALLOC) {
485 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
486 return llvm::make_unique<Section>(Data);
487 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000488 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000489 case SHT_HASH:
490 case SHT_GNU_HASH:
491 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
492 // Because of this we don't need to mess with the hash tables either.
493 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
494 return llvm::make_unique<Section>(Data);
495 case SHT_DYNSYM:
496 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
497 return llvm::make_unique<DynamicSymbolTableSection>(Data);
498 case SHT_DYNAMIC:
499 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
500 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000501 case SHT_SYMTAB: {
502 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
503 SymbolTable = SymTab.get();
504 return std::move(SymTab);
505 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000506 case SHT_NOBITS:
507 return llvm::make_unique<Section>(Data);
508 default:
509 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
510 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000511 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000512}
513
514template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000515SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000516 uint32_t Index = 0;
517 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
518 if (Index == 0) {
519 ++Index;
520 continue;
521 }
522 SecPtr Sec = makeSection(ElfFile, Shdr);
523 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
524 Sec->Type = Shdr.sh_type;
525 Sec->Flags = Shdr.sh_flags;
526 Sec->Addr = Shdr.sh_addr;
527 Sec->Offset = Shdr.sh_offset;
528 Sec->OriginalOffset = Shdr.sh_offset;
529 Sec->Size = Shdr.sh_size;
530 Sec->Link = Shdr.sh_link;
531 Sec->Info = Shdr.sh_info;
532 Sec->Align = Shdr.sh_addralign;
533 Sec->EntrySize = Shdr.sh_entsize;
534 Sec->Index = Index++;
535 Sections.push_back(std::move(Sec));
536 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000537
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000538 SectionTableRef SecTable(Sections);
539
Petr Hosek79cee9e2017-08-29 02:12:03 +0000540 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000541 // details about symbol tables. We need the symbol table filled out before
542 // any relocations.
543 if (SymbolTable) {
544 SymbolTable->initialize(SecTable);
545 initSymbolTable(ElfFile, SymbolTable, SecTable);
546 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000547
548 // Now that all sections and symbols have been added we can add
549 // relocations that reference symbols and set the link and info fields for
550 // relocation sections.
551 for (auto &Section : Sections) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000552 if (Section.get() == SymbolTable)
553 continue;
554 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000555 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000556 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
557 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000558 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000559 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000560 initRelocations(RelSec, SymbolTable,
561 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000562 }
563 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000564
565 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000566}
567
Petr Hosek05a04cb2017-08-01 00:33:58 +0000568template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
569 const auto &ElfFile = *Obj.getELFFile();
570 const auto &Ehdr = *ElfFile.getHeader();
571
572 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
573 Type = Ehdr.e_type;
574 Machine = Ehdr.e_machine;
575 Version = Ehdr.e_version;
576 Entry = Ehdr.e_entry;
577 Flags = Ehdr.e_flags;
578
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000579 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000580 readProgramHeaders(ElfFile);
581
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000582 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000583 Ehdr.e_shstrndx,
584 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
585 " is invalid",
586 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
587 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000588}
589
Petr Hosek05a04cb2017-08-01 00:33:58 +0000590template <class ELFT>
591void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
592 uint8_t *Buf = Out.getBufferStart();
593 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
594 std::copy(Ident, Ident + 16, Ehdr.e_ident);
595 Ehdr.e_type = Type;
596 Ehdr.e_machine = Machine;
597 Ehdr.e_version = Version;
598 Ehdr.e_entry = Entry;
599 Ehdr.e_phoff = sizeof(Elf_Ehdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000600 Ehdr.e_flags = Flags;
601 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
602 Ehdr.e_phentsize = sizeof(Elf_Phdr);
603 Ehdr.e_phnum = Segments.size();
604 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000605 if (WriteSectionHeaders) {
606 Ehdr.e_shoff = SHOffset;
607 Ehdr.e_shnum = Sections.size() + 1;
608 Ehdr.e_shstrndx = SectionNames->Index;
609 } else {
610 Ehdr.e_shoff = 0;
611 Ehdr.e_shnum = 0;
612 Ehdr.e_shstrndx = 0;
613 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000614}
615
616template <class ELFT>
617void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
618 for (auto &Phdr : Segments)
619 Phdr->template writeHeader<ELFT>(Out);
620}
621
622template <class ELFT>
623void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
624 uint8_t *Buf = Out.getBufferStart() + SHOffset;
625 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000626 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000627 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
628 Shdr.sh_name = 0;
629 Shdr.sh_type = SHT_NULL;
630 Shdr.sh_flags = 0;
631 Shdr.sh_addr = 0;
632 Shdr.sh_offset = 0;
633 Shdr.sh_size = 0;
634 Shdr.sh_link = 0;
635 Shdr.sh_info = 0;
636 Shdr.sh_addralign = 0;
637 Shdr.sh_entsize = 0;
638
639 for (auto &Section : Sections)
640 Section->template writeHeader<ELFT>(Out);
641}
642
643template <class ELFT>
644void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
645 for (auto &Section : Sections)
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000646 Section->writeSection(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000647}
648
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000649template <class ELFT>
650void Object<ELFT>::removeSections(
651 std::function<bool(const SectionBase &)> ToRemove) {
652
653 auto Iter = std::stable_partition(
654 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
655 if (ToRemove(*Sec))
656 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000657 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
658 if (auto ToRelSec = RelSec->getSection())
659 return !ToRemove(*ToRelSec);
660 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000661 return true;
662 });
663 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
664 SymbolTable = nullptr;
665 if (ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000666 if (WriteSectionHeaders)
667 error("Cannot remove " + SectionNames->Name +
668 " because it is the section header string table.");
669 SectionNames = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000670 }
671 // Now make sure there are no remaining references to the sections that will
672 // be removed. Sometimes it is impossible to remove a reference so we emit
673 // an error here instead.
674 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
675 for (auto &Segment : Segments)
676 Segment->removeSection(RemoveSec.get());
677 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
678 KeepSec->removeSectionReferences(RemoveSec.get());
679 }
680 // Now finally get rid of them all togethor.
681 Sections.erase(Iter, std::end(Sections));
682}
683
Jake Ehrliche8437de2017-12-19 00:47:30 +0000684template <class ELFT>
685void Object<ELFT>::addSection(StringRef SecName, ArrayRef<uint8_t> Data) {
686 auto Sec = llvm::make_unique<OwnedDataSection>(SecName, Data);
687 Sec->OriginalOffset = ~0ULL;
688 Sections.push_back(std::move(Sec));
689}
690
Petr Hosekc4df10e2017-08-04 21:09:26 +0000691template <class ELFT> void ELFObject<ELFT>::sortSections() {
692 // Put all sections in offset order. Maintain the ordering as closely as
693 // possible while meeting that demand however.
694 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
695 return A->OriginalOffset < B->OriginalOffset;
696 };
697 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
698 CompareSections);
699}
700
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000701static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
702 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
703 if (Align == 0)
704 Align = 1;
705 auto Diff =
706 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
707 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
708 // (Offset + Diff) & -Align == Addr & -Align will still hold.
709 if (Diff < 0)
710 Diff += Align;
711 return Offset + Diff;
712}
713
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000714// Orders segments such that if x = y->ParentSegment then y comes before x.
715static void OrderSegments(std::vector<Segment *> &Segments) {
716 std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
717}
718
719// This function finds a consistent layout for a list of segments starting from
720// an Offset. It assumes that Segments have been sorted by OrderSegments and
721// returns an Offset one past the end of the last segment.
722static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
723 uint64_t Offset) {
724 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
725 compareSegments));
Petr Hosek3f383832017-08-26 01:32:20 +0000726 // The only way a segment should move is if a section was between two
727 // segments and that section was removed. If that section isn't in a segment
728 // then it's acceptable, but not ideal, to simply move it to after the
729 // segments. So we can simply layout segments one after the other accounting
730 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000731 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000732 // We assume that segments have been ordered by OriginalOffset and Index
733 // such that a parent segment will always come before a child segment in
734 // OrderedSegments. This means that the Offset of the ParentSegment should
735 // already be set and we can set our offset relative to it.
736 if (Segment->ParentSegment != nullptr) {
737 auto Parent = Segment->ParentSegment;
738 Segment->Offset =
739 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
740 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000741 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000742 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000743 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000744 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000745 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000746 return Offset;
747}
748
749// This function finds a consistent layout for a list of sections. It assumes
750// that the ->ParentSegment of each section has already been laid out. The
751// supplied starting Offset is used for the starting offset of any section that
752// does not have a ParentSegment. It returns either the offset given if all
753// sections had a ParentSegment or an offset one past the last section if there
754// was a section that didn't have a ParentSegment.
755template <class SecPtr>
756static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000757 // Now the offset of every segment has been set we can assign the offsets
758 // of each section. For sections that are covered by a segment we should use
759 // the segment's original offset and the section's original offset to compute
760 // the offset from the start of the segment. Using the offset from the start
761 // of the segment we can assign a new offset to the section. For sections not
762 // covered by segments we can just bump Offset to the next valid location.
763 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000764 for (auto &Section : Sections) {
Petr Hosek3f383832017-08-26 01:32:20 +0000765 Section->Index = Index++;
766 if (Section->ParentSegment != nullptr) {
767 auto Segment = Section->ParentSegment;
768 Section->Offset =
769 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
770 } else {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000771 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000772 Section->Offset = Offset;
773 if (Section->Type != SHT_NOBITS)
774 Offset += Section->Size;
775 }
776 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000777 return Offset;
778}
Petr Hosek3f383832017-08-26 01:32:20 +0000779
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000780template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
781 // We need a temporary list of segments that has a special order to it
782 // so that we know that anytime ->ParentSegment is set that segment has
783 // already had its offset properly set.
784 std::vector<Segment *> OrderedSegments;
785 for (auto &Segment : this->Segments)
786 OrderedSegments.push_back(Segment.get());
787 OrderSegments(OrderedSegments);
788 // The size of ELF + program headers will not change so it is ok to assume
789 // that the first offset of the first segment is a good place to start
790 // outputting sections. This covers both the standard case and the PT_PHDR
791 // case.
792 uint64_t Offset;
793 if (!OrderedSegments.empty()) {
794 Offset = OrderedSegments[0]->Offset;
795 } else {
796 Offset = sizeof(Elf_Ehdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000797 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000798 Offset = LayoutSegments(OrderedSegments, Offset);
799 Offset = LayoutSections(this->Sections, Offset);
800 // If we need to write the section header table out then we need to align the
801 // Offset so that SHOffset is valid.
802 if (this->WriteSectionHeaders)
803 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Petr Hosekc4df10e2017-08-04 21:09:26 +0000804 this->SHOffset = Offset;
805}
806
807template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
808 // We already have the section header offset so we can calculate the total
809 // size by just adding up the size of each section header.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000810 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000811 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000812 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000813}
814
815template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
816 this->writeHeader(Out);
817 this->writeProgramHeaders(Out);
818 this->writeSectionData(Out);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000819 if (this->WriteSectionHeaders)
820 this->writeSectionHeaders(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000821}
822
823template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000824 // Make sure we add the names of all the sections.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000825 if (this->SectionNames != nullptr)
826 for (const auto &Section : this->Sections) {
827 this->SectionNames->addString(Section->Name);
828 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000829 // Make sure we add the names of all the symbols.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000830 if (this->SymbolTable != nullptr)
831 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000832
833 sortSections();
834 assignOffsets();
835
836 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000837 if (this->SectionNames != nullptr)
838 this->SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000839 // Finally now that all offsets and indexes have been set we can finalize any
840 // remaining issues.
841 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
842 for (auto &Section : this->Sections) {
843 Section->HeaderOffset = Offset;
844 Offset += sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000845 if (this->WriteSectionHeaders)
846 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000847 Section->finalize();
848 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000849}
850
851template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
852 return TotalSize;
853}
854
855template <class ELFT>
856void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000857 for (auto &Section : this->Sections) {
858 if ((Section->Flags & SHF_ALLOC) == 0)
859 continue;
860 Section->writeSection(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000861 }
862}
863
864template <class ELFT> void BinaryObject<ELFT>::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000865 // TODO: Create a filter range to construct OrderedSegments from so that this
866 // code can be deduped with assignOffsets above. This should also solve the
867 // todo below for LayoutSections.
868 // We need a temporary list of segments that has a special order to it
869 // so that we know that anytime ->ParentSegment is set that segment has
870 // already had it's offset properly set. We only want to consider the segments
871 // that will affect layout of allocated sections so we only add those.
872 std::vector<Segment *> OrderedSegments;
873 for (auto &Section : this->Sections) {
874 if ((Section->Flags & SHF_ALLOC) != 0 &&
875 Section->ParentSegment != nullptr) {
876 OrderedSegments.push_back(Section->ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000877 }
878 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000879 OrderSegments(OrderedSegments);
880 // Because we add a ParentSegment for each section we might have duplicate
881 // segments in OrderedSegments. If there were duplicates then LayoutSegments
882 // would do very strange things.
883 auto End =
884 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
885 OrderedSegments.erase(End, std::end(OrderedSegments));
886
887 // Modify the first segment so that there is no gap at the start. This allows
888 // our layout algorithm to proceed as expected while not out writing out the
889 // gap at the start.
890 if (!OrderedSegments.empty()) {
891 auto Seg = OrderedSegments[0];
892 auto Sec = Seg->firstSection();
893 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
894 Seg->OriginalOffset += Diff;
895 // The size needs to be shrunk as well
896 Seg->FileSize -= Diff;
897 Seg->MemSize -= Diff;
898 // The VAddr needs to be adjusted so that the alignment is correct as well
899 Seg->VAddr += Diff;
900 Seg->PAddr = Seg->VAddr;
901 // We don't want this to be shifted by alignment so we need to set the
902 // alignment to zero.
903 Seg->Align = 0;
904 }
905
906 uint64_t Offset = LayoutSegments(OrderedSegments, 0);
907
908 // TODO: generalize LayoutSections to take a range. Pass a special range
909 // constructed from an iterator that skips values for which a predicate does
910 // not hold. Then pass such a range to LayoutSections instead of constructing
911 // AllocatedSections here.
912 std::vector<SectionBase *> AllocatedSections;
913 for (auto &Section : this->Sections) {
914 if ((Section->Flags & SHF_ALLOC) == 0)
915 continue;
916 AllocatedSections.push_back(Section.get());
917 }
918 LayoutSections(AllocatedSections, Offset);
919
920 // Now that every section has been laid out we just need to compute the total
921 // file size. This might not be the same as the offset returned by
922 // LayoutSections, because we want to truncate the last segment to the end of
923 // its last section, to match GNU objcopy's behaviour.
924 TotalSize = 0;
925 for (const auto &Section : AllocatedSections) {
926 if (Section->Type != SHT_NOBITS)
927 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
928 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000929}
930
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000931namespace llvm {
932
Petr Hosek35fdbd52017-08-01 05:31:50 +0000933template class Object<ELF64LE>;
934template class Object<ELF64BE>;
935template class Object<ELF32LE>;
936template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000937
938template class ELFObject<ELF64LE>;
939template class ELFObject<ELF64BE>;
940template class ELFObject<ELF32LE>;
941template class ELFObject<ELF32BE>;
942
943template class BinaryObject<ELF64LE>;
944template class BinaryObject<ELF64BE>;
945template class BinaryObject<ELF32LE>;
946template class BinaryObject<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000947
948} // end namespace llvm