blob: b3ad7329bb6b72902655b2809d06bc682364fcc4 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "Object.h"
11#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000012#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/BinaryFormat/ELF.h"
18#include "llvm/Object/ELFObjectFile.h"
19#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Support/FileOutputBuffer.h"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000021#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000022#include <algorithm>
23#include <cstddef>
24#include <cstdint>
25#include <iterator>
26#include <utility>
27#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000028
29using namespace llvm;
30using namespace object;
31using namespace ELF;
32
Jake Ehrlich76e91102018-01-25 22:46:17 +000033template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000034 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000035
Jake Ehrlich76e91102018-01-25 22:46:17 +000036 uint8_t *Buf = BufPtr->getBufferStart();
Jake Ehrlich6452b112018-02-14 23:31:33 +000037 Buf += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +000038 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000039 Phdr.p_type = Seg.Type;
40 Phdr.p_flags = Seg.Flags;
41 Phdr.p_offset = Seg.Offset;
42 Phdr.p_vaddr = Seg.VAddr;
43 Phdr.p_paddr = Seg.PAddr;
44 Phdr.p_filesz = Seg.FileSize;
45 Phdr.p_memsz = Seg.MemSize;
46 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000047}
48
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000049void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000050void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000051void SectionBase::finalize() {}
52
Jake Ehrlich76e91102018-01-25 22:46:17 +000053template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
54 uint8_t *Buf = BufPtr->getBufferStart();
55 Buf += Sec.HeaderOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +000056 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +000057 Shdr.sh_name = Sec.NameIndex;
58 Shdr.sh_type = Sec.Type;
59 Shdr.sh_flags = Sec.Flags;
60 Shdr.sh_addr = Sec.Addr;
61 Shdr.sh_offset = Sec.Offset;
62 Shdr.sh_size = Sec.Size;
63 Shdr.sh_link = Sec.Link;
64 Shdr.sh_info = Sec.Info;
65 Shdr.sh_addralign = Sec.Align;
66 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000067}
68
Jake Ehrlich76e91102018-01-25 22:46:17 +000069SectionVisitor::~SectionVisitor() {}
70
71void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
72 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
73}
74
75void BinarySectionWriter::visit(const RelocationSection &Sec) {
76 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
77}
78
79void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
80 error("Cannot write '.gnu_debuglink' out to binary");
81}
82
83void SectionWriter::visit(const Section &Sec) {
84 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +000085 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +000086 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
87 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +000088}
89
Jake Ehrlich76e91102018-01-25 22:46:17 +000090void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
91
92void SectionWriter::visit(const OwnedDataSection &Sec) {
93 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
94 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
95}
96
97void OwnedDataSection::accept(SectionVisitor &Visitor) const {
98 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +000099}
100
Petr Hosek05a04cb2017-08-01 00:33:58 +0000101void StringTableSection::addString(StringRef Name) {
102 StrTabBuilder.add(Name);
103 Size = StrTabBuilder.getSize();
104}
105
106uint32_t StringTableSection::findIndex(StringRef Name) const {
107 return StrTabBuilder.getOffset(Name);
108}
109
110void StringTableSection::finalize() { StrTabBuilder.finalize(); }
111
Jake Ehrlich76e91102018-01-25 22:46:17 +0000112void SectionWriter::visit(const StringTableSection &Sec) {
113 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
114}
115
116void StringTableSection::accept(SectionVisitor &Visitor) const {
117 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000118}
119
Petr Hosekc1135772017-09-13 03:04:50 +0000120static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000121 switch (Index) {
122 case SHN_ABS:
123 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000124 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000125 }
Petr Hosekc1135772017-09-13 03:04:50 +0000126 if (Machine == EM_HEXAGON) {
127 switch (Index) {
128 case SHN_HEXAGON_SCOMMON:
129 case SHN_HEXAGON_SCOMMON_2:
130 case SHN_HEXAGON_SCOMMON_4:
131 case SHN_HEXAGON_SCOMMON_8:
132 return true;
133 }
134 }
135 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000136}
137
138uint16_t Symbol::getShndx() const {
139 if (DefinedIn != nullptr) {
140 return DefinedIn->Index;
141 }
142 switch (ShndxType) {
143 // This means that we don't have a defined section but we do need to
144 // output a legitimate section index.
145 case SYMBOL_SIMPLE_INDEX:
146 return SHN_UNDEF;
147 case SYMBOL_ABS:
148 case SYMBOL_COMMON:
149 case SYMBOL_HEXAGON_SCOMMON:
150 case SYMBOL_HEXAGON_SCOMMON_2:
151 case SYMBOL_HEXAGON_SCOMMON_4:
152 case SYMBOL_HEXAGON_SCOMMON_8:
153 return static_cast<uint16_t>(ShndxType);
154 }
155 llvm_unreachable("Symbol with invalid ShndxType encountered");
156}
157
Petr Hosek79cee9e2017-08-29 02:12:03 +0000158void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
159 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000160 uint8_t Visibility, uint16_t Shndx,
161 uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000162 Symbol Sym;
163 Sym.Name = Name;
164 Sym.Binding = Bind;
165 Sym.Type = Type;
166 Sym.DefinedIn = DefinedIn;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000167 if (DefinedIn == nullptr) {
168 if (Shndx >= SHN_LORESERVE)
169 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
170 else
171 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
172 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000173 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000174 Sym.Visibility = Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000175 Sym.Size = Sz;
176 Sym.Index = Symbols.size();
177 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
178 Size += this->EntrySize;
179}
180
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000181void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
182 if (SymbolNames == Sec) {
183 error("String table " + SymbolNames->Name +
184 " cannot be removed because it is referenced by the symbol table " +
185 this->Name);
186 }
187 auto Iter =
188 std::remove_if(std::begin(Symbols), std::end(Symbols),
189 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
190 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
191 Symbols.erase(Iter, std::end(Symbols));
192}
193
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000194void SymbolTableSection::localize(
195 std::function<bool(const Symbol &)> ToLocalize) {
196 for (const auto &Sym : Symbols) {
197 if (ToLocalize(*Sym))
198 Sym->Binding = STB_LOCAL;
199 }
200
201 // Now that the local symbols aren't grouped at the start we have to reorder
202 // the symbols to respect this property.
203 std::stable_partition(
204 std::begin(Symbols), std::end(Symbols),
205 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
206
207 // Lastly we fix the symbol indexes.
208 uint32_t Index = 0;
209 for (auto &Sym : Symbols)
210 Sym->Index = Index++;
211}
212
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000213void SymbolTableSection::initialize(SectionTableRef SecTable) {
214 Size = 0;
215 setStrTab(SecTable.getSectionOfType<StringTableSection>(
216 Link,
217 "Symbol table has link index of " + Twine(Link) +
218 " which is not a valid index",
219 "Symbol table has link index of " + Twine(Link) +
220 " which is not a string table"));
221}
222
Petr Hosek79cee9e2017-08-29 02:12:03 +0000223void SymbolTableSection::finalize() {
224 // Make sure SymbolNames is finalized before getting name indexes.
225 SymbolNames->finalize();
226
227 uint32_t MaxLocalIndex = 0;
228 for (auto &Sym : Symbols) {
229 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
230 if (Sym->Binding == STB_LOCAL)
231 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
232 }
233 // Now we need to set the Link and Info fields.
234 Link = SymbolNames->Index;
235 Info = MaxLocalIndex + 1;
236}
237
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000238void SymbolTableSection::addSymbolNames() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000239 // Add all of our strings to SymbolNames so that SymbolNames has the right
240 // size before layout is decided.
241 for (auto &Sym : Symbols)
242 SymbolNames->addString(Sym->Name);
243}
244
245const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
246 if (Symbols.size() <= Index)
247 error("Invalid symbol index: " + Twine(Index));
248 return Symbols[Index].get();
249}
250
251template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000252void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000253 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000254 Buf += Sec.Offset;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000255 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
256 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000257 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000258 Sym->st_name = Symbol->NameIndex;
259 Sym->st_value = Symbol->Value;
260 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000261 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000262 Sym->setBinding(Symbol->Binding);
263 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000264 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000265 ++Sym;
266 }
267}
268
Jake Ehrlich76e91102018-01-25 22:46:17 +0000269void SymbolTableSection::accept(SectionVisitor &Visitor) const {
270 Visitor.visit(*this);
271}
272
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000273template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000274void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
275 const SectionBase *Sec) {
276 if (Symbols == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000277 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
278 "referenced by the relocation "
279 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000280 this->Name);
281 }
282}
283
284template <class SymTabType>
285void RelocSectionWithSymtabBase<SymTabType>::initialize(
286 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000287 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000288 Link,
289 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
290 "Link field value " + Twine(Link) + " in section " + Name +
291 " is not a symbol table"));
292
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000293 if (Info != SHN_UNDEF)
Jake Ehrlich777fb002017-12-15 20:17:55 +0000294 setSection(SecTable.getSection(Info,
295 "Info field value " + Twine(Info) +
296 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000297 else
298 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000299}
300
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000301template <class SymTabType>
302void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000303 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000304 if (SecToApplyRel != nullptr)
305 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000306}
307
308template <class ELFT>
309void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
310
311template <class ELFT>
312void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
313 Rela.r_addend = Addend;
314}
315
Jake Ehrlich76e91102018-01-25 22:46:17 +0000316template <class RelRange, class T>
317void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000318 for (const auto &Reloc : Relocations) {
319 Buf->r_offset = Reloc.Offset;
320 setAddend(*Buf, Reloc.Addend);
321 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
322 ++Buf;
323 }
324}
325
326template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000327void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
328 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
329 if (Sec.Type == SHT_REL)
330 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000331 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000332 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000333}
334
Jake Ehrlich76e91102018-01-25 22:46:17 +0000335void RelocationSection::accept(SectionVisitor &Visitor) const {
336 Visitor.visit(*this);
337}
338
339void SectionWriter::visit(const DynamicRelocationSection &Sec) {
340 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
341 Out.getBufferStart() + Sec.Offset);
342}
343
344void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
345 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000346}
347
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000348void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
349 if (StrTab == Sec) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000350 error("String table " + StrTab->Name + " cannot be removed because it is "
351 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000352 this->Name);
353 }
354}
355
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000356bool SectionWithStrTab::classof(const SectionBase *S) {
357 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
358}
359
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000360void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Jake Ehrlich777fb002017-12-15 20:17:55 +0000361 auto StrTab = SecTable.getSection(Link,
362 "Link field value " + Twine(Link) +
363 " in section " + Name + " is invalid");
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000364 if (StrTab->Type != SHT_STRTAB) {
365 error("Link field value " + Twine(Link) + " in section " + Name +
366 " is not a string table");
367 }
368 setStrTab(StrTab);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000369}
370
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000371void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
372
Jake Ehrlich76e91102018-01-25 22:46:17 +0000373void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000374 FileName = sys::path::filename(File);
375 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000376 // followed by a null terminator and then the CRC32 of the file. The CRC32
377 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
378 // byte, and then finally push the size to alignment and add 4.
379 Size = alignTo(FileName.size() + 1, 4) + 4;
380 // The CRC32 will only be aligned if we align the whole section.
381 Align = 4;
382 Type = ELF::SHT_PROGBITS;
383 Name = ".gnu_debuglink";
384 // For sections not found in segments, OriginalOffset is only used to
385 // establish the order that sections should go in. By using the maximum
386 // possible offset we cause this section to wind up at the end.
387 OriginalOffset = std::numeric_limits<uint64_t>::max();
388 JamCRC crc;
389 crc.update(ArrayRef<char>(Data.data(), Data.size()));
390 // The CRC32 value needs to be complemented because the JamCRC dosn't
391 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
392 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
393 CRC32 = ~crc.getCRC();
394}
395
Jake Ehrlich76e91102018-01-25 22:46:17 +0000396GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000397 // Read in the file to compute the CRC of it.
398 auto DebugOrErr = MemoryBuffer::getFile(File);
399 if (!DebugOrErr)
400 error("'" + File + "': " + DebugOrErr.getError().message());
401 auto Debug = std::move(*DebugOrErr);
402 init(File, Debug->getBuffer());
403}
404
405template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000406void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
407 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000408 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000409 Elf_Word *CRC =
410 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
411 *CRC = Sec.CRC32;
412 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
413}
414
415void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
416 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000417}
418
Petr Hosek05a04cb2017-08-01 00:33:58 +0000419// Returns true IFF a section is wholly inside the range of a segment
420static bool sectionWithinSegment(const SectionBase &Section,
421 const Segment &Segment) {
422 // If a section is empty it should be treated like it has a size of 1. This is
423 // to clarify the case when an empty section lies on a boundary between two
424 // segments and ensures that the section "belongs" to the second segment and
425 // not the first.
426 uint64_t SecSize = Section.Size ? Section.Size : 1;
427 return Segment.Offset <= Section.OriginalOffset &&
428 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
429}
430
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000431// Returns true IFF a segment's original offset is inside of another segment's
432// range.
433static bool segmentOverlapsSegment(const Segment &Child,
434 const Segment &Parent) {
435
436 return Parent.OriginalOffset <= Child.OriginalOffset &&
437 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
438}
439
Jake Ehrlich46814be2018-01-22 19:27:30 +0000440static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000441 // Any segment without a parent segment should come before a segment
442 // that has a parent segment.
443 if (A->OriginalOffset < B->OriginalOffset)
444 return true;
445 if (A->OriginalOffset > B->OriginalOffset)
446 return false;
447 return A->Index < B->Index;
448}
449
Jake Ehrlich46814be2018-01-22 19:27:30 +0000450static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
451 if (A->PAddr < B->PAddr)
452 return true;
453 if (A->PAddr > B->PAddr)
454 return false;
455 return A->Index < B->Index;
456}
457
Jake Ehrlich6452b112018-02-14 23:31:33 +0000458template <class ELFT>
459void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
460 for (auto &Parent : Obj.segments()) {
461 // Every segment will overlap with itself but we don't want a segment to
462 // be it's own parent so we avoid that situation.
463 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
464 // We want a canonical "most parental" segment but this requires
465 // inspecting the ParentSegment.
466 if (compareSegmentsByOffset(&Parent, &Child))
467 if (Child.ParentSegment == nullptr ||
468 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
469 Child.ParentSegment = &Parent;
470 }
471 }
472 }
473}
474
Jake Ehrlich76e91102018-01-25 22:46:17 +0000475template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000476 uint32_t Index = 0;
477 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000478 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
479 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000480 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000481 Seg.Type = Phdr.p_type;
482 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000483 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000484 Seg.Offset = Phdr.p_offset;
485 Seg.VAddr = Phdr.p_vaddr;
486 Seg.PAddr = Phdr.p_paddr;
487 Seg.FileSize = Phdr.p_filesz;
488 Seg.MemSize = Phdr.p_memsz;
489 Seg.Align = Phdr.p_align;
490 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000491 for (auto &Section : Obj.sections()) {
492 if (sectionWithinSegment(Section, Seg)) {
493 Seg.addSection(&Section);
494 if (!Section.ParentSegment ||
495 Section.ParentSegment->Offset > Seg.Offset) {
496 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000497 }
498 }
499 }
500 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000501
502 auto &ElfHdr = Obj.ElfHdrSegment;
503 // Creating multiple PT_PHDR segments technically is not valid, but PT_LOAD
504 // segments must not overlap, and other types fit even less.
505 ElfHdr.Type = PT_PHDR;
506 ElfHdr.Flags = 0;
507 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
508 ElfHdr.VAddr = 0;
509 ElfHdr.PAddr = 0;
510 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
511 ElfHdr.Align = 0;
512 ElfHdr.Index = Index++;
513
514 const auto &Ehdr = *ElfFile.getHeader();
515 auto &PrHdr = Obj.ProgramHdrSegment;
516 PrHdr.Type = PT_PHDR;
517 PrHdr.Flags = 0;
518 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
519 // Whereas this works automatically for ElfHdr, here OriginalOffset is
520 // always non-zero and to ensure the equation we assign the same value to
521 // VAddr as well.
522 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
523 PrHdr.PAddr = 0;
524 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
525 // The spec requires us to naturally align all the fields.
526 PrHdr.Align = sizeof(Elf_Addr);
527 PrHdr.Index = Index++;
528
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000529 // Now we do an O(n^2) loop through the segments in order to match up
530 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000531 for (auto &Child : Obj.segments())
532 setParentSegment(Child);
533 setParentSegment(ElfHdr);
534 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000535}
536
537template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000538void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000539 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
540 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
541
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000542 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000543 SectionBase *DefSection = nullptr;
544 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000545
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000546 if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000547 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000548 error(
549 "Symbol '" + Name +
550 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
551 Twine(Sym.st_shndx));
552 }
553 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000554 DefSection = Obj.sections().getSection(
Jake Ehrlich777fb002017-12-15 20:17:55 +0000555 Sym.st_shndx,
556 "Symbol '" + Name + "' is defined in invalid section with index " +
557 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000558 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000559
Petr Hosek79cee9e2017-08-29 02:12:03 +0000560 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000561 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000562 }
563}
564
565template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000566static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
567
568template <class ELFT>
569static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
570 ToSet = Rela.r_addend;
571}
572
Jake Ehrlich76e91102018-01-25 22:46:17 +0000573template <class T>
574void initRelocations(RelocationSection *Relocs, SymbolTableSection *SymbolTable,
575 T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000576 for (const auto &Rel : RelRange) {
577 Relocation ToAdd;
578 ToAdd.Offset = Rel.r_offset;
579 getAddend(ToAdd.Addend, Rel);
580 ToAdd.Type = Rel.getType(false);
581 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
582 Relocs->addRelocation(ToAdd);
583 }
584}
585
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000586SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000587 if (Index == SHN_UNDEF || Index > Sections.size())
588 error(ErrMsg);
589 return Sections[Index - 1].get();
590}
591
592template <class T>
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000593T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000594 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000595 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000596 return Sec;
597 error(TypeErrMsg);
598}
599
Petr Hosekd7df9b22017-09-06 23:41:02 +0000600template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000601SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000602 ArrayRef<uint8_t> Data;
603 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000604 case SHT_REL:
605 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000606 if (Shdr.sh_flags & SHF_ALLOC) {
607 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000608 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000609 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000610 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000611 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000612 // If a string table is allocated we don't want to mess with it. That would
613 // mean altering the memory image. There are no special link types or
614 // anything so we can just use a Section.
615 if (Shdr.sh_flags & SHF_ALLOC) {
616 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000617 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000618 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000619 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000620 case SHT_HASH:
621 case SHT_GNU_HASH:
622 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
623 // Because of this we don't need to mess with the hash tables either.
624 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000625 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000626 case SHT_DYNSYM:
627 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000628 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000629 case SHT_DYNAMIC:
630 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000631 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000632 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000633 auto &SymTab = Obj.addSection<SymbolTableSection>();
634 Obj.SymbolTable = &SymTab;
635 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000636 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000637 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +0000638 return Obj.addSection<Section>(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000639 default:
640 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000641 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000642 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000643}
644
Jake Ehrlich76e91102018-01-25 22:46:17 +0000645template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000646 uint32_t Index = 0;
647 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
648 if (Index == 0) {
649 ++Index;
650 continue;
651 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000652 auto &Sec = makeSection(Shdr);
653 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
654 Sec.Type = Shdr.sh_type;
655 Sec.Flags = Shdr.sh_flags;
656 Sec.Addr = Shdr.sh_addr;
657 Sec.Offset = Shdr.sh_offset;
658 Sec.OriginalOffset = Shdr.sh_offset;
659 Sec.Size = Shdr.sh_size;
660 Sec.Link = Shdr.sh_link;
661 Sec.Info = Shdr.sh_info;
662 Sec.Align = Shdr.sh_addralign;
663 Sec.EntrySize = Shdr.sh_entsize;
664 Sec.Index = Index++;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000665 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000666
667 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000668 // details about symbol tables. We need the symbol table filled out before
669 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000670 if (Obj.SymbolTable) {
671 Obj.SymbolTable->initialize(Obj.sections());
672 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000673 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000674
675 // Now that all sections and symbols have been added we can add
676 // relocations that reference symbols and set the link and info fields for
677 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000678 for (auto &Section : Obj.sections()) {
679 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000680 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000681 Section.initialize(Obj.sections());
682 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000683 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
684 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +0000685 initRelocations(RelSec, Obj.SymbolTable,
686 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000687 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000688 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000689 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000690 }
691 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000692}
693
Jake Ehrlich76e91102018-01-25 22:46:17 +0000694template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000695 const auto &Ehdr = *ElfFile.getHeader();
696
Jake Ehrlich76e91102018-01-25 22:46:17 +0000697 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Obj.Ident);
698 Obj.Type = Ehdr.e_type;
699 Obj.Machine = Ehdr.e_machine;
700 Obj.Version = Ehdr.e_version;
701 Obj.Entry = Ehdr.e_entry;
702 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000703
Jake Ehrlich76e91102018-01-25 22:46:17 +0000704 readSectionHeaders();
705 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000706
Jake Ehrlich76e91102018-01-25 22:46:17 +0000707 Obj.SectionNames =
708 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000709 Ehdr.e_shstrndx,
710 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000711 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000712 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +0000713 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000714}
715
Jake Ehrlich76e91102018-01-25 22:46:17 +0000716// A generic size function which computes sizes of any random access range.
717template <class R> size_t size(R &&Range) {
718 return static_cast<size_t>(std::end(Range) - std::begin(Range));
719}
720
721Writer::~Writer() {}
722
723Reader::~Reader() {}
724
725ELFReader::ELFReader(StringRef File) {
726 auto BinaryOrErr = createBinary(File);
727 if (!BinaryOrErr)
728 reportError(File, BinaryOrErr.takeError());
Jake Ehrlich9634e182018-01-26 02:01:37 +0000729 auto OwnedBin = std::move(BinaryOrErr.get());
730 std::tie(Bin, Data) = OwnedBin.takeBinary();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000731}
732
733ElfType ELFReader::getElfType() const {
Jake Ehrlich9634e182018-01-26 02:01:37 +0000734 if (isa<ELFObjectFile<ELF32LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000735 return ELFT_ELF32LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000736 if (isa<ELFObjectFile<ELF64LE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000737 return ELFT_ELF64LE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000738 if (isa<ELFObjectFile<ELF32BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000739 return ELFT_ELF32BE;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000740 if (isa<ELFObjectFile<ELF64BE>>(Bin.get()))
Jake Ehrlich76e91102018-01-25 22:46:17 +0000741 return ELFT_ELF64BE;
742 llvm_unreachable("Invalid ELFType");
743}
744
745std::unique_ptr<Object> ELFReader::create() const {
746 auto Obj = llvm::make_unique<Object>(Data);
Jake Ehrlich9634e182018-01-26 02:01:37 +0000747 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000748 ELFBuilder<ELF32LE> Builder(*o, *Obj);
749 Builder.build();
750 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000751 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000752 ELFBuilder<ELF64LE> Builder(*o, *Obj);
753 Builder.build();
754 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000755 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000756 ELFBuilder<ELF32BE> Builder(*o, *Obj);
757 Builder.build();
758 return Obj;
Jake Ehrlich9634e182018-01-26 02:01:37 +0000759 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin.get())) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000760 ELFBuilder<ELF64BE> Builder(*o, *Obj);
761 Builder.build();
762 return Obj;
763 }
764 error("Invalid file type");
765}
766
767template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
768 uint8_t *Buf = BufPtr->getBufferStart();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000769 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000770 std::copy(Obj.Ident, Obj.Ident + 16, Ehdr.e_ident);
771 Ehdr.e_type = Obj.Type;
772 Ehdr.e_machine = Obj.Machine;
773 Ehdr.e_version = Obj.Version;
774 Ehdr.e_entry = Obj.Entry;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000775 Ehdr.e_phoff = Obj.ProgramHdrSegment.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000776 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000777 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
778 Ehdr.e_phentsize = sizeof(Elf_Phdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000779 Ehdr.e_phnum = size(Obj.segments());
Petr Hosek05a04cb2017-08-01 00:33:58 +0000780 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000781 if (WriteSectionHeaders) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000782 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000783 Ehdr.e_shnum = size(Obj.sections()) + 1;
784 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000785 } else {
786 Ehdr.e_shoff = 0;
787 Ehdr.e_shnum = 0;
788 Ehdr.e_shstrndx = 0;
789 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000790}
791
Jake Ehrlich76e91102018-01-25 22:46:17 +0000792template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
793 for (auto &Seg : Obj.segments())
794 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000795}
796
Jake Ehrlich76e91102018-01-25 22:46:17 +0000797template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
798 uint8_t *Buf = BufPtr->getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000799 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000800 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000801 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
802 Shdr.sh_name = 0;
803 Shdr.sh_type = SHT_NULL;
804 Shdr.sh_flags = 0;
805 Shdr.sh_addr = 0;
806 Shdr.sh_offset = 0;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000807 Shdr.sh_size = 0;
808 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000809 Shdr.sh_info = 0;
810 Shdr.sh_addralign = 0;
811 Shdr.sh_entsize = 0;
812
Jake Ehrlich76e91102018-01-25 22:46:17 +0000813 for (auto &Sec : Obj.sections())
814 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000815}
816
Jake Ehrlich76e91102018-01-25 22:46:17 +0000817template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
818 for (auto &Sec : Obj.sections())
819 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000820}
821
Jake Ehrlich76e91102018-01-25 22:46:17 +0000822void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000823
824 auto Iter = std::stable_partition(
825 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
826 if (ToRemove(*Sec))
827 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000828 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
829 if (auto ToRelSec = RelSec->getSection())
830 return !ToRemove(*ToRelSec);
831 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000832 return true;
833 });
834 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
835 SymbolTable = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000836 if (SectionNames != nullptr && ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000837 SectionNames = nullptr;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000838 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000839 // Now make sure there are no remaining references to the sections that will
840 // be removed. Sometimes it is impossible to remove a reference so we emit
841 // an error here instead.
842 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
843 for (auto &Segment : Segments)
844 Segment->removeSection(RemoveSec.get());
845 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
846 KeepSec->removeSectionReferences(RemoveSec.get());
847 }
848 // Now finally get rid of them all togethor.
849 Sections.erase(Iter, std::end(Sections));
850}
851
Jake Ehrlich76e91102018-01-25 22:46:17 +0000852void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000853 // Put all sections in offset order. Maintain the ordering as closely as
854 // possible while meeting that demand however.
855 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
856 return A->OriginalOffset < B->OriginalOffset;
857 };
858 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
859 CompareSections);
860}
861
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000862static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
863 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
864 if (Align == 0)
865 Align = 1;
866 auto Diff =
867 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
868 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
869 // (Offset + Diff) & -Align == Addr & -Align will still hold.
870 if (Diff < 0)
871 Diff += Align;
872 return Offset + Diff;
873}
874
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000875// Orders segments such that if x = y->ParentSegment then y comes before x.
876static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +0000877 std::stable_sort(std::begin(Segments), std::end(Segments),
878 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000879}
880
881// This function finds a consistent layout for a list of segments starting from
882// an Offset. It assumes that Segments have been sorted by OrderSegments and
883// returns an Offset one past the end of the last segment.
884static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
885 uint64_t Offset) {
886 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +0000887 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +0000888 // The only way a segment should move is if a section was between two
889 // segments and that section was removed. If that section isn't in a segment
890 // then it's acceptable, but not ideal, to simply move it to after the
891 // segments. So we can simply layout segments one after the other accounting
892 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000893 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000894 // We assume that segments have been ordered by OriginalOffset and Index
895 // such that a parent segment will always come before a child segment in
896 // OrderedSegments. This means that the Offset of the ParentSegment should
897 // already be set and we can set our offset relative to it.
898 if (Segment->ParentSegment != nullptr) {
899 auto Parent = Segment->ParentSegment;
900 Segment->Offset =
901 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
902 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +0000903 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000904 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000905 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000906 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000907 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000908 return Offset;
909}
910
911// This function finds a consistent layout for a list of sections. It assumes
912// that the ->ParentSegment of each section has already been laid out. The
913// supplied starting Offset is used for the starting offset of any section that
914// does not have a ParentSegment. It returns either the offset given if all
915// sections had a ParentSegment or an offset one past the last section if there
916// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000917template <class Range>
918static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +0000919 // Now the offset of every segment has been set we can assign the offsets
920 // of each section. For sections that are covered by a segment we should use
921 // the segment's original offset and the section's original offset to compute
922 // the offset from the start of the segment. Using the offset from the start
923 // of the segment we can assign a new offset to the section. For sections not
924 // covered by segments we can just bump Offset to the next valid location.
925 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000926 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000927 Section.Index = Index++;
928 if (Section.ParentSegment != nullptr) {
929 auto Segment = *Section.ParentSegment;
930 Section.Offset =
931 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +0000932 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000933 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
934 Section.Offset = Offset;
935 if (Section.Type != SHT_NOBITS)
936 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +0000937 }
938 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000939 return Offset;
940}
Petr Hosek3f383832017-08-26 01:32:20 +0000941
Jake Ehrlich76e91102018-01-25 22:46:17 +0000942template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000943 // We need a temporary list of segments that has a special order to it
944 // so that we know that anytime ->ParentSegment is set that segment has
945 // already had its offset properly set.
946 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000947 for (auto &Segment : Obj.segments())
948 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +0000949 OrderedSegments.push_back(&Obj.ElfHdrSegment);
950 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000951 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +0000952 // Offset is used as the start offset of the first segment to be laid out.
953 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
954 // we start at offset 0.
955 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000956 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000957 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000958 // If we need to write the section header table out then we need to align the
959 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000960 if (WriteSectionHeaders)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000961 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000962 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000963}
964
Jake Ehrlich76e91102018-01-25 22:46:17 +0000965template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000966 // We already have the section header offset so we can calculate the total
967 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000968 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
969 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000970 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000971}
972
Jake Ehrlich76e91102018-01-25 22:46:17 +0000973template <class ELFT> void ELFWriter<ELFT>::write() {
974 writeEhdr();
975 writePhdrs();
976 writeSectionData();
977 if (WriteSectionHeaders)
978 writeShdrs();
979 if (auto E = BufPtr->commit())
980 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +0000981}
982
Jake Ehrlich76e91102018-01-25 22:46:17 +0000983void Writer::createBuffer(uint64_t Size) {
984 auto BufferOrErr =
985 FileOutputBuffer::create(File, Size, FileOutputBuffer::F_executable);
986 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &) {
987 error("failed to open " + File);
988 });
989 BufPtr = std::move(*BufferOrErr);
990}
991
992template <class ELFT> void ELFWriter<ELFT>::finalize() {
993 // It could happen that SectionNames has been removed and yet the user wants
994 // a section header table output. We need to throw an error if a user tries
995 // to do that.
996 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
997 error("Cannot write section header table because section header string "
998 "table was removed.");
999
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001000 // Make sure we add the names of all the sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001001 if (Obj.SectionNames != nullptr)
1002 for (const auto &Section : Obj.sections()) {
1003 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001004 }
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001005 // Make sure we add the names of all the symbols.
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001006 if (Obj.SymbolTable != nullptr)
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001007 Obj.SymbolTable->addSymbolNames();
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001008
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001009 Obj.sortSections();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001010 assignOffsets();
1011
1012 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001013 if (Obj.SectionNames != nullptr)
1014 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001015 // Finally now that all offsets and indexes have been set we can finalize any
1016 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001017 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1018 for (auto &Section : Obj.sections()) {
1019 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001020 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001021 if (WriteSectionHeaders)
1022 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1023 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001024 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001025
1026 createBuffer(totalSize());
1027 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(*BufPtr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001028}
1029
Jake Ehrlich76e91102018-01-25 22:46:17 +00001030void BinaryWriter::write() {
1031 for (auto &Section : Obj.sections()) {
1032 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001033 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001034 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001035 }
Jake Ehrlichc0e9bee2018-01-26 01:17:35 +00001036 if (auto E = BufPtr->commit())
1037 reportError(File, errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001038}
1039
Jake Ehrlich76e91102018-01-25 22:46:17 +00001040void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001041 // TODO: Create a filter range to construct OrderedSegments from so that this
1042 // code can be deduped with assignOffsets above. This should also solve the
1043 // todo below for LayoutSections.
1044 // We need a temporary list of segments that has a special order to it
1045 // so that we know that anytime ->ParentSegment is set that segment has
1046 // already had it's offset properly set. We only want to consider the segments
1047 // that will affect layout of allocated sections so we only add those.
1048 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001049 for (auto &Section : Obj.sections()) {
1050 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1051 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001052 }
1053 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001054
1055 // For binary output, we're going to use physical addresses instead of
1056 // virtual addresses, since a binary output is used for cases like ROM
1057 // loading and physical addresses are intended for ROM loading.
1058 // However, if no segment has a physical address, we'll fallback to using
1059 // virtual addresses for all.
1060 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1061 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1062 for (const auto &Segment : OrderedSegments)
1063 Segment->PAddr = Segment->VAddr;
1064
1065 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1066 compareSegmentsByPAddr);
1067
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001068 // Because we add a ParentSegment for each section we might have duplicate
1069 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1070 // would do very strange things.
1071 auto End =
1072 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1073 OrderedSegments.erase(End, std::end(OrderedSegments));
1074
Jake Ehrlich46814be2018-01-22 19:27:30 +00001075 uint64_t Offset = 0;
1076
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001077 // Modify the first segment so that there is no gap at the start. This allows
1078 // our layout algorithm to proceed as expected while not out writing out the
1079 // gap at the start.
1080 if (!OrderedSegments.empty()) {
1081 auto Seg = OrderedSegments[0];
1082 auto Sec = Seg->firstSection();
1083 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1084 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001085 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001086 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001087 // The PAddr needs to be increased to remove the gap before the first
1088 // section.
1089 Seg->PAddr += Diff;
1090 uint64_t LowestPAddr = Seg->PAddr;
1091 for (auto &Segment : OrderedSegments) {
1092 Segment->Offset = Segment->PAddr - LowestPAddr;
1093 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1094 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001095 }
1096
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001097 // TODO: generalize LayoutSections to take a range. Pass a special range
1098 // constructed from an iterator that skips values for which a predicate does
1099 // not hold. Then pass such a range to LayoutSections instead of constructing
1100 // AllocatedSections here.
1101 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001102 for (auto &Section : Obj.sections()) {
1103 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001104 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001105 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001106 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001107 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001108
1109 // Now that every section has been laid out we just need to compute the total
1110 // file size. This might not be the same as the offset returned by
1111 // LayoutSections, because we want to truncate the last segment to the end of
1112 // its last section, to match GNU objcopy's behaviour.
1113 TotalSize = 0;
1114 for (const auto &Section : AllocatedSections) {
1115 if (Section->Type != SHT_NOBITS)
1116 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1117 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001118
1119 createBuffer(TotalSize);
1120 SecWriter = llvm::make_unique<BinarySectionWriter>(*BufPtr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001121}
1122
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001123namespace llvm {
1124
Jake Ehrlich76e91102018-01-25 22:46:17 +00001125template class ELFBuilder<ELF64LE>;
1126template class ELFBuilder<ELF64BE>;
1127template class ELFBuilder<ELF32LE>;
1128template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001129
Jake Ehrlich76e91102018-01-25 22:46:17 +00001130template class ELFWriter<ELF64LE>;
1131template class ELFWriter<ELF64BE>;
1132template class ELFWriter<ELF32LE>;
1133template class ELFWriter<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001134
1135} // end namespace llvm