blob: 12fd80228bfd7bf85629d3e677855bab49ae38f0 [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;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000030using namespace llvm::objcopy;
Petr Hosek05a04cb2017-08-01 00:33:58 +000031using namespace object;
32using namespace ELF;
33
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000034Buffer::~Buffer() {}
35
36void FileBuffer::allocate(size_t Size) {
37 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
38 FileOutputBuffer::create(getName(), Size, FileOutputBuffer::F_executable);
39 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &E) {
40 error("failed to open " + getName() + ": " + E.message());
41 });
42 Buf = std::move(*BufferOrErr);
43}
44
45Error FileBuffer::commit() { return Buf->commit(); }
46
47uint8_t *FileBuffer::getBufferStart() {
48 return reinterpret_cast<uint8_t *>(Buf->getBufferStart());
49}
50
51void MemBuffer::allocate(size_t Size) {
52 Buf = WritableMemoryBuffer::getNewMemBuffer(Size, getName());
53}
54
55Error MemBuffer::commit() { return Error::success(); }
56
57uint8_t *MemBuffer::getBufferStart() {
58 return reinterpret_cast<uint8_t *>(Buf->getBufferStart());
59}
60
61std::unique_ptr<WritableMemoryBuffer> MemBuffer::releaseMemoryBuffer() {
62 return std::move(Buf);
63}
64
Jake Ehrlich76e91102018-01-25 22:46:17 +000065template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000066 uint8_t *B = Buf.getBufferStart();
67 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
68 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000069 Phdr.p_type = Seg.Type;
70 Phdr.p_flags = Seg.Flags;
71 Phdr.p_offset = Seg.Offset;
72 Phdr.p_vaddr = Seg.VAddr;
73 Phdr.p_paddr = Seg.PAddr;
74 Phdr.p_filesz = Seg.FileSize;
75 Phdr.p_memsz = Seg.MemSize;
76 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000077}
78
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000079void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000080void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000081void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000082void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000083void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000084
Jake Ehrlich76e91102018-01-25 22:46:17 +000085template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000086 uint8_t *B = Buf.getBufferStart();
87 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000088 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000089 Shdr.sh_name = Sec.NameIndex;
90 Shdr.sh_type = Sec.Type;
91 Shdr.sh_flags = Sec.Flags;
92 Shdr.sh_addr = Sec.Addr;
93 Shdr.sh_offset = Sec.Offset;
94 Shdr.sh_size = Sec.Size;
95 Shdr.sh_link = Sec.Link;
96 Shdr.sh_info = Sec.Info;
97 Shdr.sh_addralign = Sec.Align;
98 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000099}
100
Jake Ehrlich76e91102018-01-25 22:46:17 +0000101SectionVisitor::~SectionVisitor() {}
102
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000103void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
104 error("Cannot write symbol section index table '" + Sec.Name + "' ");
105}
106
Jake Ehrlich76e91102018-01-25 22:46:17 +0000107void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
108 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
109}
110
111void BinarySectionWriter::visit(const RelocationSection &Sec) {
112 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
113}
114
115void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000116 error("Cannot write '" + Sec.Name + "' out to binary");
117}
118
119void BinarySectionWriter::visit(const GroupSection &Sec) {
120 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000121}
122
123void SectionWriter::visit(const Section &Sec) {
124 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000125 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000126 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
127 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000128}
129
Jake Ehrlich76e91102018-01-25 22:46:17 +0000130void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
131
132void SectionWriter::visit(const OwnedDataSection &Sec) {
133 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
134 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
135}
136
137void OwnedDataSection::accept(SectionVisitor &Visitor) const {
138 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000139}
140
Petr Hosek05a04cb2017-08-01 00:33:58 +0000141void StringTableSection::addString(StringRef Name) {
142 StrTabBuilder.add(Name);
143 Size = StrTabBuilder.getSize();
144}
145
146uint32_t StringTableSection::findIndex(StringRef Name) const {
147 return StrTabBuilder.getOffset(Name);
148}
149
150void StringTableSection::finalize() { StrTabBuilder.finalize(); }
151
Jake Ehrlich76e91102018-01-25 22:46:17 +0000152void SectionWriter::visit(const StringTableSection &Sec) {
153 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
154}
155
156void StringTableSection::accept(SectionVisitor &Visitor) const {
157 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000158}
159
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000160template <class ELFT>
161void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
162 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000163 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000164 std::copy(std::begin(Sec.Indexes), std::end(Sec.Indexes), IndexesBuffer);
165}
166
167void SectionIndexSection::initialize(SectionTableRef SecTable) {
168 Size = 0;
169 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
170 Link,
171 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
172 "Link field value " + Twine(Link) + " in section " + Name +
173 " is not a symbol table"));
174 Symbols->setShndxTable(this);
175}
176
177void SectionIndexSection::finalize() { Link = Symbols->Index; }
178
179void SectionIndexSection::accept(SectionVisitor &Visitor) const {
180 Visitor.visit(*this);
181}
182
Petr Hosekc1135772017-09-13 03:04:50 +0000183static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000184 switch (Index) {
185 case SHN_ABS:
186 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000187 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000188 }
Petr Hosekc1135772017-09-13 03:04:50 +0000189 if (Machine == EM_HEXAGON) {
190 switch (Index) {
191 case SHN_HEXAGON_SCOMMON:
192 case SHN_HEXAGON_SCOMMON_2:
193 case SHN_HEXAGON_SCOMMON_4:
194 case SHN_HEXAGON_SCOMMON_8:
195 return true;
196 }
197 }
198 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000199}
200
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000201// Large indexes force us to clarify exactly what this function should do. This
202// function should return the value that will appear in st_shndx when written
203// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000204uint16_t Symbol::getShndx() const {
205 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000206 if (DefinedIn->Index >= SHN_LORESERVE)
207 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000208 return DefinedIn->Index;
209 }
210 switch (ShndxType) {
211 // This means that we don't have a defined section but we do need to
212 // output a legitimate section index.
213 case SYMBOL_SIMPLE_INDEX:
214 return SHN_UNDEF;
215 case SYMBOL_ABS:
216 case SYMBOL_COMMON:
217 case SYMBOL_HEXAGON_SCOMMON:
218 case SYMBOL_HEXAGON_SCOMMON_2:
219 case SYMBOL_HEXAGON_SCOMMON_4:
220 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000221 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000222 return static_cast<uint16_t>(ShndxType);
223 }
224 llvm_unreachable("Symbol with invalid ShndxType encountered");
225}
226
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000227void SymbolTableSection::assignIndices() {
228 uint32_t Index = 0;
229 for (auto &Sym : Symbols)
230 Sym->Index = Index++;
231}
232
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000233void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000234 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000235 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000236 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000237 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000238 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000239 Sym.Binding = Bind;
240 Sym.Type = Type;
241 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000242 if (DefinedIn != nullptr)
243 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000244 if (DefinedIn == nullptr) {
245 if (Shndx >= SHN_LORESERVE)
246 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
247 else
248 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
249 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000250 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000251 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000252 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000253 Sym.Index = Symbols.size();
254 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
255 Size += this->EntrySize;
256}
257
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000258void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000259 if (SectionIndexTable == Sec)
260 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000261 if (SymbolNames == Sec) {
262 error("String table " + SymbolNames->Name +
263 " cannot be removed because it is referenced by the symbol table " +
264 this->Name);
265 }
Paul Semel41695f82018-05-02 20:19:22 +0000266 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000267}
268
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000269void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000270 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
271 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000272 std::stable_partition(
273 std::begin(Symbols), std::end(Symbols),
274 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000275 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000276}
277
Paul Semel4246a462018-05-09 21:36:54 +0000278void SymbolTableSection::removeSymbols(
279 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000280 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000281 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000282 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
283 std::end(Symbols));
284 Size = Symbols.size() * EntrySize;
285 assignIndices();
286}
287
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000288void SymbolTableSection::initialize(SectionTableRef SecTable) {
289 Size = 0;
290 setStrTab(SecTable.getSectionOfType<StringTableSection>(
291 Link,
292 "Symbol table has link index of " + Twine(Link) +
293 " which is not a valid index",
294 "Symbol table has link index of " + Twine(Link) +
295 " which is not a string table"));
296}
297
Petr Hosek79cee9e2017-08-29 02:12:03 +0000298void SymbolTableSection::finalize() {
299 // Make sure SymbolNames is finalized before getting name indexes.
300 SymbolNames->finalize();
301
302 uint32_t MaxLocalIndex = 0;
303 for (auto &Sym : Symbols) {
304 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
305 if (Sym->Binding == STB_LOCAL)
306 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
307 }
308 // Now we need to set the Link and Info fields.
309 Link = SymbolNames->Index;
310 Info = MaxLocalIndex + 1;
311}
312
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000313void SymbolTableSection::prepareForLayout() {
314 // Add all potential section indexes before file layout so that the section
315 // index section has the approprite size.
316 if (SectionIndexTable != nullptr) {
317 for (const auto &Sym : Symbols) {
318 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
319 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
320 else
321 SectionIndexTable->addIndex(SHN_UNDEF);
322 }
323 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000324 // Add all of our strings to SymbolNames so that SymbolNames has the right
325 // size before layout is decided.
326 for (auto &Sym : Symbols)
327 SymbolNames->addString(Sym->Name);
328}
329
330const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
331 if (Symbols.size() <= Index)
332 error("Invalid symbol index: " + Twine(Index));
333 return Symbols[Index].get();
334}
335
Paul Semel99dda0b2018-05-25 11:01:25 +0000336Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
337 return const_cast<Symbol *>(
338 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
339}
340
Petr Hosek79cee9e2017-08-29 02:12:03 +0000341template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000342void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000343 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000344 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000345 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000346 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000347 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000348 Sym->st_name = Symbol->NameIndex;
349 Sym->st_value = Symbol->Value;
350 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000351 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000352 Sym->setBinding(Symbol->Binding);
353 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000354 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000355 ++Sym;
356 }
357}
358
Jake Ehrlich76e91102018-01-25 22:46:17 +0000359void SymbolTableSection::accept(SectionVisitor &Visitor) const {
360 Visitor.visit(*this);
361}
362
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000363template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000364void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
365 const SectionBase *Sec) {
366 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000367 error("Symbol table " + Symbols->Name +
368 " cannot be removed because it is "
369 "referenced by the relocation "
370 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000371 this->Name);
372 }
373}
374
375template <class SymTabType>
376void RelocSectionWithSymtabBase<SymTabType>::initialize(
377 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000378 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000379 Link,
380 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
381 "Link field value " + Twine(Link) + " in section " + Name +
382 " is not a symbol table"));
383
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000384 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000385 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
386 " in section " + Name +
387 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000388 else
389 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000390}
391
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000392template <class SymTabType>
393void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000394 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000395 if (SecToApplyRel != nullptr)
396 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000397}
398
399template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000400static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000401
402template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000403static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000404 Rela.r_addend = Addend;
405}
406
Jake Ehrlich76e91102018-01-25 22:46:17 +0000407template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000408static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000409 for (const auto &Reloc : Relocations) {
410 Buf->r_offset = Reloc.Offset;
411 setAddend(*Buf, Reloc.Addend);
412 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
413 ++Buf;
414 }
415}
416
417template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000418void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
419 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
420 if (Sec.Type == SHT_REL)
421 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000422 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000423 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000424}
425
Jake Ehrlich76e91102018-01-25 22:46:17 +0000426void RelocationSection::accept(SectionVisitor &Visitor) const {
427 Visitor.visit(*this);
428}
429
Paul Semel4246a462018-05-09 21:36:54 +0000430void RelocationSection::removeSymbols(
431 function_ref<bool(const Symbol &)> ToRemove) {
432 for (const Relocation &Reloc : Relocations)
433 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000434 error("not stripping symbol '" + Reloc.RelocSymbol->Name +
Paul Semel4246a462018-05-09 21:36:54 +0000435 "' because it is named in a relocation");
436}
437
Paul Semel99dda0b2018-05-25 11:01:25 +0000438void RelocationSection::markSymbols() {
439 for (const Relocation &Reloc : Relocations)
440 Reloc.RelocSymbol->Referenced = true;
441}
442
Jake Ehrlich76e91102018-01-25 22:46:17 +0000443void SectionWriter::visit(const DynamicRelocationSection &Sec) {
444 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
445 Out.getBufferStart() + Sec.Offset);
446}
447
448void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
449 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000450}
451
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000452void Section::removeSectionReferences(const SectionBase *Sec) {
453 if (LinkSection == Sec) {
454 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000455 " cannot be removed because it is "
456 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000457 this->Name);
458 }
459}
460
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000461void GroupSection::finalize() {
462 this->Info = Sym->Index;
463 this->Link = SymTab->Index;
464}
465
Paul Semel4246a462018-05-09 21:36:54 +0000466void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
467 if (ToRemove(*Sym)) {
468 error("Symbol " + Sym->Name +
469 " cannot be removed because it is "
470 "referenced by the section " +
471 this->Name + "[" + Twine(this->Index) + "]");
472 }
473}
474
Paul Semel99dda0b2018-05-25 11:01:25 +0000475void GroupSection::markSymbols() {
476 if (Sym)
477 Sym->Referenced = true;
478}
479
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000480void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000481 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000482 LinkSection =
483 SecTable.getSection(Link, "Link field value " + Twine(Link) +
484 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000485 if (LinkSection->Type == ELF::SHT_SYMTAB)
486 LinkSection = nullptr;
487 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000488}
489
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000490void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000491
Jake Ehrlich76e91102018-01-25 22:46:17 +0000492void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000493 FileName = sys::path::filename(File);
494 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000495 // followed by a null terminator and then the CRC32 of the file. The CRC32
496 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
497 // byte, and then finally push the size to alignment and add 4.
498 Size = alignTo(FileName.size() + 1, 4) + 4;
499 // The CRC32 will only be aligned if we align the whole section.
500 Align = 4;
501 Type = ELF::SHT_PROGBITS;
502 Name = ".gnu_debuglink";
503 // For sections not found in segments, OriginalOffset is only used to
504 // establish the order that sections should go in. By using the maximum
505 // possible offset we cause this section to wind up at the end.
506 OriginalOffset = std::numeric_limits<uint64_t>::max();
507 JamCRC crc;
508 crc.update(ArrayRef<char>(Data.data(), Data.size()));
509 // The CRC32 value needs to be complemented because the JamCRC dosn't
510 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
511 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
512 CRC32 = ~crc.getCRC();
513}
514
Jake Ehrlich76e91102018-01-25 22:46:17 +0000515GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000516 // Read in the file to compute the CRC of it.
517 auto DebugOrErr = MemoryBuffer::getFile(File);
518 if (!DebugOrErr)
519 error("'" + File + "': " + DebugOrErr.getError().message());
520 auto Debug = std::move(*DebugOrErr);
521 init(File, Debug->getBuffer());
522}
523
524template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000525void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
526 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000527 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000528 Elf_Word *CRC =
529 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
530 *CRC = Sec.CRC32;
531 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
532}
533
534void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
535 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000536}
537
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000538template <class ELFT>
539void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
540 ELF::Elf32_Word *Buf =
541 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
542 *Buf++ = Sec.FlagWord;
543 for (const auto *S : Sec.GroupMembers)
544 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
545}
546
547void GroupSection::accept(SectionVisitor &Visitor) const {
548 Visitor.visit(*this);
549}
550
Petr Hosek05a04cb2017-08-01 00:33:58 +0000551// Returns true IFF a section is wholly inside the range of a segment
552static bool sectionWithinSegment(const SectionBase &Section,
553 const Segment &Segment) {
554 // If a section is empty it should be treated like it has a size of 1. This is
555 // to clarify the case when an empty section lies on a boundary between two
556 // segments and ensures that the section "belongs" to the second segment and
557 // not the first.
558 uint64_t SecSize = Section.Size ? Section.Size : 1;
559 return Segment.Offset <= Section.OriginalOffset &&
560 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
561}
562
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000563// Returns true IFF a segment's original offset is inside of another segment's
564// range.
565static bool segmentOverlapsSegment(const Segment &Child,
566 const Segment &Parent) {
567
568 return Parent.OriginalOffset <= Child.OriginalOffset &&
569 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
570}
571
Jake Ehrlich46814be2018-01-22 19:27:30 +0000572static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000573 // Any segment without a parent segment should come before a segment
574 // that has a parent segment.
575 if (A->OriginalOffset < B->OriginalOffset)
576 return true;
577 if (A->OriginalOffset > B->OriginalOffset)
578 return false;
579 return A->Index < B->Index;
580}
581
Jake Ehrlich46814be2018-01-22 19:27:30 +0000582static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
583 if (A->PAddr < B->PAddr)
584 return true;
585 if (A->PAddr > B->PAddr)
586 return false;
587 return A->Index < B->Index;
588}
589
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000590template <class ELFT> void BinaryELFBuilder<ELFT>::initFileHeader() {
591 Obj->Flags = 0x0;
592 Obj->Type = ET_REL;
593 Obj->Entry = 0x0;
594 Obj->Machine = EMachine;
595 Obj->Version = 1;
596}
597
598template <class ELFT> void BinaryELFBuilder<ELFT>::initHeaderSegment() {
599 Obj->ElfHdrSegment.Index = 0;
600}
601
602template <class ELFT> StringTableSection *BinaryELFBuilder<ELFT>::addStrTab() {
603 auto &StrTab = Obj->addSection<StringTableSection>();
604 StrTab.Name = ".strtab";
605
606 Obj->SectionNames = &StrTab;
607 return &StrTab;
608}
609
610template <class ELFT>
611SymbolTableSection *
612BinaryELFBuilder<ELFT>::addSymTab(StringTableSection *StrTab) {
613 auto &SymTab = Obj->addSection<SymbolTableSection>();
614
615 SymTab.Name = ".symtab";
616 SymTab.Link = StrTab->Index;
617 // TODO: Factor out dependence on ElfType here.
618 SymTab.EntrySize = sizeof(Elf_Sym);
619
620 // The symbol table always needs a null symbol
621 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
622
623 Obj->SymbolTable = &SymTab;
624 return &SymTab;
625}
626
627template <class ELFT>
628void BinaryELFBuilder<ELFT>::addData(SymbolTableSection *SymTab) {
629 auto Data = ArrayRef<uint8_t>(
630 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
631 MemBuf->getBufferSize());
632 auto &DataSection = Obj->addSection<Section>(Data);
633 DataSection.Name = ".data";
634 DataSection.Type = ELF::SHT_PROGBITS;
635 DataSection.Size = Data.size();
636 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
637
638 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
639 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
640 [](char c) { return !isalnum(c); }, '_');
641 Twine Prefix = Twine("_binary_") + SanitizedFilename;
642
643 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
644 /*Value=*/0, STV_DEFAULT, 0, 0);
645 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
646 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
647 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
648 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
649}
650
651template <class ELFT> void BinaryELFBuilder<ELFT>::initSections() {
652 for (auto &Section : Obj->sections()) {
653 Section.initialize(Obj->sections());
654 }
655}
656
657template <class ELFT> std::unique_ptr<Object> BinaryELFBuilder<ELFT>::build() {
658 initFileHeader();
659 initHeaderSegment();
660 StringTableSection *StrTab = addStrTab();
661 SymbolTableSection *SymTab = addSymTab(StrTab);
662 initSections();
663 addData(SymTab);
664
665 return std::move(Obj);
666}
667
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000668template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000669 for (auto &Parent : Obj.segments()) {
670 // Every segment will overlap with itself but we don't want a segment to
671 // be it's own parent so we avoid that situation.
672 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
673 // We want a canonical "most parental" segment but this requires
674 // inspecting the ParentSegment.
675 if (compareSegmentsByOffset(&Parent, &Child))
676 if (Child.ParentSegment == nullptr ||
677 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
678 Child.ParentSegment = &Parent;
679 }
680 }
681 }
682}
683
Jake Ehrlich76e91102018-01-25 22:46:17 +0000684template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000685 uint32_t Index = 0;
686 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000687 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
688 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000689 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000690 Seg.Type = Phdr.p_type;
691 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000692 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000693 Seg.Offset = Phdr.p_offset;
694 Seg.VAddr = Phdr.p_vaddr;
695 Seg.PAddr = Phdr.p_paddr;
696 Seg.FileSize = Phdr.p_filesz;
697 Seg.MemSize = Phdr.p_memsz;
698 Seg.Align = Phdr.p_align;
699 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000700 for (auto &Section : Obj.sections()) {
701 if (sectionWithinSegment(Section, Seg)) {
702 Seg.addSection(&Section);
703 if (!Section.ParentSegment ||
704 Section.ParentSegment->Offset > Seg.Offset) {
705 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000706 }
707 }
708 }
709 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000710
711 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000712 ElfHdr.Index = Index++;
713
714 const auto &Ehdr = *ElfFile.getHeader();
715 auto &PrHdr = Obj.ProgramHdrSegment;
716 PrHdr.Type = PT_PHDR;
717 PrHdr.Flags = 0;
718 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
719 // Whereas this works automatically for ElfHdr, here OriginalOffset is
720 // always non-zero and to ensure the equation we assign the same value to
721 // VAddr as well.
722 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
723 PrHdr.PAddr = 0;
724 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000725 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000726 PrHdr.Align = sizeof(Elf_Addr);
727 PrHdr.Index = Index++;
728
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000729 // Now we do an O(n^2) loop through the segments in order to match up
730 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000731 for (auto &Child : Obj.segments())
732 setParentSegment(Child);
733 setParentSegment(ElfHdr);
734 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000735}
736
737template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000738void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
739 auto SecTable = Obj.sections();
740 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
741 GroupSec->Link,
742 "Link field value " + Twine(GroupSec->Link) + " in section " +
743 GroupSec->Name + " is invalid",
744 "Link field value " + Twine(GroupSec->Link) + " in section " +
745 GroupSec->Name + " is not a symbol table");
746 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
747 if (!Sym)
748 error("Info field value " + Twine(GroupSec->Info) + " in section " +
749 GroupSec->Name + " is not a valid symbol index");
750 GroupSec->setSymTab(SymTab);
751 GroupSec->setSymbol(Sym);
752 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
753 GroupSec->Contents.empty())
754 error("The content of the section " + GroupSec->Name + " is malformed");
755 const ELF::Elf32_Word *Word =
756 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
757 const ELF::Elf32_Word *End =
758 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
759 GroupSec->setFlagWord(*Word++);
760 for (; Word != End; ++Word) {
761 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
762 GroupSec->addMember(SecTable.getSection(
763 Index, "Group member index " + Twine(Index) + " in section " +
764 GroupSec->Name + " is invalid"));
765 }
766}
767
768template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000769void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000770 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
771 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000772 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000773
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000774 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
775 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000776 SectionBase *DefSection = nullptr;
777 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000778
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000779 if (Sym.st_shndx == SHN_XINDEX) {
780 if (SymTab->getShndxTable() == nullptr)
781 error("Symbol '" + Name +
782 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
783 if (ShndxData.data() == nullptr) {
784 const Elf_Shdr &ShndxSec =
785 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
786 ShndxData = unwrapOrError(
787 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
788 if (ShndxData.size() != Symbols.size())
789 error("Symbol section index table does not have the same number of "
790 "entries as the symbol table.");
791 }
792 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
793 DefSection = Obj.sections().getSection(
794 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000795 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000796 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000797 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000798 error(
799 "Symbol '" + Name +
800 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
801 Twine(Sym.st_shndx));
802 }
803 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000804 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000805 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000806 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000807 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000808 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000809
Petr Hosek79cee9e2017-08-29 02:12:03 +0000810 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000811 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000812 }
813}
814
815template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000816static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
817
818template <class ELFT>
819static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
820 ToSet = Rela.r_addend;
821}
822
Jake Ehrlich76e91102018-01-25 22:46:17 +0000823template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000824static void initRelocations(RelocationSection *Relocs,
825 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000826 for (const auto &Rel : RelRange) {
827 Relocation ToAdd;
828 ToAdd.Offset = Rel.r_offset;
829 getAddend(ToAdd.Addend, Rel);
830 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000831 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000832 Relocs->addRelocation(ToAdd);
833 }
834}
835
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000836SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000837 if (Index == SHN_UNDEF || Index > Sections.size())
838 error(ErrMsg);
839 return Sections[Index - 1].get();
840}
841
842template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000843T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000844 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000845 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000846 return Sec;
847 error(TypeErrMsg);
848}
849
Petr Hosekd7df9b22017-09-06 23:41:02 +0000850template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000851SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000852 ArrayRef<uint8_t> Data;
853 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000854 case SHT_REL:
855 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000856 if (Shdr.sh_flags & SHF_ALLOC) {
857 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000858 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000859 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000860 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000861 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000862 // If a string table is allocated we don't want to mess with it. That would
863 // mean altering the memory image. There are no special link types or
864 // anything so we can just use a Section.
865 if (Shdr.sh_flags & SHF_ALLOC) {
866 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000867 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000868 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000869 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000870 case SHT_HASH:
871 case SHT_GNU_HASH:
872 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
873 // Because of this we don't need to mess with the hash tables either.
874 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000875 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000876 case SHT_GROUP:
877 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
878 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000879 case SHT_DYNSYM:
880 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000881 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000882 case SHT_DYNAMIC:
883 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000884 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000885 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000886 auto &SymTab = Obj.addSection<SymbolTableSection>();
887 Obj.SymbolTable = &SymTab;
888 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000889 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000890 case SHT_SYMTAB_SHNDX: {
891 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
892 Obj.SectionIndexTable = &ShndxSection;
893 return ShndxSection;
894 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000895 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000896 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000897 default:
898 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000899 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000900 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000901}
902
Jake Ehrlich76e91102018-01-25 22:46:17 +0000903template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000904 uint32_t Index = 0;
905 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
906 if (Index == 0) {
907 ++Index;
908 continue;
909 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000910 auto &Sec = makeSection(Shdr);
911 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
912 Sec.Type = Shdr.sh_type;
913 Sec.Flags = Shdr.sh_flags;
914 Sec.Addr = Shdr.sh_addr;
915 Sec.Offset = Shdr.sh_offset;
916 Sec.OriginalOffset = Shdr.sh_offset;
917 Sec.Size = Shdr.sh_size;
918 Sec.Link = Shdr.sh_link;
919 Sec.Info = Shdr.sh_info;
920 Sec.Align = Shdr.sh_addralign;
921 Sec.EntrySize = Shdr.sh_entsize;
922 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +0000923 Sec.OriginalData =
924 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
925 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000926 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000927
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000928 // If a section index table exists we'll need to initialize it before we
929 // initialize the symbol table because the symbol table might need to
930 // reference it.
931 if (Obj.SectionIndexTable)
932 Obj.SectionIndexTable->initialize(Obj.sections());
933
Petr Hosek79cee9e2017-08-29 02:12:03 +0000934 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000935 // details about symbol tables. We need the symbol table filled out before
936 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000937 if (Obj.SymbolTable) {
938 Obj.SymbolTable->initialize(Obj.sections());
939 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000940 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000941
942 // Now that all sections and symbols have been added we can add
943 // relocations that reference symbols and set the link and info fields for
944 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000945 for (auto &Section : Obj.sections()) {
946 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000947 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000948 Section.initialize(Obj.sections());
949 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000950 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
951 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000952 initRelocations(RelSec, Obj.SymbolTable,
953 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000954 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000955 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000956 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000957 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
958 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000959 }
960 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000961}
962
Jake Ehrlich76e91102018-01-25 22:46:17 +0000963template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000964 const auto &Ehdr = *ElfFile.getHeader();
965
Jake Ehrlich76e91102018-01-25 22:46:17 +0000966 Obj.Type = Ehdr.e_type;
967 Obj.Machine = Ehdr.e_machine;
968 Obj.Version = Ehdr.e_version;
969 Obj.Entry = Ehdr.e_entry;
970 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000971
Jake Ehrlich76e91102018-01-25 22:46:17 +0000972 readSectionHeaders();
973 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000974
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000975 uint32_t ShstrIndex = Ehdr.e_shstrndx;
976 if (ShstrIndex == SHN_XINDEX)
977 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
978
Jake Ehrlich76e91102018-01-25 22:46:17 +0000979 Obj.SectionNames =
980 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000981 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000982 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000983 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000984 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000985 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000986}
987
Jake Ehrlich76e91102018-01-25 22:46:17 +0000988// A generic size function which computes sizes of any random access range.
989template <class R> size_t size(R &&Range) {
990 return static_cast<size_t>(std::end(Range) - std::begin(Range));
991}
992
993Writer::~Writer() {}
994
995Reader::~Reader() {}
996
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000997std::unique_ptr<Object> BinaryReader::create() const {
998 if (MInfo.Is64Bit)
999 return MInfo.IsLittleEndian
1000 ? BinaryELFBuilder<ELF64LE>(MInfo.EMachine, MemBuf).build()
1001 : BinaryELFBuilder<ELF64BE>(MInfo.EMachine, MemBuf).build();
1002 else
1003 return MInfo.IsLittleEndian
1004 ? BinaryELFBuilder<ELF32LE>(MInfo.EMachine, MemBuf).build()
1005 : BinaryELFBuilder<ELF32BE>(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001006}
1007
1008std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001009 auto Obj = llvm::make_unique<Object>();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001010 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001011 ELFBuilder<ELF32LE> Builder(*o, *Obj);
1012 Builder.build();
1013 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001014 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001015 ELFBuilder<ELF64LE> Builder(*o, *Obj);
1016 Builder.build();
1017 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001018 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001019 ELFBuilder<ELF32BE> Builder(*o, *Obj);
1020 Builder.build();
1021 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001022 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001023 ELFBuilder<ELF64BE> Builder(*o, *Obj);
1024 Builder.build();
1025 return Obj;
1026 }
1027 error("Invalid file type");
1028}
1029
1030template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001031 uint8_t *B = Buf.getBufferStart();
1032 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001033 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1034 Ehdr.e_ident[EI_MAG0] = 0x7f;
1035 Ehdr.e_ident[EI_MAG1] = 'E';
1036 Ehdr.e_ident[EI_MAG2] = 'L';
1037 Ehdr.e_ident[EI_MAG3] = 'F';
1038 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1039 Ehdr.e_ident[EI_DATA] =
1040 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1041 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1042 Ehdr.e_ident[EI_OSABI] = ELFOSABI_NONE;
1043 Ehdr.e_ident[EI_ABIVERSION] = 0;
1044
Jake Ehrlich76e91102018-01-25 22:46:17 +00001045 Ehdr.e_type = Obj.Type;
1046 Ehdr.e_machine = Obj.Machine;
1047 Ehdr.e_version = Obj.Version;
1048 Ehdr.e_entry = Obj.Entry;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001049 // TODO: Only set phoff when a program header exists, to avoid tools
1050 // thinking this is corrupt data.
Jake Ehrlich6452b112018-02-14 23:31:33 +00001051 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001052 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001053 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
1054 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001055 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +00001056 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001057 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001058 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001059 // """
1060 // If the number of sections is greater than or equal to
1061 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1062 // number of section header table entries is contained in the sh_size field
1063 // of the section header at index 0.
1064 // """
1065 auto Shnum = size(Obj.sections()) + 1;
1066 if (Shnum >= SHN_LORESERVE)
1067 Ehdr.e_shnum = 0;
1068 else
1069 Ehdr.e_shnum = Shnum;
1070 // """
1071 // If the section name string table section index is greater than or equal
1072 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1073 // and the actual index of the section name string table section is
1074 // contained in the sh_link field of the section header at index 0.
1075 // """
1076 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1077 Ehdr.e_shstrndx = SHN_XINDEX;
1078 else
1079 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001080 } else {
1081 Ehdr.e_shoff = 0;
1082 Ehdr.e_shnum = 0;
1083 Ehdr.e_shstrndx = 0;
1084 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001085}
1086
Jake Ehrlich76e91102018-01-25 22:46:17 +00001087template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1088 for (auto &Seg : Obj.segments())
1089 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001090}
1091
Jake Ehrlich76e91102018-01-25 22:46:17 +00001092template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001093 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001094 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001095 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001096 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001097 Shdr.sh_name = 0;
1098 Shdr.sh_type = SHT_NULL;
1099 Shdr.sh_flags = 0;
1100 Shdr.sh_addr = 0;
1101 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001102 // See writeEhdr for why we do this.
1103 uint64_t Shnum = size(Obj.sections()) + 1;
1104 if (Shnum >= SHN_LORESERVE)
1105 Shdr.sh_size = Shnum;
1106 else
1107 Shdr.sh_size = 0;
1108 // See writeEhdr for why we do this.
1109 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1110 Shdr.sh_link = Obj.SectionNames->Index;
1111 else
1112 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001113 Shdr.sh_info = 0;
1114 Shdr.sh_addralign = 0;
1115 Shdr.sh_entsize = 0;
1116
Jake Ehrlich76e91102018-01-25 22:46:17 +00001117 for (auto &Sec : Obj.sections())
1118 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001119}
1120
Jake Ehrlich76e91102018-01-25 22:46:17 +00001121template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1122 for (auto &Sec : Obj.sections())
1123 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001124}
1125
Jake Ehrlich76e91102018-01-25 22:46:17 +00001126void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001127
1128 auto Iter = std::stable_partition(
1129 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1130 if (ToRemove(*Sec))
1131 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001132 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1133 if (auto ToRelSec = RelSec->getSection())
1134 return !ToRemove(*ToRelSec);
1135 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001136 return true;
1137 });
1138 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1139 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001140 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001141 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001142 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1143 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001144 // Now make sure there are no remaining references to the sections that will
1145 // be removed. Sometimes it is impossible to remove a reference so we emit
1146 // an error here instead.
1147 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1148 for (auto &Segment : Segments)
1149 Segment->removeSection(RemoveSec.get());
1150 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1151 KeepSec->removeSectionReferences(RemoveSec.get());
1152 }
1153 // Now finally get rid of them all togethor.
1154 Sections.erase(Iter, std::end(Sections));
1155}
1156
Paul Semel4246a462018-05-09 21:36:54 +00001157void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1158 if (!SymbolTable)
1159 return;
1160
1161 for (const SecPtr &Sec : Sections)
1162 Sec->removeSymbols(ToRemove);
1163}
1164
Jake Ehrlich76e91102018-01-25 22:46:17 +00001165void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001166 // Put all sections in offset order. Maintain the ordering as closely as
1167 // possible while meeting that demand however.
1168 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1169 return A->OriginalOffset < B->OriginalOffset;
1170 };
1171 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1172 CompareSections);
1173}
1174
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001175static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1176 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1177 if (Align == 0)
1178 Align = 1;
1179 auto Diff =
1180 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1181 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1182 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1183 if (Diff < 0)
1184 Diff += Align;
1185 return Offset + Diff;
1186}
1187
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001188// Orders segments such that if x = y->ParentSegment then y comes before x.
1189static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001190 std::stable_sort(std::begin(Segments), std::end(Segments),
1191 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001192}
1193
1194// This function finds a consistent layout for a list of segments starting from
1195// an Offset. It assumes that Segments have been sorted by OrderSegments and
1196// returns an Offset one past the end of the last segment.
1197static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1198 uint64_t Offset) {
1199 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001200 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001201 // The only way a segment should move is if a section was between two
1202 // segments and that section was removed. If that section isn't in a segment
1203 // then it's acceptable, but not ideal, to simply move it to after the
1204 // segments. So we can simply layout segments one after the other accounting
1205 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001206 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001207 // We assume that segments have been ordered by OriginalOffset and Index
1208 // such that a parent segment will always come before a child segment in
1209 // OrderedSegments. This means that the Offset of the ParentSegment should
1210 // already be set and we can set our offset relative to it.
1211 if (Segment->ParentSegment != nullptr) {
1212 auto Parent = Segment->ParentSegment;
1213 Segment->Offset =
1214 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1215 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001216 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001217 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001218 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001219 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001220 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001221 return Offset;
1222}
1223
1224// This function finds a consistent layout for a list of sections. It assumes
1225// that the ->ParentSegment of each section has already been laid out. The
1226// supplied starting Offset is used for the starting offset of any section that
1227// does not have a ParentSegment. It returns either the offset given if all
1228// sections had a ParentSegment or an offset one past the last section if there
1229// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001230template <class Range>
1231static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001232 // Now the offset of every segment has been set we can assign the offsets
1233 // of each section. For sections that are covered by a segment we should use
1234 // the segment's original offset and the section's original offset to compute
1235 // the offset from the start of the segment. Using the offset from the start
1236 // of the segment we can assign a new offset to the section. For sections not
1237 // covered by segments we can just bump Offset to the next valid location.
1238 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001239 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001240 Section.Index = Index++;
1241 if (Section.ParentSegment != nullptr) {
1242 auto Segment = *Section.ParentSegment;
1243 Section.Offset =
1244 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001245 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001246 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1247 Section.Offset = Offset;
1248 if (Section.Type != SHT_NOBITS)
1249 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001250 }
1251 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001252 return Offset;
1253}
Petr Hosek3f383832017-08-26 01:32:20 +00001254
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001255template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1256 auto &ElfHdr = Obj.ElfHdrSegment;
1257 ElfHdr.Type = PT_PHDR;
1258 ElfHdr.Flags = 0;
1259 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1260 ElfHdr.VAddr = 0;
1261 ElfHdr.PAddr = 0;
1262 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1263 ElfHdr.Align = 0;
1264}
1265
Jake Ehrlich76e91102018-01-25 22:46:17 +00001266template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001267 // We need a temporary list of segments that has a special order to it
1268 // so that we know that anytime ->ParentSegment is set that segment has
1269 // already had its offset properly set.
1270 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001271 for (auto &Segment : Obj.segments())
1272 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001273 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1274 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001275 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001276 // Offset is used as the start offset of the first segment to be laid out.
1277 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1278 // we start at offset 0.
1279 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001280 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001281 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001282 // If we need to write the section header table out then we need to align the
1283 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001284 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001285 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001286 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001287}
1288
Jake Ehrlich76e91102018-01-25 22:46:17 +00001289template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001290 // We already have the section header offset so we can calculate the total
1291 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001292 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1293 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001294 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001295}
1296
Jake Ehrlich76e91102018-01-25 22:46:17 +00001297template <class ELFT> void ELFWriter<ELFT>::write() {
1298 writeEhdr();
1299 writePhdrs();
1300 writeSectionData();
1301 if (WriteSectionHeaders)
1302 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001303 if (auto E = Buf.commit())
1304 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001305}
1306
1307template <class ELFT> void ELFWriter<ELFT>::finalize() {
1308 // It could happen that SectionNames has been removed and yet the user wants
1309 // a section header table output. We need to throw an error if a user tries
1310 // to do that.
1311 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1312 error("Cannot write section header table because section header string "
1313 "table was removed.");
1314
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001315 Obj.sortSections();
1316
1317 // We need to assign indexes before we perform layout because we need to know
1318 // if we need large indexes or not. We can assign indexes first and check as
1319 // we go to see if we will actully need large indexes.
1320 bool NeedsLargeIndexes = false;
1321 if (size(Obj.sections()) >= SHN_LORESERVE) {
1322 auto Sections = Obj.sections();
1323 NeedsLargeIndexes =
1324 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1325 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1326 // TODO: handle case where only one section needs the large index table but
1327 // only needs it because the large index table hasn't been removed yet.
1328 }
1329
1330 if (NeedsLargeIndexes) {
1331 // This means we definitely need to have a section index table but if we
1332 // already have one then we should use it instead of making a new one.
1333 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1334 // Addition of a section to the end does not invalidate the indexes of
1335 // other sections and assigns the correct index to the new section.
1336 auto &Shndx = Obj.addSection<SectionIndexSection>();
1337 Obj.SymbolTable->setShndxTable(&Shndx);
1338 Shndx.setSymTab(Obj.SymbolTable);
1339 }
1340 } else {
1341 // Since we don't need SectionIndexTable we should remove it and all
1342 // references to it.
1343 if (Obj.SectionIndexTable != nullptr) {
1344 Obj.removeSections([this](const SectionBase &Sec) {
1345 return &Sec == Obj.SectionIndexTable;
1346 });
1347 }
1348 }
1349
1350 // Make sure we add the names of all the sections. Importantly this must be
1351 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001352 if (Obj.SectionNames != nullptr)
1353 for (const auto &Section : Obj.sections()) {
1354 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001355 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001356
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001357 initEhdrSegment();
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001358 // Before we can prepare for layout the indexes need to be finalized.
1359 uint64_t Index = 0;
1360 for (auto &Sec : Obj.sections())
1361 Sec.Index = Index++;
1362
1363 // The symbol table does not update all other sections on update. For
1364 // instance, symbol names are not added as new symbols are added. This means
1365 // that some sections, like .strtab, don't yet have their final size.
1366 if (Obj.SymbolTable != nullptr)
1367 Obj.SymbolTable->prepareForLayout();
1368
Petr Hosekc4df10e2017-08-04 21:09:26 +00001369 assignOffsets();
1370
1371 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001372 if (Obj.SectionNames != nullptr)
1373 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001374 // Finally now that all offsets and indexes have been set we can finalize any
1375 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001376 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1377 for (auto &Section : Obj.sections()) {
1378 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001379 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001380 if (WriteSectionHeaders)
1381 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1382 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001383 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001384
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001385 Buf.allocate(totalSize());
1386 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001387}
1388
Jake Ehrlich76e91102018-01-25 22:46:17 +00001389void BinaryWriter::write() {
1390 for (auto &Section : Obj.sections()) {
1391 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001392 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001393 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001394 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001395 if (auto E = Buf.commit())
1396 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001397}
1398
Jake Ehrlich76e91102018-01-25 22:46:17 +00001399void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001400 // TODO: Create a filter range to construct OrderedSegments from so that this
1401 // code can be deduped with assignOffsets above. This should also solve the
1402 // todo below for LayoutSections.
1403 // We need a temporary list of segments that has a special order to it
1404 // so that we know that anytime ->ParentSegment is set that segment has
1405 // already had it's offset properly set. We only want to consider the segments
1406 // that will affect layout of allocated sections so we only add those.
1407 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001408 for (auto &Section : Obj.sections()) {
1409 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1410 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001411 }
1412 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001413
1414 // For binary output, we're going to use physical addresses instead of
1415 // virtual addresses, since a binary output is used for cases like ROM
1416 // loading and physical addresses are intended for ROM loading.
1417 // However, if no segment has a physical address, we'll fallback to using
1418 // virtual addresses for all.
1419 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1420 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1421 for (const auto &Segment : OrderedSegments)
1422 Segment->PAddr = Segment->VAddr;
1423
1424 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1425 compareSegmentsByPAddr);
1426
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001427 // Because we add a ParentSegment for each section we might have duplicate
1428 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1429 // would do very strange things.
1430 auto End =
1431 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1432 OrderedSegments.erase(End, std::end(OrderedSegments));
1433
Jake Ehrlich46814be2018-01-22 19:27:30 +00001434 uint64_t Offset = 0;
1435
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001436 // Modify the first segment so that there is no gap at the start. This allows
1437 // our layout algorithm to proceed as expected while not out writing out the
1438 // gap at the start.
1439 if (!OrderedSegments.empty()) {
1440 auto Seg = OrderedSegments[0];
1441 auto Sec = Seg->firstSection();
1442 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1443 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001444 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001445 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001446 // The PAddr needs to be increased to remove the gap before the first
1447 // section.
1448 Seg->PAddr += Diff;
1449 uint64_t LowestPAddr = Seg->PAddr;
1450 for (auto &Segment : OrderedSegments) {
1451 Segment->Offset = Segment->PAddr - LowestPAddr;
1452 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1453 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001454 }
1455
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001456 // TODO: generalize LayoutSections to take a range. Pass a special range
1457 // constructed from an iterator that skips values for which a predicate does
1458 // not hold. Then pass such a range to LayoutSections instead of constructing
1459 // AllocatedSections here.
1460 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001461 for (auto &Section : Obj.sections()) {
1462 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001463 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001464 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001465 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001466 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001467
1468 // Now that every section has been laid out we just need to compute the total
1469 // file size. This might not be the same as the offset returned by
1470 // LayoutSections, because we want to truncate the last segment to the end of
1471 // its last section, to match GNU objcopy's behaviour.
1472 TotalSize = 0;
1473 for (const auto &Section : AllocatedSections) {
1474 if (Section->Type != SHT_NOBITS)
1475 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1476 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001477
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001478 Buf.allocate(TotalSize);
1479 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001480}
1481
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001482namespace llvm {
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001483namespace objcopy {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001484
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001485template class BinaryELFBuilder<ELF64LE>;
1486template class BinaryELFBuilder<ELF64BE>;
1487template class BinaryELFBuilder<ELF32LE>;
1488template class BinaryELFBuilder<ELF32BE>;
1489
Jake Ehrlich76e91102018-01-25 22:46:17 +00001490template class ELFBuilder<ELF64LE>;
1491template class ELFBuilder<ELF64BE>;
1492template class ELFBuilder<ELF32LE>;
1493template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001494
Jake Ehrlich76e91102018-01-25 22:46:17 +00001495template class ELFWriter<ELF64LE>;
1496template class ELFWriter<ELF64BE>;
1497template class ELFWriter<ELF32LE>;
1498template class ELFWriter<ELF32BE>;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001499} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001500} // end namespace llvm