blob: c00477a1980799b8100545200e6f1b2872612ae6 [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"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000021#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000022#include <algorithm>
23#include <cstddef>
24#include <cstdint>
25#include <iterator>
26#include <utility>
27#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000028
29using namespace llvm;
30using namespace object;
31using namespace ELF;
32
Jake Ehrlich76e91102018-01-25 22:46:17 +000033template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000034 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000035
Jake Ehrlich76e91102018-01-25 22:46:17 +000036 uint8_t *Buf = BufPtr->getBufferStart();
Jake Ehrlich6452b112018-02-14 23:31:33 +000037 Buf += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +000038 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000039 Phdr.p_type = Seg.Type;
40 Phdr.p_flags = Seg.Flags;
41 Phdr.p_offset = Seg.Offset;
42 Phdr.p_vaddr = Seg.VAddr;
43 Phdr.p_paddr = Seg.PAddr;
44 Phdr.p_filesz = Seg.FileSize;
45 Phdr.p_memsz = Seg.MemSize;
46 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000047}
48
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000049void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000050void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000051void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000052void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000053void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000054
Jake Ehrlich76e91102018-01-25 22:46:17 +000055template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
56 uint8_t *Buf = BufPtr->getBufferStart();
57 Buf += Sec.HeaderOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +000058 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000059 Shdr.sh_name = Sec.NameIndex;
60 Shdr.sh_type = Sec.Type;
61 Shdr.sh_flags = Sec.Flags;
62 Shdr.sh_addr = Sec.Addr;
63 Shdr.sh_offset = Sec.Offset;
64 Shdr.sh_size = Sec.Size;
65 Shdr.sh_link = Sec.Link;
66 Shdr.sh_info = Sec.Info;
67 Shdr.sh_addralign = Sec.Align;
68 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000069}
70
Jake Ehrlich76e91102018-01-25 22:46:17 +000071SectionVisitor::~SectionVisitor() {}
72
73void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
74 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
75}
76
77void BinarySectionWriter::visit(const RelocationSection &Sec) {
78 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
79}
80
81void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +000082 error("Cannot write '" + Sec.Name + "' out to binary");
83}
84
85void BinarySectionWriter::visit(const GroupSection &Sec) {
86 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +000087}
88
89void SectionWriter::visit(const Section &Sec) {
90 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +000091 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +000092 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
93 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +000094}
95
Jake Ehrlich76e91102018-01-25 22:46:17 +000096void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
97
98void SectionWriter::visit(const OwnedDataSection &Sec) {
99 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
100 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
101}
102
103void OwnedDataSection::accept(SectionVisitor &Visitor) const {
104 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000105}
106
Petr Hosek05a04cb2017-08-01 00:33:58 +0000107void StringTableSection::addString(StringRef Name) {
108 StrTabBuilder.add(Name);
109 Size = StrTabBuilder.getSize();
110}
111
112uint32_t StringTableSection::findIndex(StringRef Name) const {
113 return StrTabBuilder.getOffset(Name);
114}
115
116void StringTableSection::finalize() { StrTabBuilder.finalize(); }
117
Jake Ehrlich76e91102018-01-25 22:46:17 +0000118void SectionWriter::visit(const StringTableSection &Sec) {
119 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
120}
121
122void StringTableSection::accept(SectionVisitor &Visitor) const {
123 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000124}
125
Petr Hosekc1135772017-09-13 03:04:50 +0000126static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000127 switch (Index) {
128 case SHN_ABS:
129 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000130 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000131 }
Petr Hosekc1135772017-09-13 03:04:50 +0000132 if (Machine == EM_HEXAGON) {
133 switch (Index) {
134 case SHN_HEXAGON_SCOMMON:
135 case SHN_HEXAGON_SCOMMON_2:
136 case SHN_HEXAGON_SCOMMON_4:
137 case SHN_HEXAGON_SCOMMON_8:
138 return true;
139 }
140 }
141 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000142}
143
144uint16_t Symbol::getShndx() const {
145 if (DefinedIn != nullptr) {
146 return DefinedIn->Index;
147 }
148 switch (ShndxType) {
149 // This means that we don't have a defined section but we do need to
150 // output a legitimate section index.
151 case SYMBOL_SIMPLE_INDEX:
152 return SHN_UNDEF;
153 case SYMBOL_ABS:
154 case SYMBOL_COMMON:
155 case SYMBOL_HEXAGON_SCOMMON:
156 case SYMBOL_HEXAGON_SCOMMON_2:
157 case SYMBOL_HEXAGON_SCOMMON_4:
158 case SYMBOL_HEXAGON_SCOMMON_8:
159 return static_cast<uint16_t>(ShndxType);
160 }
161 llvm_unreachable("Symbol with invalid ShndxType encountered");
162}
163
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000164void SymbolTableSection::assignIndices() {
165 uint32_t Index = 0;
166 for (auto &Sym : Symbols)
167 Sym->Index = Index++;
168}
169
Petr Hosek79cee9e2017-08-29 02:12:03 +0000170void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
171 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000172 uint8_t Visibility, uint16_t Shndx,
173 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000174 Symbol Sym;
175 Sym.Name = Name;
176 Sym.Binding = Bind;
177 Sym.Type = Type;
178 Sym.DefinedIn = DefinedIn;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000179 if (DefinedIn == nullptr) {
180 if (Shndx >= SHN_LORESERVE)
181 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
182 else
183 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
184 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000185 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000186 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000187 Sym.Size = Sz;
188 Sym.Index = Symbols.size();
189 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
190 Size += this->EntrySize;
191}
192
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000193void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
194 if (SymbolNames == Sec) {
195 error("String table " + SymbolNames->Name +
196 " cannot be removed because it is referenced by the symbol table " +
197 this->Name);
198 }
Paul Semel41695f82018-05-02 20:19:22 +0000199 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000200}
201
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000202void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
203 for (auto &Sym : Symbols)
204 Callable(*Sym);
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000205 std::stable_partition(
206 std::begin(Symbols), std::end(Symbols),
207 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000208 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000209}
210
Paul Semel4246a462018-05-09 21:36:54 +0000211void SymbolTableSection::removeSymbols(
212 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000213 Symbols.erase(
214 std::remove_if(std::begin(Symbols), std::end(Symbols),
215 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
216 std::end(Symbols));
217 Size = Symbols.size() * EntrySize;
218 assignIndices();
219}
220
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000221void SymbolTableSection::initialize(SectionTableRef SecTable) {
222 Size = 0;
223 setStrTab(SecTable.getSectionOfType<StringTableSection>(
224 Link,
225 "Symbol table has link index of " + Twine(Link) +
226 " which is not a valid index",
227 "Symbol table has link index of " + Twine(Link) +
228 " which is not a string table"));
229}
230
Petr Hosek79cee9e2017-08-29 02:12:03 +0000231void SymbolTableSection::finalize() {
232 // Make sure SymbolNames is finalized before getting name indexes.
233 SymbolNames->finalize();
234
235 uint32_t MaxLocalIndex = 0;
236 for (auto &Sym : Symbols) {
237 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
238 if (Sym->Binding == STB_LOCAL)
239 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
240 }
241 // Now we need to set the Link and Info fields.
242 Link = SymbolNames->Index;
243 Info = MaxLocalIndex + 1;
244}
245
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000246void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000247 // Add all of our strings to SymbolNames so that SymbolNames has the right
248 // size before layout is decided.
249 for (auto &Sym : Symbols)
250 SymbolNames->addString(Sym->Name);
251}
252
253const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
254 if (Symbols.size() <= Index)
255 error("Invalid symbol index: " + Twine(Index));
256 return Symbols[Index].get();
257}
258
Paul Semel99dda0b2018-05-25 11:01:25 +0000259Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
260 return const_cast<Symbol *>(
261 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
262}
263
Petr Hosek79cee9e2017-08-29 02:12:03 +0000264template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000265void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000266 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000267 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000268 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
269 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000270 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000271 Sym->st_name = Symbol->NameIndex;
272 Sym->st_value = Symbol->Value;
273 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000274 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000275 Sym->setBinding(Symbol->Binding);
276 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000277 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000278 ++Sym;
279 }
280}
281
Jake Ehrlich76e91102018-01-25 22:46:17 +0000282void SymbolTableSection::accept(SectionVisitor &Visitor) const {
283 Visitor.visit(*this);
284}
285
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000286template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000287void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
288 const SectionBase *Sec) {
289 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000290 error("Symbol table " + Symbols->Name +
291 " cannot be removed because it is "
292 "referenced by the relocation "
293 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000294 this->Name);
295 }
296}
297
298template <class SymTabType>
299void RelocSectionWithSymtabBase<SymTabType>::initialize(
300 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000301 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000302 Link,
303 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
304 "Link field value " + Twine(Link) + " in section " + Name +
305 " is not a symbol table"));
306
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000307 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000308 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
309 " in section " + Name +
310 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000311 else
312 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000313}
314
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000315template <class SymTabType>
316void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000317 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000318 if (SecToApplyRel != nullptr)
319 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000320}
321
322template <class ELFT>
323void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
324
325template <class ELFT>
326void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
327 Rela.r_addend = Addend;
328}
329
Jake Ehrlich76e91102018-01-25 22:46:17 +0000330template <class RelRange, class T>
331void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000332 for (const auto &Reloc : Relocations) {
333 Buf->r_offset = Reloc.Offset;
334 setAddend(*Buf, Reloc.Addend);
335 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
336 ++Buf;
337 }
338}
339
340template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000341void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
342 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
343 if (Sec.Type == SHT_REL)
344 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000345 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000346 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000347}
348
Jake Ehrlich76e91102018-01-25 22:46:17 +0000349void RelocationSection::accept(SectionVisitor &Visitor) const {
350 Visitor.visit(*this);
351}
352
Paul Semel4246a462018-05-09 21:36:54 +0000353void RelocationSection::removeSymbols(
354 function_ref<bool(const Symbol &)> ToRemove) {
355 for (const Relocation &Reloc : Relocations)
356 if (ToRemove(*Reloc.RelocSymbol))
357 error("not stripping symbol `" + Reloc.RelocSymbol->Name +
358 "' because it is named in a relocation");
359}
360
Paul Semel99dda0b2018-05-25 11:01:25 +0000361void RelocationSection::markSymbols() {
362 for (const Relocation &Reloc : Relocations)
363 Reloc.RelocSymbol->Referenced = true;
364}
365
Jake Ehrlich76e91102018-01-25 22:46:17 +0000366void SectionWriter::visit(const DynamicRelocationSection &Sec) {
367 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
368 Out.getBufferStart() + Sec.Offset);
369}
370
371void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
372 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000373}
374
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000375void Section::removeSectionReferences(const SectionBase *Sec) {
376 if (LinkSection == Sec) {
377 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000378 " cannot be removed because it is "
379 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000380 this->Name);
381 }
382}
383
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000384void GroupSection::finalize() {
385 this->Info = Sym->Index;
386 this->Link = SymTab->Index;
387}
388
Paul Semel4246a462018-05-09 21:36:54 +0000389void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
390 if (ToRemove(*Sym)) {
391 error("Symbol " + Sym->Name +
392 " cannot be removed because it is "
393 "referenced by the section " +
394 this->Name + "[" + Twine(this->Index) + "]");
395 }
396}
397
Paul Semel99dda0b2018-05-25 11:01:25 +0000398void GroupSection::markSymbols() {
399 if (Sym)
400 Sym->Referenced = true;
401}
402
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000403void Section::initialize(SectionTableRef SecTable) {
404 if (Link != ELF::SHN_UNDEF)
405 LinkSection =
406 SecTable.getSection(Link, "Link field value " + Twine(Link) +
407 " in section " + Name + " is invalid");
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000408}
409
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000410void Section::finalize() {
411 if (LinkSection)
412 this->Link = LinkSection->Index;
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000413}
414
Jake Ehrlich76e91102018-01-25 22:46:17 +0000415void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000416 FileName = sys::path::filename(File);
417 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000418 // followed by a null terminator and then the CRC32 of the file. The CRC32
419 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
420 // byte, and then finally push the size to alignment and add 4.
421 Size = alignTo(FileName.size() + 1, 4) + 4;
422 // The CRC32 will only be aligned if we align the whole section.
423 Align = 4;
424 Type = ELF::SHT_PROGBITS;
425 Name = ".gnu_debuglink";
426 // For sections not found in segments, OriginalOffset is only used to
427 // establish the order that sections should go in. By using the maximum
428 // possible offset we cause this section to wind up at the end.
429 OriginalOffset = std::numeric_limits<uint64_t>::max();
430 JamCRC crc;
431 crc.update(ArrayRef<char>(Data.data(), Data.size()));
432 // The CRC32 value needs to be complemented because the JamCRC dosn't
433 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
434 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
435 CRC32 = ~crc.getCRC();
436}
437
Jake Ehrlich76e91102018-01-25 22:46:17 +0000438GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000439 // Read in the file to compute the CRC of it.
440 auto DebugOrErr = MemoryBuffer::getFile(File);
441 if (!DebugOrErr)
442 error("'" + File + "': " + DebugOrErr.getError().message());
443 auto Debug = std::move(*DebugOrErr);
444 init(File, Debug->getBuffer());
445}
446
447template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000448void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
449 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000450 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000451 Elf_Word *CRC =
452 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
453 *CRC = Sec.CRC32;
454 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
455}
456
457void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
458 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000459}
460
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000461template <class ELFT>
462void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
463 ELF::Elf32_Word *Buf =
464 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
465 *Buf++ = Sec.FlagWord;
466 for (const auto *S : Sec.GroupMembers)
467 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
468}
469
470void GroupSection::accept(SectionVisitor &Visitor) const {
471 Visitor.visit(*this);
472}
473
Petr Hosek05a04cb2017-08-01 00:33:58 +0000474// Returns true IFF a section is wholly inside the range of a segment
475static bool sectionWithinSegment(const SectionBase &Section,
476 const Segment &Segment) {
477 // If a section is empty it should be treated like it has a size of 1. This is
478 // to clarify the case when an empty section lies on a boundary between two
479 // segments and ensures that the section "belongs" to the second segment and
480 // not the first.
481 uint64_t SecSize = Section.Size ? Section.Size : 1;
482 return Segment.Offset <= Section.OriginalOffset &&
483 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
484}
485
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000486// Returns true IFF a segment's original offset is inside of another segment's
487// range.
488static bool segmentOverlapsSegment(const Segment &Child,
489 const Segment &Parent) {
490
491 return Parent.OriginalOffset <= Child.OriginalOffset &&
492 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
493}
494
Jake Ehrlich46814be2018-01-22 19:27:30 +0000495static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000496 // Any segment without a parent segment should come before a segment
497 // that has a parent segment.
498 if (A->OriginalOffset < B->OriginalOffset)
499 return true;
500 if (A->OriginalOffset > B->OriginalOffset)
501 return false;
502 return A->Index < B->Index;
503}
504
Jake Ehrlich46814be2018-01-22 19:27:30 +0000505static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
506 if (A->PAddr < B->PAddr)
507 return true;
508 if (A->PAddr > B->PAddr)
509 return false;
510 return A->Index < B->Index;
511}
512
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000513template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000514 for (auto &Parent : Obj.segments()) {
515 // Every segment will overlap with itself but we don't want a segment to
516 // be it's own parent so we avoid that situation.
517 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
518 // We want a canonical "most parental" segment but this requires
519 // inspecting the ParentSegment.
520 if (compareSegmentsByOffset(&Parent, &Child))
521 if (Child.ParentSegment == nullptr ||
522 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
523 Child.ParentSegment = &Parent;
524 }
525 }
526 }
527}
528
Jake Ehrlich76e91102018-01-25 22:46:17 +0000529template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000530 uint32_t Index = 0;
531 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000532 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
533 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000534 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000535 Seg.Type = Phdr.p_type;
536 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000537 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000538 Seg.Offset = Phdr.p_offset;
539 Seg.VAddr = Phdr.p_vaddr;
540 Seg.PAddr = Phdr.p_paddr;
541 Seg.FileSize = Phdr.p_filesz;
542 Seg.MemSize = Phdr.p_memsz;
543 Seg.Align = Phdr.p_align;
544 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000545 for (auto &Section : Obj.sections()) {
546 if (sectionWithinSegment(Section, Seg)) {
547 Seg.addSection(&Section);
548 if (!Section.ParentSegment ||
549 Section.ParentSegment->Offset > Seg.Offset) {
550 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000551 }
552 }
553 }
554 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000555
556 auto &ElfHdr = Obj.ElfHdrSegment;
557 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
558 // segments must not overlap, and other types fit even less.
559 ElfHdr.Type = PT_PHDR;
560 ElfHdr.Flags = 0;
561 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
562 ElfHdr.VAddr = 0;
563 ElfHdr.PAddr = 0;
564 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
565 ElfHdr.Align = 0;
566 ElfHdr.Index = Index++;
567
568 const auto &Ehdr = *ElfFile.getHeader();
569 auto &PrHdr = Obj.ProgramHdrSegment;
570 PrHdr.Type = PT_PHDR;
571 PrHdr.Flags = 0;
572 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
573 // Whereas this works automatically for ElfHdr, here OriginalOffset is
574 // always non-zero and to ensure the equation we assign the same value to
575 // VAddr as well.
576 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
577 PrHdr.PAddr = 0;
578 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000579 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000580 PrHdr.Align = sizeof(Elf_Addr);
581 PrHdr.Index = Index++;
582
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000583 // Now we do an O(n^2) loop through the segments in order to match up
584 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000585 for (auto &Child : Obj.segments())
586 setParentSegment(Child);
587 setParentSegment(ElfHdr);
588 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000589}
590
591template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000592void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
593 auto SecTable = Obj.sections();
594 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
595 GroupSec->Link,
596 "Link field value " + Twine(GroupSec->Link) + " in section " +
597 GroupSec->Name + " is invalid",
598 "Link field value " + Twine(GroupSec->Link) + " in section " +
599 GroupSec->Name + " is not a symbol table");
600 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
601 if (!Sym)
602 error("Info field value " + Twine(GroupSec->Info) + " in section " +
603 GroupSec->Name + " is not a valid symbol index");
604 GroupSec->setSymTab(SymTab);
605 GroupSec->setSymbol(Sym);
606 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
607 GroupSec->Contents.empty())
608 error("The content of the section " + GroupSec->Name + " is malformed");
609 const ELF::Elf32_Word *Word =
610 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
611 const ELF::Elf32_Word *End =
612 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
613 GroupSec->setFlagWord(*Word++);
614 for (; Word != End; ++Word) {
615 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
616 GroupSec->addMember(SecTable.getSection(
617 Index, "Group member index " + Twine(Index) + " in section " +
618 GroupSec->Name + " is invalid"));
619 }
620}
621
622template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000623void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000624 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
625 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
626
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000627 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000628 SectionBase *DefSection = nullptr;
629 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000630
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000631 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000632 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000633 error(
634 "Symbol '" + Name +
635 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
636 Twine(Sym.st_shndx));
637 }
638 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000639 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000640 Sym.st_shndx, "Symbol '" + Name +
641 "' is defined in invalid section with index " +
642 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000643 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000644
Petr Hosek79cee9e2017-08-29 02:12:03 +0000645 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000646 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000647 }
648}
649
650template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000651static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
652
653template <class ELFT>
654static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
655 ToSet = Rela.r_addend;
656}
657
Jake Ehrlich76e91102018-01-25 22:46:17 +0000658template <class T>
659void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
660 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000661 for (const auto &Rel : RelRange) {
662 Relocation ToAdd;
663 ToAdd.Offset = Rel.r_offset;
664 getAddend(ToAdd.Addend, Rel);
665 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000666 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000667 Relocs->addRelocation(ToAdd);
668 }
669}
670
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000671SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000672 if (Index == SHN_UNDEF || Index > Sections.size())
673 error(ErrMsg);
674 return Sections[Index - 1].get();
675}
676
677template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000678T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000679 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000680 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000681 return Sec;
682 error(TypeErrMsg);
683}
684
Petr Hosekd7df9b22017-09-06 23:41:02 +0000685template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000686SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000687 ArrayRef<uint8_t> Data;
688 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000689 case SHT_REL:
690 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000691 if (Shdr.sh_flags & SHF_ALLOC) {
692 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000693 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000694 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000695 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000696 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000697 // If a string table is allocated we don't want to mess with it. That would
698 // mean altering the memory image. There are no special link types or
699 // anything so we can just use a Section.
700 if (Shdr.sh_flags & SHF_ALLOC) {
701 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000702 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000703 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000704 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000705 case SHT_HASH:
706 case SHT_GNU_HASH:
707 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
708 // Because of this we don't need to mess with the hash tables either.
709 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000710 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000711 case SHT_GROUP:
712 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
713 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000714 case SHT_DYNSYM:
715 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000716 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000717 case SHT_DYNAMIC:
718 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000719 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000720 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000721 auto &SymTab = Obj.addSection<SymbolTableSection>();
722 Obj.SymbolTable = &SymTab;
723 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000724 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000725 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000726 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000727 default:
728 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000729 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000730 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000731}
732
Jake Ehrlich76e91102018-01-25 22:46:17 +0000733template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000734 uint32_t Index = 0;
735 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
736 if (Index == 0) {
737 ++Index;
738 continue;
739 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000740 auto &Sec = makeSection(Shdr);
741 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
742 Sec.Type = Shdr.sh_type;
743 Sec.Flags = Shdr.sh_flags;
744 Sec.Addr = Shdr.sh_addr;
745 Sec.Offset = Shdr.sh_offset;
746 Sec.OriginalOffset = Shdr.sh_offset;
747 Sec.Size = Shdr.sh_size;
748 Sec.Link = Shdr.sh_link;
749 Sec.Info = Shdr.sh_info;
750 Sec.Align = Shdr.sh_addralign;
751 Sec.EntrySize = Shdr.sh_entsize;
752 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000753 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000754
755 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000756 // details about symbol tables. We need the symbol table filled out before
757 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000758 if (Obj.SymbolTable) {
759 Obj.SymbolTable->initialize(Obj.sections());
760 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000761 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000762
763 // Now that all sections and symbols have been added we can add
764 // relocations that reference symbols and set the link and info fields for
765 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000766 for (auto &Section : Obj.sections()) {
767 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000768 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000769 Section.initialize(Obj.sections());
770 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000771 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
772 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000773 initRelocations(RelSec, Obj.SymbolTable,
774 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000775 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000776 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000777 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000778 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
779 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000780 }
781 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000782}
783
Jake Ehrlich76e91102018-01-25 22:46:17 +0000784template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000785 const auto &Ehdr = *ElfFile.getHeader();
786
Jake Ehrlich76e91102018-01-25 22:46:17 +0000787 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
788 Obj.Type = Ehdr.e_type;
789 Obj.Machine = Ehdr.e_machine;
790 Obj.Version = Ehdr.e_version;
791 Obj.Entry = Ehdr.e_entry;
792 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000793
Jake Ehrlich76e91102018-01-25 22:46:17 +0000794 readSectionHeaders();
795 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000796
Jake Ehrlich76e91102018-01-25 22:46:17 +0000797 Obj.SectionNames =
798 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000799 Ehdr.e_shstrndx,
800 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000801 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000802 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000803 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000804}
805
Jake Ehrlich76e91102018-01-25 22:46:17 +0000806// A generic size function which computes sizes of any random access range.
807template <class R> size_t size(R &&Range) {
808 return static_cast<size_t>(std::end(Range) - std::begin(Range));
809}
810
811Writer::~Writer() {}
812
813Reader::~Reader() {}
814
815ELFReader::ELFReader(StringRef File) {
816 auto BinaryOrErr = createBinary(File);
817 if (!BinaryOrErr)
818 reportError(File, BinaryOrErr.takeError());
Jake Ehrlich9634e182018-01-26 02:01:37 +0000819 auto OwnedBin = std::move(BinaryOrErr.get());
820 std::tie(Bin, Data) = OwnedBin.takeBinary();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000821}
822
823ElfType ELFReader::getElfType() const {
Jake Ehrlich9634e182018-01-26 02:01:37 +0000824 if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000825 return ELFT_ELF32LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000826 if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000827 return ELFT_ELF64LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000828 if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000829 return ELFT_ELF32BE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000830 if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000831 return ELFT_ELF64BE;
832 llvm_unreachable("Invalid ELFType");
833}
834
835std::unique_ptr<Object> ELFReader::create() const {
836 auto Obj = llvm::make_unique<Object>(Data);
Jake Ehrlich9634e182018-01-26 02:01:37 +0000837 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000838 ELFBuilder<ELF32LE> Builder(*o, *Obj);
839 Builder.build();
840 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000841 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000842 ELFBuilder<ELF64LE> Builder(*o, *Obj);
843 Builder.build();
844 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000845 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000846 ELFBuilder<ELF32BE> Builder(*o, *Obj);
847 Builder.build();
848 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000849 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000850 ELFBuilder<ELF64BE> Builder(*o, *Obj);
851 Builder.build();
852 return Obj;
853 }
854 error("Invalid file type");
855}
856
857template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
858 uint8_t *Buf = BufPtr->getBufferStart();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000859 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000860 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
861 Ehdr.e_type = Obj.Type;
862 Ehdr.e_machine = Obj.Machine;
863 Ehdr.e_version = Obj.Version;
864 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000865 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000866 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000867 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
868 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000869 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000870 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000871 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000872 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000873 Ehdr.e_shnum = size(Obj.sections()) + 1;
874 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000875 } else {
876 Ehdr.e_shoff = 0;
877 Ehdr.e_shnum = 0;
878 Ehdr.e_shstrndx = 0;
879 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000880}
881
Jake Ehrlich76e91102018-01-25 22:46:17 +0000882template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
883 for (auto &Seg : Obj.segments())
884 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000885}
886
Jake Ehrlich76e91102018-01-25 22:46:17 +0000887template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
888 uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000889 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000890 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000891 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
892 Shdr.sh_name = 0;
893 Shdr.sh_type = SHT_NULL;
894 Shdr.sh_flags = 0;
895 Shdr.sh_addr = 0;
896 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000897 Shdr.sh_size = 0;
898 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000899 Shdr.sh_info = 0;
900 Shdr.sh_addralign = 0;
901 Shdr.sh_entsize = 0;
902
Jake Ehrlich76e91102018-01-25 22:46:17 +0000903 for (auto &Sec : Obj.sections())
904 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000905}
906
Jake Ehrlich76e91102018-01-25 22:46:17 +0000907template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
908 for (auto &Sec : Obj.sections())
909 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000910}
911
Jake Ehrlich76e91102018-01-25 22:46:17 +0000912void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000913
914 auto Iter = std::stable_partition(
915 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
916 if (ToRemove(*Sec))
917 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000918 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
919 if (auto ToRelSec = RelSec->getSection())
920 return !ToRemove(*ToRelSec);
921 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000922 return true;
923 });
924 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
925 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000926 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000927 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000928 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000929 // Now make sure there are no remaining references to the sections that will
930 // be removed. Sometimes it is impossible to remove a reference so we emit
931 // an error here instead.
932 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
933 for (auto &Segment : Segments)
934 Segment->removeSection(RemoveSec.get());
935 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
936 KeepSec->removeSectionReferences(RemoveSec.get());
937 }
938 // Now finally get rid of them all togethor.
939 Sections.erase(Iter, std::end(Sections));
940}
941
Paul Semel4246a462018-05-09 21:36:54 +0000942void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
943 if (!SymbolTable)
944 return;
945
946 for (const SecPtr &Sec : Sections)
947 Sec->removeSymbols(ToRemove);
948}
949
Jake Ehrlich76e91102018-01-25 22:46:17 +0000950void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000951 // Put all sections in offset order. Maintain the ordering as closely as
952 // possible while meeting that demand however.
953 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
954 return A->OriginalOffset < B->OriginalOffset;
955 };
956 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
957 CompareSections);
958}
959
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000960static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
961 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
962 if (Align == 0)
963 Align = 1;
964 auto Diff =
965 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
966 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
967 // (Offset + Diff) & -Align == Addr & -Align will still hold.
968 if (Diff < 0)
969 Diff += Align;
970 return Offset + Diff;
971}
972
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000973// Orders segments such that if x = y->ParentSegment then y comes before x.
974static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000975 std::stable_sort(std::begin(Segments), std::end(Segments),
976 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000977}
978
979// This function finds a consistent layout for a list of segments starting from
980// an Offset. It assumes that Segments have been sorted by OrderSegments and
981// returns an Offset one past the end of the last segment.
982static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
983 uint64_t Offset) {
984 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +0000985 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +0000986 // The only way a segment should move is if a section was between two
987 // segments and that section was removed. If that section isn't in a segment
988 // then it's acceptable, but not ideal, to simply move it to after the
989 // segments. So we can simply layout segments one after the other accounting
990 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000991 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000992 // We assume that segments have been ordered by OriginalOffset and Index
993 // such that a parent segment will always come before a child segment in
994 // OrderedSegments. This means that the Offset of the ParentSegment should
995 // already be set and we can set our offset relative to it.
996 if (Segment->ParentSegment != nullptr) {
997 auto Parent = Segment->ParentSegment;
998 Segment->Offset =
999 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1000 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001001 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001002 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001003 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001004 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001005 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001006 return Offset;
1007}
1008
1009// This function finds a consistent layout for a list of sections. It assumes
1010// that the ->ParentSegment of each section has already been laid out. The
1011// supplied starting Offset is used for the starting offset of any section that
1012// does not have a ParentSegment. It returns either the offset given if all
1013// sections had a ParentSegment or an offset one past the last section if there
1014// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001015template <class Range>
1016static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001017 // Now the offset of every segment has been set we can assign the offsets
1018 // of each section. For sections that are covered by a segment we should use
1019 // the segment's original offset and the section's original offset to compute
1020 // the offset from the start of the segment. Using the offset from the start
1021 // of the segment we can assign a new offset to the section. For sections not
1022 // covered by segments we can just bump Offset to the next valid location.
1023 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001024 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001025 Section.Index = Index++;
1026 if (Section.ParentSegment != nullptr) {
1027 auto Segment = *Section.ParentSegment;
1028 Section.Offset =
1029 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001030 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001031 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1032 Section.Offset = Offset;
1033 if (Section.Type != SHT_NOBITS)
1034 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001035 }
1036 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001037 return Offset;
1038}
Petr Hosek3f383832017-08-26 01:32:20 +00001039
Jake Ehrlich76e91102018-01-25 22:46:17 +00001040template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001041 // We need a temporary list of segments that has a special order to it
1042 // so that we know that anytime ->ParentSegment is set that segment has
1043 // already had its offset properly set.
1044 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001045 for (auto &Segment : Obj.segments())
1046 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001047 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1048 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001049 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001050 // Offset is used as the start offset of the first segment to be laid out.
1051 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1052 // we start at offset 0.
1053 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001054 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001055 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001056 // If we need to write the section header table out then we need to align the
1057 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001058 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001059 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001060 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001061}
1062
Jake Ehrlich76e91102018-01-25 22:46:17 +00001063template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001064 // We already have the section header offset so we can calculate the total
1065 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001066 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1067 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001068 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001069}
1070
Jake Ehrlich76e91102018-01-25 22:46:17 +00001071template <class ELFT> void ELFWriter<ELFT>::write() {
1072 writeEhdr();
1073 writePhdrs();
1074 writeSectionData();
1075 if (WriteSectionHeaders)
1076 writeShdrs();
1077 if (auto E = BufPtr->commit())
1078 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001079}
1080
Jake Ehrlich76e91102018-01-25 22:46:17 +00001081void Writer::createBuffer(uint64_t Size) {
1082 auto BufferOrErr =
1083 FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
1084 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
1085 error("failed to open " + File);
1086 });
1087 BufPtr = std::move(*BufferOrErr);
1088}
1089
1090template <class ELFT> void ELFWriter<ELFT>::finalize() {
1091 // It could happen that SectionNames has been removed and yet the user wants
1092 // a section header table output. We need to throw an error if a user tries
1093 // to do that.
1094 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1095 error("Cannot write section header table because section header string "
1096 "table was removed.");
1097
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001098 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001099 if (Obj.SectionNames != nullptr)
1100 for (const auto &Section : Obj.sections()) {
1101 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001102 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001103 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001104 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001105 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001106
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001107 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001108 assignOffsets();
1109
1110 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001111 if (Obj.SectionNames != nullptr)
1112 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001113 // Finally now that all offsets and indexes have been set we can finalize any
1114 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001115 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1116 for (auto &Section : Obj.sections()) {
1117 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001118 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001119 if (WriteSectionHeaders)
1120 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1121 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001122 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001123
1124 createBuffer(totalSize());
1125 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001126}
1127
Jake Ehrlich76e91102018-01-25 22:46:17 +00001128void BinaryWriter::write() {
1129 for (auto &Section : Obj.sections()) {
1130 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001131 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001132 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001133 }
Jake Ehrlichc0e9bee2018-01-26 01:17:35 +00001134 if (auto E = BufPtr->commit())
1135 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001136}
1137
Jake Ehrlich76e91102018-01-25 22:46:17 +00001138void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001139 // TODO: Create a filter range to construct OrderedSegments from so that this
1140 // code can be deduped with assignOffsets above. This should also solve the
1141 // todo below for LayoutSections.
1142 // We need a temporary list of segments that has a special order to it
1143 // so that we know that anytime ->ParentSegment is set that segment has
1144 // already had it's offset properly set. We only want to consider the segments
1145 // that will affect layout of allocated sections so we only add those.
1146 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001147 for (auto &Section : Obj.sections()) {
1148 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1149 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001150 }
1151 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001152
1153 // For binary output, we're going to use physical addresses instead of
1154 // virtual addresses, since a binary output is used for cases like ROM
1155 // loading and physical addresses are intended for ROM loading.
1156 // However, if no segment has a physical address, we'll fallback to using
1157 // virtual addresses for all.
1158 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1159 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1160 for (const auto &Segment : OrderedSegments)
1161 Segment->PAddr = Segment->VAddr;
1162
1163 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1164 compareSegmentsByPAddr);
1165
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001166 // Because we add a ParentSegment for each section we might have duplicate
1167 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1168 // would do very strange things.
1169 auto End =
1170 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1171 OrderedSegments.erase(End, std::end(OrderedSegments));
1172
Jake Ehrlich46814be2018-01-22 19:27:30 +00001173 uint64_t Offset = 0;
1174
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001175 // Modify the first segment so that there is no gap at the start. This allows
1176 // our layout algorithm to proceed as expected while not out writing out the
1177 // gap at the start.
1178 if (!OrderedSegments.empty()) {
1179 auto Seg = OrderedSegments[0];
1180 auto Sec = Seg->firstSection();
1181 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1182 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001183 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001184 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001185 // The PAddr needs to be increased to remove the gap before the first
1186 // section.
1187 Seg->PAddr += Diff;
1188 uint64_t LowestPAddr = Seg->PAddr;
1189 for (auto &Segment : OrderedSegments) {
1190 Segment->Offset = Segment->PAddr - LowestPAddr;
1191 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1192 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001193 }
1194
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001195 // TODO: generalize LayoutSections to take a range. Pass a special range
1196 // constructed from an iterator that skips values for which a predicate does
1197 // not hold. Then pass such a range to LayoutSections instead of constructing
1198 // AllocatedSections here.
1199 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001200 for (auto &Section : Obj.sections()) {
1201 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001202 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001203 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001204 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001205 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001206
1207 // Now that every section has been laid out we just need to compute the total
1208 // file size. This might not be the same as the offset returned by
1209 // LayoutSections, because we want to truncate the last segment to the end of
1210 // its last section, to match GNU objcopy's behaviour.
1211 TotalSize = 0;
1212 for (const auto &Section : AllocatedSections) {
1213 if (Section->Type != SHT_NOBITS)
1214 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1215 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001216
1217 createBuffer(TotalSize);
1218 SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001219}
1220
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001221namespace llvm {
1222
Jake Ehrlich76e91102018-01-25 22:46:17 +00001223template class ELFBuilder<ELF64LE>;
1224template class ELFBuilder<ELF64BE>;
1225template class ELFBuilder<ELF32LE>;
1226template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001227
Jake Ehrlich76e91102018-01-25 22:46:17 +00001228template class ELFWriter<ELF64LE>;
1229template class ELFWriter<ELF64BE>;
1230template class ELFWriter<ELF32LE>;
1231template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001232} // end namespace llvm