blob: efb3207aa8daedca2fdd0621aaf5e47f22aaad2f [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() {}
53
Jake Ehrlich76e91102018-01-25 22:46:17 +000054template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
55 uint8_t *Buf = BufPtr->getBufferStart();
56 Buf += Sec.HeaderOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +000057 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000058 Shdr.sh_name = Sec.NameIndex;
59 Shdr.sh_type = Sec.Type;
60 Shdr.sh_flags = Sec.Flags;
61 Shdr.sh_addr = Sec.Addr;
62 Shdr.sh_offset = Sec.Offset;
63 Shdr.sh_size = Sec.Size;
64 Shdr.sh_link = Sec.Link;
65 Shdr.sh_info = Sec.Info;
66 Shdr.sh_addralign = Sec.Align;
67 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000068}
69
Jake Ehrlich76e91102018-01-25 22:46:17 +000070SectionVisitor::~SectionVisitor() {}
71
72void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
73 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
74}
75
76void BinarySectionWriter::visit(const RelocationSection &Sec) {
77 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
78}
79
80void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +000081 error("Cannot write '" + Sec.Name + "' out to binary");
82}
83
84void BinarySectionWriter::visit(const GroupSection &Sec) {
85 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +000086}
87
88void SectionWriter::visit(const Section &Sec) {
89 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +000090 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +000091 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
92 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +000093}
94
Jake Ehrlich76e91102018-01-25 22:46:17 +000095void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
96
97void SectionWriter::visit(const OwnedDataSection &Sec) {
98 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
99 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
100}
101
102void OwnedDataSection::accept(SectionVisitor &Visitor) const {
103 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000104}
105
Petr Hosek05a04cb2017-08-01 00:33:58 +0000106void StringTableSection::addString(StringRef Name) {
107 StrTabBuilder.add(Name);
108 Size = StrTabBuilder.getSize();
109}
110
111uint32_t StringTableSection::findIndex(StringRef Name) const {
112 return StrTabBuilder.getOffset(Name);
113}
114
115void StringTableSection::finalize() { StrTabBuilder.finalize(); }
116
Jake Ehrlich76e91102018-01-25 22:46:17 +0000117void SectionWriter::visit(const StringTableSection &Sec) {
118 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
119}
120
121void StringTableSection::accept(SectionVisitor &Visitor) const {
122 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000123}
124
Petr Hosekc1135772017-09-13 03:04:50 +0000125static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000126 switch (Index) {
127 case SHN_ABS:
128 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000129 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000130 }
Petr Hosekc1135772017-09-13 03:04:50 +0000131 if (Machine == EM_HEXAGON) {
132 switch (Index) {
133 case SHN_HEXAGON_SCOMMON:
134 case SHN_HEXAGON_SCOMMON_2:
135 case SHN_HEXAGON_SCOMMON_4:
136 case SHN_HEXAGON_SCOMMON_8:
137 return true;
138 }
139 }
140 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000141}
142
143uint16_t Symbol::getShndx() const {
144 if (DefinedIn != nullptr) {
145 return DefinedIn->Index;
146 }
147 switch (ShndxType) {
148 // This means that we don't have a defined section but we do need to
149 // output a legitimate section index.
150 case SYMBOL_SIMPLE_INDEX:
151 return SHN_UNDEF;
152 case SYMBOL_ABS:
153 case SYMBOL_COMMON:
154 case SYMBOL_HEXAGON_SCOMMON:
155 case SYMBOL_HEXAGON_SCOMMON_2:
156 case SYMBOL_HEXAGON_SCOMMON_4:
157 case SYMBOL_HEXAGON_SCOMMON_8:
158 return static_cast<uint16_t>(ShndxType);
159 }
160 llvm_unreachable("Symbol with invalid ShndxType encountered");
161}
162
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000163void SymbolTableSection::assignIndices() {
164 uint32_t Index = 0;
165 for (auto &Sym : Symbols)
166 Sym->Index = Index++;
167}
168
Petr Hosek79cee9e2017-08-29 02:12:03 +0000169void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
170 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000171 uint8_t Visibility, uint16_t Shndx,
172 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000173 Symbol Sym;
174 Sym.Name = Name;
175 Sym.Binding = Bind;
176 Sym.Type = Type;
177 Sym.DefinedIn = DefinedIn;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000178 if (DefinedIn == nullptr) {
179 if (Shndx >= SHN_LORESERVE)
180 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
181 else
182 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
183 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000184 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000185 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000186 Sym.Size = Sz;
187 Sym.Index = Symbols.size();
188 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
189 Size += this->EntrySize;
190}
191
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000192void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
193 if (SymbolNames == Sec) {
194 error("String table " + SymbolNames->Name +
195 " cannot be removed because it is referenced by the symbol table " +
196 this->Name);
197 }
Paul Semel41695f82018-05-02 20:19:22 +0000198 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000199}
200
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000201void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
202 for (auto &Sym : Symbols)
203 Callable(*Sym);
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000204 std::stable_partition(
205 std::begin(Symbols), std::end(Symbols),
206 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000207 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000208}
209
Paul Semel4246a462018-05-09 21:36:54 +0000210void SymbolTableSection::removeSymbols(
211 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000212 Symbols.erase(
213 std::remove_if(std::begin(Symbols), std::end(Symbols),
214 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
215 std::end(Symbols));
216 Size = Symbols.size() * EntrySize;
217 assignIndices();
218}
219
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000220void SymbolTableSection::initialize(SectionTableRef SecTable) {
221 Size = 0;
222 setStrTab(SecTable.getSectionOfType<StringTableSection>(
223 Link,
224 "Symbol table has link index of " + Twine(Link) +
225 " which is not a valid index",
226 "Symbol table has link index of " + Twine(Link) +
227 " which is not a string table"));
228}
229
Petr Hosek79cee9e2017-08-29 02:12:03 +0000230void SymbolTableSection::finalize() {
231 // Make sure SymbolNames is finalized before getting name indexes.
232 SymbolNames->finalize();
233
234 uint32_t MaxLocalIndex = 0;
235 for (auto &Sym : Symbols) {
236 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
237 if (Sym->Binding == STB_LOCAL)
238 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
239 }
240 // Now we need to set the Link and Info fields.
241 Link = SymbolNames->Index;
242 Info = MaxLocalIndex + 1;
243}
244
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000245void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000246 // Add all of our strings to SymbolNames so that SymbolNames has the right
247 // size before layout is decided.
248 for (auto &Sym : Symbols)
249 SymbolNames->addString(Sym->Name);
250}
251
252const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
253 if (Symbols.size() <= Index)
254 error("Invalid symbol index: " + Twine(Index));
255 return Symbols[Index].get();
256}
257
258template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000259void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000260 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000261 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000262 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
263 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000264 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000265 Sym->st_name = Symbol->NameIndex;
266 Sym->st_value = Symbol->Value;
267 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000268 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000269 Sym->setBinding(Symbol->Binding);
270 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000271 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000272 ++Sym;
273 }
274}
275
Jake Ehrlich76e91102018-01-25 22:46:17 +0000276void SymbolTableSection::accept(SectionVisitor &Visitor) const {
277 Visitor.visit(*this);
278}
279
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000280template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000281void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
282 const SectionBase *Sec) {
283 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000284 error("Symbol table " + Symbols->Name +
285 " cannot be removed because it is "
286 "referenced by the relocation "
287 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000288 this->Name);
289 }
290}
291
292template <class SymTabType>
293void RelocSectionWithSymtabBase<SymTabType>::initialize(
294 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000295 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000296 Link,
297 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
298 "Link field value " + Twine(Link) + " in section " + Name +
299 " is not a symbol table"));
300
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000301 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000302 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
303 " in section " + Name +
304 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000305 else
306 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000307}
308
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000309template <class SymTabType>
310void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000311 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000312 if (SecToApplyRel != nullptr)
313 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000314}
315
316template <class ELFT>
317void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
318
319template <class ELFT>
320void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
321 Rela.r_addend = Addend;
322}
323
Jake Ehrlich76e91102018-01-25 22:46:17 +0000324template <class RelRange, class T>
325void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000326 for (const auto &Reloc : Relocations) {
327 Buf->r_offset = Reloc.Offset;
328 setAddend(*Buf, Reloc.Addend);
329 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
330 ++Buf;
331 }
332}
333
334template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000335void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
336 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
337 if (Sec.Type == SHT_REL)
338 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000339 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000340 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000341}
342
Jake Ehrlich76e91102018-01-25 22:46:17 +0000343void RelocationSection::accept(SectionVisitor &Visitor) const {
344 Visitor.visit(*this);
345}
346
Paul Semel4246a462018-05-09 21:36:54 +0000347void RelocationSection::removeSymbols(
348 function_ref<bool(const Symbol &)> ToRemove) {
349 for (const Relocation &Reloc : Relocations)
350 if (ToRemove(*Reloc.RelocSymbol))
351 error("not stripping symbol `" + Reloc.RelocSymbol->Name +
352 "' because it is named in a relocation");
353}
354
Jake Ehrlich76e91102018-01-25 22:46:17 +0000355void SectionWriter::visit(const DynamicRelocationSection &Sec) {
356 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
357 Out.getBufferStart() + Sec.Offset);
358}
359
360void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
361 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000362}
363
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000364void Section::removeSectionReferences(const SectionBase *Sec) {
365 if (LinkSection == Sec) {
366 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000367 " cannot be removed because it is "
368 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000369 this->Name);
370 }
371}
372
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000373void GroupSection::finalize() {
374 this->Info = Sym->Index;
375 this->Link = SymTab->Index;
376}
377
Paul Semel4246a462018-05-09 21:36:54 +0000378void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
379 if (ToRemove(*Sym)) {
380 error("Symbol " + Sym->Name +
381 " cannot be removed because it is "
382 "referenced by the section " +
383 this->Name + "[" + Twine(this->Index) + "]");
384 }
385}
386
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000387void Section::initialize(SectionTableRef SecTable) {
388 if (Link != ELF::SHN_UNDEF)
389 LinkSection =
390 SecTable.getSection(Link, "Link field value " + Twine(Link) +
391 " in section " + Name + " is invalid");
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000392}
393
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000394void Section::finalize() {
395 if (LinkSection)
396 this->Link = LinkSection->Index;
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000397}
398
Jake Ehrlich76e91102018-01-25 22:46:17 +0000399void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000400 FileName = sys::path::filename(File);
401 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000402 // followed by a null terminator and then the CRC32 of the file. The CRC32
403 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
404 // byte, and then finally push the size to alignment and add 4.
405 Size = alignTo(FileName.size() + 1, 4) + 4;
406 // The CRC32 will only be aligned if we align the whole section.
407 Align = 4;
408 Type = ELF::SHT_PROGBITS;
409 Name = ".gnu_debuglink";
410 // For sections not found in segments, OriginalOffset is only used to
411 // establish the order that sections should go in. By using the maximum
412 // possible offset we cause this section to wind up at the end.
413 OriginalOffset = std::numeric_limits<uint64_t>::max();
414 JamCRC crc;
415 crc.update(ArrayRef<char>(Data.data(), Data.size()));
416 // The CRC32 value needs to be complemented because the JamCRC dosn't
417 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
418 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
419 CRC32 = ~crc.getCRC();
420}
421
Jake Ehrlich76e91102018-01-25 22:46:17 +0000422GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000423 // Read in the file to compute the CRC of it.
424 auto DebugOrErr = MemoryBuffer::getFile(File);
425 if (!DebugOrErr)
426 error("'" + File + "': " + DebugOrErr.getError().message());
427 auto Debug = std::move(*DebugOrErr);
428 init(File, Debug->getBuffer());
429}
430
431template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000432void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
433 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000434 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000435 Elf_Word *CRC =
436 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
437 *CRC = Sec.CRC32;
438 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
439}
440
441void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
442 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000443}
444
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000445template <class ELFT>
446void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
447 ELF::Elf32_Word *Buf =
448 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
449 *Buf++ = Sec.FlagWord;
450 for (const auto *S : Sec.GroupMembers)
451 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
452}
453
454void GroupSection::accept(SectionVisitor &Visitor) const {
455 Visitor.visit(*this);
456}
457
Petr Hosek05a04cb2017-08-01 00:33:58 +0000458// Returns true IFF a section is wholly inside the range of a segment
459static bool sectionWithinSegment(const SectionBase &Section,
460 const Segment &Segment) {
461 // If a section is empty it should be treated like it has a size of 1. This is
462 // to clarify the case when an empty section lies on a boundary between two
463 // segments and ensures that the section "belongs" to the second segment and
464 // not the first.
465 uint64_t SecSize = Section.Size ? Section.Size : 1;
466 return Segment.Offset <= Section.OriginalOffset &&
467 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
468}
469
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000470// Returns true IFF a segment's original offset is inside of another segment's
471// range.
472static bool segmentOverlapsSegment(const Segment &Child,
473 const Segment &Parent) {
474
475 return Parent.OriginalOffset <= Child.OriginalOffset &&
476 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
477}
478
Jake Ehrlich46814be2018-01-22 19:27:30 +0000479static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000480 // Any segment without a parent segment should come before a segment
481 // that has a parent segment.
482 if (A->OriginalOffset < B->OriginalOffset)
483 return true;
484 if (A->OriginalOffset > B->OriginalOffset)
485 return false;
486 return A->Index < B->Index;
487}
488
Jake Ehrlich46814be2018-01-22 19:27:30 +0000489static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
490 if (A->PAddr < B->PAddr)
491 return true;
492 if (A->PAddr > B->PAddr)
493 return false;
494 return A->Index < B->Index;
495}
496
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000497template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000498 for (auto &Parent : Obj.segments()) {
499 // Every segment will overlap with itself but we don't want a segment to
500 // be it's own parent so we avoid that situation.
501 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
502 // We want a canonical "most parental" segment but this requires
503 // inspecting the ParentSegment.
504 if (compareSegmentsByOffset(&Parent, &Child))
505 if (Child.ParentSegment == nullptr ||
506 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
507 Child.ParentSegment = &Parent;
508 }
509 }
510 }
511}
512
Jake Ehrlich76e91102018-01-25 22:46:17 +0000513template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000514 uint32_t Index = 0;
515 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000516 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
517 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000518 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000519 Seg.Type = Phdr.p_type;
520 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000521 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000522 Seg.Offset = Phdr.p_offset;
523 Seg.VAddr = Phdr.p_vaddr;
524 Seg.PAddr = Phdr.p_paddr;
525 Seg.FileSize = Phdr.p_filesz;
526 Seg.MemSize = Phdr.p_memsz;
527 Seg.Align = Phdr.p_align;
528 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000529 for (auto &Section : Obj.sections()) {
530 if (sectionWithinSegment(Section, Seg)) {
531 Seg.addSection(&Section);
532 if (!Section.ParentSegment ||
533 Section.ParentSegment->Offset > Seg.Offset) {
534 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000535 }
536 }
537 }
538 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000539
540 auto &ElfHdr = Obj.ElfHdrSegment;
541 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
542 // segments must not overlap, and other types fit even less.
543 ElfHdr.Type = PT_PHDR;
544 ElfHdr.Flags = 0;
545 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
546 ElfHdr.VAddr = 0;
547 ElfHdr.PAddr = 0;
548 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
549 ElfHdr.Align = 0;
550 ElfHdr.Index = Index++;
551
552 const auto &Ehdr = *ElfFile.getHeader();
553 auto &PrHdr = Obj.ProgramHdrSegment;
554 PrHdr.Type = PT_PHDR;
555 PrHdr.Flags = 0;
556 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
557 // Whereas this works automatically for ElfHdr, here OriginalOffset is
558 // always non-zero and to ensure the equation we assign the same value to
559 // VAddr as well.
560 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
561 PrHdr.PAddr = 0;
562 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000563 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000564 PrHdr.Align = sizeof(Elf_Addr);
565 PrHdr.Index = Index++;
566
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000567 // Now we do an O(n^2) loop through the segments in order to match up
568 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000569 for (auto &Child : Obj.segments())
570 setParentSegment(Child);
571 setParentSegment(ElfHdr);
572 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000573}
574
575template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000576void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
577 auto SecTable = Obj.sections();
578 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
579 GroupSec->Link,
580 "Link field value " + Twine(GroupSec->Link) + " in section " +
581 GroupSec->Name + " is invalid",
582 "Link field value " + Twine(GroupSec->Link) + " in section " +
583 GroupSec->Name + " is not a symbol table");
584 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
585 if (!Sym)
586 error("Info field value " + Twine(GroupSec->Info) + " in section " +
587 GroupSec->Name + " is not a valid symbol index");
588 GroupSec->setSymTab(SymTab);
589 GroupSec->setSymbol(Sym);
590 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
591 GroupSec->Contents.empty())
592 error("The content of the section " + GroupSec->Name + " is malformed");
593 const ELF::Elf32_Word *Word =
594 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
595 const ELF::Elf32_Word *End =
596 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
597 GroupSec->setFlagWord(*Word++);
598 for (; Word != End; ++Word) {
599 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
600 GroupSec->addMember(SecTable.getSection(
601 Index, "Group member index " + Twine(Index) + " in section " +
602 GroupSec->Name + " is invalid"));
603 }
604}
605
606template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000607void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000608 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
609 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
610
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000611 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000612 SectionBase *DefSection = nullptr;
613 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000614
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000615 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000616 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000617 error(
618 "Symbol '" + Name +
619 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
620 Twine(Sym.st_shndx));
621 }
622 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000623 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000624 Sym.st_shndx, "Symbol '" + Name +
625 "' is defined in invalid section with index " +
626 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000627 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000628
Petr Hosek79cee9e2017-08-29 02:12:03 +0000629 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000630 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000631 }
632}
633
634template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000635static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
636
637template <class ELFT>
638static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
639 ToSet = Rela.r_addend;
640}
641
Jake Ehrlich76e91102018-01-25 22:46:17 +0000642template <class T>
643void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
644 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000645 for (const auto &Rel : RelRange) {
646 Relocation ToAdd;
647 ToAdd.Offset = Rel.r_offset;
648 getAddend(ToAdd.Addend, Rel);
649 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000650 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000651 Relocs->addRelocation(ToAdd);
652 }
653}
654
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000655SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000656 if (Index == SHN_UNDEF || Index > Sections.size())
657 error(ErrMsg);
658 return Sections[Index - 1].get();
659}
660
661template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000662T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000663 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000664 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000665 return Sec;
666 error(TypeErrMsg);
667}
668
Petr Hosekd7df9b22017-09-06 23:41:02 +0000669template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000670SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000671 ArrayRef<uint8_t> Data;
672 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000673 case SHT_REL:
674 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000675 if (Shdr.sh_flags & SHF_ALLOC) {
676 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000677 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000678 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000679 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000680 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000681 // If a string table is allocated we don't want to mess with it. That would
682 // mean altering the memory image. There are no special link types or
683 // anything so we can just use a Section.
684 if (Shdr.sh_flags & SHF_ALLOC) {
685 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000686 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000687 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000688 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000689 case SHT_HASH:
690 case SHT_GNU_HASH:
691 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
692 // Because of this we don't need to mess with the hash tables either.
693 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000694 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000695 case SHT_GROUP:
696 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
697 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000698 case SHT_DYNSYM:
699 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000700 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000701 case SHT_DYNAMIC:
702 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000703 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000704 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000705 auto &SymTab = Obj.addSection<SymbolTableSection>();
706 Obj.SymbolTable = &SymTab;
707 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000708 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000709 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000710 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000711 default:
712 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000713 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000714 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000715}
716
Jake Ehrlich76e91102018-01-25 22:46:17 +0000717template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000718 uint32_t Index = 0;
719 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
720 if (Index == 0) {
721 ++Index;
722 continue;
723 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000724 auto &Sec = makeSection(Shdr);
725 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
726 Sec.Type = Shdr.sh_type;
727 Sec.Flags = Shdr.sh_flags;
728 Sec.Addr = Shdr.sh_addr;
729 Sec.Offset = Shdr.sh_offset;
730 Sec.OriginalOffset = Shdr.sh_offset;
731 Sec.Size = Shdr.sh_size;
732 Sec.Link = Shdr.sh_link;
733 Sec.Info = Shdr.sh_info;
734 Sec.Align = Shdr.sh_addralign;
735 Sec.EntrySize = Shdr.sh_entsize;
736 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000737 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000738
739 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000740 // details about symbol tables. We need the symbol table filled out before
741 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000742 if (Obj.SymbolTable) {
743 Obj.SymbolTable->initialize(Obj.sections());
744 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000745 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000746
747 // Now that all sections and symbols have been added we can add
748 // relocations that reference symbols and set the link and info fields for
749 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000750 for (auto &Section : Obj.sections()) {
751 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000752 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000753 Section.initialize(Obj.sections());
754 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000755 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
756 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000757 initRelocations(RelSec, Obj.SymbolTable,
758 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000759 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000760 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000761 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000762 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
763 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000764 }
765 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000766}
767
Jake Ehrlich76e91102018-01-25 22:46:17 +0000768template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000769 const auto &Ehdr = *ElfFile.getHeader();
770
Jake Ehrlich76e91102018-01-25 22:46:17 +0000771 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
772 Obj.Type = Ehdr.e_type;
773 Obj.Machine = Ehdr.e_machine;
774 Obj.Version = Ehdr.e_version;
775 Obj.Entry = Ehdr.e_entry;
776 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000777
Jake Ehrlich76e91102018-01-25 22:46:17 +0000778 readSectionHeaders();
779 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000780
Jake Ehrlich76e91102018-01-25 22:46:17 +0000781 Obj.SectionNames =
782 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000783 Ehdr.e_shstrndx,
784 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000785 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000786 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000787 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000788}
789
Jake Ehrlich76e91102018-01-25 22:46:17 +0000790// A generic size function which computes sizes of any random access range.
791template <class R> size_t size(R &&Range) {
792 return static_cast<size_t>(std::end(Range) - std::begin(Range));
793}
794
795Writer::~Writer() {}
796
797Reader::~Reader() {}
798
799ELFReader::ELFReader(StringRef File) {
800 auto BinaryOrErr = createBinary(File);
801 if (!BinaryOrErr)
802 reportError(File, BinaryOrErr.takeError());
Jake Ehrlich9634e182018-01-26 02:01:37 +0000803 auto OwnedBin = std::move(BinaryOrErr.get());
804 std::tie(Bin, Data) = OwnedBin.takeBinary();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000805}
806
807ElfType ELFReader::getElfType() const {
Jake Ehrlich9634e182018-01-26 02:01:37 +0000808 if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000809 return ELFT_ELF32LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000810 if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000811 return ELFT_ELF64LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000812 if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000813 return ELFT_ELF32BE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000814 if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000815 return ELFT_ELF64BE;
816 llvm_unreachable("Invalid ELFType");
817}
818
819std::unique_ptr<Object> ELFReader::create() const {
820 auto Obj = llvm::make_unique<Object>(Data);
Jake Ehrlich9634e182018-01-26 02:01:37 +0000821 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000822 ELFBuilder<ELF32LE> Builder(*o, *Obj);
823 Builder.build();
824 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000825 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000826 ELFBuilder<ELF64LE> Builder(*o, *Obj);
827 Builder.build();
828 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000829 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000830 ELFBuilder<ELF32BE> Builder(*o, *Obj);
831 Builder.build();
832 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000833 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000834 ELFBuilder<ELF64BE> Builder(*o, *Obj);
835 Builder.build();
836 return Obj;
837 }
838 error("Invalid file type");
839}
840
841template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
842 uint8_t *Buf = BufPtr->getBufferStart();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000843 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000844 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
845 Ehdr.e_type = Obj.Type;
846 Ehdr.e_machine = Obj.Machine;
847 Ehdr.e_version = Obj.Version;
848 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000849 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000850 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000851 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
852 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000853 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000854 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000855 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000856 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000857 Ehdr.e_shnum = size(Obj.sections()) + 1;
858 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000859 } else {
860 Ehdr.e_shoff = 0;
861 Ehdr.e_shnum = 0;
862 Ehdr.e_shstrndx = 0;
863 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000864}
865
Jake Ehrlich76e91102018-01-25 22:46:17 +0000866template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
867 for (auto &Seg : Obj.segments())
868 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000869}
870
Jake Ehrlich76e91102018-01-25 22:46:17 +0000871template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
872 uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000873 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000874 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000875 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
876 Shdr.sh_name = 0;
877 Shdr.sh_type = SHT_NULL;
878 Shdr.sh_flags = 0;
879 Shdr.sh_addr = 0;
880 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000881 Shdr.sh_size = 0;
882 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000883 Shdr.sh_info = 0;
884 Shdr.sh_addralign = 0;
885 Shdr.sh_entsize = 0;
886
Jake Ehrlich76e91102018-01-25 22:46:17 +0000887 for (auto &Sec : Obj.sections())
888 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000889}
890
Jake Ehrlich76e91102018-01-25 22:46:17 +0000891template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
892 for (auto &Sec : Obj.sections())
893 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000894}
895
Jake Ehrlich76e91102018-01-25 22:46:17 +0000896void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000897
898 auto Iter = std::stable_partition(
899 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
900 if (ToRemove(*Sec))
901 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000902 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
903 if (auto ToRelSec = RelSec->getSection())
904 return !ToRemove(*ToRelSec);
905 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000906 return true;
907 });
908 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
909 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000910 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000911 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000912 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000913 // Now make sure there are no remaining references to the sections that will
914 // be removed. Sometimes it is impossible to remove a reference so we emit
915 // an error here instead.
916 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
917 for (auto &Segment : Segments)
918 Segment->removeSection(RemoveSec.get());
919 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
920 KeepSec->removeSectionReferences(RemoveSec.get());
921 }
922 // Now finally get rid of them all togethor.
923 Sections.erase(Iter, std::end(Sections));
924}
925
Paul Semel4246a462018-05-09 21:36:54 +0000926void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
927 if (!SymbolTable)
928 return;
929
930 for (const SecPtr &Sec : Sections)
931 Sec->removeSymbols(ToRemove);
932}
933
Jake Ehrlich76e91102018-01-25 22:46:17 +0000934void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000935 // Put all sections in offset order. Maintain the ordering as closely as
936 // possible while meeting that demand however.
937 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
938 return A->OriginalOffset < B->OriginalOffset;
939 };
940 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
941 CompareSections);
942}
943
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000944static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
945 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
946 if (Align == 0)
947 Align = 1;
948 auto Diff =
949 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
950 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
951 // (Offset + Diff) & -Align == Addr & -Align will still hold.
952 if (Diff < 0)
953 Diff += Align;
954 return Offset + Diff;
955}
956
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000957// Orders segments such that if x = y->ParentSegment then y comes before x.
958static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000959 std::stable_sort(std::begin(Segments), std::end(Segments),
960 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000961}
962
963// This function finds a consistent layout for a list of segments starting from
964// an Offset. It assumes that Segments have been sorted by OrderSegments and
965// returns an Offset one past the end of the last segment.
966static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
967 uint64_t Offset) {
968 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +0000969 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +0000970 // The only way a segment should move is if a section was between two
971 // segments and that section was removed. If that section isn't in a segment
972 // then it's acceptable, but not ideal, to simply move it to after the
973 // segments. So we can simply layout segments one after the other accounting
974 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000975 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000976 // We assume that segments have been ordered by OriginalOffset and Index
977 // such that a parent segment will always come before a child segment in
978 // OrderedSegments. This means that the Offset of the ParentSegment should
979 // already be set and we can set our offset relative to it.
980 if (Segment->ParentSegment != nullptr) {
981 auto Parent = Segment->ParentSegment;
982 Segment->Offset =
983 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
984 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000985 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000986 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000987 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000988 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000989 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000990 return Offset;
991}
992
993// This function finds a consistent layout for a list of sections. It assumes
994// that the ->ParentSegment of each section has already been laid out. The
995// supplied starting Offset is used for the starting offset of any section that
996// does not have a ParentSegment. It returns either the offset given if all
997// sections had a ParentSegment or an offset one past the last section if there
998// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000999template <class Range>
1000static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001001 // Now the offset of every segment has been set we can assign the offsets
1002 // of each section. For sections that are covered by a segment we should use
1003 // the segment's original offset and the section's original offset to compute
1004 // the offset from the start of the segment. Using the offset from the start
1005 // of the segment we can assign a new offset to the section. For sections not
1006 // covered by segments we can just bump Offset to the next valid location.
1007 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001008 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001009 Section.Index = Index++;
1010 if (Section.ParentSegment != nullptr) {
1011 auto Segment = *Section.ParentSegment;
1012 Section.Offset =
1013 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001014 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001015 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1016 Section.Offset = Offset;
1017 if (Section.Type != SHT_NOBITS)
1018 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001019 }
1020 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001021 return Offset;
1022}
Petr Hosek3f383832017-08-26 01:32:20 +00001023
Jake Ehrlich76e91102018-01-25 22:46:17 +00001024template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001025 // We need a temporary list of segments that has a special order to it
1026 // so that we know that anytime ->ParentSegment is set that segment has
1027 // already had its offset properly set.
1028 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001029 for (auto &Segment : Obj.segments())
1030 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001031 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1032 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001033 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001034 // Offset is used as the start offset of the first segment to be laid out.
1035 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1036 // we start at offset 0.
1037 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001038 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001039 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001040 // If we need to write the section header table out then we need to align the
1041 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001042 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001043 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001044 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001045}
1046
Jake Ehrlich76e91102018-01-25 22:46:17 +00001047template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001048 // We already have the section header offset so we can calculate the total
1049 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001050 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1051 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001052 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001053}
1054
Jake Ehrlich76e91102018-01-25 22:46:17 +00001055template <class ELFT> void ELFWriter<ELFT>::write() {
1056 writeEhdr();
1057 writePhdrs();
1058 writeSectionData();
1059 if (WriteSectionHeaders)
1060 writeShdrs();
1061 if (auto E = BufPtr->commit())
1062 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001063}
1064
Jake Ehrlich76e91102018-01-25 22:46:17 +00001065void Writer::createBuffer(uint64_t Size) {
1066 auto BufferOrErr =
1067 FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
1068 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
1069 error("failed to open " + File);
1070 });
1071 BufPtr = std::move(*BufferOrErr);
1072}
1073
1074template <class ELFT> void ELFWriter<ELFT>::finalize() {
1075 // It could happen that SectionNames has been removed and yet the user wants
1076 // a section header table output. We need to throw an error if a user tries
1077 // to do that.
1078 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1079 error("Cannot write section header table because section header string "
1080 "table was removed.");
1081
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001082 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083 if (Obj.SectionNames != nullptr)
1084 for (const auto &Section : Obj.sections()) {
1085 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001086 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001087 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001088 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001089 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001090
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001091 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001092 assignOffsets();
1093
1094 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001095 if (Obj.SectionNames != nullptr)
1096 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001097 // Finally now that all offsets and indexes have been set we can finalize any
1098 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001099 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1100 for (auto &Section : Obj.sections()) {
1101 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001102 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001103 if (WriteSectionHeaders)
1104 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1105 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001106 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001107
1108 createBuffer(totalSize());
1109 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001110}
1111
Jake Ehrlich76e91102018-01-25 22:46:17 +00001112void BinaryWriter::write() {
1113 for (auto &Section : Obj.sections()) {
1114 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001115 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001116 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001117 }
Jake Ehrlichc0e9bee2018-01-26 01:17:35 +00001118 if (auto E = BufPtr->commit())
1119 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001120}
1121
Jake Ehrlich76e91102018-01-25 22:46:17 +00001122void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001123 // TODO: Create a filter range to construct OrderedSegments from so that this
1124 // code can be deduped with assignOffsets above. This should also solve the
1125 // todo below for LayoutSections.
1126 // We need a temporary list of segments that has a special order to it
1127 // so that we know that anytime ->ParentSegment is set that segment has
1128 // already had it's offset properly set. We only want to consider the segments
1129 // that will affect layout of allocated sections so we only add those.
1130 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001131 for (auto &Section : Obj.sections()) {
1132 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1133 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001134 }
1135 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001136
1137 // For binary output, we're going to use physical addresses instead of
1138 // virtual addresses, since a binary output is used for cases like ROM
1139 // loading and physical addresses are intended for ROM loading.
1140 // However, if no segment has a physical address, we'll fallback to using
1141 // virtual addresses for all.
1142 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1143 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1144 for (const auto &Segment : OrderedSegments)
1145 Segment->PAddr = Segment->VAddr;
1146
1147 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1148 compareSegmentsByPAddr);
1149
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001150 // Because we add a ParentSegment for each section we might have duplicate
1151 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1152 // would do very strange things.
1153 auto End =
1154 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1155 OrderedSegments.erase(End, std::end(OrderedSegments));
1156
Jake Ehrlich46814be2018-01-22 19:27:30 +00001157 uint64_t Offset = 0;
1158
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001159 // Modify the first segment so that there is no gap at the start. This allows
1160 // our layout algorithm to proceed as expected while not out writing out the
1161 // gap at the start.
1162 if (!OrderedSegments.empty()) {
1163 auto Seg = OrderedSegments[0];
1164 auto Sec = Seg->firstSection();
1165 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1166 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001167 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001168 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001169 // The PAddr needs to be increased to remove the gap before the first
1170 // section.
1171 Seg->PAddr += Diff;
1172 uint64_t LowestPAddr = Seg->PAddr;
1173 for (auto &Segment : OrderedSegments) {
1174 Segment->Offset = Segment->PAddr - LowestPAddr;
1175 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1176 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001177 }
1178
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001179 // TODO: generalize LayoutSections to take a range. Pass a special range
1180 // constructed from an iterator that skips values for which a predicate does
1181 // not hold. Then pass such a range to LayoutSections instead of constructing
1182 // AllocatedSections here.
1183 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001184 for (auto &Section : Obj.sections()) {
1185 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001186 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001187 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001188 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001189 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001190
1191 // Now that every section has been laid out we just need to compute the total
1192 // file size. This might not be the same as the offset returned by
1193 // LayoutSections, because we want to truncate the last segment to the end of
1194 // its last section, to match GNU objcopy's behaviour.
1195 TotalSize = 0;
1196 for (const auto &Section : AllocatedSections) {
1197 if (Section->Type != SHT_NOBITS)
1198 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1199 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001200
1201 createBuffer(TotalSize);
1202 SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001203}
1204
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001205namespace llvm {
1206
Jake Ehrlich76e91102018-01-25 22:46:17 +00001207template class ELFBuilder<ELF64LE>;
1208template class ELFBuilder<ELF64BE>;
1209template class ELFBuilder<ELF32LE>;
1210template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001211
Jake Ehrlich76e91102018-01-25 22:46:17 +00001212template class ELFWriter<ELF64LE>;
1213template class ELFWriter<ELF64BE>;
1214template class ELFWriter<ELF32LE>;
1215template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001216} // end namespace llvm