blob: 07b60367b9e20cf142911e75cb21ad6ace1815ed [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) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000050void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000051void SectionBase::finalize() {}
52
Jake Ehrlich76e91102018-01-25 22:46:17 +000053template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
54 uint8_t *Buf = BufPtr->getBufferStart();
55 Buf += Sec.HeaderOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +000056 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000057 Shdr.sh_name = Sec.NameIndex;
58 Shdr.sh_type = Sec.Type;
59 Shdr.sh_flags = Sec.Flags;
60 Shdr.sh_addr = Sec.Addr;
61 Shdr.sh_offset = Sec.Offset;
62 Shdr.sh_size = Sec.Size;
63 Shdr.sh_link = Sec.Link;
64 Shdr.sh_info = Sec.Info;
65 Shdr.sh_addralign = Sec.Align;
66 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000067}
68
Jake Ehrlich76e91102018-01-25 22:46:17 +000069SectionVisitor::~SectionVisitor() {}
70
71void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
72 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
73}
74
75void BinarySectionWriter::visit(const RelocationSection &Sec) {
76 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
77}
78
79void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +000080 error("Cannot write '" + Sec.Name + "' out to binary");
81}
82
83void BinarySectionWriter::visit(const GroupSection &Sec) {
84 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +000085}
86
87void SectionWriter::visit(const Section &Sec) {
88 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +000089 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +000090 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
91 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +000092}
93
Jake Ehrlich76e91102018-01-25 22:46:17 +000094void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
95
96void SectionWriter::visit(const OwnedDataSection &Sec) {
97 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
98 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
99}
100
101void OwnedDataSection::accept(SectionVisitor &Visitor) const {
102 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000103}
104
Petr Hosek05a04cb2017-08-01 00:33:58 +0000105void StringTableSection::addString(StringRef Name) {
106 StrTabBuilder.add(Name);
107 Size = StrTabBuilder.getSize();
108}
109
110uint32_t StringTableSection::findIndex(StringRef Name) const {
111 return StrTabBuilder.getOffset(Name);
112}
113
114void StringTableSection::finalize() { StrTabBuilder.finalize(); }
115
Jake Ehrlich76e91102018-01-25 22:46:17 +0000116void SectionWriter::visit(const StringTableSection &Sec) {
117 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
118}
119
120void StringTableSection::accept(SectionVisitor &Visitor) const {
121 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000122}
123
Petr Hosekc1135772017-09-13 03:04:50 +0000124static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000125 switch (Index) {
126 case SHN_ABS:
127 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000128 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000129 }
Petr Hosekc1135772017-09-13 03:04:50 +0000130 if (Machine == EM_HEXAGON) {
131 switch (Index) {
132 case SHN_HEXAGON_SCOMMON:
133 case SHN_HEXAGON_SCOMMON_2:
134 case SHN_HEXAGON_SCOMMON_4:
135 case SHN_HEXAGON_SCOMMON_8:
136 return true;
137 }
138 }
139 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000140}
141
142uint16_t Symbol::getShndx() const {
143 if (DefinedIn != nullptr) {
144 return DefinedIn->Index;
145 }
146 switch (ShndxType) {
147 // This means that we don't have a defined section but we do need to
148 // output a legitimate section index.
149 case SYMBOL_SIMPLE_INDEX:
150 return SHN_UNDEF;
151 case SYMBOL_ABS:
152 case SYMBOL_COMMON:
153 case SYMBOL_HEXAGON_SCOMMON:
154 case SYMBOL_HEXAGON_SCOMMON_2:
155 case SYMBOL_HEXAGON_SCOMMON_4:
156 case SYMBOL_HEXAGON_SCOMMON_8:
157 return static_cast<uint16_t>(ShndxType);
158 }
159 llvm_unreachable("Symbol with invalid ShndxType encountered");
160}
161
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000162void SymbolTableSection::assignIndices() {
163 uint32_t Index = 0;
164 for (auto &Sym : Symbols)
165 Sym->Index = Index++;
166}
167
Petr Hosek79cee9e2017-08-29 02:12:03 +0000168void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
169 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000170 uint8_t Visibility, uint16_t Shndx,
171 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000172 Symbol Sym;
173 Sym.Name = Name;
174 Sym.Binding = Bind;
175 Sym.Type = Type;
176 Sym.DefinedIn = DefinedIn;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000177 if (DefinedIn == nullptr) {
178 if (Shndx >= SHN_LORESERVE)
179 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
180 else
181 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
182 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000183 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000184 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000185 Sym.Size = Sz;
186 Sym.Index = Symbols.size();
187 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
188 Size += this->EntrySize;
189}
190
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000191void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
192 if (SymbolNames == Sec) {
193 error("String table " + SymbolNames->Name +
194 " cannot be removed because it is referenced by the symbol table " +
195 this->Name);
196 }
197 auto Iter =
198 std::remove_if(std::begin(Symbols), std::end(Symbols),
199 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
200 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
201 Symbols.erase(Iter, std::end(Symbols));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000202 assignIndices();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000203}
204
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000205void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
206 for (auto &Sym : Symbols)
207 Callable(*Sym);
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000208 std::stable_partition(
209 std::begin(Symbols), std::end(Symbols),
210 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000211 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000212}
213
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000214void SymbolTableSection::initialize(SectionTableRef SecTable) {
215 Size = 0;
216 setStrTab(SecTable.getSectionOfType<StringTableSection>(
217 Link,
218 "Symbol table has link index of " + Twine(Link) +
219 " which is not a valid index",
220 "Symbol table has link index of " + Twine(Link) +
221 " which is not a string table"));
222}
223
Petr Hosek79cee9e2017-08-29 02:12:03 +0000224void SymbolTableSection::finalize() {
225 // Make sure SymbolNames is finalized before getting name indexes.
226 SymbolNames->finalize();
227
228 uint32_t MaxLocalIndex = 0;
229 for (auto &Sym : Symbols) {
230 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
231 if (Sym->Binding == STB_LOCAL)
232 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
233 }
234 // Now we need to set the Link and Info fields.
235 Link = SymbolNames->Index;
236 Info = MaxLocalIndex + 1;
237}
238
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000239void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000240 // Add all of our strings to SymbolNames so that SymbolNames has the right
241 // size before layout is decided.
242 for (auto &Sym : Symbols)
243 SymbolNames->addString(Sym->Name);
244}
245
246const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
247 if (Symbols.size() <= Index)
248 error("Invalid symbol index: " + Twine(Index));
249 return Symbols[Index].get();
250}
251
252template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000253void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000254 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000255 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000256 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
257 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000258 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000259 Sym->st_name = Symbol->NameIndex;
260 Sym->st_value = Symbol->Value;
261 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000262 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000263 Sym->setBinding(Symbol->Binding);
264 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000265 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000266 ++Sym;
267 }
268}
269
Jake Ehrlich76e91102018-01-25 22:46:17 +0000270void SymbolTableSection::accept(SectionVisitor &Visitor) const {
271 Visitor.visit(*this);
272}
273
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000274template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000275void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
276 const SectionBase *Sec) {
277 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000278 error("Symbol table " + Symbols->Name +
279 " cannot be removed because it is "
280 "referenced by the relocation "
281 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000282 this->Name);
283 }
284}
285
286template <class SymTabType>
287void RelocSectionWithSymtabBase<SymTabType>::initialize(
288 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000289 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000290 Link,
291 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
292 "Link field value " + Twine(Link) + " in section " + Name +
293 " is not a symbol table"));
294
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000295 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000296 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
297 " in section " + Name +
298 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000299 else
300 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000301}
302
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000303template <class SymTabType>
304void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000305 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000306 if (SecToApplyRel != nullptr)
307 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000308}
309
310template <class ELFT>
311void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
312
313template <class ELFT>
314void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
315 Rela.r_addend = Addend;
316}
317
Jake Ehrlich76e91102018-01-25 22:46:17 +0000318template <class RelRange, class T>
319void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000320 for (const auto &Reloc : Relocations) {
321 Buf->r_offset = Reloc.Offset;
322 setAddend(*Buf, Reloc.Addend);
323 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
324 ++Buf;
325 }
326}
327
328template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000329void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
330 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
331 if (Sec.Type == SHT_REL)
332 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000333 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000334 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000335}
336
Jake Ehrlich76e91102018-01-25 22:46:17 +0000337void RelocationSection::accept(SectionVisitor &Visitor) const {
338 Visitor.visit(*this);
339}
340
341void SectionWriter::visit(const DynamicRelocationSection &Sec) {
342 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
343 Out.getBufferStart() + Sec.Offset);
344}
345
346void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
347 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000348}
349
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000350void Section::removeSectionReferences(const SectionBase *Sec) {
351 if (LinkSection == Sec) {
352 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000353 " cannot be removed because it is "
354 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000355 this->Name);
356 }
357}
358
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000359void GroupSection::finalize() {
360 this->Info = Sym->Index;
361 this->Link = SymTab->Index;
362}
363
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000364void Section::initialize(SectionTableRef SecTable) {
365 if (Link != ELF::SHN_UNDEF)
366 LinkSection =
367 SecTable.getSection(Link, "Link field value " + Twine(Link) +
368 " in section " + Name + " is invalid");
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000369}
370
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000371void Section::finalize() {
372 if (LinkSection)
373 this->Link = LinkSection->Index;
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000374}
375
Jake Ehrlich76e91102018-01-25 22:46:17 +0000376void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000377 FileName = sys::path::filename(File);
378 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000379 // followed by a null terminator and then the CRC32 of the file. The CRC32
380 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
381 // byte, and then finally push the size to alignment and add 4.
382 Size = alignTo(FileName.size() + 1, 4) + 4;
383 // The CRC32 will only be aligned if we align the whole section.
384 Align = 4;
385 Type = ELF::SHT_PROGBITS;
386 Name = ".gnu_debuglink";
387 // For sections not found in segments, OriginalOffset is only used to
388 // establish the order that sections should go in. By using the maximum
389 // possible offset we cause this section to wind up at the end.
390 OriginalOffset = std::numeric_limits<uint64_t>::max();
391 JamCRC crc;
392 crc.update(ArrayRef<char>(Data.data(), Data.size()));
393 // The CRC32 value needs to be complemented because the JamCRC dosn't
394 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
395 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
396 CRC32 = ~crc.getCRC();
397}
398
Jake Ehrlich76e91102018-01-25 22:46:17 +0000399GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000400 // Read in the file to compute the CRC of it.
401 auto DebugOrErr = MemoryBuffer::getFile(File);
402 if (!DebugOrErr)
403 error("'" + File + "': " + DebugOrErr.getError().message());
404 auto Debug = std::move(*DebugOrErr);
405 init(File, Debug->getBuffer());
406}
407
408template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000409void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
410 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000411 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000412 Elf_Word *CRC =
413 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
414 *CRC = Sec.CRC32;
415 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
416}
417
418void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
419 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000420}
421
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000422template <class ELFT>
423void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
424 ELF::Elf32_Word *Buf =
425 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
426 *Buf++ = Sec.FlagWord;
427 for (const auto *S : Sec.GroupMembers)
428 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
429}
430
431void GroupSection::accept(SectionVisitor &Visitor) const {
432 Visitor.visit(*this);
433}
434
Petr Hosek05a04cb2017-08-01 00:33:58 +0000435// Returns true IFF a section is wholly inside the range of a segment
436static bool sectionWithinSegment(const SectionBase &Section,
437 const Segment &Segment) {
438 // If a section is empty it should be treated like it has a size of 1. This is
439 // to clarify the case when an empty section lies on a boundary between two
440 // segments and ensures that the section "belongs" to the second segment and
441 // not the first.
442 uint64_t SecSize = Section.Size ? Section.Size : 1;
443 return Segment.Offset <= Section.OriginalOffset &&
444 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
445}
446
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000447// Returns true IFF a segment's original offset is inside of another segment's
448// range.
449static bool segmentOverlapsSegment(const Segment &Child,
450 const Segment &Parent) {
451
452 return Parent.OriginalOffset <= Child.OriginalOffset &&
453 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
454}
455
Jake Ehrlich46814be2018-01-22 19:27:30 +0000456static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000457 // Any segment without a parent segment should come before a segment
458 // that has a parent segment.
459 if (A->OriginalOffset < B->OriginalOffset)
460 return true;
461 if (A->OriginalOffset > B->OriginalOffset)
462 return false;
463 return A->Index < B->Index;
464}
465
Jake Ehrlich46814be2018-01-22 19:27:30 +0000466static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
467 if (A->PAddr < B->PAddr)
468 return true;
469 if (A->PAddr > B->PAddr)
470 return false;
471 return A->Index < B->Index;
472}
473
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000474template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000475 for (auto &Parent : Obj.segments()) {
476 // Every segment will overlap with itself but we don't want a segment to
477 // be it's own parent so we avoid that situation.
478 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
479 // We want a canonical "most parental" segment but this requires
480 // inspecting the ParentSegment.
481 if (compareSegmentsByOffset(&Parent, &Child))
482 if (Child.ParentSegment == nullptr ||
483 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
484 Child.ParentSegment = &Parent;
485 }
486 }
487 }
488}
489
Jake Ehrlich76e91102018-01-25 22:46:17 +0000490template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000491 uint32_t Index = 0;
492 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000493 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
494 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000495 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000496 Seg.Type = Phdr.p_type;
497 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000498 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000499 Seg.Offset = Phdr.p_offset;
500 Seg.VAddr = Phdr.p_vaddr;
501 Seg.PAddr = Phdr.p_paddr;
502 Seg.FileSize = Phdr.p_filesz;
503 Seg.MemSize = Phdr.p_memsz;
504 Seg.Align = Phdr.p_align;
505 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000506 for (auto &Section : Obj.sections()) {
507 if (sectionWithinSegment(Section, Seg)) {
508 Seg.addSection(&Section);
509 if (!Section.ParentSegment ||
510 Section.ParentSegment->Offset > Seg.Offset) {
511 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000512 }
513 }
514 }
515 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000516
517 auto &ElfHdr = Obj.ElfHdrSegment;
518 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
519 // segments must not overlap, and other types fit even less.
520 ElfHdr.Type = PT_PHDR;
521 ElfHdr.Flags = 0;
522 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
523 ElfHdr.VAddr = 0;
524 ElfHdr.PAddr = 0;
525 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
526 ElfHdr.Align = 0;
527 ElfHdr.Index = Index++;
528
529 const auto &Ehdr = *ElfFile.getHeader();
530 auto &PrHdr = Obj.ProgramHdrSegment;
531 PrHdr.Type = PT_PHDR;
532 PrHdr.Flags = 0;
533 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
534 // Whereas this works automatically for ElfHdr, here OriginalOffset is
535 // always non-zero and to ensure the equation we assign the same value to
536 // VAddr as well.
537 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
538 PrHdr.PAddr = 0;
539 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000540 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000541 PrHdr.Align = sizeof(Elf_Addr);
542 PrHdr.Index = Index++;
543
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000544 // Now we do an O(n^2) loop through the segments in order to match up
545 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000546 for (auto &Child : Obj.segments())
547 setParentSegment(Child);
548 setParentSegment(ElfHdr);
549 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000550}
551
552template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000553void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
554 auto SecTable = Obj.sections();
555 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
556 GroupSec->Link,
557 "Link field value " + Twine(GroupSec->Link) + " in section " +
558 GroupSec->Name + " is invalid",
559 "Link field value " + Twine(GroupSec->Link) + " in section " +
560 GroupSec->Name + " is not a symbol table");
561 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
562 if (!Sym)
563 error("Info field value " + Twine(GroupSec->Info) + " in section " +
564 GroupSec->Name + " is not a valid symbol index");
565 GroupSec->setSymTab(SymTab);
566 GroupSec->setSymbol(Sym);
567 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
568 GroupSec->Contents.empty())
569 error("The content of the section " + GroupSec->Name + " is malformed");
570 const ELF::Elf32_Word *Word =
571 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
572 const ELF::Elf32_Word *End =
573 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
574 GroupSec->setFlagWord(*Word++);
575 for (; Word != End; ++Word) {
576 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
577 GroupSec->addMember(SecTable.getSection(
578 Index, "Group member index " + Twine(Index) + " in section " +
579 GroupSec->Name + " is invalid"));
580 }
581}
582
583template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000584void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000585 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
586 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
587
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000588 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000589 SectionBase *DefSection = nullptr;
590 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000591
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000592 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000593 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000594 error(
595 "Symbol '" + Name +
596 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
597 Twine(Sym.st_shndx));
598 }
599 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000600 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000601 Sym.st_shndx, "Symbol '" + Name +
602 "' is defined in invalid section with index " +
603 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000604 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000605
Petr Hosek79cee9e2017-08-29 02:12:03 +0000606 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000607 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000608 }
609}
610
611template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000612static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
613
614template <class ELFT>
615static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
616 ToSet = Rela.r_addend;
617}
618
Jake Ehrlich76e91102018-01-25 22:46:17 +0000619template <class T>
620void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
621 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000622 for (const auto &Rel : RelRange) {
623 Relocation ToAdd;
624 ToAdd.Offset = Rel.r_offset;
625 getAddend(ToAdd.Addend, Rel);
626 ToAdd.Type = Rel.getType(false);
627 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
628 Relocs->addRelocation(ToAdd);
629 }
630}
631
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000632SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000633 if (Index == SHN_UNDEF || Index > Sections.size())
634 error(ErrMsg);
635 return Sections[Index - 1].get();
636}
637
638template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000639T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000640 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000641 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000642 return Sec;
643 error(TypeErrMsg);
644}
645
Petr Hosekd7df9b22017-09-06 23:41:02 +0000646template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000647SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000648 ArrayRef<uint8_t> Data;
649 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000650 case SHT_REL:
651 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000652 if (Shdr.sh_flags & SHF_ALLOC) {
653 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000654 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000655 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000656 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000657 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000658 // If a string table is allocated we don't want to mess with it. That would
659 // mean altering the memory image. There are no special link types or
660 // anything so we can just use a Section.
661 if (Shdr.sh_flags & SHF_ALLOC) {
662 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000663 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000664 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000665 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000666 case SHT_HASH:
667 case SHT_GNU_HASH:
668 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
669 // Because of this we don't need to mess with the hash tables either.
670 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000671 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000672 case SHT_GROUP:
673 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
674 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000675 case SHT_DYNSYM:
676 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000677 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000678 case SHT_DYNAMIC:
679 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000680 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000681 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000682 auto &SymTab = Obj.addSection<SymbolTableSection>();
683 Obj.SymbolTable = &SymTab;
684 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000685 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000686 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000687 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000688 default:
689 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000690 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000691 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000692}
693
Jake Ehrlich76e91102018-01-25 22:46:17 +0000694template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000695 uint32_t Index = 0;
696 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
697 if (Index == 0) {
698 ++Index;
699 continue;
700 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000701 auto &Sec = makeSection(Shdr);
702 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
703 Sec.Type = Shdr.sh_type;
704 Sec.Flags = Shdr.sh_flags;
705 Sec.Addr = Shdr.sh_addr;
706 Sec.Offset = Shdr.sh_offset;
707 Sec.OriginalOffset = Shdr.sh_offset;
708 Sec.Size = Shdr.sh_size;
709 Sec.Link = Shdr.sh_link;
710 Sec.Info = Shdr.sh_info;
711 Sec.Align = Shdr.sh_addralign;
712 Sec.EntrySize = Shdr.sh_entsize;
713 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000714 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000715
716 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000717 // details about symbol tables. We need the symbol table filled out before
718 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000719 if (Obj.SymbolTable) {
720 Obj.SymbolTable->initialize(Obj.sections());
721 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000722 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000723
724 // Now that all sections and symbols have been added we can add
725 // relocations that reference symbols and set the link and info fields for
726 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000727 for (auto &Section : Obj.sections()) {
728 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000729 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000730 Section.initialize(Obj.sections());
731 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000732 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
733 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000734 initRelocations(RelSec, Obj.SymbolTable,
735 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000736 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000737 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000738 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000739 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
740 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000741 }
742 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000743}
744
Jake Ehrlich76e91102018-01-25 22:46:17 +0000745template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000746 const auto &Ehdr = *ElfFile.getHeader();
747
Jake Ehrlich76e91102018-01-25 22:46:17 +0000748 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
749 Obj.Type = Ehdr.e_type;
750 Obj.Machine = Ehdr.e_machine;
751 Obj.Version = Ehdr.e_version;
752 Obj.Entry = Ehdr.e_entry;
753 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000754
Jake Ehrlich76e91102018-01-25 22:46:17 +0000755 readSectionHeaders();
756 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000757
Jake Ehrlich76e91102018-01-25 22:46:17 +0000758 Obj.SectionNames =
759 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000760 Ehdr.e_shstrndx,
761 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000762 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000763 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000764 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000765}
766
Jake Ehrlich76e91102018-01-25 22:46:17 +0000767// A generic size function which computes sizes of any random access range.
768template <class R> size_t size(R &&Range) {
769 return static_cast<size_t>(std::end(Range) - std::begin(Range));
770}
771
772Writer::~Writer() {}
773
774Reader::~Reader() {}
775
776ELFReader::ELFReader(StringRef File) {
777 auto BinaryOrErr = createBinary(File);
778 if (!BinaryOrErr)
779 reportError(File, BinaryOrErr.takeError());
Jake Ehrlich9634e182018-01-26 02:01:37 +0000780 auto OwnedBin = std::move(BinaryOrErr.get());
781 std::tie(Bin, Data) = OwnedBin.takeBinary();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000782}
783
784ElfType ELFReader::getElfType() const {
Jake Ehrlich9634e182018-01-26 02:01:37 +0000785 if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000786 return ELFT_ELF32LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000787 if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000788 return ELFT_ELF64LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000789 if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000790 return ELFT_ELF32BE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000791 if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000792 return ELFT_ELF64BE;
793 llvm_unreachable("Invalid ELFType");
794}
795
796std::unique_ptr<Object> ELFReader::create() const {
797 auto Obj = llvm::make_unique<Object>(Data);
Jake Ehrlich9634e182018-01-26 02:01:37 +0000798 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000799 ELFBuilder<ELF32LE> Builder(*o, *Obj);
800 Builder.build();
801 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000802 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000803 ELFBuilder<ELF64LE> Builder(*o, *Obj);
804 Builder.build();
805 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000806 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000807 ELFBuilder<ELF32BE> Builder(*o, *Obj);
808 Builder.build();
809 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000810 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000811 ELFBuilder<ELF64BE> Builder(*o, *Obj);
812 Builder.build();
813 return Obj;
814 }
815 error("Invalid file type");
816}
817
818template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
819 uint8_t *Buf = BufPtr->getBufferStart();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000820 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000821 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
822 Ehdr.e_type = Obj.Type;
823 Ehdr.e_machine = Obj.Machine;
824 Ehdr.e_version = Obj.Version;
825 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000826 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000827 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000828 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
829 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000830 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000831 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000832 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000833 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000834 Ehdr.e_shnum = size(Obj.sections()) + 1;
835 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000836 } else {
837 Ehdr.e_shoff = 0;
838 Ehdr.e_shnum = 0;
839 Ehdr.e_shstrndx = 0;
840 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000841}
842
Jake Ehrlich76e91102018-01-25 22:46:17 +0000843template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
844 for (auto &Seg : Obj.segments())
845 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000846}
847
Jake Ehrlich76e91102018-01-25 22:46:17 +0000848template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
849 uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000850 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000851 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000852 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
853 Shdr.sh_name = 0;
854 Shdr.sh_type = SHT_NULL;
855 Shdr.sh_flags = 0;
856 Shdr.sh_addr = 0;
857 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000858 Shdr.sh_size = 0;
859 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000860 Shdr.sh_info = 0;
861 Shdr.sh_addralign = 0;
862 Shdr.sh_entsize = 0;
863
Jake Ehrlich76e91102018-01-25 22:46:17 +0000864 for (auto &Sec : Obj.sections())
865 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000866}
867
Jake Ehrlich76e91102018-01-25 22:46:17 +0000868template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
869 for (auto &Sec : Obj.sections())
870 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000871}
872
Jake Ehrlich76e91102018-01-25 22:46:17 +0000873void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000874
875 auto Iter = std::stable_partition(
876 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
877 if (ToRemove(*Sec))
878 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000879 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
880 if (auto ToRelSec = RelSec->getSection())
881 return !ToRemove(*ToRelSec);
882 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000883 return true;
884 });
885 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
886 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000887 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000888 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000889 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000890 // Now make sure there are no remaining references to the sections that will
891 // be removed. Sometimes it is impossible to remove a reference so we emit
892 // an error here instead.
893 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
894 for (auto &Segment : Segments)
895 Segment->removeSection(RemoveSec.get());
896 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
897 KeepSec->removeSectionReferences(RemoveSec.get());
898 }
899 // Now finally get rid of them all togethor.
900 Sections.erase(Iter, std::end(Sections));
901}
902
Jake Ehrlich76e91102018-01-25 22:46:17 +0000903void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000904 // Put all sections in offset order. Maintain the ordering as closely as
905 // possible while meeting that demand however.
906 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
907 return A->OriginalOffset < B->OriginalOffset;
908 };
909 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
910 CompareSections);
911}
912
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000913static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
914 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
915 if (Align == 0)
916 Align = 1;
917 auto Diff =
918 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
919 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
920 // (Offset + Diff) & -Align == Addr & -Align will still hold.
921 if (Diff < 0)
922 Diff += Align;
923 return Offset + Diff;
924}
925
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000926// Orders segments such that if x = y->ParentSegment then y comes before x.
927static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000928 std::stable_sort(std::begin(Segments), std::end(Segments),
929 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000930}
931
932// This function finds a consistent layout for a list of segments starting from
933// an Offset. It assumes that Segments have been sorted by OrderSegments and
934// returns an Offset one past the end of the last segment.
935static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
936 uint64_t Offset) {
937 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +0000938 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +0000939 // The only way a segment should move is if a section was between two
940 // segments and that section was removed. If that section isn't in a segment
941 // then it's acceptable, but not ideal, to simply move it to after the
942 // segments. So we can simply layout segments one after the other accounting
943 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000944 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000945 // We assume that segments have been ordered by OriginalOffset and Index
946 // such that a parent segment will always come before a child segment in
947 // OrderedSegments. This means that the Offset of the ParentSegment should
948 // already be set and we can set our offset relative to it.
949 if (Segment->ParentSegment != nullptr) {
950 auto Parent = Segment->ParentSegment;
951 Segment->Offset =
952 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
953 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000954 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000955 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000956 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000957 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000958 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000959 return Offset;
960}
961
962// This function finds a consistent layout for a list of sections. It assumes
963// that the ->ParentSegment of each section has already been laid out. The
964// supplied starting Offset is used for the starting offset of any section that
965// does not have a ParentSegment. It returns either the offset given if all
966// sections had a ParentSegment or an offset one past the last section if there
967// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000968template <class Range>
969static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000970 // Now the offset of every segment has been set we can assign the offsets
971 // of each section. For sections that are covered by a segment we should use
972 // the segment's original offset and the section's original offset to compute
973 // the offset from the start of the segment. Using the offset from the start
974 // of the segment we can assign a new offset to the section. For sections not
975 // covered by segments we can just bump Offset to the next valid location.
976 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000977 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000978 Section.Index = Index++;
979 if (Section.ParentSegment != nullptr) {
980 auto Segment = *Section.ParentSegment;
981 Section.Offset =
982 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +0000983 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000984 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
985 Section.Offset = Offset;
986 if (Section.Type != SHT_NOBITS)
987 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +0000988 }
989 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000990 return Offset;
991}
Petr Hosek3f383832017-08-26 01:32:20 +0000992
Jake Ehrlich76e91102018-01-25 22:46:17 +0000993template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000994 // We need a temporary list of segments that has a special order to it
995 // so that we know that anytime ->ParentSegment is set that segment has
996 // already had its offset properly set.
997 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000998 for (auto &Segment : Obj.segments())
999 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001000 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1001 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001002 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001003 // Offset is used as the start offset of the first segment to be laid out.
1004 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1005 // we start at offset 0.
1006 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001007 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001008 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001009 // If we need to write the section header table out then we need to align the
1010 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001011 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001012 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001013 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001014}
1015
Jake Ehrlich76e91102018-01-25 22:46:17 +00001016template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001017 // We already have the section header offset so we can calculate the total
1018 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001019 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1020 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001021 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001022}
1023
Jake Ehrlich76e91102018-01-25 22:46:17 +00001024template <class ELFT> void ELFWriter<ELFT>::write() {
1025 writeEhdr();
1026 writePhdrs();
1027 writeSectionData();
1028 if (WriteSectionHeaders)
1029 writeShdrs();
1030 if (auto E = BufPtr->commit())
1031 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001032}
1033
Jake Ehrlich76e91102018-01-25 22:46:17 +00001034void Writer::createBuffer(uint64_t Size) {
1035 auto BufferOrErr =
1036 FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
1037 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
1038 error("failed to open " + File);
1039 });
1040 BufPtr = std::move(*BufferOrErr);
1041}
1042
1043template <class ELFT> void ELFWriter<ELFT>::finalize() {
1044 // It could happen that SectionNames has been removed and yet the user wants
1045 // a section header table output. We need to throw an error if a user tries
1046 // to do that.
1047 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1048 error("Cannot write section header table because section header string "
1049 "table was removed.");
1050
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001051 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001052 if (Obj.SectionNames != nullptr)
1053 for (const auto &Section : Obj.sections()) {
1054 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001055 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001056 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001057 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001058 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001059
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001060 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001061 assignOffsets();
1062
1063 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001064 if (Obj.SectionNames != nullptr)
1065 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001066 // Finally now that all offsets and indexes have been set we can finalize any
1067 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1069 for (auto &Section : Obj.sections()) {
1070 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001071 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001072 if (WriteSectionHeaders)
1073 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1074 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001075 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001076
1077 createBuffer(totalSize());
1078 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001079}
1080
Jake Ehrlich76e91102018-01-25 22:46:17 +00001081void BinaryWriter::write() {
1082 for (auto &Section : Obj.sections()) {
1083 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001084 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001085 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001086 }
Jake Ehrlichc0e9bee2018-01-26 01:17:35 +00001087 if (auto E = BufPtr->commit())
1088 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001089}
1090
Jake Ehrlich76e91102018-01-25 22:46:17 +00001091void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001092 // TODO: Create a filter range to construct OrderedSegments from so that this
1093 // code can be deduped with assignOffsets above. This should also solve the
1094 // todo below for LayoutSections.
1095 // We need a temporary list of segments that has a special order to it
1096 // so that we know that anytime ->ParentSegment is set that segment has
1097 // already had it's offset properly set. We only want to consider the segments
1098 // that will affect layout of allocated sections so we only add those.
1099 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001100 for (auto &Section : Obj.sections()) {
1101 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1102 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001103 }
1104 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001105
1106 // For binary output, we're going to use physical addresses instead of
1107 // virtual addresses, since a binary output is used for cases like ROM
1108 // loading and physical addresses are intended for ROM loading.
1109 // However, if no segment has a physical address, we'll fallback to using
1110 // virtual addresses for all.
1111 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1112 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1113 for (const auto &Segment : OrderedSegments)
1114 Segment->PAddr = Segment->VAddr;
1115
1116 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1117 compareSegmentsByPAddr);
1118
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001119 // Because we add a ParentSegment for each section we might have duplicate
1120 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1121 // would do very strange things.
1122 auto End =
1123 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1124 OrderedSegments.erase(End, std::end(OrderedSegments));
1125
Jake Ehrlich46814be2018-01-22 19:27:30 +00001126 uint64_t Offset = 0;
1127
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001128 // Modify the first segment so that there is no gap at the start. This allows
1129 // our layout algorithm to proceed as expected while not out writing out the
1130 // gap at the start.
1131 if (!OrderedSegments.empty()) {
1132 auto Seg = OrderedSegments[0];
1133 auto Sec = Seg->firstSection();
1134 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1135 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001136 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001137 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001138 // The PAddr needs to be increased to remove the gap before the first
1139 // section.
1140 Seg->PAddr += Diff;
1141 uint64_t LowestPAddr = Seg->PAddr;
1142 for (auto &Segment : OrderedSegments) {
1143 Segment->Offset = Segment->PAddr - LowestPAddr;
1144 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1145 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001146 }
1147
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001148 // TODO: generalize LayoutSections to take a range. Pass a special range
1149 // constructed from an iterator that skips values for which a predicate does
1150 // not hold. Then pass such a range to LayoutSections instead of constructing
1151 // AllocatedSections here.
1152 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001153 for (auto &Section : Obj.sections()) {
1154 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001155 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001156 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001157 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001158 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001159
1160 // Now that every section has been laid out we just need to compute the total
1161 // file size. This might not be the same as the offset returned by
1162 // LayoutSections, because we want to truncate the last segment to the end of
1163 // its last section, to match GNU objcopy's behaviour.
1164 TotalSize = 0;
1165 for (const auto &Section : AllocatedSections) {
1166 if (Section->Type != SHT_NOBITS)
1167 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1168 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001169
1170 createBuffer(TotalSize);
1171 SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001172}
1173
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001174namespace llvm {
1175
Jake Ehrlich76e91102018-01-25 22:46:17 +00001176template class ELFBuilder<ELF64LE>;
1177template class ELFBuilder<ELF64BE>;
1178template class ELFBuilder<ELF32LE>;
1179template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001180
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181template class ELFWriter<ELF64LE>;
1182template class ELFWriter<ELF64BE>;
1183template class ELFWriter<ELF32LE>;
1184template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001185} // end namespace llvm