blob: 0d5dbf759bbbed345783fbcc9bf79526853bf03c [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) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000066 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000067
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000068 uint8_t *B = Buf.getBufferStart();
69 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
70 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000071 Phdr.p_type = Seg.Type;
72 Phdr.p_flags = Seg.Flags;
73 Phdr.p_offset = Seg.Offset;
74 Phdr.p_vaddr = Seg.VAddr;
75 Phdr.p_paddr = Seg.PAddr;
76 Phdr.p_filesz = Seg.FileSize;
77 Phdr.p_memsz = Seg.MemSize;
78 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000079}
80
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000081void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000082void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000083void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000084void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000085void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000086
Jake Ehrlich76e91102018-01-25 22:46:17 +000087template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000088 uint8_t *B = Buf.getBufferStart();
89 B += Sec.HeaderOffset;
90 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000091 Shdr.sh_name = Sec.NameIndex;
92 Shdr.sh_type = Sec.Type;
93 Shdr.sh_flags = Sec.Flags;
94 Shdr.sh_addr = Sec.Addr;
95 Shdr.sh_offset = Sec.Offset;
96 Shdr.sh_size = Sec.Size;
97 Shdr.sh_link = Sec.Link;
98 Shdr.sh_info = Sec.Info;
99 Shdr.sh_addralign = Sec.Align;
100 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000101}
102
Jake Ehrlich76e91102018-01-25 22:46:17 +0000103SectionVisitor::~SectionVisitor() {}
104
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000105void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
106 error("Cannot write symbol section index table '" + Sec.Name + "' ");
107}
108
Jake Ehrlich76e91102018-01-25 22:46:17 +0000109void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
110 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
111}
112
113void BinarySectionWriter::visit(const RelocationSection &Sec) {
114 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
115}
116
117void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000118 error("Cannot write '" + Sec.Name + "' out to binary");
119}
120
121void BinarySectionWriter::visit(const GroupSection &Sec) {
122 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000123}
124
125void SectionWriter::visit(const Section &Sec) {
126 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000127 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000128 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
129 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000130}
131
Jake Ehrlich76e91102018-01-25 22:46:17 +0000132void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
133
134void SectionWriter::visit(const OwnedDataSection &Sec) {
135 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
136 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
137}
138
139void OwnedDataSection::accept(SectionVisitor &Visitor) const {
140 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000141}
142
Petr Hosek05a04cb2017-08-01 00:33:58 +0000143void StringTableSection::addString(StringRef Name) {
144 StrTabBuilder.add(Name);
145 Size = StrTabBuilder.getSize();
146}
147
148uint32_t StringTableSection::findIndex(StringRef Name) const {
149 return StrTabBuilder.getOffset(Name);
150}
151
152void StringTableSection::finalize() { StrTabBuilder.finalize(); }
153
Jake Ehrlich76e91102018-01-25 22:46:17 +0000154void SectionWriter::visit(const StringTableSection &Sec) {
155 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
156}
157
158void StringTableSection::accept(SectionVisitor &Visitor) const {
159 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000160}
161
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000162template <class ELFT>
163void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
164 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
165 auto *IndexesBuffer = reinterpret_cast<typename ELFT::Word *>(Buf);
166 std::copy(std::begin(Sec.Indexes), std::end(Sec.Indexes), IndexesBuffer);
167}
168
169void SectionIndexSection::initialize(SectionTableRef SecTable) {
170 Size = 0;
171 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
172 Link,
173 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
174 "Link field value " + Twine(Link) + " in section " + Name +
175 " is not a symbol table"));
176 Symbols->setShndxTable(this);
177}
178
179void SectionIndexSection::finalize() { Link = Symbols->Index; }
180
181void SectionIndexSection::accept(SectionVisitor &Visitor) const {
182 Visitor.visit(*this);
183}
184
Petr Hosekc1135772017-09-13 03:04:50 +0000185static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000186 switch (Index) {
187 case SHN_ABS:
188 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000189 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000190 }
Petr Hosekc1135772017-09-13 03:04:50 +0000191 if (Machine == EM_HEXAGON) {
192 switch (Index) {
193 case SHN_HEXAGON_SCOMMON:
194 case SHN_HEXAGON_SCOMMON_2:
195 case SHN_HEXAGON_SCOMMON_4:
196 case SHN_HEXAGON_SCOMMON_8:
197 return true;
198 }
199 }
200 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000201}
202
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000203// Large indexes force us to clarify exactly what this function should do. This
204// function should return the value that will appear in st_shndx when written
205// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000206uint16_t Symbol::getShndx() const {
207 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000208 if (DefinedIn->Index >= SHN_LORESERVE)
209 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000210 return DefinedIn->Index;
211 }
212 switch (ShndxType) {
213 // This means that we don't have a defined section but we do need to
214 // output a legitimate section index.
215 case SYMBOL_SIMPLE_INDEX:
216 return SHN_UNDEF;
217 case SYMBOL_ABS:
218 case SYMBOL_COMMON:
219 case SYMBOL_HEXAGON_SCOMMON:
220 case SYMBOL_HEXAGON_SCOMMON_2:
221 case SYMBOL_HEXAGON_SCOMMON_4:
222 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000223 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000224 return static_cast<uint16_t>(ShndxType);
225 }
226 llvm_unreachable("Symbol with invalid ShndxType encountered");
227}
228
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000229void SymbolTableSection::assignIndices() {
230 uint32_t Index = 0;
231 for (auto &Sym : Symbols)
232 Sym->Index = Index++;
233}
234
Petr Hosek79cee9e2017-08-29 02:12:03 +0000235void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
236 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000237 uint8_t Visibility, uint16_t Shndx,
238 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000239 Symbol Sym;
240 Sym.Name = Name;
241 Sym.Binding = Bind;
242 Sym.Type = Type;
243 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000244 if (DefinedIn != nullptr)
245 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000246 if (DefinedIn == nullptr) {
247 if (Shndx >= SHN_LORESERVE)
248 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
249 else
250 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
251 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000252 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000253 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000254 Sym.Size = Sz;
255 Sym.Index = Symbols.size();
256 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
257 Size += this->EntrySize;
258}
259
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000260void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000261 if (SectionIndexTable == Sec)
262 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000263 if (SymbolNames == Sec) {
264 error("String table " + SymbolNames->Name +
265 " cannot be removed because it is referenced by the symbol table " +
266 this->Name);
267 }
Paul Semel41695f82018-05-02 20:19:22 +0000268 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000269}
270
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000271void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000272 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
273 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000274 std::stable_partition(
275 std::begin(Symbols), std::end(Symbols),
276 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000277 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000278}
279
Paul Semel4246a462018-05-09 21:36:54 +0000280void SymbolTableSection::removeSymbols(
281 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000282 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000283 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000284 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
285 std::end(Symbols));
286 Size = Symbols.size() * EntrySize;
287 assignIndices();
288}
289
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000290void SymbolTableSection::initialize(SectionTableRef SecTable) {
291 Size = 0;
292 setStrTab(SecTable.getSectionOfType<StringTableSection>(
293 Link,
294 "Symbol table has link index of " + Twine(Link) +
295 " which is not a valid index",
296 "Symbol table has link index of " + Twine(Link) +
297 " which is not a string table"));
298}
299
Petr Hosek79cee9e2017-08-29 02:12:03 +0000300void SymbolTableSection::finalize() {
301 // Make sure SymbolNames is finalized before getting name indexes.
302 SymbolNames->finalize();
303
304 uint32_t MaxLocalIndex = 0;
305 for (auto &Sym : Symbols) {
306 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
307 if (Sym->Binding == STB_LOCAL)
308 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
309 }
310 // Now we need to set the Link and Info fields.
311 Link = SymbolNames->Index;
312 Info = MaxLocalIndex + 1;
313}
314
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000315void SymbolTableSection::prepareForLayout() {
316 // Add all potential section indexes before file layout so that the section
317 // index section has the approprite size.
318 if (SectionIndexTable != nullptr) {
319 for (const auto &Sym : Symbols) {
320 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
321 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
322 else
323 SectionIndexTable->addIndex(SHN_UNDEF);
324 }
325 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000326 // Add all of our strings to SymbolNames so that SymbolNames has the right
327 // size before layout is decided.
328 for (auto &Sym : Symbols)
329 SymbolNames->addString(Sym->Name);
330}
331
332const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
333 if (Symbols.size() <= Index)
334 error("Invalid symbol index: " + Twine(Index));
335 return Symbols[Index].get();
336}
337
Paul Semel99dda0b2018-05-25 11:01:25 +0000338Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
339 return const_cast<Symbol *>(
340 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
341}
342
Petr Hosek79cee9e2017-08-29 02:12:03 +0000343template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000344void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000345 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000346 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000347 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
348 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000349 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000350 Sym->st_name = Symbol->NameIndex;
351 Sym->st_value = Symbol->Value;
352 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000353 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000354 Sym->setBinding(Symbol->Binding);
355 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000356 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000357 ++Sym;
358 }
359}
360
Jake Ehrlich76e91102018-01-25 22:46:17 +0000361void SymbolTableSection::accept(SectionVisitor &Visitor) const {
362 Visitor.visit(*this);
363}
364
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000365template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000366void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
367 const SectionBase *Sec) {
368 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000369 error("Symbol table " + Symbols->Name +
370 " cannot be removed because it is "
371 "referenced by the relocation "
372 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000373 this->Name);
374 }
375}
376
377template <class SymTabType>
378void RelocSectionWithSymtabBase<SymTabType>::initialize(
379 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000380 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000381 Link,
382 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
383 "Link field value " + Twine(Link) + " in section " + Name +
384 " is not a symbol table"));
385
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000386 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000387 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
388 " in section " + Name +
389 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000390 else
391 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000392}
393
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000394template <class SymTabType>
395void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000396 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000397 if (SecToApplyRel != nullptr)
398 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000399}
400
401template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000402static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000403
404template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000405static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000406 Rela.r_addend = Addend;
407}
408
Jake Ehrlich76e91102018-01-25 22:46:17 +0000409template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000410static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000411 for (const auto &Reloc : Relocations) {
412 Buf->r_offset = Reloc.Offset;
413 setAddend(*Buf, Reloc.Addend);
414 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
415 ++Buf;
416 }
417}
418
419template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000420void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
421 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
422 if (Sec.Type == SHT_REL)
423 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000424 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000425 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000426}
427
Jake Ehrlich76e91102018-01-25 22:46:17 +0000428void RelocationSection::accept(SectionVisitor &Visitor) const {
429 Visitor.visit(*this);
430}
431
Paul Semel4246a462018-05-09 21:36:54 +0000432void RelocationSection::removeSymbols(
433 function_ref<bool(const Symbol &)> ToRemove) {
434 for (const Relocation &Reloc : Relocations)
435 if (ToRemove(*Reloc.RelocSymbol))
436 error("not stripping symbol `" + Reloc.RelocSymbol->Name +
437 "' because it is named in a relocation");
438}
439
Paul Semel99dda0b2018-05-25 11:01:25 +0000440void RelocationSection::markSymbols() {
441 for (const Relocation &Reloc : Relocations)
442 Reloc.RelocSymbol->Referenced = true;
443}
444
Jake Ehrlich76e91102018-01-25 22:46:17 +0000445void SectionWriter::visit(const DynamicRelocationSection &Sec) {
446 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
447 Out.getBufferStart() + Sec.Offset);
448}
449
450void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
451 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000452}
453
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000454void Section::removeSectionReferences(const SectionBase *Sec) {
455 if (LinkSection == Sec) {
456 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000457 " cannot be removed because it is "
458 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000459 this->Name);
460 }
461}
462
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000463void GroupSection::finalize() {
464 this->Info = Sym->Index;
465 this->Link = SymTab->Index;
466}
467
Paul Semel4246a462018-05-09 21:36:54 +0000468void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
469 if (ToRemove(*Sym)) {
470 error("Symbol " + Sym->Name +
471 " cannot be removed because it is "
472 "referenced by the section " +
473 this->Name + "[" + Twine(this->Index) + "]");
474 }
475}
476
Paul Semel99dda0b2018-05-25 11:01:25 +0000477void GroupSection::markSymbols() {
478 if (Sym)
479 Sym->Referenced = true;
480}
481
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000482void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000483 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000484 LinkSection =
485 SecTable.getSection(Link, "Link field value " + Twine(Link) +
486 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000487 if (LinkSection->Type == ELF::SHT_SYMTAB)
488 LinkSection = nullptr;
489 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000490}
491
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000492void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000493
Jake Ehrlich76e91102018-01-25 22:46:17 +0000494void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000495 FileName = sys::path::filename(File);
496 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000497 // followed by a null terminator and then the CRC32 of the file. The CRC32
498 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
499 // byte, and then finally push the size to alignment and add 4.
500 Size = alignTo(FileName.size() + 1, 4) + 4;
501 // The CRC32 will only be aligned if we align the whole section.
502 Align = 4;
503 Type = ELF::SHT_PROGBITS;
504 Name = ".gnu_debuglink";
505 // For sections not found in segments, OriginalOffset is only used to
506 // establish the order that sections should go in. By using the maximum
507 // possible offset we cause this section to wind up at the end.
508 OriginalOffset = std::numeric_limits<uint64_t>::max();
509 JamCRC crc;
510 crc.update(ArrayRef<char>(Data.data(), Data.size()));
511 // The CRC32 value needs to be complemented because the JamCRC dosn't
512 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
513 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
514 CRC32 = ~crc.getCRC();
515}
516
Jake Ehrlich76e91102018-01-25 22:46:17 +0000517GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000518 // Read in the file to compute the CRC of it.
519 auto DebugOrErr = MemoryBuffer::getFile(File);
520 if (!DebugOrErr)
521 error("'" + File + "': " + DebugOrErr.getError().message());
522 auto Debug = std::move(*DebugOrErr);
523 init(File, Debug->getBuffer());
524}
525
526template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000527void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
528 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000529 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000530 Elf_Word *CRC =
531 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
532 *CRC = Sec.CRC32;
533 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
534}
535
536void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
537 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000538}
539
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000540template <class ELFT>
541void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
542 ELF::Elf32_Word *Buf =
543 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
544 *Buf++ = Sec.FlagWord;
545 for (const auto *S : Sec.GroupMembers)
546 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
547}
548
549void GroupSection::accept(SectionVisitor &Visitor) const {
550 Visitor.visit(*this);
551}
552
Petr Hosek05a04cb2017-08-01 00:33:58 +0000553// Returns true IFF a section is wholly inside the range of a segment
554static bool sectionWithinSegment(const SectionBase &Section,
555 const Segment &Segment) {
556 // If a section is empty it should be treated like it has a size of 1. This is
557 // to clarify the case when an empty section lies on a boundary between two
558 // segments and ensures that the section "belongs" to the second segment and
559 // not the first.
560 uint64_t SecSize = Section.Size ? Section.Size : 1;
561 return Segment.Offset <= Section.OriginalOffset &&
562 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
563}
564
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000565// Returns true IFF a segment's original offset is inside of another segment's
566// range.
567static bool segmentOverlapsSegment(const Segment &Child,
568 const Segment &Parent) {
569
570 return Parent.OriginalOffset <= Child.OriginalOffset &&
571 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
572}
573
Jake Ehrlich46814be2018-01-22 19:27:30 +0000574static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000575 // Any segment without a parent segment should come before a segment
576 // that has a parent segment.
577 if (A->OriginalOffset < B->OriginalOffset)
578 return true;
579 if (A->OriginalOffset > B->OriginalOffset)
580 return false;
581 return A->Index < B->Index;
582}
583
Jake Ehrlich46814be2018-01-22 19:27:30 +0000584static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
585 if (A->PAddr < B->PAddr)
586 return true;
587 if (A->PAddr > B->PAddr)
588 return false;
589 return A->Index < B->Index;
590}
591
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000592template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000593 for (auto &Parent : Obj.segments()) {
594 // Every segment will overlap with itself but we don't want a segment to
595 // be it's own parent so we avoid that situation.
596 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
597 // We want a canonical "most parental" segment but this requires
598 // inspecting the ParentSegment.
599 if (compareSegmentsByOffset(&Parent, &Child))
600 if (Child.ParentSegment == nullptr ||
601 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
602 Child.ParentSegment = &Parent;
603 }
604 }
605 }
606}
607
Jake Ehrlich76e91102018-01-25 22:46:17 +0000608template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000609 uint32_t Index = 0;
610 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000611 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
612 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000613 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000614 Seg.Type = Phdr.p_type;
615 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000616 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000617 Seg.Offset = Phdr.p_offset;
618 Seg.VAddr = Phdr.p_vaddr;
619 Seg.PAddr = Phdr.p_paddr;
620 Seg.FileSize = Phdr.p_filesz;
621 Seg.MemSize = Phdr.p_memsz;
622 Seg.Align = Phdr.p_align;
623 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000624 for (auto &Section : Obj.sections()) {
625 if (sectionWithinSegment(Section, Seg)) {
626 Seg.addSection(&Section);
627 if (!Section.ParentSegment ||
628 Section.ParentSegment->Offset > Seg.Offset) {
629 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000630 }
631 }
632 }
633 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000634
635 auto &ElfHdr = Obj.ElfHdrSegment;
636 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
637 // segments must not overlap, and other types fit even less.
638 ElfHdr.Type = PT_PHDR;
639 ElfHdr.Flags = 0;
640 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
641 ElfHdr.VAddr = 0;
642 ElfHdr.PAddr = 0;
643 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
644 ElfHdr.Align = 0;
645 ElfHdr.Index = Index++;
646
647 const auto &Ehdr = *ElfFile.getHeader();
648 auto &PrHdr = Obj.ProgramHdrSegment;
649 PrHdr.Type = PT_PHDR;
650 PrHdr.Flags = 0;
651 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
652 // Whereas this works automatically for ElfHdr, here OriginalOffset is
653 // always non-zero and to ensure the equation we assign the same value to
654 // VAddr as well.
655 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
656 PrHdr.PAddr = 0;
657 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000658 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000659 PrHdr.Align = sizeof(Elf_Addr);
660 PrHdr.Index = Index++;
661
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000662 // Now we do an O(n^2) loop through the segments in order to match up
663 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000664 for (auto &Child : Obj.segments())
665 setParentSegment(Child);
666 setParentSegment(ElfHdr);
667 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000668}
669
670template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000671void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
672 auto SecTable = Obj.sections();
673 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
674 GroupSec->Link,
675 "Link field value " + Twine(GroupSec->Link) + " in section " +
676 GroupSec->Name + " is invalid",
677 "Link field value " + Twine(GroupSec->Link) + " in section " +
678 GroupSec->Name + " is not a symbol table");
679 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
680 if (!Sym)
681 error("Info field value " + Twine(GroupSec->Info) + " in section " +
682 GroupSec->Name + " is not a valid symbol index");
683 GroupSec->setSymTab(SymTab);
684 GroupSec->setSymbol(Sym);
685 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
686 GroupSec->Contents.empty())
687 error("The content of the section " + GroupSec->Name + " is malformed");
688 const ELF::Elf32_Word *Word =
689 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
690 const ELF::Elf32_Word *End =
691 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
692 GroupSec->setFlagWord(*Word++);
693 for (; Word != End; ++Word) {
694 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
695 GroupSec->addMember(SecTable.getSection(
696 Index, "Group member index " + Twine(Index) + " in section " +
697 GroupSec->Name + " is invalid"));
698 }
699}
700
701template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000702void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000703 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
704 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000705 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000706
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000707 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
708 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000709 SectionBase *DefSection = nullptr;
710 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000711
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000712 if (Sym.st_shndx == SHN_XINDEX) {
713 if (SymTab->getShndxTable() == nullptr)
714 error("Symbol '" + Name +
715 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
716 if (ShndxData.data() == nullptr) {
717 const Elf_Shdr &ShndxSec =
718 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
719 ShndxData = unwrapOrError(
720 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
721 if (ShndxData.size() != Symbols.size())
722 error("Symbol section index table does not have the same number of "
723 "entries as the symbol table.");
724 }
725 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
726 DefSection = Obj.sections().getSection(
727 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000728 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000729 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000730 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000731 error(
732 "Symbol '" + Name +
733 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
734 Twine(Sym.st_shndx));
735 }
736 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000737 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000738 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000739 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000740 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000741 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000742
Petr Hosek79cee9e2017-08-29 02:12:03 +0000743 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000744 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000745 }
746}
747
748template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000749static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
750
751template <class ELFT>
752static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
753 ToSet = Rela.r_addend;
754}
755
Jake Ehrlich76e91102018-01-25 22:46:17 +0000756template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000757static void initRelocations(RelocationSection *Relocs,
758 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000759 for (const auto &Rel : RelRange) {
760 Relocation ToAdd;
761 ToAdd.Offset = Rel.r_offset;
762 getAddend(ToAdd.Addend, Rel);
763 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000764 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000765 Relocs->addRelocation(ToAdd);
766 }
767}
768
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000769SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000770 if (Index == SHN_UNDEF || Index > Sections.size())
771 error(ErrMsg);
772 return Sections[Index - 1].get();
773}
774
775template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000776T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000777 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000778 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000779 return Sec;
780 error(TypeErrMsg);
781}
782
Petr Hosekd7df9b22017-09-06 23:41:02 +0000783template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000784SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000785 ArrayRef<uint8_t> Data;
786 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000787 case SHT_REL:
788 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000789 if (Shdr.sh_flags & SHF_ALLOC) {
790 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000791 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000792 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000793 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000794 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000795 // If a string table is allocated we don't want to mess with it. That would
796 // mean altering the memory image. There are no special link types or
797 // anything so we can just use a Section.
798 if (Shdr.sh_flags & SHF_ALLOC) {
799 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000800 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000801 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000802 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000803 case SHT_HASH:
804 case SHT_GNU_HASH:
805 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
806 // Because of this we don't need to mess with the hash tables either.
807 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000808 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000809 case SHT_GROUP:
810 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
811 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000812 case SHT_DYNSYM:
813 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000814 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000815 case SHT_DYNAMIC:
816 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000817 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000818 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000819 auto &SymTab = Obj.addSection<SymbolTableSection>();
820 Obj.SymbolTable = &SymTab;
821 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000822 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000823 case SHT_SYMTAB_SHNDX: {
824 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
825 Obj.SectionIndexTable = &ShndxSection;
826 return ShndxSection;
827 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000828 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000829 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000830 default:
831 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000832 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000833 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000834}
835
Jake Ehrlich76e91102018-01-25 22:46:17 +0000836template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000837 uint32_t Index = 0;
838 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
839 if (Index == 0) {
840 ++Index;
841 continue;
842 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000843 auto &Sec = makeSection(Shdr);
844 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
845 Sec.Type = Shdr.sh_type;
846 Sec.Flags = Shdr.sh_flags;
847 Sec.Addr = Shdr.sh_addr;
848 Sec.Offset = Shdr.sh_offset;
849 Sec.OriginalOffset = Shdr.sh_offset;
850 Sec.Size = Shdr.sh_size;
851 Sec.Link = Shdr.sh_link;
852 Sec.Info = Shdr.sh_info;
853 Sec.Align = Shdr.sh_addralign;
854 Sec.EntrySize = Shdr.sh_entsize;
855 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000856 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000857
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000858 // If a section index table exists we'll need to initialize it before we
859 // initialize the symbol table because the symbol table might need to
860 // reference it.
861 if (Obj.SectionIndexTable)
862 Obj.SectionIndexTable->initialize(Obj.sections());
863
Petr Hosek79cee9e2017-08-29 02:12:03 +0000864 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000865 // details about symbol tables. We need the symbol table filled out before
866 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000867 if (Obj.SymbolTable) {
868 Obj.SymbolTable->initialize(Obj.sections());
869 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000870 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000871
872 // Now that all sections and symbols have been added we can add
873 // relocations that reference symbols and set the link and info fields for
874 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000875 for (auto &Section : Obj.sections()) {
876 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000877 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000878 Section.initialize(Obj.sections());
879 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000880 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
881 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000882 initRelocations(RelSec, Obj.SymbolTable,
883 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000884 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000885 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000886 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000887 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
888 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000889 }
890 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000891}
892
Jake Ehrlich76e91102018-01-25 22:46:17 +0000893template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000894 const auto &Ehdr = *ElfFile.getHeader();
895
Jake Ehrlich76e91102018-01-25 22:46:17 +0000896 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
897 Obj.Type = Ehdr.e_type;
898 Obj.Machine = Ehdr.e_machine;
899 Obj.Version = Ehdr.e_version;
900 Obj.Entry = Ehdr.e_entry;
901 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000902
Jake Ehrlich76e91102018-01-25 22:46:17 +0000903 readSectionHeaders();
904 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000905
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000906 uint32_t ShstrIndex = Ehdr.e_shstrndx;
907 if (ShstrIndex == SHN_XINDEX)
908 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
909
Jake Ehrlich76e91102018-01-25 22:46:17 +0000910 Obj.SectionNames =
911 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000912 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000913 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000914 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000915 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000916 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000917}
918
Jake Ehrlich76e91102018-01-25 22:46:17 +0000919// A generic size function which computes sizes of any random access range.
920template <class R> size_t size(R &&Range) {
921 return static_cast<size_t>(std::end(Range) - std::begin(Range));
922}
923
924Writer::~Writer() {}
925
926Reader::~Reader() {}
927
Jake Ehrlich76e91102018-01-25 22:46:17 +0000928ElfType ELFReader::getElfType() const {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000929 if (isa<ELFObjectFile<ELF32LE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000930 return ELFT_ELF32LE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000931 if (isa<ELFObjectFile<ELF64LE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000932 return ELFT_ELF64LE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000933 if (isa<ELFObjectFile<ELF32BE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000934 return ELFT_ELF32BE;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000935 if (isa<ELFObjectFile<ELF64BE>>(Bin))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000936 return ELFT_ELF64BE;
937 llvm_unreachable("Invalid ELFType");
938}
939
940std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +0000941 auto Obj = llvm::make_unique<Object>();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000942 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000943 ELFBuilder<ELF32LE> Builder(*o, *Obj);
944 Builder.build();
945 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000946 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000947 ELFBuilder<ELF64LE> Builder(*o, *Obj);
948 Builder.build();
949 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000950 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000951 ELFBuilder<ELF32BE> Builder(*o, *Obj);
952 Builder.build();
953 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000954 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000955 ELFBuilder<ELF64BE> Builder(*o, *Obj);
956 Builder.build();
957 return Obj;
958 }
959 error("Invalid file type");
960}
961
962template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000963 uint8_t *B = Buf.getBufferStart();
964 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000965 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
966 Ehdr.e_type = Obj.Type;
967 Ehdr.e_machine = Obj.Machine;
968 Ehdr.e_version = Obj.Version;
969 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000970 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000971 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000972 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
973 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000974 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000975 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000976 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000977 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000978 // """
979 // If the number of sections is greater than or equal to
980 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
981 // number of section header table entries is contained in the sh_size field
982 // of the section header at index 0.
983 // """
984 auto Shnum = size(Obj.sections()) + 1;
985 if (Shnum >= SHN_LORESERVE)
986 Ehdr.e_shnum = 0;
987 else
988 Ehdr.e_shnum = Shnum;
989 // """
990 // If the section name string table section index is greater than or equal
991 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
992 // and the actual index of the section name string table section is
993 // contained in the sh_link field of the section header at index 0.
994 // """
995 if (Obj.SectionNames->Index >= SHN_LORESERVE)
996 Ehdr.e_shstrndx = SHN_XINDEX;
997 else
998 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000999 } else {
1000 Ehdr.e_shoff = 0;
1001 Ehdr.e_shnum = 0;
1002 Ehdr.e_shstrndx = 0;
1003 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001004}
1005
Jake Ehrlich76e91102018-01-25 22:46:17 +00001006template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1007 for (auto &Seg : Obj.segments())
1008 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001009}
1010
Jake Ehrlich76e91102018-01-25 22:46:17 +00001011template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001012 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001013 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001014 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001015 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001016 Shdr.sh_name = 0;
1017 Shdr.sh_type = SHT_NULL;
1018 Shdr.sh_flags = 0;
1019 Shdr.sh_addr = 0;
1020 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001021 // See writeEhdr for why we do this.
1022 uint64_t Shnum = size(Obj.sections()) + 1;
1023 if (Shnum >= SHN_LORESERVE)
1024 Shdr.sh_size = Shnum;
1025 else
1026 Shdr.sh_size = 0;
1027 // See writeEhdr for why we do this.
1028 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1029 Shdr.sh_link = Obj.SectionNames->Index;
1030 else
1031 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001032 Shdr.sh_info = 0;
1033 Shdr.sh_addralign = 0;
1034 Shdr.sh_entsize = 0;
1035
Jake Ehrlich76e91102018-01-25 22:46:17 +00001036 for (auto &Sec : Obj.sections())
1037 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001038}
1039
Jake Ehrlich76e91102018-01-25 22:46:17 +00001040template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1041 for (auto &Sec : Obj.sections())
1042 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001043}
1044
Jake Ehrlich76e91102018-01-25 22:46:17 +00001045void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001046
1047 auto Iter = std::stable_partition(
1048 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1049 if (ToRemove(*Sec))
1050 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001051 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1052 if (auto ToRelSec = RelSec->getSection())
1053 return !ToRemove(*ToRelSec);
1054 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001055 return true;
1056 });
1057 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1058 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001059 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001060 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001061 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1062 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001063 // Now make sure there are no remaining references to the sections that will
1064 // be removed. Sometimes it is impossible to remove a reference so we emit
1065 // an error here instead.
1066 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1067 for (auto &Segment : Segments)
1068 Segment->removeSection(RemoveSec.get());
1069 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1070 KeepSec->removeSectionReferences(RemoveSec.get());
1071 }
1072 // Now finally get rid of them all togethor.
1073 Sections.erase(Iter, std::end(Sections));
1074}
1075
Paul Semel4246a462018-05-09 21:36:54 +00001076void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1077 if (!SymbolTable)
1078 return;
1079
1080 for (const SecPtr &Sec : Sections)
1081 Sec->removeSymbols(ToRemove);
1082}
1083
Jake Ehrlich76e91102018-01-25 22:46:17 +00001084void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001085 // Put all sections in offset order. Maintain the ordering as closely as
1086 // possible while meeting that demand however.
1087 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1088 return A->OriginalOffset < B->OriginalOffset;
1089 };
1090 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1091 CompareSections);
1092}
1093
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001094static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1095 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1096 if (Align == 0)
1097 Align = 1;
1098 auto Diff =
1099 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1100 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1101 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1102 if (Diff < 0)
1103 Diff += Align;
1104 return Offset + Diff;
1105}
1106
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001107// Orders segments such that if x = y->ParentSegment then y comes before x.
1108static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001109 std::stable_sort(std::begin(Segments), std::end(Segments),
1110 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001111}
1112
1113// This function finds a consistent layout for a list of segments starting from
1114// an Offset. It assumes that Segments have been sorted by OrderSegments and
1115// returns an Offset one past the end of the last segment.
1116static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1117 uint64_t Offset) {
1118 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001119 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001120 // The only way a segment should move is if a section was between two
1121 // segments and that section was removed. If that section isn't in a segment
1122 // then it's acceptable, but not ideal, to simply move it to after the
1123 // segments. So we can simply layout segments one after the other accounting
1124 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001125 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001126 // We assume that segments have been ordered by OriginalOffset and Index
1127 // such that a parent segment will always come before a child segment in
1128 // OrderedSegments. This means that the Offset of the ParentSegment should
1129 // already be set and we can set our offset relative to it.
1130 if (Segment->ParentSegment != nullptr) {
1131 auto Parent = Segment->ParentSegment;
1132 Segment->Offset =
1133 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1134 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001135 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001136 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001137 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001138 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001139 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001140 return Offset;
1141}
1142
1143// This function finds a consistent layout for a list of sections. It assumes
1144// that the ->ParentSegment of each section has already been laid out. The
1145// supplied starting Offset is used for the starting offset of any section that
1146// does not have a ParentSegment. It returns either the offset given if all
1147// sections had a ParentSegment or an offset one past the last section if there
1148// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001149template <class Range>
1150static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001151 // Now the offset of every segment has been set we can assign the offsets
1152 // of each section. For sections that are covered by a segment we should use
1153 // the segment's original offset and the section's original offset to compute
1154 // the offset from the start of the segment. Using the offset from the start
1155 // of the segment we can assign a new offset to the section. For sections not
1156 // covered by segments we can just bump Offset to the next valid location.
1157 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001158 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001159 Section.Index = Index++;
1160 if (Section.ParentSegment != nullptr) {
1161 auto Segment = *Section.ParentSegment;
1162 Section.Offset =
1163 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001164 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001165 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1166 Section.Offset = Offset;
1167 if (Section.Type != SHT_NOBITS)
1168 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001169 }
1170 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001171 return Offset;
1172}
Petr Hosek3f383832017-08-26 01:32:20 +00001173
Jake Ehrlich76e91102018-01-25 22:46:17 +00001174template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001175 // We need a temporary list of segments that has a special order to it
1176 // so that we know that anytime ->ParentSegment is set that segment has
1177 // already had its offset properly set.
1178 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001179 for (auto &Segment : Obj.segments())
1180 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001181 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1182 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001183 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001184 // Offset is used as the start offset of the first segment to be laid out.
1185 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1186 // we start at offset 0.
1187 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001188 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001189 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001190 // If we need to write the section header table out then we need to align the
1191 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001192 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001193 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001194 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001195}
1196
Jake Ehrlich76e91102018-01-25 22:46:17 +00001197template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001198 // We already have the section header offset so we can calculate the total
1199 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001200 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1201 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001202 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001203}
1204
Jake Ehrlich76e91102018-01-25 22:46:17 +00001205template <class ELFT> void ELFWriter<ELFT>::write() {
1206 writeEhdr();
1207 writePhdrs();
1208 writeSectionData();
1209 if (WriteSectionHeaders)
1210 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001211 if (auto E = Buf.commit())
1212 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001213}
1214
1215template <class ELFT> void ELFWriter<ELFT>::finalize() {
1216 // It could happen that SectionNames has been removed and yet the user wants
1217 // a section header table output. We need to throw an error if a user tries
1218 // to do that.
1219 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1220 error("Cannot write section header table because section header string "
1221 "table was removed.");
1222
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001223 Obj.sortSections();
1224
1225 // We need to assign indexes before we perform layout because we need to know
1226 // if we need large indexes or not. We can assign indexes first and check as
1227 // we go to see if we will actully need large indexes.
1228 bool NeedsLargeIndexes = false;
1229 if (size(Obj.sections()) >= SHN_LORESERVE) {
1230 auto Sections = Obj.sections();
1231 NeedsLargeIndexes =
1232 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1233 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1234 // TODO: handle case where only one section needs the large index table but
1235 // only needs it because the large index table hasn't been removed yet.
1236 }
1237
1238 if (NeedsLargeIndexes) {
1239 // This means we definitely need to have a section index table but if we
1240 // already have one then we should use it instead of making a new one.
1241 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1242 // Addition of a section to the end does not invalidate the indexes of
1243 // other sections and assigns the correct index to the new section.
1244 auto &Shndx = Obj.addSection<SectionIndexSection>();
1245 Obj.SymbolTable->setShndxTable(&Shndx);
1246 Shndx.setSymTab(Obj.SymbolTable);
1247 }
1248 } else {
1249 // Since we don't need SectionIndexTable we should remove it and all
1250 // references to it.
1251 if (Obj.SectionIndexTable != nullptr) {
1252 Obj.removeSections([this](const SectionBase &Sec) {
1253 return &Sec == Obj.SectionIndexTable;
1254 });
1255 }
1256 }
1257
1258 // Make sure we add the names of all the sections. Importantly this must be
1259 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001260 if (Obj.SectionNames != nullptr)
1261 for (const auto &Section : Obj.sections()) {
1262 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001263 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001264
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001265 // Before we can prepare for layout the indexes need to be finalized.
1266 uint64_t Index = 0;
1267 for (auto &Sec : Obj.sections())
1268 Sec.Index = Index++;
1269
1270 // The symbol table does not update all other sections on update. For
1271 // instance, symbol names are not added as new symbols are added. This means
1272 // that some sections, like .strtab, don't yet have their final size.
1273 if (Obj.SymbolTable != nullptr)
1274 Obj.SymbolTable->prepareForLayout();
1275
Petr Hosekc4df10e2017-08-04 21:09:26 +00001276 assignOffsets();
1277
1278 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001279 if (Obj.SectionNames != nullptr)
1280 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001281 // Finally now that all offsets and indexes have been set we can finalize any
1282 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001283 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1284 for (auto &Section : Obj.sections()) {
1285 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001286 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001287 if (WriteSectionHeaders)
1288 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1289 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001290 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001291
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001292 Buf.allocate(totalSize());
1293 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001294}
1295
Jake Ehrlich76e91102018-01-25 22:46:17 +00001296void BinaryWriter::write() {
1297 for (auto &Section : Obj.sections()) {
1298 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001299 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001300 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001301 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001302 if (auto E = Buf.commit())
1303 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001304}
1305
Jake Ehrlich76e91102018-01-25 22:46:17 +00001306void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001307 // TODO: Create a filter range to construct OrderedSegments from so that this
1308 // code can be deduped with assignOffsets above. This should also solve the
1309 // todo below for LayoutSections.
1310 // We need a temporary list of segments that has a special order to it
1311 // so that we know that anytime ->ParentSegment is set that segment has
1312 // already had it's offset properly set. We only want to consider the segments
1313 // that will affect layout of allocated sections so we only add those.
1314 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001315 for (auto &Section : Obj.sections()) {
1316 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1317 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001318 }
1319 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001320
1321 // For binary output, we're going to use physical addresses instead of
1322 // virtual addresses, since a binary output is used for cases like ROM
1323 // loading and physical addresses are intended for ROM loading.
1324 // However, if no segment has a physical address, we'll fallback to using
1325 // virtual addresses for all.
1326 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1327 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1328 for (const auto &Segment : OrderedSegments)
1329 Segment->PAddr = Segment->VAddr;
1330
1331 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1332 compareSegmentsByPAddr);
1333
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001334 // Because we add a ParentSegment for each section we might have duplicate
1335 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1336 // would do very strange things.
1337 auto End =
1338 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1339 OrderedSegments.erase(End, std::end(OrderedSegments));
1340
Jake Ehrlich46814be2018-01-22 19:27:30 +00001341 uint64_t Offset = 0;
1342
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001343 // Modify the first segment so that there is no gap at the start. This allows
1344 // our layout algorithm to proceed as expected while not out writing out the
1345 // gap at the start.
1346 if (!OrderedSegments.empty()) {
1347 auto Seg = OrderedSegments[0];
1348 auto Sec = Seg->firstSection();
1349 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1350 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001351 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001352 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001353 // The PAddr needs to be increased to remove the gap before the first
1354 // section.
1355 Seg->PAddr += Diff;
1356 uint64_t LowestPAddr = Seg->PAddr;
1357 for (auto &Segment : OrderedSegments) {
1358 Segment->Offset = Segment->PAddr - LowestPAddr;
1359 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1360 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001361 }
1362
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001363 // TODO: generalize LayoutSections to take a range. Pass a special range
1364 // constructed from an iterator that skips values for which a predicate does
1365 // not hold. Then pass such a range to LayoutSections instead of constructing
1366 // AllocatedSections here.
1367 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001368 for (auto &Section : Obj.sections()) {
1369 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001370 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001371 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001372 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001373 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001374
1375 // Now that every section has been laid out we just need to compute the total
1376 // file size. This might not be the same as the offset returned by
1377 // LayoutSections, because we want to truncate the last segment to the end of
1378 // its last section, to match GNU objcopy's behaviour.
1379 TotalSize = 0;
1380 for (const auto &Section : AllocatedSections) {
1381 if (Section->Type != SHT_NOBITS)
1382 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1383 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001384
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001385 Buf.allocate(TotalSize);
1386 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001387}
1388
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001389namespace llvm {
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001390namespace objcopy {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001391
Jake Ehrlich76e91102018-01-25 22:46:17 +00001392template class ELFBuilder<ELF64LE>;
1393template class ELFBuilder<ELF64BE>;
1394template class ELFBuilder<ELF32LE>;
1395template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001396
Jake Ehrlich76e91102018-01-25 22:46:17 +00001397template class ELFWriter<ELF64LE>;
1398template class ELFWriter<ELF64BE>;
1399template class ELFWriter<ELF32LE>;
1400template class ELFWriter<ELF32BE>;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001401} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001402} // end namespace llvm