blob: 201b76772f925bdb99a5dacbb7709db5c9d85af2 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Petr Hosek05a04cb2017-08-01 00:33:58 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00008
Petr Hosek05a04cb2017-08-01 00:33:58 +00009#include "Object.h"
10#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/ADT/iterator_range.h"
16#include "llvm/BinaryFormat/ELF.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000017#include "llvm/MC/MCTargetOptions.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000018#include "llvm/Object/ELFObjectFile.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000019#include "llvm/Support/Compression.h"
Jordan Rupprecht971d47622019-02-01 15:20:36 +000020#include "llvm/Support/Errc.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000021#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/FileOutputBuffer.h"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000023#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000024#include <algorithm>
25#include <cstddef>
26#include <cstdint>
27#include <iterator>
Jordan Rupprecht52d57812019-02-21 16:45:42 +000028#include <unordered_set>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include <utility>
30#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000031
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000032namespace llvm {
33namespace objcopy {
34namespace elf {
35
Petr Hosek05a04cb2017-08-01 00:33:58 +000036using namespace object;
37using namespace ELF;
38
Jake Ehrlich76e91102018-01-25 22:46:17 +000039template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000040 uint8_t *B = Buf.getBufferStart();
41 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
42 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000043 Phdr.p_type = Seg.Type;
44 Phdr.p_flags = Seg.Flags;
45 Phdr.p_offset = Seg.Offset;
46 Phdr.p_vaddr = Seg.VAddr;
47 Phdr.p_paddr = Seg.PAddr;
48 Phdr.p_filesz = Seg.FileSize;
49 Phdr.p_memsz = Seg.MemSize;
50 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000051}
52
Jordan Rupprecht52d57812019-02-21 16:45:42 +000053Error SectionBase::removeSectionReferences(
54 function_ref<bool(const SectionBase *)> ToRemove) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +000055 return Error::success();
56}
57
58Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
59 return Error::success();
60}
61
Jake Ehrlichf5a43772017-09-25 20:37:28 +000062void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000063void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000064void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000065
Jake Ehrlich76e91102018-01-25 22:46:17 +000066template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000067 uint8_t *B = Buf.getBufferStart();
68 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000069 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000070 Shdr.sh_name = Sec.NameIndex;
71 Shdr.sh_type = Sec.Type;
72 Shdr.sh_flags = Sec.Flags;
73 Shdr.sh_addr = Sec.Addr;
74 Shdr.sh_offset = Sec.Offset;
75 Shdr.sh_size = Sec.Size;
76 Shdr.sh_link = Sec.Link;
77 Shdr.sh_info = Sec.Info;
78 Shdr.sh_addralign = Sec.Align;
79 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000080}
81
Jordan Rupprecht1f821762019-01-03 17:45:30 +000082template <class ELFT> void ELFSectionSizer<ELFT>::visit(Section &Sec) {}
83
84template <class ELFT>
85void ELFSectionSizer<ELFT>::visit(OwnedDataSection &Sec) {}
86
87template <class ELFT>
88void ELFSectionSizer<ELFT>::visit(StringTableSection &Sec) {}
89
90template <class ELFT>
91void ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &Sec) {}
92
93template <class ELFT>
94void ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
95 Sec.EntrySize = sizeof(Elf_Sym);
96 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000097 // Align to the largest field in Elf_Sym.
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +000098 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +000099}
100
101template <class ELFT>
102void ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
103 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
104 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +0000105 // Align to the largest field in Elf_Rel(a).
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000106 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000107}
108
109template <class ELFT>
110void ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &Sec) {}
111
112template <class ELFT> void ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {}
113
114template <class ELFT>
115void ELFSectionSizer<ELFT>::visit(SectionIndexSection &Sec) {}
116
117template <class ELFT>
118void ELFSectionSizer<ELFT>::visit(CompressedSection &Sec) {}
119
120template <class ELFT>
121void ELFSectionSizer<ELFT>::visit(DecompressedSection &Sec) {}
Jake Ehrlich76e91102018-01-25 22:46:17 +0000122
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000123void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
124 error("Cannot write symbol section index table '" + Sec.Name + "' ");
125}
126
Jake Ehrlich76e91102018-01-25 22:46:17 +0000127void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
128 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
129}
130
131void BinarySectionWriter::visit(const RelocationSection &Sec) {
132 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
133}
134
135void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000136 error("Cannot write '" + Sec.Name + "' out to binary");
137}
138
139void BinarySectionWriter::visit(const GroupSection &Sec) {
140 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000141}
142
143void SectionWriter::visit(const Section &Sec) {
144 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000145 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000146 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000147 llvm::copy(Sec.Contents, Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000148}
149
Jake Ehrlich76e91102018-01-25 22:46:17 +0000150void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
151
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000152void Section::accept(MutableSectionVisitor &Visitor) { Visitor.visit(*this); }
153
Jake Ehrlich76e91102018-01-25 22:46:17 +0000154void SectionWriter::visit(const OwnedDataSection &Sec) {
155 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000156 llvm::copy(Sec.Data, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000157}
158
Puyan Lotfiaf048642018-10-01 10:29:41 +0000159static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
160
161static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
162 return Data.size() > ZlibGnuMagic.size() &&
163 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
164}
165
166template <class ELFT>
167static std::tuple<uint64_t, uint64_t>
168getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
169 const bool IsGnuDebug = isDataGnuCompressed(Data);
170 const uint64_t DecompressedSize =
171 IsGnuDebug
172 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
173 Data.data() + ZlibGnuMagic.size()))
174 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
175 const uint64_t DecompressedAlign =
176 IsGnuDebug ? 1
177 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
178 ->ch_addralign;
179
180 return std::make_tuple(DecompressedSize, DecompressedAlign);
181}
182
183template <class ELFT>
184void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
185 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
186
187 if (!zlib::isAvailable()) {
188 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
189 return;
190 }
191
192 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
193 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
194 : sizeof(Elf_Chdr_Impl<ELFT>);
195
196 StringRef CompressedContent(
197 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
198 Sec.OriginalData.size() - DataOffset);
199
200 SmallVector<char, 128> DecompressedContent;
201 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
202 static_cast<size_t>(Sec.Size)))
203 reportError(Sec.Name, std::move(E));
204
205 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
206}
207
208void BinarySectionWriter::visit(const DecompressedSection &Sec) {
209 error("Cannot write compressed section '" + Sec.Name + "' ");
210}
211
212void DecompressedSection::accept(SectionVisitor &Visitor) const {
213 Visitor.visit(*this);
214}
215
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000216void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
217 Visitor.visit(*this);
218}
219
Jake Ehrlich76e91102018-01-25 22:46:17 +0000220void OwnedDataSection::accept(SectionVisitor &Visitor) const {
221 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000222}
223
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000224void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
225 Visitor.visit(*this);
226}
227
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000228void BinarySectionWriter::visit(const CompressedSection &Sec) {
229 error("Cannot write compressed section '" + Sec.Name + "' ");
230}
231
232template <class ELFT>
233void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
234 uint8_t *Buf = Out.getBufferStart();
235 Buf += Sec.Offset;
236
237 if (Sec.CompressionType == DebugCompressionType::None) {
238 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
239 return;
240 }
241
242 if (Sec.CompressionType == DebugCompressionType::GNU) {
243 const char *Magic = "ZLIB";
244 memcpy(Buf, Magic, strlen(Magic));
245 Buf += strlen(Magic);
246 const uint64_t DecompressedSize =
247 support::endian::read64be(&Sec.DecompressedSize);
248 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
249 Buf += sizeof(DecompressedSize);
250 } else {
251 Elf_Chdr_Impl<ELFT> Chdr;
252 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
253 Chdr.ch_size = Sec.DecompressedSize;
254 Chdr.ch_addralign = Sec.DecompressedAlign;
255 memcpy(Buf, &Chdr, sizeof(Chdr));
256 Buf += sizeof(Chdr);
257 }
258
259 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
260}
261
262CompressedSection::CompressedSection(const SectionBase &Sec,
263 DebugCompressionType CompressionType)
264 : SectionBase(Sec), CompressionType(CompressionType),
265 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
266
267 if (!zlib::isAvailable()) {
268 CompressionType = DebugCompressionType::None;
269 return;
270 }
271
272 if (Error E = zlib::compress(
273 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
274 OriginalData.size()),
275 CompressedData))
276 reportError(Name, std::move(E));
277
278 size_t ChdrSize;
279 if (CompressionType == DebugCompressionType::GNU) {
280 Name = ".z" + Sec.Name.substr(1);
281 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
282 } else {
283 Flags |= ELF::SHF_COMPRESSED;
284 ChdrSize =
285 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
286 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
287 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
288 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
289 }
290 Size = ChdrSize + CompressedData.size();
291 Align = 8;
292}
293
Puyan Lotfiaf048642018-10-01 10:29:41 +0000294CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
295 uint64_t DecompressedSize,
296 uint64_t DecompressedAlign)
297 : CompressionType(DebugCompressionType::None),
298 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
299 OriginalData = CompressedData;
300}
301
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000302void CompressedSection::accept(SectionVisitor &Visitor) const {
303 Visitor.visit(*this);
304}
305
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000306void CompressedSection::accept(MutableSectionVisitor &Visitor) {
307 Visitor.visit(*this);
308}
309
Petr Hosek05a04cb2017-08-01 00:33:58 +0000310void StringTableSection::addString(StringRef Name) {
311 StrTabBuilder.add(Name);
312 Size = StrTabBuilder.getSize();
313}
314
315uint32_t StringTableSection::findIndex(StringRef Name) const {
316 return StrTabBuilder.getOffset(Name);
317}
318
319void StringTableSection::finalize() { StrTabBuilder.finalize(); }
320
Jake Ehrlich76e91102018-01-25 22:46:17 +0000321void SectionWriter::visit(const StringTableSection &Sec) {
322 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
323}
324
325void StringTableSection::accept(SectionVisitor &Visitor) const {
326 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000327}
328
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000329void StringTableSection::accept(MutableSectionVisitor &Visitor) {
330 Visitor.visit(*this);
331}
332
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000333template <class ELFT>
334void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
335 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000336 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000337 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000338}
339
340void SectionIndexSection::initialize(SectionTableRef SecTable) {
341 Size = 0;
342 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
343 Link,
344 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
345 "Link field value " + Twine(Link) + " in section " + Name +
346 " is not a symbol table"));
347 Symbols->setShndxTable(this);
348}
349
350void SectionIndexSection::finalize() { Link = Symbols->Index; }
351
352void SectionIndexSection::accept(SectionVisitor &Visitor) const {
353 Visitor.visit(*this);
354}
355
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000356void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
357 Visitor.visit(*this);
358}
359
Petr Hosekc1135772017-09-13 03:04:50 +0000360static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000361 switch (Index) {
362 case SHN_ABS:
363 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000364 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000365 }
Petr Hosekc1135772017-09-13 03:04:50 +0000366 if (Machine == EM_HEXAGON) {
367 switch (Index) {
368 case SHN_HEXAGON_SCOMMON:
369 case SHN_HEXAGON_SCOMMON_2:
370 case SHN_HEXAGON_SCOMMON_4:
371 case SHN_HEXAGON_SCOMMON_8:
372 return true;
373 }
374 }
375 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000376}
377
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000378// Large indexes force us to clarify exactly what this function should do. This
379// function should return the value that will appear in st_shndx when written
380// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000381uint16_t Symbol::getShndx() const {
382 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000383 if (DefinedIn->Index >= SHN_LORESERVE)
384 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000385 return DefinedIn->Index;
386 }
387 switch (ShndxType) {
388 // This means that we don't have a defined section but we do need to
389 // output a legitimate section index.
390 case SYMBOL_SIMPLE_INDEX:
391 return SHN_UNDEF;
392 case SYMBOL_ABS:
393 case SYMBOL_COMMON:
394 case SYMBOL_HEXAGON_SCOMMON:
395 case SYMBOL_HEXAGON_SCOMMON_2:
396 case SYMBOL_HEXAGON_SCOMMON_4:
397 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000398 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000399 return static_cast<uint16_t>(ShndxType);
400 }
401 llvm_unreachable("Symbol with invalid ShndxType encountered");
402}
403
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000404bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
405
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000406void SymbolTableSection::assignIndices() {
407 uint32_t Index = 0;
408 for (auto &Sym : Symbols)
409 Sym->Index = Index++;
410}
411
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000412void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000413 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000414 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000415 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000416 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000417 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000418 Sym.Binding = Bind;
419 Sym.Type = Type;
420 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000421 if (DefinedIn != nullptr)
422 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000423 if (DefinedIn == nullptr) {
424 if (Shndx >= SHN_LORESERVE)
425 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
426 else
427 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
428 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000429 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000430 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000431 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000432 Sym.Index = Symbols.size();
433 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
434 Size += this->EntrySize;
435}
436
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000437Error SymbolTableSection::removeSectionReferences(
438 function_ref<bool(const SectionBase *)> ToRemove) {
439 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000440 SectionIndexTable = nullptr;
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000441 if (ToRemove(SymbolNames))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000442 return createStringError(llvm::errc::invalid_argument,
443 "String table %s cannot be removed because it is "
444 "referenced by the symbol table %s",
445 SymbolNames->Name.data(), this->Name.data());
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000446 return removeSymbols(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000447 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000448}
449
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000450void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000451 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
452 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000453 std::stable_partition(
454 std::begin(Symbols), std::end(Symbols),
455 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000456 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000457}
458
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000459Error SymbolTableSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000460 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000461 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000462 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000463 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
464 std::end(Symbols));
465 Size = Symbols.size() * EntrySize;
466 assignIndices();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000467 return Error::success();
Paul Semel41695f82018-05-02 20:19:22 +0000468}
469
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000470void SymbolTableSection::initialize(SectionTableRef SecTable) {
471 Size = 0;
472 setStrTab(SecTable.getSectionOfType<StringTableSection>(
473 Link,
474 "Symbol table has link index of " + Twine(Link) +
475 " which is not a valid index",
476 "Symbol table has link index of " + Twine(Link) +
477 " which is not a string table"));
478}
479
Petr Hosek79cee9e2017-08-29 02:12:03 +0000480void SymbolTableSection::finalize() {
481 // Make sure SymbolNames is finalized before getting name indexes.
482 SymbolNames->finalize();
483
484 uint32_t MaxLocalIndex = 0;
485 for (auto &Sym : Symbols) {
486 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
487 if (Sym->Binding == STB_LOCAL)
488 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
489 }
490 // Now we need to set the Link and Info fields.
491 Link = SymbolNames->Index;
492 Info = MaxLocalIndex + 1;
493}
494
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000495void SymbolTableSection::prepareForLayout() {
496 // Add all potential section indexes before file layout so that the section
497 // index section has the approprite size.
498 if (SectionIndexTable != nullptr) {
499 for (const auto &Sym : Symbols) {
500 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
501 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
502 else
503 SectionIndexTable->addIndex(SHN_UNDEF);
504 }
505 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000506 // Add all of our strings to SymbolNames so that SymbolNames has the right
507 // size before layout is decided.
508 for (auto &Sym : Symbols)
509 SymbolNames->addString(Sym->Name);
510}
511
512const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
513 if (Symbols.size() <= Index)
514 error("Invalid symbol index: " + Twine(Index));
515 return Symbols[Index].get();
516}
517
Paul Semel99dda0b2018-05-25 11:01:25 +0000518Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
519 return const_cast<Symbol *>(
520 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
521}
522
Petr Hosek79cee9e2017-08-29 02:12:03 +0000523template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000524void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000525 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000526 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000527 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000528 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000529 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000530 Sym->st_name = Symbol->NameIndex;
531 Sym->st_value = Symbol->Value;
532 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000533 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000534 Sym->setBinding(Symbol->Binding);
535 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000536 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000537 ++Sym;
538 }
539}
540
Jake Ehrlich76e91102018-01-25 22:46:17 +0000541void SymbolTableSection::accept(SectionVisitor &Visitor) const {
542 Visitor.visit(*this);
543}
544
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000545void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
546 Visitor.visit(*this);
547}
548
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000549template <class SymTabType>
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000550Error RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000551 function_ref<bool(const SectionBase *)> ToRemove) {
552 if (ToRemove(Symbols))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000553 return createStringError(llvm::errc::invalid_argument,
554 "Symbol table %s cannot be removed because it is "
555 "referenced by the relocation section %s.",
556 Symbols->Name.data(), this->Name.data());
557 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000558}
559
560template <class SymTabType>
561void RelocSectionWithSymtabBase<SymTabType>::initialize(
562 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000563 if (Link != SHN_UNDEF)
564 setSymTab(SecTable.getSectionOfType<SymTabType>(
565 Link,
566 "Link field value " + Twine(Link) + " in section " + Name +
567 " is invalid",
568 "Link field value " + Twine(Link) + " in section " + Name +
569 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000570
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000571 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000572 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
573 " in section " + Name +
574 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000575 else
576 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000577}
578
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000579template <class SymTabType>
580void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000581 this->Link = Symbols ? Symbols->Index : 0;
582
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000583 if (SecToApplyRel != nullptr)
584 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000585}
586
587template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000588static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000589
590template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000591static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000592 Rela.r_addend = Addend;
593}
594
Jake Ehrlich76e91102018-01-25 22:46:17 +0000595template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000596static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000597 for (const auto &Reloc : Relocations) {
598 Buf->r_offset = Reloc.Offset;
599 setAddend(*Buf, Reloc.Addend);
600 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
601 ++Buf;
602 }
603}
604
605template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000606void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
607 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
608 if (Sec.Type == SHT_REL)
609 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000610 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000611 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000612}
613
Jake Ehrlich76e91102018-01-25 22:46:17 +0000614void RelocationSection::accept(SectionVisitor &Visitor) const {
615 Visitor.visit(*this);
616}
617
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000618void RelocationSection::accept(MutableSectionVisitor &Visitor) {
619 Visitor.visit(*this);
620}
621
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000622Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000623 function_ref<bool(const Symbol &)> ToRemove) {
624 for (const Relocation &Reloc : Relocations)
625 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000626 return createStringError(
627 llvm::errc::invalid_argument,
628 "not stripping symbol '%s' because it is named in a relocation.",
629 Reloc.RelocSymbol->Name.data());
630 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000631}
632
Paul Semel99dda0b2018-05-25 11:01:25 +0000633void RelocationSection::markSymbols() {
634 for (const Relocation &Reloc : Relocations)
635 Reloc.RelocSymbol->Referenced = true;
636}
637
Jake Ehrlich76e91102018-01-25 22:46:17 +0000638void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000639 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000640 Out.getBufferStart() + Sec.Offset);
641}
642
643void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
644 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000645}
646
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000647void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
648 Visitor.visit(*this);
649}
650
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000651Error Section::removeSectionReferences(
652 function_ref<bool(const SectionBase *)> ToRemove) {
653 if (ToRemove(LinkSection))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000654 return createStringError(llvm::errc::invalid_argument,
655 "Section %s cannot be removed because it is "
656 "referenced by the section %s",
657 LinkSection->Name.data(), this->Name.data());
658 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000659}
660
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000661void GroupSection::finalize() {
662 this->Info = Sym->Index;
663 this->Link = SymTab->Index;
664}
665
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000666Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
667 if (ToRemove(*Sym))
668 return createStringError(llvm::errc::invalid_argument,
669 "Symbol %s cannot be removed because it is "
670 "referenced by the section %s[%d].",
671 Sym->Name.data(), this->Name.data(), this->Index);
672 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000673}
674
Paul Semel99dda0b2018-05-25 11:01:25 +0000675void GroupSection::markSymbols() {
676 if (Sym)
677 Sym->Referenced = true;
678}
679
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000680void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000681 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000682 LinkSection =
683 SecTable.getSection(Link, "Link field value " + Twine(Link) +
684 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000685 if (LinkSection->Type == ELF::SHT_SYMTAB)
686 LinkSection = nullptr;
687 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000688}
689
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000690void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000691
Jake Ehrlich76e91102018-01-25 22:46:17 +0000692void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000693 FileName = sys::path::filename(File);
694 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000695 // followed by a null terminator and then the CRC32 of the file. The CRC32
696 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
697 // byte, and then finally push the size to alignment and add 4.
698 Size = alignTo(FileName.size() + 1, 4) + 4;
699 // The CRC32 will only be aligned if we align the whole section.
700 Align = 4;
701 Type = ELF::SHT_PROGBITS;
702 Name = ".gnu_debuglink";
703 // For sections not found in segments, OriginalOffset is only used to
704 // establish the order that sections should go in. By using the maximum
705 // possible offset we cause this section to wind up at the end.
706 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000707 JamCRC CRC;
708 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000709 // The CRC32 value needs to be complemented because the JamCRC dosn't
710 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
711 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000712 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000713}
714
Jake Ehrlich76e91102018-01-25 22:46:17 +0000715GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000716 // Read in the file to compute the CRC of it.
717 auto DebugOrErr = MemoryBuffer::getFile(File);
718 if (!DebugOrErr)
719 error("'" + File + "': " + DebugOrErr.getError().message());
720 auto Debug = std::move(*DebugOrErr);
721 init(File, Debug->getBuffer());
722}
723
724template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000725void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
726 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000727 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000728 Elf_Word *CRC =
729 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
730 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000731 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000732}
733
734void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
735 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000736}
737
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000738void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
739 Visitor.visit(*this);
740}
741
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000742template <class ELFT>
743void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
744 ELF::Elf32_Word *Buf =
745 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
746 *Buf++ = Sec.FlagWord;
747 for (const auto *S : Sec.GroupMembers)
748 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
749}
750
751void GroupSection::accept(SectionVisitor &Visitor) const {
752 Visitor.visit(*this);
753}
754
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000755void GroupSection::accept(MutableSectionVisitor &Visitor) {
756 Visitor.visit(*this);
757}
758
Petr Hosek05a04cb2017-08-01 00:33:58 +0000759// Returns true IFF a section is wholly inside the range of a segment
760static bool sectionWithinSegment(const SectionBase &Section,
761 const Segment &Segment) {
762 // If a section is empty it should be treated like it has a size of 1. This is
763 // to clarify the case when an empty section lies on a boundary between two
764 // segments and ensures that the section "belongs" to the second segment and
765 // not the first.
766 uint64_t SecSize = Section.Size ? Section.Size : 1;
767 return Segment.Offset <= Section.OriginalOffset &&
768 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
769}
770
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000771// Returns true IFF a segment's original offset is inside of another segment's
772// range.
773static bool segmentOverlapsSegment(const Segment &Child,
774 const Segment &Parent) {
775
776 return Parent.OriginalOffset <= Child.OriginalOffset &&
777 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
778}
779
Jake Ehrlich46814be2018-01-22 19:27:30 +0000780static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000781 // Any segment without a parent segment should come before a segment
782 // that has a parent segment.
783 if (A->OriginalOffset < B->OriginalOffset)
784 return true;
785 if (A->OriginalOffset > B->OriginalOffset)
786 return false;
787 return A->Index < B->Index;
788}
789
Jake Ehrlich46814be2018-01-22 19:27:30 +0000790static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
791 if (A->PAddr < B->PAddr)
792 return true;
793 if (A->PAddr > B->PAddr)
794 return false;
795 return A->Index < B->Index;
796}
797
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000798void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000799 Obj->Flags = 0x0;
800 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000801 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000802 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000803 Obj->Entry = 0x0;
804 Obj->Machine = EMachine;
805 Obj->Version = 1;
806}
807
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000808void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000809
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000810StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000811 auto &StrTab = Obj->addSection<StringTableSection>();
812 StrTab.Name = ".strtab";
813
814 Obj->SectionNames = &StrTab;
815 return &StrTab;
816}
817
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000818SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000819 auto &SymTab = Obj->addSection<SymbolTableSection>();
820
821 SymTab.Name = ".symtab";
822 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000823
824 // The symbol table always needs a null symbol
825 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
826
827 Obj->SymbolTable = &SymTab;
828 return &SymTab;
829}
830
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000831void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000832 auto Data = ArrayRef<uint8_t>(
833 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
834 MemBuf->getBufferSize());
835 auto &DataSection = Obj->addSection<Section>(Data);
836 DataSection.Name = ".data";
837 DataSection.Type = ELF::SHT_PROGBITS;
838 DataSection.Size = Data.size();
839 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
840
841 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
842 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000843 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000844 Twine Prefix = Twine("_binary_") + SanitizedFilename;
845
846 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
847 /*Value=*/0, STV_DEFAULT, 0, 0);
848 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
849 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
850 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
851 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
852}
853
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000854void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000855 for (auto &Section : Obj->sections()) {
856 Section.initialize(Obj->sections());
857 }
858}
859
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000860std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000861 initFileHeader();
862 initHeaderSegment();
863 StringTableSection *StrTab = addStrTab();
864 SymbolTableSection *SymTab = addSymTab(StrTab);
865 initSections();
866 addData(SymTab);
867
868 return std::move(Obj);
869}
870
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000871template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000872 for (auto &Parent : Obj.segments()) {
873 // Every segment will overlap with itself but we don't want a segment to
874 // be it's own parent so we avoid that situation.
875 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
876 // We want a canonical "most parental" segment but this requires
877 // inspecting the ParentSegment.
878 if (compareSegmentsByOffset(&Parent, &Child))
879 if (Child.ParentSegment == nullptr ||
880 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
881 Child.ParentSegment = &Parent;
882 }
883 }
884 }
885}
886
Jake Ehrlich76e91102018-01-25 22:46:17 +0000887template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000888 uint32_t Index = 0;
889 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000890 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
891 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000892 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000893 Seg.Type = Phdr.p_type;
894 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000895 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000896 Seg.Offset = Phdr.p_offset;
897 Seg.VAddr = Phdr.p_vaddr;
898 Seg.PAddr = Phdr.p_paddr;
899 Seg.FileSize = Phdr.p_filesz;
900 Seg.MemSize = Phdr.p_memsz;
901 Seg.Align = Phdr.p_align;
902 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000903 for (auto &Section : Obj.sections()) {
904 if (sectionWithinSegment(Section, Seg)) {
905 Seg.addSection(&Section);
906 if (!Section.ParentSegment ||
907 Section.ParentSegment->Offset > Seg.Offset) {
908 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000909 }
910 }
911 }
912 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000913
914 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000915 ElfHdr.Index = Index++;
916
917 const auto &Ehdr = *ElfFile.getHeader();
918 auto &PrHdr = Obj.ProgramHdrSegment;
919 PrHdr.Type = PT_PHDR;
920 PrHdr.Flags = 0;
921 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
922 // Whereas this works automatically for ElfHdr, here OriginalOffset is
923 // always non-zero and to ensure the equation we assign the same value to
924 // VAddr as well.
925 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
926 PrHdr.PAddr = 0;
927 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000928 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000929 PrHdr.Align = sizeof(Elf_Addr);
930 PrHdr.Index = Index++;
931
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000932 // Now we do an O(n^2) loop through the segments in order to match up
933 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000934 for (auto &Child : Obj.segments())
935 setParentSegment(Child);
936 setParentSegment(ElfHdr);
937 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000938}
939
940template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000941void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
942 auto SecTable = Obj.sections();
943 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
944 GroupSec->Link,
945 "Link field value " + Twine(GroupSec->Link) + " in section " +
946 GroupSec->Name + " is invalid",
947 "Link field value " + Twine(GroupSec->Link) + " in section " +
948 GroupSec->Name + " is not a symbol table");
949 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
950 if (!Sym)
951 error("Info field value " + Twine(GroupSec->Info) + " in section " +
952 GroupSec->Name + " is not a valid symbol index");
953 GroupSec->setSymTab(SymTab);
954 GroupSec->setSymbol(Sym);
955 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
956 GroupSec->Contents.empty())
957 error("The content of the section " + GroupSec->Name + " is malformed");
958 const ELF::Elf32_Word *Word =
959 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
960 const ELF::Elf32_Word *End =
961 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
962 GroupSec->setFlagWord(*Word++);
963 for (; Word != End; ++Word) {
964 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
965 GroupSec->addMember(SecTable.getSection(
966 Index, "Group member index " + Twine(Index) + " in section " +
967 GroupSec->Name + " is invalid"));
968 }
969}
970
971template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000972void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000973 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
974 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000975 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000976
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000977 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
978 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000979 SectionBase *DefSection = nullptr;
980 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000981
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000982 if (Sym.st_shndx == SHN_XINDEX) {
983 if (SymTab->getShndxTable() == nullptr)
984 error("Symbol '" + Name +
985 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
986 if (ShndxData.data() == nullptr) {
987 const Elf_Shdr &ShndxSec =
988 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
989 ShndxData = unwrapOrError(
990 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
991 if (ShndxData.size() != Symbols.size())
992 error("Symbol section index table does not have the same number of "
993 "entries as the symbol table.");
994 }
995 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
996 DefSection = Obj.sections().getSection(
997 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000998 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000999 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001000 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001001 error(
1002 "Symbol '" + Name +
1003 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1004 Twine(Sym.st_shndx));
1005 }
1006 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001007 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001008 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001009 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001010 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001011 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001012
Petr Hosek79cee9e2017-08-29 02:12:03 +00001013 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001014 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001015 }
1016}
1017
1018template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001019static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1020
1021template <class ELFT>
1022static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1023 ToSet = Rela.r_addend;
1024}
1025
Jake Ehrlich76e91102018-01-25 22:46:17 +00001026template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001027static void initRelocations(RelocationSection *Relocs,
1028 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001029 for (const auto &Rel : RelRange) {
1030 Relocation ToAdd;
1031 ToAdd.Offset = Rel.r_offset;
1032 getAddend(ToAdd.Addend, Rel);
1033 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001034 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001035 Relocs->addRelocation(ToAdd);
1036 }
1037}
1038
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001039SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001040 if (Index == SHN_UNDEF || Index > Sections.size())
1041 error(ErrMsg);
1042 return Sections[Index - 1].get();
1043}
1044
1045template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001046T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001047 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001048 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001049 return Sec;
1050 error(TypeErrMsg);
1051}
1052
Petr Hosekd7df9b22017-09-06 23:41:02 +00001053template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001054SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001055 ArrayRef<uint8_t> Data;
1056 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001057 case SHT_REL:
1058 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001059 if (Shdr.sh_flags & SHF_ALLOC) {
1060 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001061 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001062 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001063 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001064 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001065 // If a string table is allocated we don't want to mess with it. That would
1066 // mean altering the memory image. There are no special link types or
1067 // anything so we can just use a Section.
1068 if (Shdr.sh_flags & SHF_ALLOC) {
1069 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001070 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001071 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001072 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001073 case SHT_HASH:
1074 case SHT_GNU_HASH:
1075 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1076 // Because of this we don't need to mess with the hash tables either.
1077 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001078 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001079 case SHT_GROUP:
1080 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1081 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001082 case SHT_DYNSYM:
1083 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001084 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001085 case SHT_DYNAMIC:
1086 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001087 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001088 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001089 auto &SymTab = Obj.addSection<SymbolTableSection>();
1090 Obj.SymbolTable = &SymTab;
1091 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001092 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001093 case SHT_SYMTAB_SHNDX: {
1094 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1095 Obj.SectionIndexTable = &ShndxSection;
1096 return ShndxSection;
1097 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001098 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001099 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001100 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001101 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001102
1103 if (isDataGnuCompressed(Data) || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
1104 uint64_t DecompressedSize, DecompressedAlign;
1105 std::tie(DecompressedSize, DecompressedAlign) =
1106 getDecompressedSizeAndAlignment<ELFT>(Data);
1107 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1108 DecompressedAlign);
1109 }
1110
Jake Ehrlich76e91102018-01-25 22:46:17 +00001111 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001112 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001113 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001114}
1115
Jake Ehrlich76e91102018-01-25 22:46:17 +00001116template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001117 uint32_t Index = 0;
1118 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1119 if (Index == 0) {
1120 ++Index;
1121 continue;
1122 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001123 auto &Sec = makeSection(Shdr);
1124 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1125 Sec.Type = Shdr.sh_type;
1126 Sec.Flags = Shdr.sh_flags;
1127 Sec.Addr = Shdr.sh_addr;
1128 Sec.Offset = Shdr.sh_offset;
1129 Sec.OriginalOffset = Shdr.sh_offset;
1130 Sec.Size = Shdr.sh_size;
1131 Sec.Link = Shdr.sh_link;
1132 Sec.Info = Shdr.sh_info;
1133 Sec.Align = Shdr.sh_addralign;
1134 Sec.EntrySize = Shdr.sh_entsize;
1135 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001136 Sec.OriginalData =
1137 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1138 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001139 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001140
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001141 // If a section index table exists we'll need to initialize it before we
1142 // initialize the symbol table because the symbol table might need to
1143 // reference it.
1144 if (Obj.SectionIndexTable)
1145 Obj.SectionIndexTable->initialize(Obj.sections());
1146
Petr Hosek79cee9e2017-08-29 02:12:03 +00001147 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001148 // details about symbol tables. We need the symbol table filled out before
1149 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001150 if (Obj.SymbolTable) {
1151 Obj.SymbolTable->initialize(Obj.sections());
1152 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001153 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001154
1155 // Now that all sections and symbols have been added we can add
1156 // relocations that reference symbols and set the link and info fields for
1157 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001158 for (auto &Section : Obj.sections()) {
1159 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001160 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001161 Section.initialize(Obj.sections());
1162 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001163 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1164 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001165 initRelocations(RelSec, Obj.SymbolTable,
1166 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001167 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001168 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001169 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001170 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1171 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001172 }
1173 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001174}
1175
Jake Ehrlich76e91102018-01-25 22:46:17 +00001176template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001177 const auto &Ehdr = *ElfFile.getHeader();
1178
George Rimar4ded7732018-12-20 10:51:42 +00001179 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1180 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181 Obj.Type = Ehdr.e_type;
1182 Obj.Machine = Ehdr.e_machine;
1183 Obj.Version = Ehdr.e_version;
1184 Obj.Entry = Ehdr.e_entry;
1185 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001186
Jake Ehrlich76e91102018-01-25 22:46:17 +00001187 readSectionHeaders();
1188 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001189
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001190 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1191 if (ShstrIndex == SHN_XINDEX)
1192 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1193
Jake Ehrlich76e91102018-01-25 22:46:17 +00001194 Obj.SectionNames =
1195 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001196 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001197 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001198 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001199 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001200 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001201}
1202
Jake Ehrlich76e91102018-01-25 22:46:17 +00001203// A generic size function which computes sizes of any random access range.
1204template <class R> size_t size(R &&Range) {
1205 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1206}
1207
1208Writer::~Writer() {}
1209
1210Reader::~Reader() {}
1211
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001212std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001213 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001214}
1215
1216std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001217 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001218 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1219 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001220 Builder.build();
1221 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001222 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1223 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001224 Builder.build();
1225 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001226 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1227 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001228 Builder.build();
1229 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001230 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1231 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001232 Builder.build();
1233 return Obj;
1234 }
1235 error("Invalid file type");
1236}
1237
1238template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001239 uint8_t *B = Buf.getBufferStart();
1240 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001241 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1242 Ehdr.e_ident[EI_MAG0] = 0x7f;
1243 Ehdr.e_ident[EI_MAG1] = 'E';
1244 Ehdr.e_ident[EI_MAG2] = 'L';
1245 Ehdr.e_ident[EI_MAG3] = 'F';
1246 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1247 Ehdr.e_ident[EI_DATA] =
1248 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1249 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001250 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1251 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001252
Jake Ehrlich76e91102018-01-25 22:46:17 +00001253 Ehdr.e_type = Obj.Type;
1254 Ehdr.e_machine = Obj.Machine;
1255 Ehdr.e_version = Obj.Version;
1256 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001257 // We have to use the fully-qualified name llvm::size
1258 // since some compilers complain on ambiguous resolution.
1259 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001260 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1261 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001262 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001263 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001264 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1265 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001266 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001267 // """
1268 // If the number of sections is greater than or equal to
1269 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1270 // number of section header table entries is contained in the sh_size field
1271 // of the section header at index 0.
1272 // """
1273 auto Shnum = size(Obj.sections()) + 1;
1274 if (Shnum >= SHN_LORESERVE)
1275 Ehdr.e_shnum = 0;
1276 else
1277 Ehdr.e_shnum = Shnum;
1278 // """
1279 // If the section name string table section index is greater than or equal
1280 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1281 // and the actual index of the section name string table section is
1282 // contained in the sh_link field of the section header at index 0.
1283 // """
1284 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1285 Ehdr.e_shstrndx = SHN_XINDEX;
1286 else
1287 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001288 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001289 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001290 Ehdr.e_shoff = 0;
1291 Ehdr.e_shnum = 0;
1292 Ehdr.e_shstrndx = 0;
1293 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001294}
1295
Jake Ehrlich76e91102018-01-25 22:46:17 +00001296template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1297 for (auto &Seg : Obj.segments())
1298 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001299}
1300
Jake Ehrlich76e91102018-01-25 22:46:17 +00001301template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001302 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001303 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001304 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001305 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001306 Shdr.sh_name = 0;
1307 Shdr.sh_type = SHT_NULL;
1308 Shdr.sh_flags = 0;
1309 Shdr.sh_addr = 0;
1310 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001311 // See writeEhdr for why we do this.
1312 uint64_t Shnum = size(Obj.sections()) + 1;
1313 if (Shnum >= SHN_LORESERVE)
1314 Shdr.sh_size = Shnum;
1315 else
1316 Shdr.sh_size = 0;
1317 // See writeEhdr for why we do this.
1318 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1319 Shdr.sh_link = Obj.SectionNames->Index;
1320 else
1321 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001322 Shdr.sh_info = 0;
1323 Shdr.sh_addralign = 0;
1324 Shdr.sh_entsize = 0;
1325
Jake Ehrlich76e91102018-01-25 22:46:17 +00001326 for (auto &Sec : Obj.sections())
1327 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001328}
1329
Jake Ehrlich76e91102018-01-25 22:46:17 +00001330template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1331 for (auto &Sec : Obj.sections())
1332 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001333}
1334
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001335Error Object::removeSections(
1336 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001337
1338 auto Iter = std::stable_partition(
1339 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1340 if (ToRemove(*Sec))
1341 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001342 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1343 if (auto ToRelSec = RelSec->getSection())
1344 return !ToRemove(*ToRelSec);
1345 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001346 return true;
1347 });
1348 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1349 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001350 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001351 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001352 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1353 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001354 // Now make sure there are no remaining references to the sections that will
1355 // be removed. Sometimes it is impossible to remove a reference so we emit
1356 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001357 std::unordered_set<const SectionBase *> RemoveSections;
1358 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001359 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1360 for (auto &Segment : Segments)
1361 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001362 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001363 }
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001364 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1365 if (Error E = KeepSec->removeSectionReferences(
1366 [&RemoveSections](const SectionBase *Sec) {
1367 return RemoveSections.find(Sec) != RemoveSections.end();
1368 }))
1369 return E;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001370 // Now finally get rid of them all togethor.
1371 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001372 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001373}
1374
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001375Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1376 if (SymbolTable)
1377 for (const SecPtr &Sec : Sections)
1378 if (Error E = Sec->removeSymbols(ToRemove))
1379 return E;
1380 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001381}
1382
Jake Ehrlich76e91102018-01-25 22:46:17 +00001383void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001384 // Put all sections in offset order. Maintain the ordering as closely as
1385 // possible while meeting that demand however.
1386 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1387 return A->OriginalOffset < B->OriginalOffset;
1388 };
1389 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1390 CompareSections);
1391}
1392
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001393static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1394 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1395 if (Align == 0)
1396 Align = 1;
1397 auto Diff =
1398 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1399 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1400 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1401 if (Diff < 0)
1402 Diff += Align;
1403 return Offset + Diff;
1404}
1405
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001406// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001407static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001408 std::stable_sort(std::begin(Segments), std::end(Segments),
1409 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001410}
1411
1412// This function finds a consistent layout for a list of segments starting from
1413// an Offset. It assumes that Segments have been sorted by OrderSegments and
1414// returns an Offset one past the end of the last segment.
1415static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1416 uint64_t Offset) {
1417 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001418 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001419 // The only way a segment should move is if a section was between two
1420 // segments and that section was removed. If that section isn't in a segment
1421 // then it's acceptable, but not ideal, to simply move it to after the
1422 // segments. So we can simply layout segments one after the other accounting
1423 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001424 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001425 // We assume that segments have been ordered by OriginalOffset and Index
1426 // such that a parent segment will always come before a child segment in
1427 // OrderedSegments. This means that the Offset of the ParentSegment should
1428 // already be set and we can set our offset relative to it.
1429 if (Segment->ParentSegment != nullptr) {
1430 auto Parent = Segment->ParentSegment;
1431 Segment->Offset =
1432 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1433 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001434 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001435 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001436 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001437 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001438 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001439 return Offset;
1440}
1441
1442// This function finds a consistent layout for a list of sections. It assumes
1443// that the ->ParentSegment of each section has already been laid out. The
1444// supplied starting Offset is used for the starting offset of any section that
1445// does not have a ParentSegment. It returns either the offset given if all
1446// sections had a ParentSegment or an offset one past the last section if there
1447// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001448template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001449static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001450 // Now the offset of every segment has been set we can assign the offsets
1451 // of each section. For sections that are covered by a segment we should use
1452 // the segment's original offset and the section's original offset to compute
1453 // the offset from the start of the segment. Using the offset from the start
1454 // of the segment we can assign a new offset to the section. For sections not
1455 // covered by segments we can just bump Offset to the next valid location.
1456 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001457 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001458 Section.Index = Index++;
1459 if (Section.ParentSegment != nullptr) {
1460 auto Segment = *Section.ParentSegment;
1461 Section.Offset =
1462 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001463 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001464 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1465 Section.Offset = Offset;
1466 if (Section.Type != SHT_NOBITS)
1467 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001468 }
1469 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001470 return Offset;
1471}
Petr Hosek3f383832017-08-26 01:32:20 +00001472
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001473template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1474 auto &ElfHdr = Obj.ElfHdrSegment;
1475 ElfHdr.Type = PT_PHDR;
1476 ElfHdr.Flags = 0;
1477 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1478 ElfHdr.VAddr = 0;
1479 ElfHdr.PAddr = 0;
1480 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1481 ElfHdr.Align = 0;
1482}
1483
Jake Ehrlich76e91102018-01-25 22:46:17 +00001484template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001485 // We need a temporary list of segments that has a special order to it
1486 // so that we know that anytime ->ParentSegment is set that segment has
1487 // already had its offset properly set.
1488 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001489 for (auto &Segment : Obj.segments())
1490 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001491 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1492 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001493 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001494 // Offset is used as the start offset of the first segment to be laid out.
1495 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1496 // we start at offset 0.
1497 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001498 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001499 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001500 // If we need to write the section header table out then we need to align the
1501 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001502 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001503 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001504 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001505}
1506
Jake Ehrlich76e91102018-01-25 22:46:17 +00001507template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001508 // We already have the section header offset so we can calculate the total
1509 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001510 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1511 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001512 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001513}
1514
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001515template <class ELFT> Error ELFWriter<ELFT>::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001516 writeEhdr();
1517 writePhdrs();
1518 writeSectionData();
1519 if (WriteSectionHeaders)
1520 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001521 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001522}
1523
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001524template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001525 // It could happen that SectionNames has been removed and yet the user wants
1526 // a section header table output. We need to throw an error if a user tries
1527 // to do that.
1528 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001529 return createStringError(llvm::errc::invalid_argument,
1530 "Cannot write section header table because "
1531 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001532
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001533 Obj.sortSections();
1534
1535 // We need to assign indexes before we perform layout because we need to know
1536 // if we need large indexes or not. We can assign indexes first and check as
1537 // we go to see if we will actully need large indexes.
1538 bool NeedsLargeIndexes = false;
1539 if (size(Obj.sections()) >= SHN_LORESERVE) {
1540 auto Sections = Obj.sections();
1541 NeedsLargeIndexes =
1542 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1543 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1544 // TODO: handle case where only one section needs the large index table but
1545 // only needs it because the large index table hasn't been removed yet.
1546 }
1547
1548 if (NeedsLargeIndexes) {
1549 // This means we definitely need to have a section index table but if we
1550 // already have one then we should use it instead of making a new one.
1551 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1552 // Addition of a section to the end does not invalidate the indexes of
1553 // other sections and assigns the correct index to the new section.
1554 auto &Shndx = Obj.addSection<SectionIndexSection>();
1555 Obj.SymbolTable->setShndxTable(&Shndx);
1556 Shndx.setSymTab(Obj.SymbolTable);
1557 }
1558 } else {
1559 // Since we don't need SectionIndexTable we should remove it and all
1560 // references to it.
1561 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001562 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1563 return &Sec == Obj.SectionIndexTable;
1564 }))
1565 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001566 }
1567 }
1568
1569 // Make sure we add the names of all the sections. Importantly this must be
1570 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001571 if (Obj.SectionNames != nullptr)
1572 for (const auto &Section : Obj.sections()) {
1573 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001574 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001575
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001576 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001577
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001578 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001579 // Also, the output arch may not be the same as the input arch, so fix up
1580 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001581 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001582 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1583 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001584 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001585 Sec.accept(*SecSizer);
1586 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001587
1588 // The symbol table does not update all other sections on update. For
1589 // instance, symbol names are not added as new symbols are added. This means
1590 // that some sections, like .strtab, don't yet have their final size.
1591 if (Obj.SymbolTable != nullptr)
1592 Obj.SymbolTable->prepareForLayout();
1593
Petr Hosekc4df10e2017-08-04 21:09:26 +00001594 assignOffsets();
1595
1596 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001597 if (Obj.SectionNames != nullptr)
1598 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001599 // Finally now that all offsets and indexes have been set we can finalize any
1600 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001601 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1602 for (auto &Section : Obj.sections()) {
1603 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001604 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001605 if (WriteSectionHeaders)
1606 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1607 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001608 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001609
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001610 if (Error E = Buf.allocate(totalSize()))
1611 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001612 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001613 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001614}
1615
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001616Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001617 for (auto &Section : Obj.sections()) {
1618 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001619 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001620 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001621 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001622 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001623}
1624
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001625Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001626 // TODO: Create a filter range to construct OrderedSegments from so that this
1627 // code can be deduped with assignOffsets above. This should also solve the
1628 // todo below for LayoutSections.
1629 // We need a temporary list of segments that has a special order to it
1630 // so that we know that anytime ->ParentSegment is set that segment has
1631 // already had it's offset properly set. We only want to consider the segments
1632 // that will affect layout of allocated sections so we only add those.
1633 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001634 for (auto &Section : Obj.sections()) {
1635 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1636 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001637 }
1638 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001639
1640 // For binary output, we're going to use physical addresses instead of
1641 // virtual addresses, since a binary output is used for cases like ROM
1642 // loading and physical addresses are intended for ROM loading.
1643 // However, if no segment has a physical address, we'll fallback to using
1644 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001645 if (all_of(OrderedSegments,
1646 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1647 for (Segment *Seg : OrderedSegments)
1648 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001649
1650 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1651 compareSegmentsByPAddr);
1652
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001653 // Because we add a ParentSegment for each section we might have duplicate
1654 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1655 // would do very strange things.
1656 auto End =
1657 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1658 OrderedSegments.erase(End, std::end(OrderedSegments));
1659
Jake Ehrlich46814be2018-01-22 19:27:30 +00001660 uint64_t Offset = 0;
1661
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001662 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001663 // our layout algorithm to proceed as expected while not writing out the gap
1664 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001665 if (!OrderedSegments.empty()) {
1666 auto Seg = OrderedSegments[0];
1667 auto Sec = Seg->firstSection();
1668 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1669 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001670 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001671 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001672 // The PAddr needs to be increased to remove the gap before the first
1673 // section.
1674 Seg->PAddr += Diff;
1675 uint64_t LowestPAddr = Seg->PAddr;
1676 for (auto &Segment : OrderedSegments) {
1677 Segment->Offset = Segment->PAddr - LowestPAddr;
1678 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1679 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001680 }
1681
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001682 // TODO: generalize LayoutSections to take a range. Pass a special range
1683 // constructed from an iterator that skips values for which a predicate does
1684 // not hold. Then pass such a range to LayoutSections instead of constructing
1685 // AllocatedSections here.
1686 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001687 for (auto &Section : Obj.sections()) {
1688 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001689 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001690 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001691 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001692 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001693
1694 // Now that every section has been laid out we just need to compute the total
1695 // file size. This might not be the same as the offset returned by
1696 // LayoutSections, because we want to truncate the last segment to the end of
1697 // its last section, to match GNU objcopy's behaviour.
1698 TotalSize = 0;
1699 for (const auto &Section : AllocatedSections) {
1700 if (Section->Type != SHT_NOBITS)
1701 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1702 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001703
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001704 if (Error E = Buf.allocate(TotalSize))
1705 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001706 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001707 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001708}
1709
Jake Ehrlich76e91102018-01-25 22:46:17 +00001710template class ELFBuilder<ELF64LE>;
1711template class ELFBuilder<ELF64BE>;
1712template class ELFBuilder<ELF32LE>;
1713template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001714
Jake Ehrlich76e91102018-01-25 22:46:17 +00001715template class ELFWriter<ELF64LE>;
1716template class ELFWriter<ELF64BE>;
1717template class ELFWriter<ELF32LE>;
1718template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001719
1720} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001721} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001722} // end namespace llvm