blob: 1fb0de81c8b7a56eaa04f2179144b66e93e6e850 [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
Petr Hosek79cee9e2017-08-29 02:12:03 +0000233void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
234 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000235 uint8_t Visibility, uint16_t Shndx,
236 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000237 Symbol Sym;
238 Sym.Name = Name;
239 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;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000252 Sym.Size = Sz;
253 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
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000590template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000591 for (auto &Parent : Obj.segments()) {
592 // Every segment will overlap with itself but we don't want a segment to
593 // be it's own parent so we avoid that situation.
594 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
595 // We want a canonical "most parental" segment but this requires
596 // inspecting the ParentSegment.
597 if (compareSegmentsByOffset(&Parent, &Child))
598 if (Child.ParentSegment == nullptr ||
599 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
600 Child.ParentSegment = &Parent;
601 }
602 }
603 }
604}
605
Jake Ehrlich76e91102018-01-25 22:46:17 +0000606template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000607 uint32_t Index = 0;
608 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000609 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
610 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000611 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000612 Seg.Type = Phdr.p_type;
613 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000614 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000615 Seg.Offset = Phdr.p_offset;
616 Seg.VAddr = Phdr.p_vaddr;
617 Seg.PAddr = Phdr.p_paddr;
618 Seg.FileSize = Phdr.p_filesz;
619 Seg.MemSize = Phdr.p_memsz;
620 Seg.Align = Phdr.p_align;
621 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000622 for (auto &Section : Obj.sections()) {
623 if (sectionWithinSegment(Section, Seg)) {
624 Seg.addSection(&Section);
625 if (!Section.ParentSegment ||
626 Section.ParentSegment->Offset > Seg.Offset) {
627 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000628 }
629 }
630 }
631 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000632
633 auto &ElfHdr = Obj.ElfHdrSegment;
634 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
635 // segments must not overlap, and other types fit even less.
636 ElfHdr.Type = PT_PHDR;
637 ElfHdr.Flags = 0;
638 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
639 ElfHdr.VAddr = 0;
640 ElfHdr.PAddr = 0;
641 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
642 ElfHdr.Align = 0;
643 ElfHdr.Index = Index++;
644
645 const auto &Ehdr = *ElfFile.getHeader();
646 auto &PrHdr = Obj.ProgramHdrSegment;
647 PrHdr.Type = PT_PHDR;
648 PrHdr.Flags = 0;
649 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
650 // Whereas this works automatically for ElfHdr, here OriginalOffset is
651 // always non-zero and to ensure the equation we assign the same value to
652 // VAddr as well.
653 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
654 PrHdr.PAddr = 0;
655 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000656 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000657 PrHdr.Align = sizeof(Elf_Addr);
658 PrHdr.Index = Index++;
659
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000660 // Now we do an O(n^2) loop through the segments in order to match up
661 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000662 for (auto &Child : Obj.segments())
663 setParentSegment(Child);
664 setParentSegment(ElfHdr);
665 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000666}
667
668template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000669void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
670 auto SecTable = Obj.sections();
671 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
672 GroupSec->Link,
673 "Link field value " + Twine(GroupSec->Link) + " in section " +
674 GroupSec->Name + " is invalid",
675 "Link field value " + Twine(GroupSec->Link) + " in section " +
676 GroupSec->Name + " is not a symbol table");
677 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
678 if (!Sym)
679 error("Info field value " + Twine(GroupSec->Info) + " in section " +
680 GroupSec->Name + " is not a valid symbol index");
681 GroupSec->setSymTab(SymTab);
682 GroupSec->setSymbol(Sym);
683 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
684 GroupSec->Contents.empty())
685 error("The content of the section " + GroupSec->Name + " is malformed");
686 const ELF::Elf32_Word *Word =
687 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
688 const ELF::Elf32_Word *End =
689 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
690 GroupSec->setFlagWord(*Word++);
691 for (; Word != End; ++Word) {
692 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
693 GroupSec->addMember(SecTable.getSection(
694 Index, "Group member index " + Twine(Index) + " in section " +
695 GroupSec->Name + " is invalid"));
696 }
697}
698
699template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000700void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000701 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
702 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000703 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000704
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000705 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
706 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000707 SectionBase *DefSection = nullptr;
708 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000709
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000710 if (Sym.st_shndx == SHN_XINDEX) {
711 if (SymTab->getShndxTable() == nullptr)
712 error("Symbol '" + Name +
713 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
714 if (ShndxData.data() == nullptr) {
715 const Elf_Shdr &ShndxSec =
716 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
717 ShndxData = unwrapOrError(
718 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
719 if (ShndxData.size() != Symbols.size())
720 error("Symbol section index table does not have the same number of "
721 "entries as the symbol table.");
722 }
723 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
724 DefSection = Obj.sections().getSection(
725 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000726 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000727 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000728 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000729 error(
730 "Symbol '" + Name +
731 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
732 Twine(Sym.st_shndx));
733 }
734 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000735 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000736 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000737 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000738 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000739 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000740
Petr Hosek79cee9e2017-08-29 02:12:03 +0000741 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000742 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000743 }
744}
745
746template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000747static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
748
749template <class ELFT>
750static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
751 ToSet = Rela.r_addend;
752}
753
Jake Ehrlich76e91102018-01-25 22:46:17 +0000754template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000755static void initRelocations(RelocationSection *Relocs,
756 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000757 for (const auto &Rel : RelRange) {
758 Relocation ToAdd;
759 ToAdd.Offset = Rel.r_offset;
760 getAddend(ToAdd.Addend, Rel);
761 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000762 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000763 Relocs->addRelocation(ToAdd);
764 }
765}
766
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000767SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000768 if (Index == SHN_UNDEF || Index > Sections.size())
769 error(ErrMsg);
770 return Sections[Index - 1].get();
771}
772
773template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000774T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000775 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000776 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000777 return Sec;
778 error(TypeErrMsg);
779}
780
Petr Hosekd7df9b22017-09-06 23:41:02 +0000781template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000782SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000783 ArrayRef<uint8_t> Data;
784 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000785 case SHT_REL:
786 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000787 if (Shdr.sh_flags & SHF_ALLOC) {
788 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000789 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000790 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000791 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000792 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000793 // If a string table is allocated we don't want to mess with it. That would
794 // mean altering the memory image. There are no special link types or
795 // anything so we can just use a Section.
796 if (Shdr.sh_flags & SHF_ALLOC) {
797 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000798 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000799 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000800 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000801 case SHT_HASH:
802 case SHT_GNU_HASH:
803 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
804 // Because of this we don't need to mess with the hash tables either.
805 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000806 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000807 case SHT_GROUP:
808 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
809 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000810 case SHT_DYNSYM:
811 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000812 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000813 case SHT_DYNAMIC:
814 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000815 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000816 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000817 auto &SymTab = Obj.addSection<SymbolTableSection>();
818 Obj.SymbolTable = &SymTab;
819 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000820 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000821 case SHT_SYMTAB_SHNDX: {
822 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
823 Obj.SectionIndexTable = &ShndxSection;
824 return ShndxSection;
825 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000826 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000827 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000828 default:
829 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000830 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000831 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000832}
833
Jake Ehrlich76e91102018-01-25 22:46:17 +0000834template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000835 uint32_t Index = 0;
836 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
837 if (Index == 0) {
838 ++Index;
839 continue;
840 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000841 auto &Sec = makeSection(Shdr);
842 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
843 Sec.Type = Shdr.sh_type;
844 Sec.Flags = Shdr.sh_flags;
845 Sec.Addr = Shdr.sh_addr;
846 Sec.Offset = Shdr.sh_offset;
847 Sec.OriginalOffset = Shdr.sh_offset;
848 Sec.Size = Shdr.sh_size;
849 Sec.Link = Shdr.sh_link;
850 Sec.Info = Shdr.sh_info;
851 Sec.Align = Shdr.sh_addralign;
852 Sec.EntrySize = Shdr.sh_entsize;
853 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +0000854 Sec.OriginalData =
855 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
856 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000857 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000858
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000859 // If a section index table exists we'll need to initialize it before we
860 // initialize the symbol table because the symbol table might need to
861 // reference it.
862 if (Obj.SectionIndexTable)
863 Obj.SectionIndexTable->initialize(Obj.sections());
864
Petr Hosek79cee9e2017-08-29 02:12:03 +0000865 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000866 // details about symbol tables. We need the symbol table filled out before
867 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000868 if (Obj.SymbolTable) {
869 Obj.SymbolTable->initialize(Obj.sections());
870 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000871 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000872
873 // Now that all sections and symbols have been added we can add
874 // relocations that reference symbols and set the link and info fields for
875 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000876 for (auto &Section : Obj.sections()) {
877 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000878 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000879 Section.initialize(Obj.sections());
880 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000881 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
882 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000883 initRelocations(RelSec, Obj.SymbolTable,
884 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000885 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000886 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000887 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000888 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
889 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000890 }
891 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000892}
893
Jake Ehrlich76e91102018-01-25 22:46:17 +0000894template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000895 const auto &Ehdr = *ElfFile.getHeader();
896
Jake Ehrlich76e91102018-01-25 22:46:17 +0000897 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
898 Obj.Type = Ehdr.e_type;
899 Obj.Machine = Ehdr.e_machine;
900 Obj.Version = Ehdr.e_version;
901 Obj.Entry = Ehdr.e_entry;
902 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000903
Jake Ehrlich76e91102018-01-25 22:46:17 +0000904 readSectionHeaders();
905 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000906
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000907 uint32_t ShstrIndex = Ehdr.e_shstrndx;
908 if (ShstrIndex == SHN_XINDEX)
909 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
910
Jake Ehrlich76e91102018-01-25 22:46:17 +0000911 Obj.SectionNames =
912 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000913 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000914 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000915 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000916 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000917 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000918}
919
Jake Ehrlich76e91102018-01-25 22:46:17 +0000920// A generic size function which computes sizes of any random access range.
921template <class R> size_t size(R &&Range) {
922 return static_cast<size_t>(std::end(Range) - std::begin(Range));
923}
924
925Writer::~Writer() {}
926
927Reader::~Reader() {}
928
Jake Ehrlich76e91102018-01-25 22:46:17 +0000929ElfType ELFReader::getElfType() const {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000930 if (isa<ELFObjectFile<ELF32LE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000931 return ELFT_ELF32LE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000932 if (isa<ELFObjectFile<ELF64LE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000933 return ELFT_ELF64LE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000934 if (isa<ELFObjectFile<ELF32BE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000935 return ELFT_ELF32BE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000936 if (isa<ELFObjectFile<ELF64BE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000937 return ELFT_ELF64BE;
938 llvm_unreachable("Invalid ELFType");
939}
940
941std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +0000942 auto Obj = llvm::make_unique<Object>();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000943 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000944 ELFBuilder<ELF32LE> Builder(*o, *Obj);
945 Builder.build();
946 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000947 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000948 ELFBuilder<ELF64LE> Builder(*o, *Obj);
949 Builder.build();
950 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000951 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000952 ELFBuilder<ELF32BE> Builder(*o, *Obj);
953 Builder.build();
954 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000955 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000956 ELFBuilder<ELF64BE> Builder(*o, *Obj);
957 Builder.build();
958 return Obj;
959 }
960 error("Invalid file type");
961}
962
963template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000964 uint8_t *B = Buf.getBufferStart();
965 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000966 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
967 Ehdr.e_type = Obj.Type;
968 Ehdr.e_machine = Obj.Machine;
969 Ehdr.e_version = Obj.Version;
970 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000971 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000972 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000973 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
974 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000975 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000976 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000977 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000978 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000979 // """
980 // If the number of sections is greater than or equal to
981 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
982 // number of section header table entries is contained in the sh_size field
983 // of the section header at index 0.
984 // """
985 auto Shnum = size(Obj.sections()) + 1;
986 if (Shnum >= SHN_LORESERVE)
987 Ehdr.e_shnum = 0;
988 else
989 Ehdr.e_shnum = Shnum;
990 // """
991 // If the section name string table section index is greater than or equal
992 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
993 // and the actual index of the section name string table section is
994 // contained in the sh_link field of the section header at index 0.
995 // """
996 if (Obj.SectionNames->Index >= SHN_LORESERVE)
997 Ehdr.e_shstrndx = SHN_XINDEX;
998 else
999 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001000 } else {
1001 Ehdr.e_shoff = 0;
1002 Ehdr.e_shnum = 0;
1003 Ehdr.e_shstrndx = 0;
1004 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001005}
1006
Jake Ehrlich76e91102018-01-25 22:46:17 +00001007template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1008 for (auto &Seg : Obj.segments())
1009 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001010}
1011
Jake Ehrlich76e91102018-01-25 22:46:17 +00001012template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001013 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001014 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001015 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001016 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001017 Shdr.sh_name = 0;
1018 Shdr.sh_type = SHT_NULL;
1019 Shdr.sh_flags = 0;
1020 Shdr.sh_addr = 0;
1021 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001022 // See writeEhdr for why we do this.
1023 uint64_t Shnum = size(Obj.sections()) + 1;
1024 if (Shnum >= SHN_LORESERVE)
1025 Shdr.sh_size = Shnum;
1026 else
1027 Shdr.sh_size = 0;
1028 // See writeEhdr for why we do this.
1029 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1030 Shdr.sh_link = Obj.SectionNames->Index;
1031 else
1032 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001033 Shdr.sh_info = 0;
1034 Shdr.sh_addralign = 0;
1035 Shdr.sh_entsize = 0;
1036
Jake Ehrlich76e91102018-01-25 22:46:17 +00001037 for (auto &Sec : Obj.sections())
1038 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001039}
1040
Jake Ehrlich76e91102018-01-25 22:46:17 +00001041template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1042 for (auto &Sec : Obj.sections())
1043 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001044}
1045
Jake Ehrlich76e91102018-01-25 22:46:17 +00001046void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001047
1048 auto Iter = std::stable_partition(
1049 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1050 if (ToRemove(*Sec))
1051 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001052 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1053 if (auto ToRelSec = RelSec->getSection())
1054 return !ToRemove(*ToRelSec);
1055 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001056 return true;
1057 });
1058 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1059 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001060 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001061 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001062 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1063 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001064 // Now make sure there are no remaining references to the sections that will
1065 // be removed. Sometimes it is impossible to remove a reference so we emit
1066 // an error here instead.
1067 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1068 for (auto &Segment : Segments)
1069 Segment->removeSection(RemoveSec.get());
1070 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1071 KeepSec->removeSectionReferences(RemoveSec.get());
1072 }
1073 // Now finally get rid of them all togethor.
1074 Sections.erase(Iter, std::end(Sections));
1075}
1076
Paul Semel4246a462018-05-09 21:36:54 +00001077void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1078 if (!SymbolTable)
1079 return;
1080
1081 for (const SecPtr &Sec : Sections)
1082 Sec->removeSymbols(ToRemove);
1083}
1084
Jake Ehrlich76e91102018-01-25 22:46:17 +00001085void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001086 // Put all sections in offset order. Maintain the ordering as closely as
1087 // possible while meeting that demand however.
1088 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1089 return A->OriginalOffset < B->OriginalOffset;
1090 };
1091 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1092 CompareSections);
1093}
1094
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001095static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1096 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1097 if (Align == 0)
1098 Align = 1;
1099 auto Diff =
1100 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1101 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1102 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1103 if (Diff < 0)
1104 Diff += Align;
1105 return Offset + Diff;
1106}
1107
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001108// Orders segments such that if x = y->ParentSegment then y comes before x.
1109static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001110 std::stable_sort(std::begin(Segments), std::end(Segments),
1111 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001112}
1113
1114// This function finds a consistent layout for a list of segments starting from
1115// an Offset. It assumes that Segments have been sorted by OrderSegments and
1116// returns an Offset one past the end of the last segment.
1117static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1118 uint64_t Offset) {
1119 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001120 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001121 // The only way a segment should move is if a section was between two
1122 // segments and that section was removed. If that section isn't in a segment
1123 // then it's acceptable, but not ideal, to simply move it to after the
1124 // segments. So we can simply layout segments one after the other accounting
1125 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001126 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001127 // We assume that segments have been ordered by OriginalOffset and Index
1128 // such that a parent segment will always come before a child segment in
1129 // OrderedSegments. This means that the Offset of the ParentSegment should
1130 // already be set and we can set our offset relative to it.
1131 if (Segment->ParentSegment != nullptr) {
1132 auto Parent = Segment->ParentSegment;
1133 Segment->Offset =
1134 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1135 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001136 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001137 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001138 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001139 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001140 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001141 return Offset;
1142}
1143
1144// This function finds a consistent layout for a list of sections. It assumes
1145// that the ->ParentSegment of each section has already been laid out. The
1146// supplied starting Offset is used for the starting offset of any section that
1147// does not have a ParentSegment. It returns either the offset given if all
1148// sections had a ParentSegment or an offset one past the last section if there
1149// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001150template <class Range>
1151static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001152 // Now the offset of every segment has been set we can assign the offsets
1153 // of each section. For sections that are covered by a segment we should use
1154 // the segment's original offset and the section's original offset to compute
1155 // the offset from the start of the segment. Using the offset from the start
1156 // of the segment we can assign a new offset to the section. For sections not
1157 // covered by segments we can just bump Offset to the next valid location.
1158 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001159 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001160 Section.Index = Index++;
1161 if (Section.ParentSegment != nullptr) {
1162 auto Segment = *Section.ParentSegment;
1163 Section.Offset =
1164 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001165 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001166 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1167 Section.Offset = Offset;
1168 if (Section.Type != SHT_NOBITS)
1169 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001170 }
1171 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001172 return Offset;
1173}
Petr Hosek3f383832017-08-26 01:32:20 +00001174
Jake Ehrlich76e91102018-01-25 22:46:17 +00001175template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001176 // We need a temporary list of segments that has a special order to it
1177 // so that we know that anytime ->ParentSegment is set that segment has
1178 // already had its offset properly set.
1179 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001180 for (auto &Segment : Obj.segments())
1181 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001182 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1183 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001184 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001185 // Offset is used as the start offset of the first segment to be laid out.
1186 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1187 // we start at offset 0.
1188 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001189 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001190 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001191 // If we need to write the section header table out then we need to align the
1192 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001193 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001194 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001195 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001196}
1197
Jake Ehrlich76e91102018-01-25 22:46:17 +00001198template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001199 // We already have the section header offset so we can calculate the total
1200 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001201 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1202 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001203 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001204}
1205
Jake Ehrlich76e91102018-01-25 22:46:17 +00001206template <class ELFT> void ELFWriter<ELFT>::write() {
1207 writeEhdr();
1208 writePhdrs();
1209 writeSectionData();
1210 if (WriteSectionHeaders)
1211 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001212 if (auto E = Buf.commit())
1213 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001214}
1215
1216template <class ELFT> void ELFWriter<ELFT>::finalize() {
1217 // It could happen that SectionNames has been removed and yet the user wants
1218 // a section header table output. We need to throw an error if a user tries
1219 // to do that.
1220 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1221 error("Cannot write section header table because section header string "
1222 "table was removed.");
1223
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001224 Obj.sortSections();
1225
1226 // We need to assign indexes before we perform layout because we need to know
1227 // if we need large indexes or not. We can assign indexes first and check as
1228 // we go to see if we will actully need large indexes.
1229 bool NeedsLargeIndexes = false;
1230 if (size(Obj.sections()) >= SHN_LORESERVE) {
1231 auto Sections = Obj.sections();
1232 NeedsLargeIndexes =
1233 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1234 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1235 // TODO: handle case where only one section needs the large index table but
1236 // only needs it because the large index table hasn't been removed yet.
1237 }
1238
1239 if (NeedsLargeIndexes) {
1240 // This means we definitely need to have a section index table but if we
1241 // already have one then we should use it instead of making a new one.
1242 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1243 // Addition of a section to the end does not invalidate the indexes of
1244 // other sections and assigns the correct index to the new section.
1245 auto &Shndx = Obj.addSection<SectionIndexSection>();
1246 Obj.SymbolTable->setShndxTable(&Shndx);
1247 Shndx.setSymTab(Obj.SymbolTable);
1248 }
1249 } else {
1250 // Since we don't need SectionIndexTable we should remove it and all
1251 // references to it.
1252 if (Obj.SectionIndexTable != nullptr) {
1253 Obj.removeSections([this](const SectionBase &Sec) {
1254 return &Sec == Obj.SectionIndexTable;
1255 });
1256 }
1257 }
1258
1259 // Make sure we add the names of all the sections. Importantly this must be
1260 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001261 if (Obj.SectionNames != nullptr)
1262 for (const auto &Section : Obj.sections()) {
1263 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001264 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001265
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001266 // Before we can prepare for layout the indexes need to be finalized.
1267 uint64_t Index = 0;
1268 for (auto &Sec : Obj.sections())
1269 Sec.Index = Index++;
1270
1271 // The symbol table does not update all other sections on update. For
1272 // instance, symbol names are not added as new symbols are added. This means
1273 // that some sections, like .strtab, don't yet have their final size.
1274 if (Obj.SymbolTable != nullptr)
1275 Obj.SymbolTable->prepareForLayout();
1276
Petr Hosekc4df10e2017-08-04 21:09:26 +00001277 assignOffsets();
1278
1279 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001280 if (Obj.SectionNames != nullptr)
1281 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001282 // Finally now that all offsets and indexes have been set we can finalize any
1283 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001284 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1285 for (auto &Section : Obj.sections()) {
1286 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001287 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001288 if (WriteSectionHeaders)
1289 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1290 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001291 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001292
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001293 Buf.allocate(totalSize());
1294 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001295}
1296
Jake Ehrlich76e91102018-01-25 22:46:17 +00001297void BinaryWriter::write() {
1298 for (auto &Section : Obj.sections()) {
1299 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001300 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001301 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001302 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001303 if (auto E = Buf.commit())
1304 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001305}
1306
Jake Ehrlich76e91102018-01-25 22:46:17 +00001307void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001308 // TODO: Create a filter range to construct OrderedSegments from so that this
1309 // code can be deduped with assignOffsets above. This should also solve the
1310 // todo below for LayoutSections.
1311 // We need a temporary list of segments that has a special order to it
1312 // so that we know that anytime ->ParentSegment is set that segment has
1313 // already had it's offset properly set. We only want to consider the segments
1314 // that will affect layout of allocated sections so we only add those.
1315 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001316 for (auto &Section : Obj.sections()) {
1317 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1318 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001319 }
1320 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001321
1322 // For binary output, we're going to use physical addresses instead of
1323 // virtual addresses, since a binary output is used for cases like ROM
1324 // loading and physical addresses are intended for ROM loading.
1325 // However, if no segment has a physical address, we'll fallback to using
1326 // virtual addresses for all.
1327 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1328 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1329 for (const auto &Segment : OrderedSegments)
1330 Segment->PAddr = Segment->VAddr;
1331
1332 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1333 compareSegmentsByPAddr);
1334
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001335 // Because we add a ParentSegment for each section we might have duplicate
1336 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1337 // would do very strange things.
1338 auto End =
1339 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1340 OrderedSegments.erase(End, std::end(OrderedSegments));
1341
Jake Ehrlich46814be2018-01-22 19:27:30 +00001342 uint64_t Offset = 0;
1343
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001344 // Modify the first segment so that there is no gap at the start. This allows
1345 // our layout algorithm to proceed as expected while not out writing out the
1346 // gap at the start.
1347 if (!OrderedSegments.empty()) {
1348 auto Seg = OrderedSegments[0];
1349 auto Sec = Seg->firstSection();
1350 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1351 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001352 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001353 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001354 // The PAddr needs to be increased to remove the gap before the first
1355 // section.
1356 Seg->PAddr += Diff;
1357 uint64_t LowestPAddr = Seg->PAddr;
1358 for (auto &Segment : OrderedSegments) {
1359 Segment->Offset = Segment->PAddr - LowestPAddr;
1360 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1361 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001362 }
1363
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001364 // TODO: generalize LayoutSections to take a range. Pass a special range
1365 // constructed from an iterator that skips values for which a predicate does
1366 // not hold. Then pass such a range to LayoutSections instead of constructing
1367 // AllocatedSections here.
1368 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001369 for (auto &Section : Obj.sections()) {
1370 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001371 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001372 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001373 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001374 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001375
1376 // Now that every section has been laid out we just need to compute the total
1377 // file size. This might not be the same as the offset returned by
1378 // LayoutSections, because we want to truncate the last segment to the end of
1379 // its last section, to match GNU objcopy's behaviour.
1380 TotalSize = 0;
1381 for (const auto &Section : AllocatedSections) {
1382 if (Section->Type != SHT_NOBITS)
1383 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1384 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001385
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001386 Buf.allocate(TotalSize);
1387 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001388}
1389
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001390namespace llvm {
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001391namespace objcopy {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001392
Jake Ehrlich76e91102018-01-25 22:46:17 +00001393template class ELFBuilder<ELF64LE>;
1394template class ELFBuilder<ELF64BE>;
1395template class ELFBuilder<ELF32LE>;
1396template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001397
Jake Ehrlich76e91102018-01-25 22:46:17 +00001398template class ELFWriter<ELF64LE>;
1399template class ELFWriter<ELF64BE>;
1400template class ELFWriter<ELF32LE>;
1401template class ELFWriter<ELF32BE>;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001402} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001403} // end namespace llvm