blob: 68420670d52ad4ccf27f70358ebdf2372376a719 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "Object.h"
11#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000012#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/BinaryFormat/ELF.h"
18#include "llvm/Object/ELFObjectFile.h"
19#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Support/FileOutputBuffer.h"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000021#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000022#include <algorithm>
23#include <cstddef>
24#include <cstdint>
25#include <iterator>
26#include <utility>
27#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000028
29using namespace llvm;
30using namespace object;
31using namespace ELF;
32
Jake Ehrlich76e91102018-01-25 22:46:17 +000033template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000034 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000035
Jake Ehrlich76e91102018-01-25 22:46:17 +000036 uint8_t *Buf = BufPtr->getBufferStart();
Jake Ehrlich6452b112018-02-14 23:31:33 +000037 Buf += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +000038 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000039 Phdr.p_type = Seg.Type;
40 Phdr.p_flags = Seg.Flags;
41 Phdr.p_offset = Seg.Offset;
42 Phdr.p_vaddr = Seg.VAddr;
43 Phdr.p_paddr = Seg.PAddr;
44 Phdr.p_filesz = Seg.FileSize;
45 Phdr.p_memsz = Seg.MemSize;
46 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000047}
48
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000049void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000050void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000051void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000052void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000053void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000054
Jake Ehrlich76e91102018-01-25 22:46:17 +000055template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
56 uint8_t *Buf = BufPtr->getBufferStart();
57 Buf += Sec.HeaderOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +000058 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000059 Shdr.sh_name = Sec.NameIndex;
60 Shdr.sh_type = Sec.Type;
61 Shdr.sh_flags = Sec.Flags;
62 Shdr.sh_addr = Sec.Addr;
63 Shdr.sh_offset = Sec.Offset;
64 Shdr.sh_size = Sec.Size;
65 Shdr.sh_link = Sec.Link;
66 Shdr.sh_info = Sec.Info;
67 Shdr.sh_addralign = Sec.Align;
68 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000069}
70
Jake Ehrlich76e91102018-01-25 22:46:17 +000071SectionVisitor::~SectionVisitor() {}
72
73void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
74 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
75}
76
77void BinarySectionWriter::visit(const RelocationSection &Sec) {
78 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
79}
80
81void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +000082 error("Cannot write '" + Sec.Name + "' out to binary");
83}
84
85void BinarySectionWriter::visit(const GroupSection &Sec) {
86 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +000087}
88
89void SectionWriter::visit(const Section &Sec) {
90 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +000091 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +000092 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
93 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +000094}
95
Jake Ehrlich76e91102018-01-25 22:46:17 +000096void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
97
98void SectionWriter::visit(const OwnedDataSection &Sec) {
99 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
100 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
101}
102
103void OwnedDataSection::accept(SectionVisitor &Visitor) const {
104 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000105}
106
Petr Hosek05a04cb2017-08-01 00:33:58 +0000107void StringTableSection::addString(StringRef Name) {
108 StrTabBuilder.add(Name);
109 Size = StrTabBuilder.getSize();
110}
111
112uint32_t StringTableSection::findIndex(StringRef Name) const {
113 return StrTabBuilder.getOffset(Name);
114}
115
116void StringTableSection::finalize() { StrTabBuilder.finalize(); }
117
Jake Ehrlich76e91102018-01-25 22:46:17 +0000118void SectionWriter::visit(const StringTableSection &Sec) {
119 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
120}
121
122void StringTableSection::accept(SectionVisitor &Visitor) const {
123 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000124}
125
Petr Hosekc1135772017-09-13 03:04:50 +0000126static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000127 switch (Index) {
128 case SHN_ABS:
129 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000130 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000131 }
Petr Hosekc1135772017-09-13 03:04:50 +0000132 if (Machine == EM_HEXAGON) {
133 switch (Index) {
134 case SHN_HEXAGON_SCOMMON:
135 case SHN_HEXAGON_SCOMMON_2:
136 case SHN_HEXAGON_SCOMMON_4:
137 case SHN_HEXAGON_SCOMMON_8:
138 return true;
139 }
140 }
141 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000142}
143
144uint16_t Symbol::getShndx() const {
145 if (DefinedIn != nullptr) {
146 return DefinedIn->Index;
147 }
148 switch (ShndxType) {
149 // This means that we don't have a defined section but we do need to
150 // output a legitimate section index.
151 case SYMBOL_SIMPLE_INDEX:
152 return SHN_UNDEF;
153 case SYMBOL_ABS:
154 case SYMBOL_COMMON:
155 case SYMBOL_HEXAGON_SCOMMON:
156 case SYMBOL_HEXAGON_SCOMMON_2:
157 case SYMBOL_HEXAGON_SCOMMON_4:
158 case SYMBOL_HEXAGON_SCOMMON_8:
159 return static_cast<uint16_t>(ShndxType);
160 }
161 llvm_unreachable("Symbol with invalid ShndxType encountered");
162}
163
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000164void SymbolTableSection::assignIndices() {
165 uint32_t Index = 0;
166 for (auto &Sym : Symbols)
167 Sym->Index = Index++;
168}
169
Petr Hosek79cee9e2017-08-29 02:12:03 +0000170void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
171 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000172 uint8_t Visibility, uint16_t Shndx,
173 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000174 Symbol Sym;
175 Sym.Name = Name;
176 Sym.Binding = Bind;
177 Sym.Type = Type;
178 Sym.DefinedIn = DefinedIn;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000179 if (DefinedIn == nullptr) {
180 if (Shndx >= SHN_LORESERVE)
181 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
182 else
183 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
184 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000185 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000186 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000187 Sym.Size = Sz;
188 Sym.Index = Symbols.size();
189 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
190 Size += this->EntrySize;
191}
192
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000193void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
194 if (SymbolNames == Sec) {
195 error("String table " + SymbolNames->Name +
196 " cannot be removed because it is referenced by the symbol table " +
197 this->Name);
198 }
Paul Semel41695f82018-05-02 20:19:22 +0000199 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000200}
201
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000202void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000203 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
204 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000205 std::stable_partition(
206 std::begin(Symbols), std::end(Symbols),
207 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000208 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000209}
210
Paul Semel4246a462018-05-09 21:36:54 +0000211void SymbolTableSection::removeSymbols(
212 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000213 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000214 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000215 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
216 std::end(Symbols));
217 Size = Symbols.size() * EntrySize;
218 assignIndices();
219}
220
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000221void SymbolTableSection::initialize(SectionTableRef SecTable) {
222 Size = 0;
223 setStrTab(SecTable.getSectionOfType<StringTableSection>(
224 Link,
225 "Symbol table has link index of " + Twine(Link) +
226 " which is not a valid index",
227 "Symbol table has link index of " + Twine(Link) +
228 " which is not a string table"));
229}
230
Petr Hosek79cee9e2017-08-29 02:12:03 +0000231void SymbolTableSection::finalize() {
232 // Make sure SymbolNames is finalized before getting name indexes.
233 SymbolNames->finalize();
234
235 uint32_t MaxLocalIndex = 0;
236 for (auto &Sym : Symbols) {
237 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
238 if (Sym->Binding == STB_LOCAL)
239 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
240 }
241 // Now we need to set the Link and Info fields.
242 Link = SymbolNames->Index;
243 Info = MaxLocalIndex + 1;
244}
245
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000246void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000247 // Add all of our strings to SymbolNames so that SymbolNames has the right
248 // size before layout is decided.
249 for (auto &Sym : Symbols)
250 SymbolNames->addString(Sym->Name);
251}
252
253const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
254 if (Symbols.size() <= Index)
255 error("Invalid symbol index: " + Twine(Index));
256 return Symbols[Index].get();
257}
258
Paul Semel99dda0b2018-05-25 11:01:25 +0000259Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
260 return const_cast<Symbol *>(
261 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
262}
263
Petr Hosek79cee9e2017-08-29 02:12:03 +0000264template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000265void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000266 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000267 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000268 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
269 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000270 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000271 Sym->st_name = Symbol->NameIndex;
272 Sym->st_value = Symbol->Value;
273 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000274 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000275 Sym->setBinding(Symbol->Binding);
276 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000277 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000278 ++Sym;
279 }
280}
281
Jake Ehrlich76e91102018-01-25 22:46:17 +0000282void SymbolTableSection::accept(SectionVisitor &Visitor) const {
283 Visitor.visit(*this);
284}
285
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000286template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000287void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
288 const SectionBase *Sec) {
289 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000290 error("Symbol table " + Symbols->Name +
291 " cannot be removed because it is "
292 "referenced by the relocation "
293 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000294 this->Name);
295 }
296}
297
298template <class SymTabType>
299void RelocSectionWithSymtabBase<SymTabType>::initialize(
300 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000301 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000302 Link,
303 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
304 "Link field value " + Twine(Link) + " in section " + Name +
305 " is not a symbol table"));
306
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000307 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000308 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
309 " in section " + Name +
310 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000311 else
312 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000313}
314
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000315template <class SymTabType>
316void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000317 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000318 if (SecToApplyRel != nullptr)
319 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000320}
321
322template <class ELFT>
323void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
324
325template <class ELFT>
326void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
327 Rela.r_addend = Addend;
328}
329
Jake Ehrlich76e91102018-01-25 22:46:17 +0000330template <class RelRange, class T>
331void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000332 for (const auto &Reloc : Relocations) {
333 Buf->r_offset = Reloc.Offset;
334 setAddend(*Buf, Reloc.Addend);
335 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
336 ++Buf;
337 }
338}
339
340template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000341void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
342 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
343 if (Sec.Type == SHT_REL)
344 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000345 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000346 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000347}
348
Jake Ehrlich76e91102018-01-25 22:46:17 +0000349void RelocationSection::accept(SectionVisitor &Visitor) const {
350 Visitor.visit(*this);
351}
352
Paul Semel4246a462018-05-09 21:36:54 +0000353void RelocationSection::removeSymbols(
354 function_ref<bool(const Symbol &)> ToRemove) {
355 for (const Relocation &Reloc : Relocations)
356 if (ToRemove(*Reloc.RelocSymbol))
357 error("not stripping symbol `" + Reloc.RelocSymbol->Name +
358 "' because it is named in a relocation");
359}
360
Paul Semel99dda0b2018-05-25 11:01:25 +0000361void RelocationSection::markSymbols() {
362 for (const Relocation &Reloc : Relocations)
363 Reloc.RelocSymbol->Referenced = true;
364}
365
Jake Ehrlich76e91102018-01-25 22:46:17 +0000366void SectionWriter::visit(const DynamicRelocationSection &Sec) {
367 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
368 Out.getBufferStart() + Sec.Offset);
369}
370
371void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
372 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000373}
374
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000375void Section::removeSectionReferences(const SectionBase *Sec) {
376 if (LinkSection == Sec) {
377 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000378 " cannot be removed because it is "
379 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000380 this->Name);
381 }
382}
383
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000384void GroupSection::finalize() {
385 this->Info = Sym->Index;
386 this->Link = SymTab->Index;
387}
388
Paul Semel4246a462018-05-09 21:36:54 +0000389void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
390 if (ToRemove(*Sym)) {
391 error("Symbol " + Sym->Name +
392 " cannot be removed because it is "
393 "referenced by the section " +
394 this->Name + "[" + Twine(this->Index) + "]");
395 }
396}
397
Paul Semel99dda0b2018-05-25 11:01:25 +0000398void GroupSection::markSymbols() {
399 if (Sym)
400 Sym->Referenced = true;
401}
402
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000403void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000404 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000405 LinkSection =
406 SecTable.getSection(Link, "Link field value " + Twine(Link) +
407 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000408 if (LinkSection->Type == ELF::SHT_SYMTAB)
409 LinkSection = nullptr;
410 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000411}
412
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000413void Section::finalize() {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000414 this->Link = LinkSection ? LinkSection->Index : 0;
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000415}
416
Jake Ehrlich76e91102018-01-25 22:46:17 +0000417void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000418 FileName = sys::path::filename(File);
419 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000420 // followed by a null terminator and then the CRC32 of the file. The CRC32
421 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
422 // byte, and then finally push the size to alignment and add 4.
423 Size = alignTo(FileName.size() + 1, 4) + 4;
424 // The CRC32 will only be aligned if we align the whole section.
425 Align = 4;
426 Type = ELF::SHT_PROGBITS;
427 Name = ".gnu_debuglink";
428 // For sections not found in segments, OriginalOffset is only used to
429 // establish the order that sections should go in. By using the maximum
430 // possible offset we cause this section to wind up at the end.
431 OriginalOffset = std::numeric_limits<uint64_t>::max();
432 JamCRC crc;
433 crc.update(ArrayRef<char>(Data.data(), Data.size()));
434 // The CRC32 value needs to be complemented because the JamCRC dosn't
435 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
436 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
437 CRC32 = ~crc.getCRC();
438}
439
Jake Ehrlich76e91102018-01-25 22:46:17 +0000440GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000441 // Read in the file to compute the CRC of it.
442 auto DebugOrErr = MemoryBuffer::getFile(File);
443 if (!DebugOrErr)
444 error("'" + File + "': " + DebugOrErr.getError().message());
445 auto Debug = std::move(*DebugOrErr);
446 init(File, Debug->getBuffer());
447}
448
449template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000450void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
451 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000452 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000453 Elf_Word *CRC =
454 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
455 *CRC = Sec.CRC32;
456 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
457}
458
459void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
460 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000461}
462
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000463template <class ELFT>
464void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
465 ELF::Elf32_Word *Buf =
466 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
467 *Buf++ = Sec.FlagWord;
468 for (const auto *S : Sec.GroupMembers)
469 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
470}
471
472void GroupSection::accept(SectionVisitor &Visitor) const {
473 Visitor.visit(*this);
474}
475
Petr Hosek05a04cb2017-08-01 00:33:58 +0000476// Returns true IFF a section is wholly inside the range of a segment
477static bool sectionWithinSegment(const SectionBase &Section,
478 const Segment &Segment) {
479 // If a section is empty it should be treated like it has a size of 1. This is
480 // to clarify the case when an empty section lies on a boundary between two
481 // segments and ensures that the section "belongs" to the second segment and
482 // not the first.
483 uint64_t SecSize = Section.Size ? Section.Size : 1;
484 return Segment.Offset <= Section.OriginalOffset &&
485 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
486}
487
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000488// Returns true IFF a segment's original offset is inside of another segment's
489// range.
490static bool segmentOverlapsSegment(const Segment &Child,
491 const Segment &Parent) {
492
493 return Parent.OriginalOffset <= Child.OriginalOffset &&
494 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
495}
496
Jake Ehrlich46814be2018-01-22 19:27:30 +0000497static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000498 // Any segment without a parent segment should come before a segment
499 // that has a parent segment.
500 if (A->OriginalOffset < B->OriginalOffset)
501 return true;
502 if (A->OriginalOffset > B->OriginalOffset)
503 return false;
504 return A->Index < B->Index;
505}
506
Jake Ehrlich46814be2018-01-22 19:27:30 +0000507static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
508 if (A->PAddr < B->PAddr)
509 return true;
510 if (A->PAddr > B->PAddr)
511 return false;
512 return A->Index < B->Index;
513}
514
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000515template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000516 for (auto &Parent : Obj.segments()) {
517 // Every segment will overlap with itself but we don't want a segment to
518 // be it's own parent so we avoid that situation.
519 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
520 // We want a canonical "most parental" segment but this requires
521 // inspecting the ParentSegment.
522 if (compareSegmentsByOffset(&Parent, &Child))
523 if (Child.ParentSegment == nullptr ||
524 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
525 Child.ParentSegment = &Parent;
526 }
527 }
528 }
529}
530
Jake Ehrlich76e91102018-01-25 22:46:17 +0000531template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000532 uint32_t Index = 0;
533 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000534 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
535 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000536 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000537 Seg.Type = Phdr.p_type;
538 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000539 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000540 Seg.Offset = Phdr.p_offset;
541 Seg.VAddr = Phdr.p_vaddr;
542 Seg.PAddr = Phdr.p_paddr;
543 Seg.FileSize = Phdr.p_filesz;
544 Seg.MemSize = Phdr.p_memsz;
545 Seg.Align = Phdr.p_align;
546 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000547 for (auto &Section : Obj.sections()) {
548 if (sectionWithinSegment(Section, Seg)) {
549 Seg.addSection(&Section);
550 if (!Section.ParentSegment ||
551 Section.ParentSegment->Offset > Seg.Offset) {
552 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000553 }
554 }
555 }
556 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000557
558 auto &ElfHdr = Obj.ElfHdrSegment;
559 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
560 // segments must not overlap, and other types fit even less.
561 ElfHdr.Type = PT_PHDR;
562 ElfHdr.Flags = 0;
563 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
564 ElfHdr.VAddr = 0;
565 ElfHdr.PAddr = 0;
566 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
567 ElfHdr.Align = 0;
568 ElfHdr.Index = Index++;
569
570 const auto &Ehdr = *ElfFile.getHeader();
571 auto &PrHdr = Obj.ProgramHdrSegment;
572 PrHdr.Type = PT_PHDR;
573 PrHdr.Flags = 0;
574 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
575 // Whereas this works automatically for ElfHdr, here OriginalOffset is
576 // always non-zero and to ensure the equation we assign the same value to
577 // VAddr as well.
578 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
579 PrHdr.PAddr = 0;
580 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000581 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000582 PrHdr.Align = sizeof(Elf_Addr);
583 PrHdr.Index = Index++;
584
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000585 // Now we do an O(n^2) loop through the segments in order to match up
586 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000587 for (auto &Child : Obj.segments())
588 setParentSegment(Child);
589 setParentSegment(ElfHdr);
590 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000591}
592
593template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000594void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
595 auto SecTable = Obj.sections();
596 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
597 GroupSec->Link,
598 "Link field value " + Twine(GroupSec->Link) + " in section " +
599 GroupSec->Name + " is invalid",
600 "Link field value " + Twine(GroupSec->Link) + " in section " +
601 GroupSec->Name + " is not a symbol table");
602 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
603 if (!Sym)
604 error("Info field value " + Twine(GroupSec->Info) + " in section " +
605 GroupSec->Name + " is not a valid symbol index");
606 GroupSec->setSymTab(SymTab);
607 GroupSec->setSymbol(Sym);
608 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
609 GroupSec->Contents.empty())
610 error("The content of the section " + GroupSec->Name + " is malformed");
611 const ELF::Elf32_Word *Word =
612 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
613 const ELF::Elf32_Word *End =
614 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
615 GroupSec->setFlagWord(*Word++);
616 for (; Word != End; ++Word) {
617 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
618 GroupSec->addMember(SecTable.getSection(
619 Index, "Group member index " + Twine(Index) + " in section " +
620 GroupSec->Name + " is invalid"));
621 }
622}
623
624template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000625void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000626 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
627 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
628
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000629 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000630 SectionBase *DefSection = nullptr;
631 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000632
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000633 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000634 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000635 error(
636 "Symbol '" + Name +
637 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
638 Twine(Sym.st_shndx));
639 }
640 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000641 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000642 Sym.st_shndx, "Symbol '" + Name +
643 "' is defined in invalid section with index " +
644 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000645 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000646
Petr Hosek79cee9e2017-08-29 02:12:03 +0000647 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000648 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000649 }
650}
651
652template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000653static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
654
655template <class ELFT>
656static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
657 ToSet = Rela.r_addend;
658}
659
Jake Ehrlich76e91102018-01-25 22:46:17 +0000660template <class T>
661void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
662 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000663 for (const auto &Rel : RelRange) {
664 Relocation ToAdd;
665 ToAdd.Offset = Rel.r_offset;
666 getAddend(ToAdd.Addend, Rel);
667 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000668 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000669 Relocs->addRelocation(ToAdd);
670 }
671}
672
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000673SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000674 if (Index == SHN_UNDEF || Index > Sections.size())
675 error(ErrMsg);
676 return Sections[Index - 1].get();
677}
678
679template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000680T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000681 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000682 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000683 return Sec;
684 error(TypeErrMsg);
685}
686
Petr Hosekd7df9b22017-09-06 23:41:02 +0000687template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000688SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000689 ArrayRef<uint8_t> Data;
690 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000691 case SHT_REL:
692 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000693 if (Shdr.sh_flags & SHF_ALLOC) {
694 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000695 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000696 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000697 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000698 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000699 // If a string table is allocated we don't want to mess with it. That would
700 // mean altering the memory image. There are no special link types or
701 // anything so we can just use a Section.
702 if (Shdr.sh_flags & SHF_ALLOC) {
703 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000704 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000705 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000706 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000707 case SHT_HASH:
708 case SHT_GNU_HASH:
709 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
710 // Because of this we don't need to mess with the hash tables either.
711 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000712 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000713 case SHT_GROUP:
714 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
715 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000716 case SHT_DYNSYM:
717 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000718 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000719 case SHT_DYNAMIC:
720 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000721 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000722 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000723 auto &SymTab = Obj.addSection<SymbolTableSection>();
724 Obj.SymbolTable = &SymTab;
725 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000726 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000727 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000728 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000729 default:
730 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000731 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000732 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000733}
734
Jake Ehrlich76e91102018-01-25 22:46:17 +0000735template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000736 uint32_t Index = 0;
737 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
738 if (Index == 0) {
739 ++Index;
740 continue;
741 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000742 auto &Sec = makeSection(Shdr);
743 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
744 Sec.Type = Shdr.sh_type;
745 Sec.Flags = Shdr.sh_flags;
746 Sec.Addr = Shdr.sh_addr;
747 Sec.Offset = Shdr.sh_offset;
748 Sec.OriginalOffset = Shdr.sh_offset;
749 Sec.Size = Shdr.sh_size;
750 Sec.Link = Shdr.sh_link;
751 Sec.Info = Shdr.sh_info;
752 Sec.Align = Shdr.sh_addralign;
753 Sec.EntrySize = Shdr.sh_entsize;
754 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000755 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000756
757 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000758 // details about symbol tables. We need the symbol table filled out before
759 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000760 if (Obj.SymbolTable) {
761 Obj.SymbolTable->initialize(Obj.sections());
762 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000763 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000764
765 // Now that all sections and symbols have been added we can add
766 // relocations that reference symbols and set the link and info fields for
767 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000768 for (auto &Section : Obj.sections()) {
769 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000770 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000771 Section.initialize(Obj.sections());
772 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000773 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
774 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000775 initRelocations(RelSec, Obj.SymbolTable,
776 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000777 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000778 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000779 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000780 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
781 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000782 }
783 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000784}
785
Jake Ehrlich76e91102018-01-25 22:46:17 +0000786template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000787 const auto &Ehdr = *ElfFile.getHeader();
788
Jake Ehrlich76e91102018-01-25 22:46:17 +0000789 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
790 Obj.Type = Ehdr.e_type;
791 Obj.Machine = Ehdr.e_machine;
792 Obj.Version = Ehdr.e_version;
793 Obj.Entry = Ehdr.e_entry;
794 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000795
Jake Ehrlich76e91102018-01-25 22:46:17 +0000796 readSectionHeaders();
797 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000798
Jake Ehrlich76e91102018-01-25 22:46:17 +0000799 Obj.SectionNames =
800 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000801 Ehdr.e_shstrndx,
802 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000803 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000804 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000805 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000806}
807
Jake Ehrlich76e91102018-01-25 22:46:17 +0000808// A generic size function which computes sizes of any random access range.
809template <class R> size_t size(R &&Range) {
810 return static_cast<size_t>(std::end(Range) - std::begin(Range));
811}
812
813Writer::~Writer() {}
814
815Reader::~Reader() {}
816
817ELFReader::ELFReader(StringRef File) {
818 auto BinaryOrErr = createBinary(File);
819 if (!BinaryOrErr)
820 reportError(File, BinaryOrErr.takeError());
Jake Ehrlich9634e182018-01-26 02:01:37 +0000821 auto OwnedBin = std::move(BinaryOrErr.get());
822 std::tie(Bin, Data) = OwnedBin.takeBinary();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000823}
824
825ElfType ELFReader::getElfType() const {
Jake Ehrlich9634e182018-01-26 02:01:37 +0000826 if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000827 return ELFT_ELF32LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000828 if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000829 return ELFT_ELF64LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000830 if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000831 return ELFT_ELF32BE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000832 if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000833 return ELFT_ELF64BE;
834 llvm_unreachable("Invalid ELFType");
835}
836
837std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +0000838 auto Obj = llvm::make_unique<Object>();
Jake Ehrlich9634e182018-01-26 02:01:37 +0000839 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000840 ELFBuilder<ELF32LE> Builder(*o, *Obj);
841 Builder.build();
842 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000843 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000844 ELFBuilder<ELF64LE> Builder(*o, *Obj);
845 Builder.build();
846 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000847 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000848 ELFBuilder<ELF32BE> Builder(*o, *Obj);
849 Builder.build();
850 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000851 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000852 ELFBuilder<ELF64BE> Builder(*o, *Obj);
853 Builder.build();
854 return Obj;
855 }
856 error("Invalid file type");
857}
858
859template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
860 uint8_t *Buf = BufPtr->getBufferStart();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000861 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000862 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
863 Ehdr.e_type = Obj.Type;
864 Ehdr.e_machine = Obj.Machine;
865 Ehdr.e_version = Obj.Version;
866 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000867 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000868 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000869 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
870 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000871 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000872 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000873 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000874 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000875 Ehdr.e_shnum = size(Obj.sections()) + 1;
876 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000877 } else {
878 Ehdr.e_shoff = 0;
879 Ehdr.e_shnum = 0;
880 Ehdr.e_shstrndx = 0;
881 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000882}
883
Jake Ehrlich76e91102018-01-25 22:46:17 +0000884template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
885 for (auto &Seg : Obj.segments())
886 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000887}
888
Jake Ehrlich76e91102018-01-25 22:46:17 +0000889template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
890 uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000891 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000892 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000893 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
894 Shdr.sh_name = 0;
895 Shdr.sh_type = SHT_NULL;
896 Shdr.sh_flags = 0;
897 Shdr.sh_addr = 0;
898 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000899 Shdr.sh_size = 0;
900 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000901 Shdr.sh_info = 0;
902 Shdr.sh_addralign = 0;
903 Shdr.sh_entsize = 0;
904
Jake Ehrlich76e91102018-01-25 22:46:17 +0000905 for (auto &Sec : Obj.sections())
906 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000907}
908
Jake Ehrlich76e91102018-01-25 22:46:17 +0000909template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
910 for (auto &Sec : Obj.sections())
911 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000912}
913
Jake Ehrlich76e91102018-01-25 22:46:17 +0000914void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000915
916 auto Iter = std::stable_partition(
917 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
918 if (ToRemove(*Sec))
919 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000920 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
921 if (auto ToRelSec = RelSec->getSection())
922 return !ToRemove(*ToRelSec);
923 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000924 return true;
925 });
926 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
927 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000928 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000929 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000930 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000931 // Now make sure there are no remaining references to the sections that will
932 // be removed. Sometimes it is impossible to remove a reference so we emit
933 // an error here instead.
934 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
935 for (auto &Segment : Segments)
936 Segment->removeSection(RemoveSec.get());
937 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
938 KeepSec->removeSectionReferences(RemoveSec.get());
939 }
940 // Now finally get rid of them all togethor.
941 Sections.erase(Iter, std::end(Sections));
942}
943
Paul Semel4246a462018-05-09 21:36:54 +0000944void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
945 if (!SymbolTable)
946 return;
947
948 for (const SecPtr &Sec : Sections)
949 Sec->removeSymbols(ToRemove);
950}
951
Jake Ehrlich76e91102018-01-25 22:46:17 +0000952void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000953 // Put all sections in offset order. Maintain the ordering as closely as
954 // possible while meeting that demand however.
955 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
956 return A->OriginalOffset < B->OriginalOffset;
957 };
958 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
959 CompareSections);
960}
961
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000962static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
963 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
964 if (Align == 0)
965 Align = 1;
966 auto Diff =
967 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
968 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
969 // (Offset + Diff) & -Align == Addr & -Align will still hold.
970 if (Diff < 0)
971 Diff += Align;
972 return Offset + Diff;
973}
974
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000975// Orders segments such that if x = y->ParentSegment then y comes before x.
976static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000977 std::stable_sort(std::begin(Segments), std::end(Segments),
978 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000979}
980
981// This function finds a consistent layout for a list of segments starting from
982// an Offset. It assumes that Segments have been sorted by OrderSegments and
983// returns an Offset one past the end of the last segment.
984static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
985 uint64_t Offset) {
986 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +0000987 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +0000988 // The only way a segment should move is if a section was between two
989 // segments and that section was removed. If that section isn't in a segment
990 // then it's acceptable, but not ideal, to simply move it to after the
991 // segments. So we can simply layout segments one after the other accounting
992 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000993 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000994 // We assume that segments have been ordered by OriginalOffset and Index
995 // such that a parent segment will always come before a child segment in
996 // OrderedSegments. This means that the Offset of the ParentSegment should
997 // already be set and we can set our offset relative to it.
998 if (Segment->ParentSegment != nullptr) {
999 auto Parent = Segment->ParentSegment;
1000 Segment->Offset =
1001 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1002 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001003 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001004 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001005 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001006 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001007 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001008 return Offset;
1009}
1010
1011// This function finds a consistent layout for a list of sections. It assumes
1012// that the ->ParentSegment of each section has already been laid out. The
1013// supplied starting Offset is used for the starting offset of any section that
1014// does not have a ParentSegment. It returns either the offset given if all
1015// sections had a ParentSegment or an offset one past the last section if there
1016// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001017template <class Range>
1018static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001019 // Now the offset of every segment has been set we can assign the offsets
1020 // of each section. For sections that are covered by a segment we should use
1021 // the segment's original offset and the section's original offset to compute
1022 // the offset from the start of the segment. Using the offset from the start
1023 // of the segment we can assign a new offset to the section. For sections not
1024 // covered by segments we can just bump Offset to the next valid location.
1025 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001026 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001027 Section.Index = Index++;
1028 if (Section.ParentSegment != nullptr) {
1029 auto Segment = *Section.ParentSegment;
1030 Section.Offset =
1031 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001032 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001033 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1034 Section.Offset = Offset;
1035 if (Section.Type != SHT_NOBITS)
1036 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001037 }
1038 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001039 return Offset;
1040}
Petr Hosek3f383832017-08-26 01:32:20 +00001041
Jake Ehrlich76e91102018-01-25 22:46:17 +00001042template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001043 // We need a temporary list of segments that has a special order to it
1044 // so that we know that anytime ->ParentSegment is set that segment has
1045 // already had its offset properly set.
1046 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001047 for (auto &Segment : Obj.segments())
1048 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001049 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1050 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001051 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001052 // Offset is used as the start offset of the first segment to be laid out.
1053 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1054 // we start at offset 0.
1055 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001056 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001057 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001058 // If we need to write the section header table out then we need to align the
1059 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001060 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001061 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001062 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001063}
1064
Jake Ehrlich76e91102018-01-25 22:46:17 +00001065template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001066 // We already have the section header offset so we can calculate the total
1067 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1069 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001070 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001071}
1072
Jake Ehrlich76e91102018-01-25 22:46:17 +00001073template <class ELFT> void ELFWriter<ELFT>::write() {
1074 writeEhdr();
1075 writePhdrs();
1076 writeSectionData();
1077 if (WriteSectionHeaders)
1078 writeShdrs();
1079 if (auto E = BufPtr->commit())
1080 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001081}
1082
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083void Writer::createBuffer(uint64_t Size) {
1084 auto BufferOrErr =
1085 FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
1086 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
1087 error("failed to open " + File);
1088 });
1089 BufPtr = std::move(*BufferOrErr);
1090}
1091
1092template <class ELFT> void ELFWriter<ELFT>::finalize() {
1093 // It could happen that SectionNames has been removed and yet the user wants
1094 // a section header table output. We need to throw an error if a user tries
1095 // to do that.
1096 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1097 error("Cannot write section header table because section header string "
1098 "table was removed.");
1099
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001100 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001101 if (Obj.SectionNames != nullptr)
1102 for (const auto &Section : Obj.sections()) {
1103 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001104 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001105 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001106 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001107 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001108
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001109 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001110 assignOffsets();
1111
1112 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001113 if (Obj.SectionNames != nullptr)
1114 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001115 // Finally now that all offsets and indexes have been set we can finalize any
1116 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001117 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1118 for (auto &Section : Obj.sections()) {
1119 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001120 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001121 if (WriteSectionHeaders)
1122 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1123 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001124 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001125
1126 createBuffer(totalSize());
1127 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001128}
1129
Jake Ehrlich76e91102018-01-25 22:46:17 +00001130void BinaryWriter::write() {
1131 for (auto &Section : Obj.sections()) {
1132 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001133 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001134 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001135 }
Jake Ehrlichc0e9bee2018-01-26 01:17:35 +00001136 if (auto E = BufPtr->commit())
1137 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001138}
1139
Jake Ehrlich76e91102018-01-25 22:46:17 +00001140void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001141 // TODO: Create a filter range to construct OrderedSegments from so that this
1142 // code can be deduped with assignOffsets above. This should also solve the
1143 // todo below for LayoutSections.
1144 // We need a temporary list of segments that has a special order to it
1145 // so that we know that anytime ->ParentSegment is set that segment has
1146 // already had it's offset properly set. We only want to consider the segments
1147 // that will affect layout of allocated sections so we only add those.
1148 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001149 for (auto &Section : Obj.sections()) {
1150 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1151 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001152 }
1153 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001154
1155 // For binary output, we're going to use physical addresses instead of
1156 // virtual addresses, since a binary output is used for cases like ROM
1157 // loading and physical addresses are intended for ROM loading.
1158 // However, if no segment has a physical address, we'll fallback to using
1159 // virtual addresses for all.
1160 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1161 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1162 for (const auto &Segment : OrderedSegments)
1163 Segment->PAddr = Segment->VAddr;
1164
1165 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1166 compareSegmentsByPAddr);
1167
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001168 // Because we add a ParentSegment for each section we might have duplicate
1169 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1170 // would do very strange things.
1171 auto End =
1172 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1173 OrderedSegments.erase(End, std::end(OrderedSegments));
1174
Jake Ehrlich46814be2018-01-22 19:27:30 +00001175 uint64_t Offset = 0;
1176
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001177 // Modify the first segment so that there is no gap at the start. This allows
1178 // our layout algorithm to proceed as expected while not out writing out the
1179 // gap at the start.
1180 if (!OrderedSegments.empty()) {
1181 auto Seg = OrderedSegments[0];
1182 auto Sec = Seg->firstSection();
1183 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1184 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001185 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001186 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001187 // The PAddr needs to be increased to remove the gap before the first
1188 // section.
1189 Seg->PAddr += Diff;
1190 uint64_t LowestPAddr = Seg->PAddr;
1191 for (auto &Segment : OrderedSegments) {
1192 Segment->Offset = Segment->PAddr - LowestPAddr;
1193 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1194 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001195 }
1196
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001197 // TODO: generalize LayoutSections to take a range. Pass a special range
1198 // constructed from an iterator that skips values for which a predicate does
1199 // not hold. Then pass such a range to LayoutSections instead of constructing
1200 // AllocatedSections here.
1201 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001202 for (auto &Section : Obj.sections()) {
1203 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001204 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001205 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001206 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001207 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001208
1209 // Now that every section has been laid out we just need to compute the total
1210 // file size. This might not be the same as the offset returned by
1211 // LayoutSections, because we want to truncate the last segment to the end of
1212 // its last section, to match GNU objcopy's behaviour.
1213 TotalSize = 0;
1214 for (const auto &Section : AllocatedSections) {
1215 if (Section->Type != SHT_NOBITS)
1216 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1217 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001218
1219 createBuffer(TotalSize);
1220 SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001221}
1222
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001223namespace llvm {
1224
Jake Ehrlich76e91102018-01-25 22:46:17 +00001225template class ELFBuilder<ELF64LE>;
1226template class ELFBuilder<ELF64BE>;
1227template class ELFBuilder<ELF32LE>;
1228template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001229
Jake Ehrlich76e91102018-01-25 22:46:17 +00001230template class ELFWriter<ELF64LE>;
1231template class ELFWriter<ELF64BE>;
1232template class ELFWriter<ELF32LE>;
1233template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001234} // end namespace llvm