blob: f803ffe1d81c9be8eb2faa47ded78e039bcaf68c [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
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000033Buffer::~Buffer() {}
34
35void FileBuffer::allocate(size_t Size) {
36 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
37 FileOutputBuffer::create(getName(), Size, FileOutputBuffer::F_executable);
38 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &E) {
39 error("failed to open " + getName() + ": " + E.message());
40 });
41 Buf = std::move(*BufferOrErr);
42}
43
44Error FileBuffer::commit() { return Buf->commit(); }
45
46uint8_t *FileBuffer::getBufferStart() {
47 return reinterpret_cast<uint8_t *>(Buf->getBufferStart());
48}
49
50void MemBuffer::allocate(size_t Size) {
51 Buf = WritableMemoryBuffer::getNewMemBuffer(Size, getName());
52}
53
54Error MemBuffer::commit() { return Error::success(); }
55
56uint8_t *MemBuffer::getBufferStart() {
57 return reinterpret_cast<uint8_t *>(Buf->getBufferStart());
58}
59
60std::unique_ptr<WritableMemoryBuffer> MemBuffer::releaseMemoryBuffer() {
61 return std::move(Buf);
62}
63
Jake Ehrlich76e91102018-01-25 22:46:17 +000064template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000065 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000066
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000067 uint8_t *B = Buf.getBufferStart();
68 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
69 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000070 Phdr.p_type = Seg.Type;
71 Phdr.p_flags = Seg.Flags;
72 Phdr.p_offset = Seg.Offset;
73 Phdr.p_vaddr = Seg.VAddr;
74 Phdr.p_paddr = Seg.PAddr;
75 Phdr.p_filesz = Seg.FileSize;
76 Phdr.p_memsz = Seg.MemSize;
77 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000078}
79
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000080void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000081void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000082void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000083void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000084void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000085
Jake Ehrlich76e91102018-01-25 22:46:17 +000086template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000087 uint8_t *B = Buf.getBufferStart();
88 B += Sec.HeaderOffset;
89 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000090 Shdr.sh_name = Sec.NameIndex;
91 Shdr.sh_type = Sec.Type;
92 Shdr.sh_flags = Sec.Flags;
93 Shdr.sh_addr = Sec.Addr;
94 Shdr.sh_offset = Sec.Offset;
95 Shdr.sh_size = Sec.Size;
96 Shdr.sh_link = Sec.Link;
97 Shdr.sh_info = Sec.Info;
98 Shdr.sh_addralign = Sec.Align;
99 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000100}
101
Jake Ehrlich76e91102018-01-25 22:46:17 +0000102SectionVisitor::~SectionVisitor() {}
103
104void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
105 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
106}
107
108void BinarySectionWriter::visit(const RelocationSection &Sec) {
109 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
110}
111
112void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000113 error("Cannot write '" + Sec.Name + "' out to binary");
114}
115
116void BinarySectionWriter::visit(const GroupSection &Sec) {
117 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000118}
119
120void SectionWriter::visit(const Section &Sec) {
121 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000122 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000123 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
124 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000125}
126
Jake Ehrlich76e91102018-01-25 22:46:17 +0000127void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
128
129void SectionWriter::visit(const OwnedDataSection &Sec) {
130 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
131 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
132}
133
134void OwnedDataSection::accept(SectionVisitor &Visitor) const {
135 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000136}
137
Petr Hosek05a04cb2017-08-01 00:33:58 +0000138void StringTableSection::addString(StringRef Name) {
139 StrTabBuilder.add(Name);
140 Size = StrTabBuilder.getSize();
141}
142
143uint32_t StringTableSection::findIndex(StringRef Name) const {
144 return StrTabBuilder.getOffset(Name);
145}
146
147void StringTableSection::finalize() { StrTabBuilder.finalize(); }
148
Jake Ehrlich76e91102018-01-25 22:46:17 +0000149void SectionWriter::visit(const StringTableSection &Sec) {
150 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
151}
152
153void StringTableSection::accept(SectionVisitor &Visitor) const {
154 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000155}
156
Petr Hosekc1135772017-09-13 03:04:50 +0000157static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000158 switch (Index) {
159 case SHN_ABS:
160 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000161 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000162 }
Petr Hosekc1135772017-09-13 03:04:50 +0000163 if (Machine == EM_HEXAGON) {
164 switch (Index) {
165 case SHN_HEXAGON_SCOMMON:
166 case SHN_HEXAGON_SCOMMON_2:
167 case SHN_HEXAGON_SCOMMON_4:
168 case SHN_HEXAGON_SCOMMON_8:
169 return true;
170 }
171 }
172 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000173}
174
175uint16_t Symbol::getShndx() const {
176 if (DefinedIn != nullptr) {
177 return DefinedIn->Index;
178 }
179 switch (ShndxType) {
180 // This means that we don't have a defined section but we do need to
181 // output a legitimate section index.
182 case SYMBOL_SIMPLE_INDEX:
183 return SHN_UNDEF;
184 case SYMBOL_ABS:
185 case SYMBOL_COMMON:
186 case SYMBOL_HEXAGON_SCOMMON:
187 case SYMBOL_HEXAGON_SCOMMON_2:
188 case SYMBOL_HEXAGON_SCOMMON_4:
189 case SYMBOL_HEXAGON_SCOMMON_8:
190 return static_cast<uint16_t>(ShndxType);
191 }
192 llvm_unreachable("Symbol with invalid ShndxType encountered");
193}
194
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000195void SymbolTableSection::assignIndices() {
196 uint32_t Index = 0;
197 for (auto &Sym : Symbols)
198 Sym->Index = Index++;
199}
200
Petr Hosek79cee9e2017-08-29 02:12:03 +0000201void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
202 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000203 uint8_t Visibility, uint16_t Shndx,
204 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000205 Symbol Sym;
206 Sym.Name = Name;
207 Sym.Binding = Bind;
208 Sym.Type = Type;
209 Sym.DefinedIn = DefinedIn;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000210 if (DefinedIn == nullptr) {
211 if (Shndx >= SHN_LORESERVE)
212 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
213 else
214 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
215 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000216 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000217 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000218 Sym.Size = Sz;
219 Sym.Index = Symbols.size();
220 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
221 Size += this->EntrySize;
222}
223
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000224void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
225 if (SymbolNames == Sec) {
226 error("String table " + SymbolNames->Name +
227 " cannot be removed because it is referenced by the symbol table " +
228 this->Name);
229 }
Paul Semel41695f82018-05-02 20:19:22 +0000230 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000231}
232
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000233void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000234 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
235 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000236 std::stable_partition(
237 std::begin(Symbols), std::end(Symbols),
238 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000239 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000240}
241
Paul Semel4246a462018-05-09 21:36:54 +0000242void SymbolTableSection::removeSymbols(
243 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000244 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000245 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000246 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
247 std::end(Symbols));
248 Size = Symbols.size() * EntrySize;
249 assignIndices();
250}
251
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000252void SymbolTableSection::initialize(SectionTableRef SecTable) {
253 Size = 0;
254 setStrTab(SecTable.getSectionOfType<StringTableSection>(
255 Link,
256 "Symbol table has link index of " + Twine(Link) +
257 " which is not a valid index",
258 "Symbol table has link index of " + Twine(Link) +
259 " which is not a string table"));
260}
261
Petr Hosek79cee9e2017-08-29 02:12:03 +0000262void SymbolTableSection::finalize() {
263 // Make sure SymbolNames is finalized before getting name indexes.
264 SymbolNames->finalize();
265
266 uint32_t MaxLocalIndex = 0;
267 for (auto &Sym : Symbols) {
268 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
269 if (Sym->Binding == STB_LOCAL)
270 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
271 }
272 // Now we need to set the Link and Info fields.
273 Link = SymbolNames->Index;
274 Info = MaxLocalIndex + 1;
275}
276
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000277void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000278 // Add all of our strings to SymbolNames so that SymbolNames has the right
279 // size before layout is decided.
280 for (auto &Sym : Symbols)
281 SymbolNames->addString(Sym->Name);
282}
283
284const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
285 if (Symbols.size() <= Index)
286 error("Invalid symbol index: " + Twine(Index));
287 return Symbols[Index].get();
288}
289
Paul Semel99dda0b2018-05-25 11:01:25 +0000290Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
291 return const_cast<Symbol *>(
292 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
293}
294
Petr Hosek79cee9e2017-08-29 02:12:03 +0000295template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000296void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000297 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000298 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000299 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
300 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000301 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000302 Sym->st_name = Symbol->NameIndex;
303 Sym->st_value = Symbol->Value;
304 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000305 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000306 Sym->setBinding(Symbol->Binding);
307 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000308 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000309 ++Sym;
310 }
311}
312
Jake Ehrlich76e91102018-01-25 22:46:17 +0000313void SymbolTableSection::accept(SectionVisitor &Visitor) const {
314 Visitor.visit(*this);
315}
316
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000317template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000318void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
319 const SectionBase *Sec) {
320 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000321 error("Symbol table " + Symbols->Name +
322 " cannot be removed because it is "
323 "referenced by the relocation "
324 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000325 this->Name);
326 }
327}
328
329template <class SymTabType>
330void RelocSectionWithSymtabBase<SymTabType>::initialize(
331 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000332 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000333 Link,
334 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
335 "Link field value " + Twine(Link) + " in section " + Name +
336 " is not a symbol table"));
337
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000338 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000339 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
340 " in section " + Name +
341 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000342 else
343 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000344}
345
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000346template <class SymTabType>
347void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000348 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000349 if (SecToApplyRel != nullptr)
350 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000351}
352
353template <class ELFT>
354void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
355
356template <class ELFT>
357void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
358 Rela.r_addend = Addend;
359}
360
Jake Ehrlich76e91102018-01-25 22:46:17 +0000361template <class RelRange, class T>
362void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000363 for (const auto &Reloc : Relocations) {
364 Buf->r_offset = Reloc.Offset;
365 setAddend(*Buf, Reloc.Addend);
366 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
367 ++Buf;
368 }
369}
370
371template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000372void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
373 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
374 if (Sec.Type == SHT_REL)
375 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000376 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000377 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000378}
379
Jake Ehrlich76e91102018-01-25 22:46:17 +0000380void RelocationSection::accept(SectionVisitor &Visitor) const {
381 Visitor.visit(*this);
382}
383
Paul Semel4246a462018-05-09 21:36:54 +0000384void RelocationSection::removeSymbols(
385 function_ref<bool(const Symbol &)> ToRemove) {
386 for (const Relocation &Reloc : Relocations)
387 if (ToRemove(*Reloc.RelocSymbol))
388 error("not stripping symbol `" + Reloc.RelocSymbol->Name +
389 "' because it is named in a relocation");
390}
391
Paul Semel99dda0b2018-05-25 11:01:25 +0000392void RelocationSection::markSymbols() {
393 for (const Relocation &Reloc : Relocations)
394 Reloc.RelocSymbol->Referenced = true;
395}
396
Jake Ehrlich76e91102018-01-25 22:46:17 +0000397void SectionWriter::visit(const DynamicRelocationSection &Sec) {
398 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
399 Out.getBufferStart() + Sec.Offset);
400}
401
402void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
403 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000404}
405
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000406void Section::removeSectionReferences(const SectionBase *Sec) {
407 if (LinkSection == Sec) {
408 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000409 " cannot be removed because it is "
410 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000411 this->Name);
412 }
413}
414
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000415void GroupSection::finalize() {
416 this->Info = Sym->Index;
417 this->Link = SymTab->Index;
418}
419
Paul Semel4246a462018-05-09 21:36:54 +0000420void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
421 if (ToRemove(*Sym)) {
422 error("Symbol " + Sym->Name +
423 " cannot be removed because it is "
424 "referenced by the section " +
425 this->Name + "[" + Twine(this->Index) + "]");
426 }
427}
428
Paul Semel99dda0b2018-05-25 11:01:25 +0000429void GroupSection::markSymbols() {
430 if (Sym)
431 Sym->Referenced = true;
432}
433
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000434void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000435 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000436 LinkSection =
437 SecTable.getSection(Link, "Link field value " + Twine(Link) +
438 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000439 if (LinkSection->Type == ELF::SHT_SYMTAB)
440 LinkSection = nullptr;
441 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000442}
443
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000444void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000445
Jake Ehrlich76e91102018-01-25 22:46:17 +0000446void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000447 FileName = sys::path::filename(File);
448 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000449 // followed by a null terminator and then the CRC32 of the file. The CRC32
450 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
451 // byte, and then finally push the size to alignment and add 4.
452 Size = alignTo(FileName.size() + 1, 4) + 4;
453 // The CRC32 will only be aligned if we align the whole section.
454 Align = 4;
455 Type = ELF::SHT_PROGBITS;
456 Name = ".gnu_debuglink";
457 // For sections not found in segments, OriginalOffset is only used to
458 // establish the order that sections should go in. By using the maximum
459 // possible offset we cause this section to wind up at the end.
460 OriginalOffset = std::numeric_limits<uint64_t>::max();
461 JamCRC crc;
462 crc.update(ArrayRef<char>(Data.data(), Data.size()));
463 // The CRC32 value needs to be complemented because the JamCRC dosn't
464 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
465 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
466 CRC32 = ~crc.getCRC();
467}
468
Jake Ehrlich76e91102018-01-25 22:46:17 +0000469GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000470 // Read in the file to compute the CRC of it.
471 auto DebugOrErr = MemoryBuffer::getFile(File);
472 if (!DebugOrErr)
473 error("'" + File + "': " + DebugOrErr.getError().message());
474 auto Debug = std::move(*DebugOrErr);
475 init(File, Debug->getBuffer());
476}
477
478template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000479void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
480 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000481 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000482 Elf_Word *CRC =
483 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
484 *CRC = Sec.CRC32;
485 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
486}
487
488void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
489 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000490}
491
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000492template <class ELFT>
493void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
494 ELF::Elf32_Word *Buf =
495 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
496 *Buf++ = Sec.FlagWord;
497 for (const auto *S : Sec.GroupMembers)
498 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
499}
500
501void GroupSection::accept(SectionVisitor &Visitor) const {
502 Visitor.visit(*this);
503}
504
Petr Hosek05a04cb2017-08-01 00:33:58 +0000505// Returns true IFF a section is wholly inside the range of a segment
506static bool sectionWithinSegment(const SectionBase &Section,
507 const Segment &Segment) {
508 // If a section is empty it should be treated like it has a size of 1. This is
509 // to clarify the case when an empty section lies on a boundary between two
510 // segments and ensures that the section "belongs" to the second segment and
511 // not the first.
512 uint64_t SecSize = Section.Size ? Section.Size : 1;
513 return Segment.Offset <= Section.OriginalOffset &&
514 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
515}
516
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000517// Returns true IFF a segment's original offset is inside of another segment's
518// range.
519static bool segmentOverlapsSegment(const Segment &Child,
520 const Segment &Parent) {
521
522 return Parent.OriginalOffset <= Child.OriginalOffset &&
523 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
524}
525
Jake Ehrlich46814be2018-01-22 19:27:30 +0000526static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000527 // Any segment without a parent segment should come before a segment
528 // that has a parent segment.
529 if (A->OriginalOffset < B->OriginalOffset)
530 return true;
531 if (A->OriginalOffset > B->OriginalOffset)
532 return false;
533 return A->Index < B->Index;
534}
535
Jake Ehrlich46814be2018-01-22 19:27:30 +0000536static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
537 if (A->PAddr < B->PAddr)
538 return true;
539 if (A->PAddr > B->PAddr)
540 return false;
541 return A->Index < B->Index;
542}
543
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000544template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000545 for (auto &Parent : Obj.segments()) {
546 // Every segment will overlap with itself but we don't want a segment to
547 // be it's own parent so we avoid that situation.
548 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
549 // We want a canonical "most parental" segment but this requires
550 // inspecting the ParentSegment.
551 if (compareSegmentsByOffset(&Parent, &Child))
552 if (Child.ParentSegment == nullptr ||
553 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
554 Child.ParentSegment = &Parent;
555 }
556 }
557 }
558}
559
Jake Ehrlich76e91102018-01-25 22:46:17 +0000560template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000561 uint32_t Index = 0;
562 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000563 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
564 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000565 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000566 Seg.Type = Phdr.p_type;
567 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000568 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000569 Seg.Offset = Phdr.p_offset;
570 Seg.VAddr = Phdr.p_vaddr;
571 Seg.PAddr = Phdr.p_paddr;
572 Seg.FileSize = Phdr.p_filesz;
573 Seg.MemSize = Phdr.p_memsz;
574 Seg.Align = Phdr.p_align;
575 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000576 for (auto &Section : Obj.sections()) {
577 if (sectionWithinSegment(Section, Seg)) {
578 Seg.addSection(&Section);
579 if (!Section.ParentSegment ||
580 Section.ParentSegment->Offset > Seg.Offset) {
581 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000582 }
583 }
584 }
585 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000586
587 auto &ElfHdr = Obj.ElfHdrSegment;
588 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
589 // segments must not overlap, and other types fit even less.
590 ElfHdr.Type = PT_PHDR;
591 ElfHdr.Flags = 0;
592 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
593 ElfHdr.VAddr = 0;
594 ElfHdr.PAddr = 0;
595 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
596 ElfHdr.Align = 0;
597 ElfHdr.Index = Index++;
598
599 const auto &Ehdr = *ElfFile.getHeader();
600 auto &PrHdr = Obj.ProgramHdrSegment;
601 PrHdr.Type = PT_PHDR;
602 PrHdr.Flags = 0;
603 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
604 // Whereas this works automatically for ElfHdr, here OriginalOffset is
605 // always non-zero and to ensure the equation we assign the same value to
606 // VAddr as well.
607 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
608 PrHdr.PAddr = 0;
609 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000610 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000611 PrHdr.Align = sizeof(Elf_Addr);
612 PrHdr.Index = Index++;
613
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000614 // Now we do an O(n^2) loop through the segments in order to match up
615 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000616 for (auto &Child : Obj.segments())
617 setParentSegment(Child);
618 setParentSegment(ElfHdr);
619 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000620}
621
622template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000623void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
624 auto SecTable = Obj.sections();
625 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
626 GroupSec->Link,
627 "Link field value " + Twine(GroupSec->Link) + " in section " +
628 GroupSec->Name + " is invalid",
629 "Link field value " + Twine(GroupSec->Link) + " in section " +
630 GroupSec->Name + " is not a symbol table");
631 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
632 if (!Sym)
633 error("Info field value " + Twine(GroupSec->Info) + " in section " +
634 GroupSec->Name + " is not a valid symbol index");
635 GroupSec->setSymTab(SymTab);
636 GroupSec->setSymbol(Sym);
637 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
638 GroupSec->Contents.empty())
639 error("The content of the section " + GroupSec->Name + " is malformed");
640 const ELF::Elf32_Word *Word =
641 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
642 const ELF::Elf32_Word *End =
643 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
644 GroupSec->setFlagWord(*Word++);
645 for (; Word != End; ++Word) {
646 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
647 GroupSec->addMember(SecTable.getSection(
648 Index, "Group member index " + Twine(Index) + " in section " +
649 GroupSec->Name + " is invalid"));
650 }
651}
652
653template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000654void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000655 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
656 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
657
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000658 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000659 SectionBase *DefSection = nullptr;
660 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000661
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000662 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000663 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000664 error(
665 "Symbol '" + Name +
666 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
667 Twine(Sym.st_shndx));
668 }
669 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000670 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000671 Sym.st_shndx, "Symbol '" + Name +
672 "' is defined in invalid section with index " +
673 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000674 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000675
Petr Hosek79cee9e2017-08-29 02:12:03 +0000676 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000677 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000678 }
679}
680
681template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000682static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
683
684template <class ELFT>
685static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
686 ToSet = Rela.r_addend;
687}
688
Jake Ehrlich76e91102018-01-25 22:46:17 +0000689template <class T>
690void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
691 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000692 for (const auto &Rel : RelRange) {
693 Relocation ToAdd;
694 ToAdd.Offset = Rel.r_offset;
695 getAddend(ToAdd.Addend, Rel);
696 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000697 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000698 Relocs->addRelocation(ToAdd);
699 }
700}
701
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000702SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000703 if (Index == SHN_UNDEF || Index > Sections.size())
704 error(ErrMsg);
705 return Sections[Index - 1].get();
706}
707
708template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000709T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000710 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000711 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000712 return Sec;
713 error(TypeErrMsg);
714}
715
Petr Hosekd7df9b22017-09-06 23:41:02 +0000716template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000717SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000718 ArrayRef<uint8_t> Data;
719 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000720 case SHT_REL:
721 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000722 if (Shdr.sh_flags & SHF_ALLOC) {
723 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000724 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000725 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000726 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000727 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000728 // If a string table is allocated we don't want to mess with it. That would
729 // mean altering the memory image. There are no special link types or
730 // anything so we can just use a Section.
731 if (Shdr.sh_flags & SHF_ALLOC) {
732 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000733 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000734 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000735 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000736 case SHT_HASH:
737 case SHT_GNU_HASH:
738 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
739 // Because of this we don't need to mess with the hash tables either.
740 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000741 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000742 case SHT_GROUP:
743 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
744 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000745 case SHT_DYNSYM:
746 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000747 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000748 case SHT_DYNAMIC:
749 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000750 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000751 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000752 auto &SymTab = Obj.addSection<SymbolTableSection>();
753 Obj.SymbolTable = &SymTab;
754 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000755 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000756 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000757 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000758 default:
759 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000760 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000761 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000762}
763
Jake Ehrlich76e91102018-01-25 22:46:17 +0000764template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000765 uint32_t Index = 0;
766 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
767 if (Index == 0) {
768 ++Index;
769 continue;
770 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000771 auto &Sec = makeSection(Shdr);
772 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
773 Sec.Type = Shdr.sh_type;
774 Sec.Flags = Shdr.sh_flags;
775 Sec.Addr = Shdr.sh_addr;
776 Sec.Offset = Shdr.sh_offset;
777 Sec.OriginalOffset = Shdr.sh_offset;
778 Sec.Size = Shdr.sh_size;
779 Sec.Link = Shdr.sh_link;
780 Sec.Info = Shdr.sh_info;
781 Sec.Align = Shdr.sh_addralign;
782 Sec.EntrySize = Shdr.sh_entsize;
783 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000784 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000785
786 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000787 // details about symbol tables. We need the symbol table filled out before
788 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000789 if (Obj.SymbolTable) {
790 Obj.SymbolTable->initialize(Obj.sections());
791 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000792 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000793
794 // Now that all sections and symbols have been added we can add
795 // relocations that reference symbols and set the link and info fields for
796 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000797 for (auto &Section : Obj.sections()) {
798 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000799 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000800 Section.initialize(Obj.sections());
801 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000802 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
803 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000804 initRelocations(RelSec, Obj.SymbolTable,
805 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000806 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000807 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000808 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000809 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
810 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000811 }
812 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000813}
814
Jake Ehrlich76e91102018-01-25 22:46:17 +0000815template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000816 const auto &Ehdr = *ElfFile.getHeader();
817
Jake Ehrlich76e91102018-01-25 22:46:17 +0000818 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
819 Obj.Type = Ehdr.e_type;
820 Obj.Machine = Ehdr.e_machine;
821 Obj.Version = Ehdr.e_version;
822 Obj.Entry = Ehdr.e_entry;
823 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000824
Jake Ehrlich76e91102018-01-25 22:46:17 +0000825 readSectionHeaders();
826 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000827
Jake Ehrlich76e91102018-01-25 22:46:17 +0000828 Obj.SectionNames =
829 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000830 Ehdr.e_shstrndx,
831 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000832 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000833 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000834 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000835}
836
Jake Ehrlich76e91102018-01-25 22:46:17 +0000837// A generic size function which computes sizes of any random access range.
838template <class R> size_t size(R &&Range) {
839 return static_cast<size_t>(std::end(Range) - std::begin(Range));
840}
841
842Writer::~Writer() {}
843
844Reader::~Reader() {}
845
Jake Ehrlich76e91102018-01-25 22:46:17 +0000846ElfType ELFReader::getElfType() const {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000847 if (isa<ELFObjectFile<ELF32LE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000848 return ELFT_ELF32LE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000849 if (isa<ELFObjectFile<ELF64LE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000850 return ELFT_ELF64LE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000851 if (isa<ELFObjectFile<ELF32BE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000852 return ELFT_ELF32BE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000853 if (isa<ELFObjectFile<ELF64BE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000854 return ELFT_ELF64BE;
855 llvm_unreachable("Invalid ELFType");
856}
857
858std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +0000859 auto Obj = llvm::make_unique<Object>();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000860 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000861 ELFBuilder<ELF32LE> Builder(*o, *Obj);
862 Builder.build();
863 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000864 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000865 ELFBuilder<ELF64LE> Builder(*o, *Obj);
866 Builder.build();
867 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000868 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000869 ELFBuilder<ELF32BE> Builder(*o, *Obj);
870 Builder.build();
871 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000872 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000873 ELFBuilder<ELF64BE> Builder(*o, *Obj);
874 Builder.build();
875 return Obj;
876 }
877 error("Invalid file type");
878}
879
880template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000881 uint8_t *B = Buf.getBufferStart();
882 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000883 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
884 Ehdr.e_type = Obj.Type;
885 Ehdr.e_machine = Obj.Machine;
886 Ehdr.e_version = Obj.Version;
887 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000888 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000889 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000890 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
891 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000892 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000893 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000894 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000895 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000896 Ehdr.e_shnum = size(Obj.sections()) + 1;
897 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000898 } else {
899 Ehdr.e_shoff = 0;
900 Ehdr.e_shnum = 0;
901 Ehdr.e_shstrndx = 0;
902 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000903}
904
Jake Ehrlich76e91102018-01-25 22:46:17 +0000905template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
906 for (auto &Seg : Obj.segments())
907 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000908}
909
Jake Ehrlich76e91102018-01-25 22:46:17 +0000910template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000911 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000912 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000913 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000914 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000915 Shdr.sh_name = 0;
916 Shdr.sh_type = SHT_NULL;
917 Shdr.sh_flags = 0;
918 Shdr.sh_addr = 0;
919 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000920 Shdr.sh_size = 0;
921 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000922 Shdr.sh_info = 0;
923 Shdr.sh_addralign = 0;
924 Shdr.sh_entsize = 0;
925
Jake Ehrlich76e91102018-01-25 22:46:17 +0000926 for (auto &Sec : Obj.sections())
927 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000928}
929
Jake Ehrlich76e91102018-01-25 22:46:17 +0000930template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
931 for (auto &Sec : Obj.sections())
932 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000933}
934
Jake Ehrlich76e91102018-01-25 22:46:17 +0000935void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000936
937 auto Iter = std::stable_partition(
938 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
939 if (ToRemove(*Sec))
940 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000941 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
942 if (auto ToRelSec = RelSec->getSection())
943 return !ToRemove(*ToRelSec);
944 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000945 return true;
946 });
947 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
948 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000949 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000950 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000951 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000952 // Now make sure there are no remaining references to the sections that will
953 // be removed. Sometimes it is impossible to remove a reference so we emit
954 // an error here instead.
955 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
956 for (auto &Segment : Segments)
957 Segment->removeSection(RemoveSec.get());
958 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
959 KeepSec->removeSectionReferences(RemoveSec.get());
960 }
961 // Now finally get rid of them all togethor.
962 Sections.erase(Iter, std::end(Sections));
963}
964
Paul Semel4246a462018-05-09 21:36:54 +0000965void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
966 if (!SymbolTable)
967 return;
968
969 for (const SecPtr &Sec : Sections)
970 Sec->removeSymbols(ToRemove);
971}
972
Jake Ehrlich76e91102018-01-25 22:46:17 +0000973void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000974 // Put all sections in offset order. Maintain the ordering as closely as
975 // possible while meeting that demand however.
976 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
977 return A->OriginalOffset < B->OriginalOffset;
978 };
979 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
980 CompareSections);
981}
982
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000983static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
984 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
985 if (Align == 0)
986 Align = 1;
987 auto Diff =
988 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
989 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
990 // (Offset + Diff) & -Align == Addr & -Align will still hold.
991 if (Diff < 0)
992 Diff += Align;
993 return Offset + Diff;
994}
995
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000996// Orders segments such that if x = y->ParentSegment then y comes before x.
997static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000998 std::stable_sort(std::begin(Segments), std::end(Segments),
999 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001000}
1001
1002// This function finds a consistent layout for a list of segments starting from
1003// an Offset. It assumes that Segments have been sorted by OrderSegments and
1004// returns an Offset one past the end of the last segment.
1005static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1006 uint64_t Offset) {
1007 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001008 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001009 // The only way a segment should move is if a section was between two
1010 // segments and that section was removed. If that section isn't in a segment
1011 // then it's acceptable, but not ideal, to simply move it to after the
1012 // segments. So we can simply layout segments one after the other accounting
1013 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001014 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001015 // We assume that segments have been ordered by OriginalOffset and Index
1016 // such that a parent segment will always come before a child segment in
1017 // OrderedSegments. This means that the Offset of the ParentSegment should
1018 // already be set and we can set our offset relative to it.
1019 if (Segment->ParentSegment != nullptr) {
1020 auto Parent = Segment->ParentSegment;
1021 Segment->Offset =
1022 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1023 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001024 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001025 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001026 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001027 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001028 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001029 return Offset;
1030}
1031
1032// This function finds a consistent layout for a list of sections. It assumes
1033// that the ->ParentSegment of each section has already been laid out. The
1034// supplied starting Offset is used for the starting offset of any section that
1035// does not have a ParentSegment. It returns either the offset given if all
1036// sections had a ParentSegment or an offset one past the last section if there
1037// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001038template <class Range>
1039static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001040 // Now the offset of every segment has been set we can assign the offsets
1041 // of each section. For sections that are covered by a segment we should use
1042 // the segment's original offset and the section's original offset to compute
1043 // the offset from the start of the segment. Using the offset from the start
1044 // of the segment we can assign a new offset to the section. For sections not
1045 // covered by segments we can just bump Offset to the next valid location.
1046 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001047 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001048 Section.Index = Index++;
1049 if (Section.ParentSegment != nullptr) {
1050 auto Segment = *Section.ParentSegment;
1051 Section.Offset =
1052 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001053 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001054 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1055 Section.Offset = Offset;
1056 if (Section.Type != SHT_NOBITS)
1057 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001058 }
1059 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001060 return Offset;
1061}
Petr Hosek3f383832017-08-26 01:32:20 +00001062
Jake Ehrlich76e91102018-01-25 22:46:17 +00001063template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001064 // We need a temporary list of segments that has a special order to it
1065 // so that we know that anytime ->ParentSegment is set that segment has
1066 // already had its offset properly set.
1067 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068 for (auto &Segment : Obj.segments())
1069 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001070 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1071 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001072 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001073 // Offset is used as the start offset of the first segment to be laid out.
1074 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1075 // we start at offset 0.
1076 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001077 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001078 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001079 // If we need to write the section header table out then we need to align the
1080 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001081 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001082 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001084}
1085
Jake Ehrlich76e91102018-01-25 22:46:17 +00001086template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001087 // We already have the section header offset so we can calculate the total
1088 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001089 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1090 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001091 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001092}
1093
Jake Ehrlich76e91102018-01-25 22:46:17 +00001094template <class ELFT> void ELFWriter<ELFT>::write() {
1095 writeEhdr();
1096 writePhdrs();
1097 writeSectionData();
1098 if (WriteSectionHeaders)
1099 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001100 if (auto E = Buf.commit())
1101 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001102}
1103
1104template <class ELFT> void ELFWriter<ELFT>::finalize() {
1105 // It could happen that SectionNames has been removed and yet the user wants
1106 // a section header table output. We need to throw an error if a user tries
1107 // to do that.
1108 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1109 error("Cannot write section header table because section header string "
1110 "table was removed.");
1111
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001112 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001113 if (Obj.SectionNames != nullptr)
1114 for (const auto &Section : Obj.sections()) {
1115 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001116 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001117 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001118 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001119 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001120
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001121 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001122 assignOffsets();
1123
1124 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001125 if (Obj.SectionNames != nullptr)
1126 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001127 // Finally now that all offsets and indexes have been set we can finalize any
1128 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001129 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1130 for (auto &Section : Obj.sections()) {
1131 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001132 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001133 if (WriteSectionHeaders)
1134 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1135 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001136 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001137
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001138 Buf.allocate(totalSize());
1139 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001140}
1141
Jake Ehrlich76e91102018-01-25 22:46:17 +00001142void BinaryWriter::write() {
1143 for (auto &Section : Obj.sections()) {
1144 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001145 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001146 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001147 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001148 if (auto E = Buf.commit())
1149 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001150}
1151
Jake Ehrlich76e91102018-01-25 22:46:17 +00001152void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001153 // TODO: Create a filter range to construct OrderedSegments from so that this
1154 // code can be deduped with assignOffsets above. This should also solve the
1155 // todo below for LayoutSections.
1156 // We need a temporary list of segments that has a special order to it
1157 // so that we know that anytime ->ParentSegment is set that segment has
1158 // already had it's offset properly set. We only want to consider the segments
1159 // that will affect layout of allocated sections so we only add those.
1160 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001161 for (auto &Section : Obj.sections()) {
1162 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1163 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001164 }
1165 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001166
1167 // For binary output, we're going to use physical addresses instead of
1168 // virtual addresses, since a binary output is used for cases like ROM
1169 // loading and physical addresses are intended for ROM loading.
1170 // However, if no segment has a physical address, we'll fallback to using
1171 // virtual addresses for all.
1172 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1173 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1174 for (const auto &Segment : OrderedSegments)
1175 Segment->PAddr = Segment->VAddr;
1176
1177 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1178 compareSegmentsByPAddr);
1179
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001180 // Because we add a ParentSegment for each section we might have duplicate
1181 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1182 // would do very strange things.
1183 auto End =
1184 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1185 OrderedSegments.erase(End, std::end(OrderedSegments));
1186
Jake Ehrlich46814be2018-01-22 19:27:30 +00001187 uint64_t Offset = 0;
1188
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001189 // Modify the first segment so that there is no gap at the start. This allows
1190 // our layout algorithm to proceed as expected while not out writing out the
1191 // gap at the start.
1192 if (!OrderedSegments.empty()) {
1193 auto Seg = OrderedSegments[0];
1194 auto Sec = Seg->firstSection();
1195 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1196 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001197 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001198 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001199 // The PAddr needs to be increased to remove the gap before the first
1200 // section.
1201 Seg->PAddr += Diff;
1202 uint64_t LowestPAddr = Seg->PAddr;
1203 for (auto &Segment : OrderedSegments) {
1204 Segment->Offset = Segment->PAddr - LowestPAddr;
1205 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1206 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001207 }
1208
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001209 // TODO: generalize LayoutSections to take a range. Pass a special range
1210 // constructed from an iterator that skips values for which a predicate does
1211 // not hold. Then pass such a range to LayoutSections instead of constructing
1212 // AllocatedSections here.
1213 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001214 for (auto &Section : Obj.sections()) {
1215 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001216 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001217 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001218 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001219 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001220
1221 // Now that every section has been laid out we just need to compute the total
1222 // file size. This might not be the same as the offset returned by
1223 // LayoutSections, because we want to truncate the last segment to the end of
1224 // its last section, to match GNU objcopy's behaviour.
1225 TotalSize = 0;
1226 for (const auto &Section : AllocatedSections) {
1227 if (Section->Type != SHT_NOBITS)
1228 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1229 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001230
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001231 Buf.allocate(TotalSize);
1232 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001233}
1234
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001235namespace llvm {
1236
Jake Ehrlich76e91102018-01-25 22:46:17 +00001237template class ELFBuilder<ELF64LE>;
1238template class ELFBuilder<ELF64BE>;
1239template class ELFBuilder<ELF32LE>;
1240template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001241
Jake Ehrlich76e91102018-01-25 22:46:17 +00001242template class ELFWriter<ELF64LE>;
1243template class ELFWriter<ELF64BE>;
1244template class ELFWriter<ELF32LE>;
1245template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001246} // end namespace llvm