blob: 93487dc5bf6c2f526543f0612f5713b6ff5e5316 [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 }
Paul Semel41695f82018-05-02 20:19:22 +0000197 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000198}
199
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000200void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
201 for (auto &Sym : Symbols)
202 Callable(*Sym);
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000203 std::stable_partition(
204 std::begin(Symbols), std::end(Symbols),
205 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000206 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000207}
208
Paul Semel41695f82018-05-02 20:19:22 +0000209void SymbolTableSection::removeSymbols(function_ref<bool(Symbol &)> ToRemove) {
210 Symbols.erase(
211 std::remove_if(std::begin(Symbols), std::end(Symbols),
212 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
213 std::end(Symbols));
214 Size = Symbols.size() * EntrySize;
215 assignIndices();
216}
217
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000218void SymbolTableSection::initialize(SectionTableRef SecTable) {
219 Size = 0;
220 setStrTab(SecTable.getSectionOfType<StringTableSection>(
221 Link,
222 "Symbol table has link index of " + Twine(Link) +
223 " which is not a valid index",
224 "Symbol table has link index of " + Twine(Link) +
225 " which is not a string table"));
226}
227
Petr Hosek79cee9e2017-08-29 02:12:03 +0000228void SymbolTableSection::finalize() {
229 // Make sure SymbolNames is finalized before getting name indexes.
230 SymbolNames->finalize();
231
232 uint32_t MaxLocalIndex = 0;
233 for (auto &Sym : Symbols) {
234 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
235 if (Sym->Binding == STB_LOCAL)
236 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
237 }
238 // Now we need to set the Link and Info fields.
239 Link = SymbolNames->Index;
240 Info = MaxLocalIndex + 1;
241}
242
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000243void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000244 // Add all of our strings to SymbolNames so that SymbolNames has the right
245 // size before layout is decided.
246 for (auto &Sym : Symbols)
247 SymbolNames->addString(Sym->Name);
248}
249
250const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
251 if (Symbols.size() <= Index)
252 error("Invalid symbol index: " + Twine(Index));
253 return Symbols[Index].get();
254}
255
256template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000257void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000258 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000259 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000260 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
261 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000262 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000263 Sym->st_name = Symbol->NameIndex;
264 Sym->st_value = Symbol->Value;
265 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000266 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000267 Sym->setBinding(Symbol->Binding);
268 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000269 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000270 ++Sym;
271 }
272}
273
Jake Ehrlich76e91102018-01-25 22:46:17 +0000274void SymbolTableSection::accept(SectionVisitor &Visitor) const {
275 Visitor.visit(*this);
276}
277
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000278template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000279void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
280 const SectionBase *Sec) {
281 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000282 error("Symbol table " + Symbols->Name +
283 " cannot be removed because it is "
284 "referenced by the relocation "
285 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000286 this->Name);
287 }
288}
289
290template <class SymTabType>
291void RelocSectionWithSymtabBase<SymTabType>::initialize(
292 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000293 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000294 Link,
295 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
296 "Link field value " + Twine(Link) + " in section " + Name +
297 " is not a symbol table"));
298
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000299 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000300 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
301 " in section " + Name +
302 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000303 else
304 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000305}
306
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000307template <class SymTabType>
308void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000309 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000310 if (SecToApplyRel != nullptr)
311 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000312}
313
314template <class ELFT>
315void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
316
317template <class ELFT>
318void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
319 Rela.r_addend = Addend;
320}
321
Jake Ehrlich76e91102018-01-25 22:46:17 +0000322template <class RelRange, class T>
323void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000324 for (const auto &Reloc : Relocations) {
325 Buf->r_offset = Reloc.Offset;
326 setAddend(*Buf, Reloc.Addend);
327 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
328 ++Buf;
329 }
330}
331
332template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000333void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
334 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
335 if (Sec.Type == SHT_REL)
336 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000337 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000338 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000339}
340
Jake Ehrlich76e91102018-01-25 22:46:17 +0000341void RelocationSection::accept(SectionVisitor &Visitor) const {
342 Visitor.visit(*this);
343}
344
345void SectionWriter::visit(const DynamicRelocationSection &Sec) {
346 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
347 Out.getBufferStart() + Sec.Offset);
348}
349
350void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
351 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000352}
353
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000354void Section::removeSectionReferences(const SectionBase *Sec) {
355 if (LinkSection == Sec) {
356 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000357 " cannot be removed because it is "
358 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000359 this->Name);
360 }
361}
362
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000363void GroupSection::finalize() {
364 this->Info = Sym->Index;
365 this->Link = SymTab->Index;
366}
367
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000368void Section::initialize(SectionTableRef SecTable) {
369 if (Link != ELF::SHN_UNDEF)
370 LinkSection =
371 SecTable.getSection(Link, "Link field value " + Twine(Link) +
372 " in section " + Name + " is invalid");
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000373}
374
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000375void Section::finalize() {
376 if (LinkSection)
377 this->Link = LinkSection->Index;
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000378}
379
Jake Ehrlich76e91102018-01-25 22:46:17 +0000380void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000381 FileName = sys::path::filename(File);
382 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000383 // followed by a null terminator and then the CRC32 of the file. The CRC32
384 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
385 // byte, and then finally push the size to alignment and add 4.
386 Size = alignTo(FileName.size() + 1, 4) + 4;
387 // The CRC32 will only be aligned if we align the whole section.
388 Align = 4;
389 Type = ELF::SHT_PROGBITS;
390 Name = ".gnu_debuglink";
391 // For sections not found in segments, OriginalOffset is only used to
392 // establish the order that sections should go in. By using the maximum
393 // possible offset we cause this section to wind up at the end.
394 OriginalOffset = std::numeric_limits<uint64_t>::max();
395 JamCRC crc;
396 crc.update(ArrayRef<char>(Data.data(), Data.size()));
397 // The CRC32 value needs to be complemented because the JamCRC dosn't
398 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
399 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
400 CRC32 = ~crc.getCRC();
401}
402
Jake Ehrlich76e91102018-01-25 22:46:17 +0000403GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000404 // Read in the file to compute the CRC of it.
405 auto DebugOrErr = MemoryBuffer::getFile(File);
406 if (!DebugOrErr)
407 error("'" + File + "': " + DebugOrErr.getError().message());
408 auto Debug = std::move(*DebugOrErr);
409 init(File, Debug->getBuffer());
410}
411
412template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000413void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
414 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000415 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000416 Elf_Word *CRC =
417 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
418 *CRC = Sec.CRC32;
419 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
420}
421
422void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
423 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000424}
425
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000426template <class ELFT>
427void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
428 ELF::Elf32_Word *Buf =
429 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
430 *Buf++ = Sec.FlagWord;
431 for (const auto *S : Sec.GroupMembers)
432 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
433}
434
435void GroupSection::accept(SectionVisitor &Visitor) const {
436 Visitor.visit(*this);
437}
438
Petr Hosek05a04cb2017-08-01 00:33:58 +0000439// Returns true IFF a section is wholly inside the range of a segment
440static bool sectionWithinSegment(const SectionBase &Section,
441 const Segment &Segment) {
442 // If a section is empty it should be treated like it has a size of 1. This is
443 // to clarify the case when an empty section lies on a boundary between two
444 // segments and ensures that the section "belongs" to the second segment and
445 // not the first.
446 uint64_t SecSize = Section.Size ? Section.Size : 1;
447 return Segment.Offset <= Section.OriginalOffset &&
448 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
449}
450
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000451// Returns true IFF a segment's original offset is inside of another segment's
452// range.
453static bool segmentOverlapsSegment(const Segment &Child,
454 const Segment &Parent) {
455
456 return Parent.OriginalOffset <= Child.OriginalOffset &&
457 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
458}
459
Jake Ehrlich46814be2018-01-22 19:27:30 +0000460static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000461 // Any segment without a parent segment should come before a segment
462 // that has a parent segment.
463 if (A->OriginalOffset < B->OriginalOffset)
464 return true;
465 if (A->OriginalOffset > B->OriginalOffset)
466 return false;
467 return A->Index < B->Index;
468}
469
Jake Ehrlich46814be2018-01-22 19:27:30 +0000470static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
471 if (A->PAddr < B->PAddr)
472 return true;
473 if (A->PAddr > B->PAddr)
474 return false;
475 return A->Index < B->Index;
476}
477
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000478template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000479 for (auto &Parent : Obj.segments()) {
480 // Every segment will overlap with itself but we don't want a segment to
481 // be it's own parent so we avoid that situation.
482 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
483 // We want a canonical "most parental" segment but this requires
484 // inspecting the ParentSegment.
485 if (compareSegmentsByOffset(&Parent, &Child))
486 if (Child.ParentSegment == nullptr ||
487 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
488 Child.ParentSegment = &Parent;
489 }
490 }
491 }
492}
493
Jake Ehrlich76e91102018-01-25 22:46:17 +0000494template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000495 uint32_t Index = 0;
496 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000497 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
498 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000499 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000500 Seg.Type = Phdr.p_type;
501 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000502 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000503 Seg.Offset = Phdr.p_offset;
504 Seg.VAddr = Phdr.p_vaddr;
505 Seg.PAddr = Phdr.p_paddr;
506 Seg.FileSize = Phdr.p_filesz;
507 Seg.MemSize = Phdr.p_memsz;
508 Seg.Align = Phdr.p_align;
509 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000510 for (auto &Section : Obj.sections()) {
511 if (sectionWithinSegment(Section, Seg)) {
512 Seg.addSection(&Section);
513 if (!Section.ParentSegment ||
514 Section.ParentSegment->Offset > Seg.Offset) {
515 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000516 }
517 }
518 }
519 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000520
521 auto &ElfHdr = Obj.ElfHdrSegment;
522 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
523 // segments must not overlap, and other types fit even less.
524 ElfHdr.Type = PT_PHDR;
525 ElfHdr.Flags = 0;
526 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
527 ElfHdr.VAddr = 0;
528 ElfHdr.PAddr = 0;
529 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
530 ElfHdr.Align = 0;
531 ElfHdr.Index = Index++;
532
533 const auto &Ehdr = *ElfFile.getHeader();
534 auto &PrHdr = Obj.ProgramHdrSegment;
535 PrHdr.Type = PT_PHDR;
536 PrHdr.Flags = 0;
537 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
538 // Whereas this works automatically for ElfHdr, here OriginalOffset is
539 // always non-zero and to ensure the equation we assign the same value to
540 // VAddr as well.
541 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
542 PrHdr.PAddr = 0;
543 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000544 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000545 PrHdr.Align = sizeof(Elf_Addr);
546 PrHdr.Index = Index++;
547
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000548 // Now we do an O(n^2) loop through the segments in order to match up
549 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000550 for (auto &Child : Obj.segments())
551 setParentSegment(Child);
552 setParentSegment(ElfHdr);
553 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000554}
555
556template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000557void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
558 auto SecTable = Obj.sections();
559 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
560 GroupSec->Link,
561 "Link field value " + Twine(GroupSec->Link) + " in section " +
562 GroupSec->Name + " is invalid",
563 "Link field value " + Twine(GroupSec->Link) + " in section " +
564 GroupSec->Name + " is not a symbol table");
565 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
566 if (!Sym)
567 error("Info field value " + Twine(GroupSec->Info) + " in section " +
568 GroupSec->Name + " is not a valid symbol index");
569 GroupSec->setSymTab(SymTab);
570 GroupSec->setSymbol(Sym);
571 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
572 GroupSec->Contents.empty())
573 error("The content of the section " + GroupSec->Name + " is malformed");
574 const ELF::Elf32_Word *Word =
575 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
576 const ELF::Elf32_Word *End =
577 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
578 GroupSec->setFlagWord(*Word++);
579 for (; Word != End; ++Word) {
580 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
581 GroupSec->addMember(SecTable.getSection(
582 Index, "Group member index " + Twine(Index) + " in section " +
583 GroupSec->Name + " is invalid"));
584 }
585}
586
587template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000588void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000589 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
590 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
591
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000592 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000593 SectionBase *DefSection = nullptr;
594 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000595
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000596 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000597 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000598 error(
599 "Symbol '" + Name +
600 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
601 Twine(Sym.st_shndx));
602 }
603 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000604 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000605 Sym.st_shndx, "Symbol '" + Name +
606 "' is defined in invalid section with index " +
607 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000608 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000609
Petr Hosek79cee9e2017-08-29 02:12:03 +0000610 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000611 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000612 }
613}
614
615template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000616static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
617
618template <class ELFT>
619static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
620 ToSet = Rela.r_addend;
621}
622
Jake Ehrlich76e91102018-01-25 22:46:17 +0000623template <class T>
624void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
625 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000626 for (const auto &Rel : RelRange) {
627 Relocation ToAdd;
628 ToAdd.Offset = Rel.r_offset;
629 getAddend(ToAdd.Addend, Rel);
630 ToAdd.Type = Rel.getType(false);
631 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
632 Relocs->addRelocation(ToAdd);
633 }
634}
635
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000636SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000637 if (Index == SHN_UNDEF || Index > Sections.size())
638 error(ErrMsg);
639 return Sections[Index - 1].get();
640}
641
642template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000643T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000644 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000645 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000646 return Sec;
647 error(TypeErrMsg);
648}
649
Petr Hosekd7df9b22017-09-06 23:41:02 +0000650template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000651SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000652 ArrayRef<uint8_t> Data;
653 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000654 case SHT_REL:
655 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000656 if (Shdr.sh_flags & SHF_ALLOC) {
657 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000658 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000659 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000660 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000661 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000662 // If a string table is allocated we don't want to mess with it. That would
663 // mean altering the memory image. There are no special link types or
664 // anything so we can just use a Section.
665 if (Shdr.sh_flags & SHF_ALLOC) {
666 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000667 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000668 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000669 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000670 case SHT_HASH:
671 case SHT_GNU_HASH:
672 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
673 // Because of this we don't need to mess with the hash tables either.
674 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000675 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000676 case SHT_GROUP:
677 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
678 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000679 case SHT_DYNSYM:
680 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000681 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000682 case SHT_DYNAMIC:
683 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000684 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000685 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000686 auto &SymTab = Obj.addSection<SymbolTableSection>();
687 Obj.SymbolTable = &SymTab;
688 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000689 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000690 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000691 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000692 default:
693 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000694 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000695 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000696}
697
Jake Ehrlich76e91102018-01-25 22:46:17 +0000698template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000699 uint32_t Index = 0;
700 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
701 if (Index == 0) {
702 ++Index;
703 continue;
704 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000705 auto &Sec = makeSection(Shdr);
706 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
707 Sec.Type = Shdr.sh_type;
708 Sec.Flags = Shdr.sh_flags;
709 Sec.Addr = Shdr.sh_addr;
710 Sec.Offset = Shdr.sh_offset;
711 Sec.OriginalOffset = Shdr.sh_offset;
712 Sec.Size = Shdr.sh_size;
713 Sec.Link = Shdr.sh_link;
714 Sec.Info = Shdr.sh_info;
715 Sec.Align = Shdr.sh_addralign;
716 Sec.EntrySize = Shdr.sh_entsize;
717 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000718 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000719
720 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000721 // details about symbol tables. We need the symbol table filled out before
722 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000723 if (Obj.SymbolTable) {
724 Obj.SymbolTable->initialize(Obj.sections());
725 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000726 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000727
728 // Now that all sections and symbols have been added we can add
729 // relocations that reference symbols and set the link and info fields for
730 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000731 for (auto &Section : Obj.sections()) {
732 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000733 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000734 Section.initialize(Obj.sections());
735 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000736 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
737 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000738 initRelocations(RelSec, Obj.SymbolTable,
739 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000740 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000741 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000742 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000743 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
744 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000745 }
746 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000747}
748
Jake Ehrlich76e91102018-01-25 22:46:17 +0000749template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000750 const auto &Ehdr = *ElfFile.getHeader();
751
Jake Ehrlich76e91102018-01-25 22:46:17 +0000752 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
753 Obj.Type = Ehdr.e_type;
754 Obj.Machine = Ehdr.e_machine;
755 Obj.Version = Ehdr.e_version;
756 Obj.Entry = Ehdr.e_entry;
757 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000758
Jake Ehrlich76e91102018-01-25 22:46:17 +0000759 readSectionHeaders();
760 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000761
Jake Ehrlich76e91102018-01-25 22:46:17 +0000762 Obj.SectionNames =
763 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000764 Ehdr.e_shstrndx,
765 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000766 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000767 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000768 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000769}
770
Jake Ehrlich76e91102018-01-25 22:46:17 +0000771// A generic size function which computes sizes of any random access range.
772template <class R> size_t size(R &&Range) {
773 return static_cast<size_t>(std::end(Range) - std::begin(Range));
774}
775
776Writer::~Writer() {}
777
778Reader::~Reader() {}
779
780ELFReader::ELFReader(StringRef File) {
781 auto BinaryOrErr = createBinary(File);
782 if (!BinaryOrErr)
783 reportError(File, BinaryOrErr.takeError());
Jake Ehrlich9634e182018-01-26 02:01:37 +0000784 auto OwnedBin = std::move(BinaryOrErr.get());
785 std::tie(Bin, Data) = OwnedBin.takeBinary();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000786}
787
788ElfType ELFReader::getElfType() const {
Jake Ehrlich9634e182018-01-26 02:01:37 +0000789 if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000790 return ELFT_ELF32LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000791 if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000792 return ELFT_ELF64LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000793 if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000794 return ELFT_ELF32BE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000795 if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000796 return ELFT_ELF64BE;
797 llvm_unreachable("Invalid ELFType");
798}
799
800std::unique_ptr<Object> ELFReader::create() const {
801 auto Obj = llvm::make_unique<Object>(Data);
Jake Ehrlich9634e182018-01-26 02:01:37 +0000802 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000803 ELFBuilder<ELF32LE> Builder(*o, *Obj);
804 Builder.build();
805 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000806 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000807 ELFBuilder<ELF64LE> Builder(*o, *Obj);
808 Builder.build();
809 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000810 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000811 ELFBuilder<ELF32BE> Builder(*o, *Obj);
812 Builder.build();
813 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000814 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000815 ELFBuilder<ELF64BE> Builder(*o, *Obj);
816 Builder.build();
817 return Obj;
818 }
819 error("Invalid file type");
820}
821
822template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
823 uint8_t *Buf = BufPtr->getBufferStart();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000824 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000825 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
826 Ehdr.e_type = Obj.Type;
827 Ehdr.e_machine = Obj.Machine;
828 Ehdr.e_version = Obj.Version;
829 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000830 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000831 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000832 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
833 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000834 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000835 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000836 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000837 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000838 Ehdr.e_shnum = size(Obj.sections()) + 1;
839 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000840 } else {
841 Ehdr.e_shoff = 0;
842 Ehdr.e_shnum = 0;
843 Ehdr.e_shstrndx = 0;
844 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000845}
846
Jake Ehrlich76e91102018-01-25 22:46:17 +0000847template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
848 for (auto &Seg : Obj.segments())
849 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000850}
851
Jake Ehrlich76e91102018-01-25 22:46:17 +0000852template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
853 uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000854 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000855 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000856 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
857 Shdr.sh_name = 0;
858 Shdr.sh_type = SHT_NULL;
859 Shdr.sh_flags = 0;
860 Shdr.sh_addr = 0;
861 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000862 Shdr.sh_size = 0;
863 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000864 Shdr.sh_info = 0;
865 Shdr.sh_addralign = 0;
866 Shdr.sh_entsize = 0;
867
Jake Ehrlich76e91102018-01-25 22:46:17 +0000868 for (auto &Sec : Obj.sections())
869 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000870}
871
Jake Ehrlich76e91102018-01-25 22:46:17 +0000872template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
873 for (auto &Sec : Obj.sections())
874 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000875}
876
Jake Ehrlich76e91102018-01-25 22:46:17 +0000877void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000878
879 auto Iter = std::stable_partition(
880 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
881 if (ToRemove(*Sec))
882 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000883 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
884 if (auto ToRelSec = RelSec->getSection())
885 return !ToRemove(*ToRelSec);
886 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000887 return true;
888 });
889 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
890 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000891 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000892 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000893 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000894 // Now make sure there are no remaining references to the sections that will
895 // be removed. Sometimes it is impossible to remove a reference so we emit
896 // an error here instead.
897 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
898 for (auto &Segment : Segments)
899 Segment->removeSection(RemoveSec.get());
900 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
901 KeepSec->removeSectionReferences(RemoveSec.get());
902 }
903 // Now finally get rid of them all togethor.
904 Sections.erase(Iter, std::end(Sections));
905}
906
Jake Ehrlich76e91102018-01-25 22:46:17 +0000907void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000908 // Put all sections in offset order. Maintain the ordering as closely as
909 // possible while meeting that demand however.
910 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
911 return A->OriginalOffset < B->OriginalOffset;
912 };
913 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
914 CompareSections);
915}
916
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000917static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
918 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
919 if (Align == 0)
920 Align = 1;
921 auto Diff =
922 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
923 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
924 // (Offset + Diff) & -Align == Addr & -Align will still hold.
925 if (Diff < 0)
926 Diff += Align;
927 return Offset + Diff;
928}
929
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000930// Orders segments such that if x = y->ParentSegment then y comes before x.
931static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000932 std::stable_sort(std::begin(Segments), std::end(Segments),
933 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000934}
935
936// This function finds a consistent layout for a list of segments starting from
937// an Offset. It assumes that Segments have been sorted by OrderSegments and
938// returns an Offset one past the end of the last segment.
939static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
940 uint64_t Offset) {
941 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +0000942 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +0000943 // The only way a segment should move is if a section was between two
944 // segments and that section was removed. If that section isn't in a segment
945 // then it's acceptable, but not ideal, to simply move it to after the
946 // segments. So we can simply layout segments one after the other accounting
947 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000948 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000949 // We assume that segments have been ordered by OriginalOffset and Index
950 // such that a parent segment will always come before a child segment in
951 // OrderedSegments. This means that the Offset of the ParentSegment should
952 // already be set and we can set our offset relative to it.
953 if (Segment->ParentSegment != nullptr) {
954 auto Parent = Segment->ParentSegment;
955 Segment->Offset =
956 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
957 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000958 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000959 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000960 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000961 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000962 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000963 return Offset;
964}
965
966// This function finds a consistent layout for a list of sections. It assumes
967// that the ->ParentSegment of each section has already been laid out. The
968// supplied starting Offset is used for the starting offset of any section that
969// does not have a ParentSegment. It returns either the offset given if all
970// sections had a ParentSegment or an offset one past the last section if there
971// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000972template <class Range>
973static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000974 // Now the offset of every segment has been set we can assign the offsets
975 // of each section. For sections that are covered by a segment we should use
976 // the segment's original offset and the section's original offset to compute
977 // the offset from the start of the segment. Using the offset from the start
978 // of the segment we can assign a new offset to the section. For sections not
979 // covered by segments we can just bump Offset to the next valid location.
980 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000981 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000982 Section.Index = Index++;
983 if (Section.ParentSegment != nullptr) {
984 auto Segment = *Section.ParentSegment;
985 Section.Offset =
986 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +0000987 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000988 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
989 Section.Offset = Offset;
990 if (Section.Type != SHT_NOBITS)
991 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +0000992 }
993 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000994 return Offset;
995}
Petr Hosek3f383832017-08-26 01:32:20 +0000996
Jake Ehrlich76e91102018-01-25 22:46:17 +0000997template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000998 // We need a temporary list of segments that has a special order to it
999 // so that we know that anytime ->ParentSegment is set that segment has
1000 // already had its offset properly set.
1001 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001002 for (auto &Segment : Obj.segments())
1003 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001004 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1005 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001006 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001007 // Offset is used as the start offset of the first segment to be laid out.
1008 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1009 // we start at offset 0.
1010 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001011 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001012 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001013 // If we need to write the section header table out then we need to align the
1014 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001015 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001016 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001017 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001018}
1019
Jake Ehrlich76e91102018-01-25 22:46:17 +00001020template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001021 // We already have the section header offset so we can calculate the total
1022 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001023 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1024 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001025 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001026}
1027
Jake Ehrlich76e91102018-01-25 22:46:17 +00001028template <class ELFT> void ELFWriter<ELFT>::write() {
1029 writeEhdr();
1030 writePhdrs();
1031 writeSectionData();
1032 if (WriteSectionHeaders)
1033 writeShdrs();
1034 if (auto E = BufPtr->commit())
1035 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001036}
1037
Jake Ehrlich76e91102018-01-25 22:46:17 +00001038void Writer::createBuffer(uint64_t Size) {
1039 auto BufferOrErr =
1040 FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
1041 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
1042 error("failed to open " + File);
1043 });
1044 BufPtr = std::move(*BufferOrErr);
1045}
1046
1047template <class ELFT> void ELFWriter<ELFT>::finalize() {
1048 // It could happen that SectionNames has been removed and yet the user wants
1049 // a section header table output. We need to throw an error if a user tries
1050 // to do that.
1051 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1052 error("Cannot write section header table because section header string "
1053 "table was removed.");
1054
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001055 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001056 if (Obj.SectionNames != nullptr)
1057 for (const auto &Section : Obj.sections()) {
1058 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001059 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001060 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001061 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001062 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001063
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001064 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001065 assignOffsets();
1066
1067 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068 if (Obj.SectionNames != nullptr)
1069 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001070 // Finally now that all offsets and indexes have been set we can finalize any
1071 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001072 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1073 for (auto &Section : Obj.sections()) {
1074 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001075 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001076 if (WriteSectionHeaders)
1077 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1078 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001079 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001080
1081 createBuffer(totalSize());
1082 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001083}
1084
Jake Ehrlich76e91102018-01-25 22:46:17 +00001085void BinaryWriter::write() {
1086 for (auto &Section : Obj.sections()) {
1087 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001088 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001089 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001090 }
Jake Ehrlichc0e9bee2018-01-26 01:17:35 +00001091 if (auto E = BufPtr->commit())
1092 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001093}
1094
Jake Ehrlich76e91102018-01-25 22:46:17 +00001095void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001096 // TODO: Create a filter range to construct OrderedSegments from so that this
1097 // code can be deduped with assignOffsets above. This should also solve the
1098 // todo below for LayoutSections.
1099 // We need a temporary list of segments that has a special order to it
1100 // so that we know that anytime ->ParentSegment is set that segment has
1101 // already had it's offset properly set. We only want to consider the segments
1102 // that will affect layout of allocated sections so we only add those.
1103 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001104 for (auto &Section : Obj.sections()) {
1105 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1106 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001107 }
1108 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001109
1110 // For binary output, we're going to use physical addresses instead of
1111 // virtual addresses, since a binary output is used for cases like ROM
1112 // loading and physical addresses are intended for ROM loading.
1113 // However, if no segment has a physical address, we'll fallback to using
1114 // virtual addresses for all.
1115 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1116 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1117 for (const auto &Segment : OrderedSegments)
1118 Segment->PAddr = Segment->VAddr;
1119
1120 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1121 compareSegmentsByPAddr);
1122
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001123 // Because we add a ParentSegment for each section we might have duplicate
1124 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1125 // would do very strange things.
1126 auto End =
1127 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1128 OrderedSegments.erase(End, std::end(OrderedSegments));
1129
Jake Ehrlich46814be2018-01-22 19:27:30 +00001130 uint64_t Offset = 0;
1131
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001132 // Modify the first segment so that there is no gap at the start. This allows
1133 // our layout algorithm to proceed as expected while not out writing out the
1134 // gap at the start.
1135 if (!OrderedSegments.empty()) {
1136 auto Seg = OrderedSegments[0];
1137 auto Sec = Seg->firstSection();
1138 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1139 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001140 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001141 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001142 // The PAddr needs to be increased to remove the gap before the first
1143 // section.
1144 Seg->PAddr += Diff;
1145 uint64_t LowestPAddr = Seg->PAddr;
1146 for (auto &Segment : OrderedSegments) {
1147 Segment->Offset = Segment->PAddr - LowestPAddr;
1148 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1149 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001150 }
1151
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001152 // TODO: generalize LayoutSections to take a range. Pass a special range
1153 // constructed from an iterator that skips values for which a predicate does
1154 // not hold. Then pass such a range to LayoutSections instead of constructing
1155 // AllocatedSections here.
1156 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001157 for (auto &Section : Obj.sections()) {
1158 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001159 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001160 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001161 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001162 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001163
1164 // Now that every section has been laid out we just need to compute the total
1165 // file size. This might not be the same as the offset returned by
1166 // LayoutSections, because we want to truncate the last segment to the end of
1167 // its last section, to match GNU objcopy's behaviour.
1168 TotalSize = 0;
1169 for (const auto &Section : AllocatedSections) {
1170 if (Section->Type != SHT_NOBITS)
1171 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1172 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001173
1174 createBuffer(TotalSize);
1175 SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001176}
1177
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001178namespace llvm {
1179
Jake Ehrlich76e91102018-01-25 22:46:17 +00001180template class ELFBuilder<ELF64LE>;
1181template class ELFBuilder<ELF64BE>;
1182template class ELFBuilder<ELF32LE>;
1183template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001184
Jake Ehrlich76e91102018-01-25 22:46:17 +00001185template class ELFWriter<ELF64LE>;
1186template class ELFWriter<ELF64BE>;
1187template class ELFWriter<ELF32LE>;
1188template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001189} // end namespace llvm