blob: 43c0564c98631dc57499b07aeb374416fbe5433f [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() {}
George Rimard8a5c6c2019-03-11 11:01:24 +000065void SectionBase::replaceSectionReferences(
66 const DenseMap<SectionBase *, SectionBase *> &) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000067
Jake Ehrlich76e91102018-01-25 22:46:17 +000068template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000069 uint8_t *B = Buf.getBufferStart();
70 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000071 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000072 Shdr.sh_name = Sec.NameIndex;
73 Shdr.sh_type = Sec.Type;
74 Shdr.sh_flags = Sec.Flags;
75 Shdr.sh_addr = Sec.Addr;
76 Shdr.sh_offset = Sec.Offset;
77 Shdr.sh_size = Sec.Size;
78 Shdr.sh_link = Sec.Link;
79 Shdr.sh_info = Sec.Info;
80 Shdr.sh_addralign = Sec.Align;
81 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000082}
83
Jordan Rupprecht1f821762019-01-03 17:45:30 +000084template <class ELFT> void ELFSectionSizer<ELFT>::visit(Section &Sec) {}
85
86template <class ELFT>
87void ELFSectionSizer<ELFT>::visit(OwnedDataSection &Sec) {}
88
89template <class ELFT>
90void ELFSectionSizer<ELFT>::visit(StringTableSection &Sec) {}
91
92template <class ELFT>
93void ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &Sec) {}
94
95template <class ELFT>
96void ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
97 Sec.EntrySize = sizeof(Elf_Sym);
98 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000099 // Align to the largest field in Elf_Sym.
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000100 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000101}
102
103template <class ELFT>
104void ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
105 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
106 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +0000107 // Align to the largest field in Elf_Rel(a).
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000108 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000109}
110
111template <class ELFT>
112void ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &Sec) {}
113
114template <class ELFT> void ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {}
115
116template <class ELFT>
117void ELFSectionSizer<ELFT>::visit(SectionIndexSection &Sec) {}
118
119template <class ELFT>
120void ELFSectionSizer<ELFT>::visit(CompressedSection &Sec) {}
121
122template <class ELFT>
123void ELFSectionSizer<ELFT>::visit(DecompressedSection &Sec) {}
Jake Ehrlich76e91102018-01-25 22:46:17 +0000124
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000125void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
126 error("Cannot write symbol section index table '" + Sec.Name + "' ");
127}
128
Jake Ehrlich76e91102018-01-25 22:46:17 +0000129void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
130 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
131}
132
133void BinarySectionWriter::visit(const RelocationSection &Sec) {
134 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
135}
136
137void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000138 error("Cannot write '" + Sec.Name + "' out to binary");
139}
140
141void BinarySectionWriter::visit(const GroupSection &Sec) {
142 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000143}
144
145void SectionWriter::visit(const Section &Sec) {
146 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000147 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000148 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000149 llvm::copy(Sec.Contents, Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000150}
151
Jake Ehrlich76e91102018-01-25 22:46:17 +0000152void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
153
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000154void Section::accept(MutableSectionVisitor &Visitor) { Visitor.visit(*this); }
155
Jake Ehrlich76e91102018-01-25 22:46:17 +0000156void SectionWriter::visit(const OwnedDataSection &Sec) {
157 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000158 llvm::copy(Sec.Data, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000159}
160
Puyan Lotfiaf048642018-10-01 10:29:41 +0000161static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
162
163static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
164 return Data.size() > ZlibGnuMagic.size() &&
165 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
166}
167
168template <class ELFT>
169static std::tuple<uint64_t, uint64_t>
170getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
171 const bool IsGnuDebug = isDataGnuCompressed(Data);
172 const uint64_t DecompressedSize =
173 IsGnuDebug
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000174 ? support::endian::read64be(Data.data() + ZlibGnuMagic.size())
Puyan Lotfiaf048642018-10-01 10:29:41 +0000175 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
176 const uint64_t DecompressedAlign =
177 IsGnuDebug ? 1
178 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
179 ->ch_addralign;
180
181 return std::make_tuple(DecompressedSize, DecompressedAlign);
182}
183
184template <class ELFT>
185void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
Puyan Lotfiaf048642018-10-01 10:29:41 +0000186 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
187 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
188 : sizeof(Elf_Chdr_Impl<ELFT>);
189
190 StringRef CompressedContent(
191 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
192 Sec.OriginalData.size() - DataOffset);
193
194 SmallVector<char, 128> DecompressedContent;
195 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
196 static_cast<size_t>(Sec.Size)))
197 reportError(Sec.Name, std::move(E));
198
George Rimar281a5be2019-03-06 14:12:18 +0000199 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfiaf048642018-10-01 10:29:41 +0000200 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
201}
202
203void BinarySectionWriter::visit(const DecompressedSection &Sec) {
204 error("Cannot write compressed section '" + Sec.Name + "' ");
205}
206
207void DecompressedSection::accept(SectionVisitor &Visitor) const {
208 Visitor.visit(*this);
209}
210
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000211void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
212 Visitor.visit(*this);
213}
214
Jake Ehrlich76e91102018-01-25 22:46:17 +0000215void OwnedDataSection::accept(SectionVisitor &Visitor) const {
216 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000217}
218
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000219void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
220 Visitor.visit(*this);
221}
222
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000223void BinarySectionWriter::visit(const CompressedSection &Sec) {
224 error("Cannot write compressed section '" + Sec.Name + "' ");
225}
226
227template <class ELFT>
228void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
229 uint8_t *Buf = Out.getBufferStart();
230 Buf += Sec.Offset;
231
232 if (Sec.CompressionType == DebugCompressionType::None) {
233 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
234 return;
235 }
236
237 if (Sec.CompressionType == DebugCompressionType::GNU) {
238 const char *Magic = "ZLIB";
239 memcpy(Buf, Magic, strlen(Magic));
240 Buf += strlen(Magic);
241 const uint64_t DecompressedSize =
242 support::endian::read64be(&Sec.DecompressedSize);
243 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
244 Buf += sizeof(DecompressedSize);
245 } else {
246 Elf_Chdr_Impl<ELFT> Chdr;
247 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
248 Chdr.ch_size = Sec.DecompressedSize;
249 Chdr.ch_addralign = Sec.DecompressedAlign;
250 memcpy(Buf, &Chdr, sizeof(Chdr));
251 Buf += sizeof(Chdr);
252 }
253
254 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
255}
256
257CompressedSection::CompressedSection(const SectionBase &Sec,
258 DebugCompressionType CompressionType)
259 : SectionBase(Sec), CompressionType(CompressionType),
260 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000261 if (Error E = zlib::compress(
262 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
263 OriginalData.size()),
264 CompressedData))
265 reportError(Name, std::move(E));
266
267 size_t ChdrSize;
268 if (CompressionType == DebugCompressionType::GNU) {
269 Name = ".z" + Sec.Name.substr(1);
270 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
271 } else {
272 Flags |= ELF::SHF_COMPRESSED;
273 ChdrSize =
274 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
275 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
276 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
277 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
278 }
279 Size = ChdrSize + CompressedData.size();
280 Align = 8;
281}
282
Puyan Lotfiaf048642018-10-01 10:29:41 +0000283CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
284 uint64_t DecompressedSize,
285 uint64_t DecompressedAlign)
286 : CompressionType(DebugCompressionType::None),
287 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
288 OriginalData = CompressedData;
289}
290
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000291void CompressedSection::accept(SectionVisitor &Visitor) const {
292 Visitor.visit(*this);
293}
294
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000295void CompressedSection::accept(MutableSectionVisitor &Visitor) {
296 Visitor.visit(*this);
297}
298
George Rimarfaf308b2019-03-18 14:27:41 +0000299void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000300
301uint32_t StringTableSection::findIndex(StringRef Name) const {
302 return StrTabBuilder.getOffset(Name);
303}
304
George Rimarfaf308b2019-03-18 14:27:41 +0000305void StringTableSection::prepareForLayout() {
306 StrTabBuilder.finalize();
307 Size = StrTabBuilder.getSize();
308}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000309
Jake Ehrlich76e91102018-01-25 22:46:17 +0000310void SectionWriter::visit(const StringTableSection &Sec) {
311 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
312}
313
314void StringTableSection::accept(SectionVisitor &Visitor) const {
315 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000316}
317
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000318void StringTableSection::accept(MutableSectionVisitor &Visitor) {
319 Visitor.visit(*this);
320}
321
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000322template <class ELFT>
323void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
324 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000325 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000326 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000327}
328
329void SectionIndexSection::initialize(SectionTableRef SecTable) {
330 Size = 0;
331 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
332 Link,
333 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
334 "Link field value " + Twine(Link) + " in section " + Name +
335 " is not a symbol table"));
336 Symbols->setShndxTable(this);
337}
338
339void SectionIndexSection::finalize() { Link = Symbols->Index; }
340
341void SectionIndexSection::accept(SectionVisitor &Visitor) const {
342 Visitor.visit(*this);
343}
344
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000345void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
346 Visitor.visit(*this);
347}
348
Petr Hosekc1135772017-09-13 03:04:50 +0000349static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000350 switch (Index) {
351 case SHN_ABS:
352 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000353 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000354 }
Petr Hosekc1135772017-09-13 03:04:50 +0000355 if (Machine == EM_HEXAGON) {
356 switch (Index) {
357 case SHN_HEXAGON_SCOMMON:
358 case SHN_HEXAGON_SCOMMON_2:
359 case SHN_HEXAGON_SCOMMON_4:
360 case SHN_HEXAGON_SCOMMON_8:
361 return true;
362 }
363 }
364 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000365}
366
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000367// Large indexes force us to clarify exactly what this function should do. This
368// function should return the value that will appear in st_shndx when written
369// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000370uint16_t Symbol::getShndx() const {
371 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000372 if (DefinedIn->Index >= SHN_LORESERVE)
373 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000374 return DefinedIn->Index;
375 }
376 switch (ShndxType) {
377 // This means that we don't have a defined section but we do need to
378 // output a legitimate section index.
379 case SYMBOL_SIMPLE_INDEX:
380 return SHN_UNDEF;
381 case SYMBOL_ABS:
382 case SYMBOL_COMMON:
383 case SYMBOL_HEXAGON_SCOMMON:
384 case SYMBOL_HEXAGON_SCOMMON_2:
385 case SYMBOL_HEXAGON_SCOMMON_4:
386 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000387 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000388 return static_cast<uint16_t>(ShndxType);
389 }
390 llvm_unreachable("Symbol with invalid ShndxType encountered");
391}
392
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000393bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
394
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000395void SymbolTableSection::assignIndices() {
396 uint32_t Index = 0;
397 for (auto &Sym : Symbols)
398 Sym->Index = Index++;
399}
400
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000401void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000402 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000403 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000404 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000405 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000406 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000407 Sym.Binding = Bind;
408 Sym.Type = Type;
409 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000410 if (DefinedIn != nullptr)
411 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000412 if (DefinedIn == nullptr) {
413 if (Shndx >= SHN_LORESERVE)
414 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
415 else
416 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
417 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000418 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000419 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000420 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000421 Sym.Index = Symbols.size();
422 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
423 Size += this->EntrySize;
424}
425
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000426Error SymbolTableSection::removeSectionReferences(
427 function_ref<bool(const SectionBase *)> ToRemove) {
428 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000429 SectionIndexTable = nullptr;
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000430 if (ToRemove(SymbolNames))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000431 return createStringError(llvm::errc::invalid_argument,
432 "String table %s cannot be removed because it is "
433 "referenced by the symbol table %s",
434 SymbolNames->Name.data(), this->Name.data());
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000435 return removeSymbols(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000436 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000437}
438
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000439void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000440 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
441 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000442 std::stable_partition(
443 std::begin(Symbols), std::end(Symbols),
444 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000445 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000446}
447
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000448Error SymbolTableSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000449 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000450 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000451 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000452 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
453 std::end(Symbols));
454 Size = Symbols.size() * EntrySize;
455 assignIndices();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000456 return Error::success();
Paul Semel41695f82018-05-02 20:19:22 +0000457}
458
George Rimar0373bed2019-03-20 13:57:47 +0000459void SymbolTableSection::replaceSectionReferences(
460 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
461 for (std::unique_ptr<Symbol> &Sym : Symbols)
462 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
463 Sym->DefinedIn = To;
464}
465
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000466void SymbolTableSection::initialize(SectionTableRef SecTable) {
467 Size = 0;
468 setStrTab(SecTable.getSectionOfType<StringTableSection>(
469 Link,
470 "Symbol table has link index of " + Twine(Link) +
471 " which is not a valid index",
472 "Symbol table has link index of " + Twine(Link) +
473 " which is not a string table"));
474}
475
Petr Hosek79cee9e2017-08-29 02:12:03 +0000476void SymbolTableSection::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000477 uint32_t MaxLocalIndex = 0;
478 for (auto &Sym : Symbols) {
479 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
480 if (Sym->Binding == STB_LOCAL)
481 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
482 }
483 // Now we need to set the Link and Info fields.
484 Link = SymbolNames->Index;
485 Info = MaxLocalIndex + 1;
486}
487
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000488void SymbolTableSection::prepareForLayout() {
489 // Add all potential section indexes before file layout so that the section
490 // index section has the approprite size.
491 if (SectionIndexTable != nullptr) {
492 for (const auto &Sym : Symbols) {
493 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
494 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
495 else
496 SectionIndexTable->addIndex(SHN_UNDEF);
497 }
498 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000499 // Add all of our strings to SymbolNames so that SymbolNames has the right
500 // size before layout is decided.
501 for (auto &Sym : Symbols)
502 SymbolNames->addString(Sym->Name);
503}
504
505const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
506 if (Symbols.size() <= Index)
507 error("Invalid symbol index: " + Twine(Index));
508 return Symbols[Index].get();
509}
510
Paul Semel99dda0b2018-05-25 11:01:25 +0000511Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
512 return const_cast<Symbol *>(
513 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
514}
515
Petr Hosek79cee9e2017-08-29 02:12:03 +0000516template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000517void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000518 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000519 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000520 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000521 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000522 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000523 Sym->st_name = Symbol->NameIndex;
524 Sym->st_value = Symbol->Value;
525 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000526 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000527 Sym->setBinding(Symbol->Binding);
528 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000529 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000530 ++Sym;
531 }
532}
533
Jake Ehrlich76e91102018-01-25 22:46:17 +0000534void SymbolTableSection::accept(SectionVisitor &Visitor) const {
535 Visitor.visit(*this);
536}
537
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000538void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
539 Visitor.visit(*this);
540}
541
George Rimar79fb8582019-02-27 11:18:27 +0000542Error RelocationSection::removeSectionReferences(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000543 function_ref<bool(const SectionBase *)> ToRemove) {
544 if (ToRemove(Symbols))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000545 return createStringError(llvm::errc::invalid_argument,
546 "Symbol table %s cannot be removed because it is "
547 "referenced by the relocation section %s.",
548 Symbols->Name.data(), this->Name.data());
George Rimar79fb8582019-02-27 11:18:27 +0000549
550 for (const Relocation &R : Relocations) {
551 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
552 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000553 return createStringError(llvm::errc::invalid_argument,
554 "Section %s can't be removed: (%s+0x%" PRIx64
555 ") has relocation against symbol '%s'",
556 R.RelocSymbol->DefinedIn->Name.data(),
557 SecToApplyRel->Name.data(), R.Offset,
558 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000559 }
560
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000561 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000562}
563
564template <class SymTabType>
565void RelocSectionWithSymtabBase<SymTabType>::initialize(
566 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000567 if (Link != SHN_UNDEF)
568 setSymTab(SecTable.getSectionOfType<SymTabType>(
569 Link,
570 "Link field value " + Twine(Link) + " in section " + Name +
571 " is invalid",
572 "Link field value " + Twine(Link) + " in section " + Name +
573 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000574
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000575 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000576 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
577 " in section " + Name +
578 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000579 else
580 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000581}
582
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000583template <class SymTabType>
584void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000585 this->Link = Symbols ? Symbols->Index : 0;
586
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000587 if (SecToApplyRel != nullptr)
588 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000589}
590
591template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000592static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000593
594template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000595static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000596 Rela.r_addend = Addend;
597}
598
Jake Ehrlich76e91102018-01-25 22:46:17 +0000599template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000600static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000601 for (const auto &Reloc : Relocations) {
602 Buf->r_offset = Reloc.Offset;
603 setAddend(*Buf, Reloc.Addend);
604 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
605 ++Buf;
606 }
607}
608
609template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000610void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
611 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
612 if (Sec.Type == SHT_REL)
613 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000614 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000615 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000616}
617
Jake Ehrlich76e91102018-01-25 22:46:17 +0000618void RelocationSection::accept(SectionVisitor &Visitor) const {
619 Visitor.visit(*this);
620}
621
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000622void RelocationSection::accept(MutableSectionVisitor &Visitor) {
623 Visitor.visit(*this);
624}
625
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000626Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000627 function_ref<bool(const Symbol &)> ToRemove) {
628 for (const Relocation &Reloc : Relocations)
629 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000630 return createStringError(
631 llvm::errc::invalid_argument,
632 "not stripping symbol '%s' because it is named in a relocation.",
633 Reloc.RelocSymbol->Name.data());
634 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000635}
636
Paul Semel99dda0b2018-05-25 11:01:25 +0000637void RelocationSection::markSymbols() {
638 for (const Relocation &Reloc : Relocations)
639 Reloc.RelocSymbol->Referenced = true;
640}
641
George Rimard8a5c6c2019-03-11 11:01:24 +0000642void RelocationSection::replaceSectionReferences(
643 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
644 // Update the target section if it was replaced.
645 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
646 SecToApplyRel = To;
George Rimard8a5c6c2019-03-11 11:01:24 +0000647}
648
Jake Ehrlich76e91102018-01-25 22:46:17 +0000649void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000650 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000651 Out.getBufferStart() + Sec.Offset);
652}
653
654void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
655 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000656}
657
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000658void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
659 Visitor.visit(*this);
660}
661
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000662Error Section::removeSectionReferences(
663 function_ref<bool(const SectionBase *)> ToRemove) {
664 if (ToRemove(LinkSection))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000665 return createStringError(llvm::errc::invalid_argument,
666 "Section %s cannot be removed because it is "
667 "referenced by the section %s",
668 LinkSection->Name.data(), this->Name.data());
669 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000670}
671
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000672void GroupSection::finalize() {
673 this->Info = Sym->Index;
674 this->Link = SymTab->Index;
675}
676
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000677Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
678 if (ToRemove(*Sym))
679 return createStringError(llvm::errc::invalid_argument,
680 "Symbol %s cannot be removed because it is "
681 "referenced by the section %s[%d].",
682 Sym->Name.data(), this->Name.data(), this->Index);
683 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000684}
685
Paul Semel99dda0b2018-05-25 11:01:25 +0000686void GroupSection::markSymbols() {
687 if (Sym)
688 Sym->Referenced = true;
689}
690
George Rimar27257172019-03-24 14:41:45 +0000691void GroupSection::replaceSectionReferences(
692 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
693 for (SectionBase *&Sec : GroupMembers)
694 if (SectionBase *To = FromTo.lookup(Sec))
695 Sec = To;
696}
697
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000698void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000699 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000700 LinkSection =
701 SecTable.getSection(Link, "Link field value " + Twine(Link) +
702 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000703 if (LinkSection->Type == ELF::SHT_SYMTAB)
704 LinkSection = nullptr;
705 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000706}
707
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000708void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000709
Jake Ehrlich76e91102018-01-25 22:46:17 +0000710void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000711 FileName = sys::path::filename(File);
712 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000713 // followed by a null terminator and then the CRC32 of the file. The CRC32
714 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
715 // byte, and then finally push the size to alignment and add 4.
716 Size = alignTo(FileName.size() + 1, 4) + 4;
717 // The CRC32 will only be aligned if we align the whole section.
718 Align = 4;
719 Type = ELF::SHT_PROGBITS;
720 Name = ".gnu_debuglink";
721 // For sections not found in segments, OriginalOffset is only used to
722 // establish the order that sections should go in. By using the maximum
723 // possible offset we cause this section to wind up at the end.
724 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000725 JamCRC CRC;
726 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000727 // The CRC32 value needs to be complemented because the JamCRC dosn't
728 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
729 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000730 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000731}
732
Jake Ehrlich76e91102018-01-25 22:46:17 +0000733GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000734 // Read in the file to compute the CRC of it.
735 auto DebugOrErr = MemoryBuffer::getFile(File);
736 if (!DebugOrErr)
737 error("'" + File + "': " + DebugOrErr.getError().message());
738 auto Debug = std::move(*DebugOrErr);
739 init(File, Debug->getBuffer());
740}
741
742template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000743void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000744 unsigned char *Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000745 Elf_Word *CRC =
746 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
747 *CRC = Sec.CRC32;
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000748 llvm::copy(Sec.FileName, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000749}
750
751void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
752 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000753}
754
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000755void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
756 Visitor.visit(*this);
757}
758
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000759template <class ELFT>
760void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
761 ELF::Elf32_Word *Buf =
762 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
763 *Buf++ = Sec.FlagWord;
764 for (const auto *S : Sec.GroupMembers)
765 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
766}
767
768void GroupSection::accept(SectionVisitor &Visitor) const {
769 Visitor.visit(*this);
770}
771
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000772void GroupSection::accept(MutableSectionVisitor &Visitor) {
773 Visitor.visit(*this);
774}
775
Petr Hosek05a04cb2017-08-01 00:33:58 +0000776// Returns true IFF a section is wholly inside the range of a segment
777static bool sectionWithinSegment(const SectionBase &Section,
778 const Segment &Segment) {
779 // If a section is empty it should be treated like it has a size of 1. This is
780 // to clarify the case when an empty section lies on a boundary between two
781 // segments and ensures that the section "belongs" to the second segment and
782 // not the first.
783 uint64_t SecSize = Section.Size ? Section.Size : 1;
784 return Segment.Offset <= Section.OriginalOffset &&
785 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
786}
787
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000788// Returns true IFF a segment's original offset is inside of another segment's
789// range.
790static bool segmentOverlapsSegment(const Segment &Child,
791 const Segment &Parent) {
792
793 return Parent.OriginalOffset <= Child.OriginalOffset &&
794 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
795}
796
Jake Ehrlich46814be2018-01-22 19:27:30 +0000797static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000798 // Any segment without a parent segment should come before a segment
799 // that has a parent segment.
800 if (A->OriginalOffset < B->OriginalOffset)
801 return true;
802 if (A->OriginalOffset > B->OriginalOffset)
803 return false;
804 return A->Index < B->Index;
805}
806
Jake Ehrlich46814be2018-01-22 19:27:30 +0000807static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
808 if (A->PAddr < B->PAddr)
809 return true;
810 if (A->PAddr > B->PAddr)
811 return false;
812 return A->Index < B->Index;
813}
814
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000815void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000816 Obj->Flags = 0x0;
817 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000818 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000819 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000820 Obj->Entry = 0x0;
821 Obj->Machine = EMachine;
822 Obj->Version = 1;
823}
824
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000825void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000826
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000827StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000828 auto &StrTab = Obj->addSection<StringTableSection>();
829 StrTab.Name = ".strtab";
830
831 Obj->SectionNames = &StrTab;
832 return &StrTab;
833}
834
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000835SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000836 auto &SymTab = Obj->addSection<SymbolTableSection>();
837
838 SymTab.Name = ".symtab";
839 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000840
841 // The symbol table always needs a null symbol
842 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
843
844 Obj->SymbolTable = &SymTab;
845 return &SymTab;
846}
847
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000848void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000849 auto Data = ArrayRef<uint8_t>(
850 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
851 MemBuf->getBufferSize());
852 auto &DataSection = Obj->addSection<Section>(Data);
853 DataSection.Name = ".data";
854 DataSection.Type = ELF::SHT_PROGBITS;
855 DataSection.Size = Data.size();
856 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
857
858 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
859 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000860 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000861 Twine Prefix = Twine("_binary_") + SanitizedFilename;
862
863 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
864 /*Value=*/0, STV_DEFAULT, 0, 0);
865 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
866 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
867 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
868 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
869}
870
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000871void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000872 for (auto &Section : Obj->sections()) {
873 Section.initialize(Obj->sections());
874 }
875}
876
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000877std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000878 initFileHeader();
879 initHeaderSegment();
880 StringTableSection *StrTab = addStrTab();
881 SymbolTableSection *SymTab = addSymTab(StrTab);
882 initSections();
883 addData(SymTab);
884
885 return std::move(Obj);
886}
887
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000888template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000889 for (auto &Parent : Obj.segments()) {
890 // Every segment will overlap with itself but we don't want a segment to
891 // be it's own parent so we avoid that situation.
892 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
893 // We want a canonical "most parental" segment but this requires
894 // inspecting the ParentSegment.
895 if (compareSegmentsByOffset(&Parent, &Child))
896 if (Child.ParentSegment == nullptr ||
897 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
898 Child.ParentSegment = &Parent;
899 }
900 }
901 }
902}
903
Jake Ehrlich76e91102018-01-25 22:46:17 +0000904template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000905 uint32_t Index = 0;
906 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
James Henderson1f448142019-03-25 16:36:26 +0000907 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
908 (size_t)Phdr.p_filesz};
909 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000910 Seg.Type = Phdr.p_type;
911 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000912 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000913 Seg.Offset = Phdr.p_offset;
914 Seg.VAddr = Phdr.p_vaddr;
915 Seg.PAddr = Phdr.p_paddr;
916 Seg.FileSize = Phdr.p_filesz;
917 Seg.MemSize = Phdr.p_memsz;
918 Seg.Align = Phdr.p_align;
919 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000920 for (auto &Section : Obj.sections()) {
921 if (sectionWithinSegment(Section, Seg)) {
922 Seg.addSection(&Section);
923 if (!Section.ParentSegment ||
924 Section.ParentSegment->Offset > Seg.Offset) {
925 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000926 }
927 }
928 }
929 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000930
931 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000932 ElfHdr.Index = Index++;
933
934 const auto &Ehdr = *ElfFile.getHeader();
935 auto &PrHdr = Obj.ProgramHdrSegment;
936 PrHdr.Type = PT_PHDR;
937 PrHdr.Flags = 0;
938 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
939 // Whereas this works automatically for ElfHdr, here OriginalOffset is
940 // always non-zero and to ensure the equation we assign the same value to
941 // VAddr as well.
942 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
943 PrHdr.PAddr = 0;
944 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000945 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000946 PrHdr.Align = sizeof(Elf_Addr);
947 PrHdr.Index = Index++;
948
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000949 // Now we do an O(n^2) loop through the segments in order to match up
950 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000951 for (auto &Child : Obj.segments())
952 setParentSegment(Child);
953 setParentSegment(ElfHdr);
954 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000955}
956
957template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000958void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
George Rimar0a5d4b82019-03-24 13:31:08 +0000959 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
960 error("Invalid alignment " + Twine(GroupSec->Align) + " of group section " +
961 GroupSec->Name);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000962 auto SecTable = Obj.sections();
963 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
964 GroupSec->Link,
965 "Link field value " + Twine(GroupSec->Link) + " in section " +
966 GroupSec->Name + " is invalid",
967 "Link field value " + Twine(GroupSec->Link) + " in section " +
968 GroupSec->Name + " is not a symbol table");
969 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
970 if (!Sym)
971 error("Info field value " + Twine(GroupSec->Info) + " in section " +
972 GroupSec->Name + " is not a valid symbol index");
973 GroupSec->setSymTab(SymTab);
974 GroupSec->setSymbol(Sym);
975 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
976 GroupSec->Contents.empty())
977 error("The content of the section " + GroupSec->Name + " is malformed");
978 const ELF::Elf32_Word *Word =
979 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
980 const ELF::Elf32_Word *End =
981 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
982 GroupSec->setFlagWord(*Word++);
983 for (; Word != End; ++Word) {
984 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
985 GroupSec->addMember(SecTable.getSection(
986 Index, "Group member index " + Twine(Index) + " in section " +
987 GroupSec->Name + " is invalid"));
988 }
989}
990
991template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000992void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000993 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
994 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000995 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000996
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000997 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
998 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000999 SectionBase *DefSection = nullptr;
1000 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001001
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001002 if (Sym.st_shndx == SHN_XINDEX) {
1003 if (SymTab->getShndxTable() == nullptr)
1004 error("Symbol '" + Name +
1005 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
1006 if (ShndxData.data() == nullptr) {
1007 const Elf_Shdr &ShndxSec =
1008 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1009 ShndxData = unwrapOrError(
1010 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1011 if (ShndxData.size() != Symbols.size())
1012 error("Symbol section index table does not have the same number of "
1013 "entries as the symbol table.");
1014 }
1015 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1016 DefSection = Obj.sections().getSection(
1017 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +00001018 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001019 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001020 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001021 error(
1022 "Symbol '" + Name +
1023 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1024 Twine(Sym.st_shndx));
1025 }
1026 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001027 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001028 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001029 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001030 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001031 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001032
Petr Hosek79cee9e2017-08-29 02:12:03 +00001033 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001034 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001035 }
1036}
1037
1038template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001039static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1040
1041template <class ELFT>
1042static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1043 ToSet = Rela.r_addend;
1044}
1045
Jake Ehrlich76e91102018-01-25 22:46:17 +00001046template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001047static void initRelocations(RelocationSection *Relocs,
1048 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001049 for (const auto &Rel : RelRange) {
1050 Relocation ToAdd;
1051 ToAdd.Offset = Rel.r_offset;
1052 getAddend(ToAdd.Addend, Rel);
1053 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001054 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001055 Relocs->addRelocation(ToAdd);
1056 }
1057}
1058
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001059SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001060 if (Index == SHN_UNDEF || Index > Sections.size())
1061 error(ErrMsg);
1062 return Sections[Index - 1].get();
1063}
1064
1065template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001066T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001067 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001068 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001069 return Sec;
1070 error(TypeErrMsg);
1071}
1072
Petr Hosekd7df9b22017-09-06 23:41:02 +00001073template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001074SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001075 ArrayRef<uint8_t> Data;
1076 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001077 case SHT_REL:
1078 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001079 if (Shdr.sh_flags & SHF_ALLOC) {
1080 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001081 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001082 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001084 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001085 // If a string table is allocated we don't want to mess with it. That would
1086 // mean altering the memory image. There are no special link types or
1087 // anything so we can just use a Section.
1088 if (Shdr.sh_flags & SHF_ALLOC) {
1089 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001090 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001091 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001092 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001093 case SHT_HASH:
1094 case SHT_GNU_HASH:
1095 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1096 // Because of this we don't need to mess with the hash tables either.
1097 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001098 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001099 case SHT_GROUP:
1100 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1101 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001102 case SHT_DYNSYM:
1103 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001104 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001105 case SHT_DYNAMIC:
1106 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001107 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001108 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001109 auto &SymTab = Obj.addSection<SymbolTableSection>();
1110 Obj.SymbolTable = &SymTab;
1111 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001112 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001113 case SHT_SYMTAB_SHNDX: {
1114 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1115 Obj.SectionIndexTable = &ShndxSection;
1116 return ShndxSection;
1117 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001118 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001119 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001120 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001121 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001122
George Rimarf2eb8ca2019-03-06 14:01:54 +00001123 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1124 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001125 uint64_t DecompressedSize, DecompressedAlign;
1126 std::tie(DecompressedSize, DecompressedAlign) =
1127 getDecompressedSizeAndAlignment<ELFT>(Data);
1128 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1129 DecompressedAlign);
1130 }
1131
Jake Ehrlich76e91102018-01-25 22:46:17 +00001132 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001133 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001134 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001135}
1136
Jake Ehrlich76e91102018-01-25 22:46:17 +00001137template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001138 uint32_t Index = 0;
1139 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1140 if (Index == 0) {
1141 ++Index;
1142 continue;
1143 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001144 auto &Sec = makeSection(Shdr);
1145 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1146 Sec.Type = Shdr.sh_type;
1147 Sec.Flags = Shdr.sh_flags;
1148 Sec.Addr = Shdr.sh_addr;
1149 Sec.Offset = Shdr.sh_offset;
1150 Sec.OriginalOffset = Shdr.sh_offset;
1151 Sec.Size = Shdr.sh_size;
1152 Sec.Link = Shdr.sh_link;
1153 Sec.Info = Shdr.sh_info;
1154 Sec.Align = Shdr.sh_addralign;
1155 Sec.EntrySize = Shdr.sh_entsize;
1156 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001157 Sec.OriginalData =
1158 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1159 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001160 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001161
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001162 // If a section index table exists we'll need to initialize it before we
1163 // initialize the symbol table because the symbol table might need to
1164 // reference it.
1165 if (Obj.SectionIndexTable)
1166 Obj.SectionIndexTable->initialize(Obj.sections());
1167
Petr Hosek79cee9e2017-08-29 02:12:03 +00001168 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001169 // details about symbol tables. We need the symbol table filled out before
1170 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001171 if (Obj.SymbolTable) {
1172 Obj.SymbolTable->initialize(Obj.sections());
1173 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001174 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001175
1176 // Now that all sections and symbols have been added we can add
1177 // relocations that reference symbols and set the link and info fields for
1178 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001179 for (auto &Section : Obj.sections()) {
1180 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001181 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001182 Section.initialize(Obj.sections());
1183 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001184 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1185 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001186 initRelocations(RelSec, Obj.SymbolTable,
1187 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001188 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001189 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001190 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001191 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1192 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001193 }
1194 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001195}
1196
Jake Ehrlich76e91102018-01-25 22:46:17 +00001197template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001198 const auto &Ehdr = *ElfFile.getHeader();
1199
George Rimar4ded7732018-12-20 10:51:42 +00001200 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1201 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001202 Obj.Type = Ehdr.e_type;
1203 Obj.Machine = Ehdr.e_machine;
1204 Obj.Version = Ehdr.e_version;
1205 Obj.Entry = Ehdr.e_entry;
1206 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001207
Jake Ehrlich76e91102018-01-25 22:46:17 +00001208 readSectionHeaders();
1209 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001210
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001211 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1212 if (ShstrIndex == SHN_XINDEX)
1213 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1214
Jake Ehrlich76e91102018-01-25 22:46:17 +00001215 Obj.SectionNames =
1216 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001217 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001218 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001219 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001220 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001221 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001222}
1223
Jake Ehrlich76e91102018-01-25 22:46:17 +00001224// A generic size function which computes sizes of any random access range.
1225template <class R> size_t size(R &&Range) {
1226 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1227}
1228
1229Writer::~Writer() {}
1230
1231Reader::~Reader() {}
1232
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001233std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001234 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001235}
1236
1237std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001238 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001239 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1240 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001241 Builder.build();
1242 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001243 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1244 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001245 Builder.build();
1246 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001247 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1248 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001249 Builder.build();
1250 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001251 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1252 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001253 Builder.build();
1254 return Obj;
1255 }
1256 error("Invalid file type");
1257}
1258
1259template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001260 uint8_t *B = Buf.getBufferStart();
1261 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001262 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1263 Ehdr.e_ident[EI_MAG0] = 0x7f;
1264 Ehdr.e_ident[EI_MAG1] = 'E';
1265 Ehdr.e_ident[EI_MAG2] = 'L';
1266 Ehdr.e_ident[EI_MAG3] = 'F';
1267 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1268 Ehdr.e_ident[EI_DATA] =
1269 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1270 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001271 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1272 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001273
Jake Ehrlich76e91102018-01-25 22:46:17 +00001274 Ehdr.e_type = Obj.Type;
1275 Ehdr.e_machine = Obj.Machine;
1276 Ehdr.e_version = Obj.Version;
1277 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001278 // We have to use the fully-qualified name llvm::size
1279 // since some compilers complain on ambiguous resolution.
1280 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001281 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1282 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001283 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001284 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001285 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1286 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001287 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001288 // """
1289 // If the number of sections is greater than or equal to
1290 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1291 // number of section header table entries is contained in the sh_size field
1292 // of the section header at index 0.
1293 // """
1294 auto Shnum = size(Obj.sections()) + 1;
1295 if (Shnum >= SHN_LORESERVE)
1296 Ehdr.e_shnum = 0;
1297 else
1298 Ehdr.e_shnum = Shnum;
1299 // """
1300 // If the section name string table section index is greater than or equal
1301 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1302 // and the actual index of the section name string table section is
1303 // contained in the sh_link field of the section header at index 0.
1304 // """
1305 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1306 Ehdr.e_shstrndx = SHN_XINDEX;
1307 else
1308 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001309 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001310 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001311 Ehdr.e_shoff = 0;
1312 Ehdr.e_shnum = 0;
1313 Ehdr.e_shstrndx = 0;
1314 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001315}
1316
Jake Ehrlich76e91102018-01-25 22:46:17 +00001317template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1318 for (auto &Seg : Obj.segments())
1319 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001320}
1321
Jake Ehrlich76e91102018-01-25 22:46:17 +00001322template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001323 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001324 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001325 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001326 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001327 Shdr.sh_name = 0;
1328 Shdr.sh_type = SHT_NULL;
1329 Shdr.sh_flags = 0;
1330 Shdr.sh_addr = 0;
1331 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001332 // See writeEhdr for why we do this.
1333 uint64_t Shnum = size(Obj.sections()) + 1;
1334 if (Shnum >= SHN_LORESERVE)
1335 Shdr.sh_size = Shnum;
1336 else
1337 Shdr.sh_size = 0;
1338 // See writeEhdr for why we do this.
1339 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1340 Shdr.sh_link = Obj.SectionNames->Index;
1341 else
1342 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001343 Shdr.sh_info = 0;
1344 Shdr.sh_addralign = 0;
1345 Shdr.sh_entsize = 0;
1346
Jake Ehrlich76e91102018-01-25 22:46:17 +00001347 for (auto &Sec : Obj.sections())
1348 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001349}
1350
Jake Ehrlich76e91102018-01-25 22:46:17 +00001351template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1352 for (auto &Sec : Obj.sections())
James Henderson1f448142019-03-25 16:36:26 +00001353 // Segments are responsible for writing their contents, so only write the
1354 // section data if the section is not in a segment. Note that this renders
1355 // sections in segments effectively immutable.
1356 if (Sec.ParentSegment == nullptr)
1357 Sec.accept(*SecWriter);
1358}
1359
1360template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
1361 for (Segment &Seg : Obj.segments()) {
1362 uint8_t *B = Buf.getBufferStart() + Seg.Offset;
1363 assert(Seg.FileSize == Seg.getContents().size() &&
1364 "Segment size must match contents size");
1365 std::memcpy(B, Seg.getContents().data(), Seg.FileSize);
1366 }
1367
1368 // Iterate over removed sections and overwrite their old data with zeroes.
1369 for (auto &Sec : Obj.removedSections()) {
1370 Segment *Parent = Sec.ParentSegment;
1371 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
1372 continue;
1373 uint64_t Offset =
1374 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
1375 uint8_t *B = Buf.getBufferStart();
1376 std::memset(B + Offset, 0, Sec.Size);
1377 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001378}
1379
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001380Error Object::removeSections(
1381 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001382
1383 auto Iter = std::stable_partition(
1384 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1385 if (ToRemove(*Sec))
1386 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001387 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1388 if (auto ToRelSec = RelSec->getSection())
1389 return !ToRemove(*ToRelSec);
1390 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001391 return true;
1392 });
1393 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1394 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001395 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001396 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001397 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1398 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001399 // Now make sure there are no remaining references to the sections that will
1400 // be removed. Sometimes it is impossible to remove a reference so we emit
1401 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001402 std::unordered_set<const SectionBase *> RemoveSections;
1403 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001404 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1405 for (auto &Segment : Segments)
1406 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001407 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001408 }
George Rimar79fb8582019-02-27 11:18:27 +00001409
1410 // For each section that remains alive, we want to remove the dead references.
1411 // This either might update the content of the section (e.g. remove symbols
1412 // from symbol table that belongs to removed section) or trigger an error if
1413 // a live section critically depends on a section being removed somehow
1414 // (e.g. the removed section is referenced by a relocation).
1415 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001416 if (Error E = KeepSec->removeSectionReferences(
1417 [&RemoveSections](const SectionBase *Sec) {
1418 return RemoveSections.find(Sec) != RemoveSections.end();
1419 }))
1420 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001421 }
1422
James Henderson1f448142019-03-25 16:36:26 +00001423 // Transfer removed sections into the Object RemovedSections container for use
1424 // later.
1425 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
1426 // Now finally get rid of them all together.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001427 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001428 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001429}
1430
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001431Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1432 if (SymbolTable)
1433 for (const SecPtr &Sec : Sections)
1434 if (Error E = Sec->removeSymbols(ToRemove))
1435 return E;
1436 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001437}
1438
Jake Ehrlich76e91102018-01-25 22:46:17 +00001439void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001440 // Put all sections in offset order. Maintain the ordering as closely as
1441 // possible while meeting that demand however.
1442 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1443 return A->OriginalOffset < B->OriginalOffset;
1444 };
1445 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1446 CompareSections);
1447}
1448
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001449static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1450 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1451 if (Align == 0)
1452 Align = 1;
1453 auto Diff =
1454 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1455 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1456 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1457 if (Diff < 0)
1458 Diff += Align;
1459 return Offset + Diff;
1460}
1461
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001462// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001463static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001464 std::stable_sort(std::begin(Segments), std::end(Segments),
1465 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001466}
1467
1468// This function finds a consistent layout for a list of segments starting from
1469// an Offset. It assumes that Segments have been sorted by OrderSegments and
1470// returns an Offset one past the end of the last segment.
1471static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1472 uint64_t Offset) {
1473 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001474 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001475 // The only way a segment should move is if a section was between two
1476 // segments and that section was removed. If that section isn't in a segment
1477 // then it's acceptable, but not ideal, to simply move it to after the
1478 // segments. So we can simply layout segments one after the other accounting
1479 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001480 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001481 // We assume that segments have been ordered by OriginalOffset and Index
1482 // such that a parent segment will always come before a child segment in
1483 // OrderedSegments. This means that the Offset of the ParentSegment should
1484 // already be set and we can set our offset relative to it.
1485 if (Segment->ParentSegment != nullptr) {
1486 auto Parent = Segment->ParentSegment;
1487 Segment->Offset =
1488 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1489 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001490 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001491 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001492 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001493 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001494 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001495 return Offset;
1496}
1497
1498// This function finds a consistent layout for a list of sections. It assumes
1499// that the ->ParentSegment of each section has already been laid out. The
1500// supplied starting Offset is used for the starting offset of any section that
1501// does not have a ParentSegment. It returns either the offset given if all
1502// sections had a ParentSegment or an offset one past the last section if there
1503// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001504template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001505static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001506 // Now the offset of every segment has been set we can assign the offsets
1507 // of each section. For sections that are covered by a segment we should use
1508 // the segment's original offset and the section's original offset to compute
1509 // the offset from the start of the segment. Using the offset from the start
1510 // of the segment we can assign a new offset to the section. For sections not
1511 // covered by segments we can just bump Offset to the next valid location.
1512 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001513 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001514 Section.Index = Index++;
1515 if (Section.ParentSegment != nullptr) {
1516 auto Segment = *Section.ParentSegment;
1517 Section.Offset =
1518 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001519 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001520 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1521 Section.Offset = Offset;
1522 if (Section.Type != SHT_NOBITS)
1523 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001524 }
1525 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001526 return Offset;
1527}
Petr Hosek3f383832017-08-26 01:32:20 +00001528
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001529template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1530 auto &ElfHdr = Obj.ElfHdrSegment;
1531 ElfHdr.Type = PT_PHDR;
1532 ElfHdr.Flags = 0;
1533 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1534 ElfHdr.VAddr = 0;
1535 ElfHdr.PAddr = 0;
1536 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1537 ElfHdr.Align = 0;
1538}
1539
Jake Ehrlich76e91102018-01-25 22:46:17 +00001540template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001541 // We need a temporary list of segments that has a special order to it
1542 // so that we know that anytime ->ParentSegment is set that segment has
1543 // already had its offset properly set.
1544 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001545 for (auto &Segment : Obj.segments())
1546 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001547 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1548 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001549 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001550 // Offset is used as the start offset of the first segment to be laid out.
1551 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1552 // we start at offset 0.
1553 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001554 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001555 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001556 // If we need to write the section header table out then we need to align the
1557 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001558 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001559 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001560 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001561}
1562
Jake Ehrlich76e91102018-01-25 22:46:17 +00001563template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001564 // We already have the section header offset so we can calculate the total
1565 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001566 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1567 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001568 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001569}
1570
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001571template <class ELFT> Error ELFWriter<ELFT>::write() {
James Henderson1f448142019-03-25 16:36:26 +00001572 // Segment data must be written first, so that the ELF header and program
1573 // header tables can overwrite it, if covered by a segment.
1574 writeSegmentData();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001575 writeEhdr();
1576 writePhdrs();
1577 writeSectionData();
1578 if (WriteSectionHeaders)
1579 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001580 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001581}
1582
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001583template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001584 // It could happen that SectionNames has been removed and yet the user wants
1585 // a section header table output. We need to throw an error if a user tries
1586 // to do that.
1587 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001588 return createStringError(llvm::errc::invalid_argument,
1589 "Cannot write section header table because "
1590 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001591
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001592 Obj.sortSections();
1593
1594 // We need to assign indexes before we perform layout because we need to know
1595 // if we need large indexes or not. We can assign indexes first and check as
1596 // we go to see if we will actully need large indexes.
1597 bool NeedsLargeIndexes = false;
1598 if (size(Obj.sections()) >= SHN_LORESERVE) {
1599 auto Sections = Obj.sections();
1600 NeedsLargeIndexes =
1601 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1602 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1603 // TODO: handle case where only one section needs the large index table but
1604 // only needs it because the large index table hasn't been removed yet.
1605 }
1606
1607 if (NeedsLargeIndexes) {
1608 // This means we definitely need to have a section index table but if we
1609 // already have one then we should use it instead of making a new one.
1610 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1611 // Addition of a section to the end does not invalidate the indexes of
1612 // other sections and assigns the correct index to the new section.
1613 auto &Shndx = Obj.addSection<SectionIndexSection>();
1614 Obj.SymbolTable->setShndxTable(&Shndx);
1615 Shndx.setSymTab(Obj.SymbolTable);
1616 }
1617 } else {
1618 // Since we don't need SectionIndexTable we should remove it and all
1619 // references to it.
1620 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001621 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1622 return &Sec == Obj.SectionIndexTable;
1623 }))
1624 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001625 }
1626 }
1627
1628 // Make sure we add the names of all the sections. Importantly this must be
1629 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001630 if (Obj.SectionNames != nullptr)
1631 for (const auto &Section : Obj.sections()) {
1632 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001633 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001634
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001635 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001636
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001637 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001638 // Also, the output arch may not be the same as the input arch, so fix up
1639 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001640 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001641 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1642 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001643 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001644 Sec.accept(*SecSizer);
1645 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001646
1647 // The symbol table does not update all other sections on update. For
1648 // instance, symbol names are not added as new symbols are added. This means
1649 // that some sections, like .strtab, don't yet have their final size.
1650 if (Obj.SymbolTable != nullptr)
1651 Obj.SymbolTable->prepareForLayout();
1652
George Rimarfaf308b2019-03-18 14:27:41 +00001653 // Now that all strings are added we want to finalize string table builders,
1654 // because that affects section sizes which in turn affects section offsets.
1655 for (auto &Sec : Obj.sections())
1656 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
1657 StrTab->prepareForLayout();
1658
Petr Hosekc4df10e2017-08-04 21:09:26 +00001659 assignOffsets();
1660
Petr Hosekc4df10e2017-08-04 21:09:26 +00001661 // Finally now that all offsets and indexes have been set we can finalize any
1662 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001663 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1664 for (auto &Section : Obj.sections()) {
1665 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001666 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001667 if (WriteSectionHeaders)
1668 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1669 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001670 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001671
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001672 if (Error E = Buf.allocate(totalSize()))
1673 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001674 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001675 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001676}
1677
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001678Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001679 for (auto &Section : Obj.sections()) {
1680 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001681 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001682 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001683 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001684 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001685}
1686
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001687Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001688 // TODO: Create a filter range to construct OrderedSegments from so that this
1689 // code can be deduped with assignOffsets above. This should also solve the
1690 // todo below for LayoutSections.
1691 // We need a temporary list of segments that has a special order to it
1692 // so that we know that anytime ->ParentSegment is set that segment has
1693 // already had it's offset properly set. We only want to consider the segments
1694 // that will affect layout of allocated sections so we only add those.
1695 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001696 for (auto &Section : Obj.sections()) {
1697 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1698 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001699 }
1700 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001701
1702 // For binary output, we're going to use physical addresses instead of
1703 // virtual addresses, since a binary output is used for cases like ROM
1704 // loading and physical addresses are intended for ROM loading.
1705 // However, if no segment has a physical address, we'll fallback to using
1706 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001707 if (all_of(OrderedSegments,
1708 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1709 for (Segment *Seg : OrderedSegments)
1710 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001711
1712 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1713 compareSegmentsByPAddr);
1714
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001715 // Because we add a ParentSegment for each section we might have duplicate
1716 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1717 // would do very strange things.
1718 auto End =
1719 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1720 OrderedSegments.erase(End, std::end(OrderedSegments));
1721
Jake Ehrlich46814be2018-01-22 19:27:30 +00001722 uint64_t Offset = 0;
1723
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001724 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001725 // our layout algorithm to proceed as expected while not writing out the gap
1726 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001727 if (!OrderedSegments.empty()) {
1728 auto Seg = OrderedSegments[0];
1729 auto Sec = Seg->firstSection();
1730 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1731 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001732 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001733 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001734 // The PAddr needs to be increased to remove the gap before the first
1735 // section.
1736 Seg->PAddr += Diff;
1737 uint64_t LowestPAddr = Seg->PAddr;
1738 for (auto &Segment : OrderedSegments) {
1739 Segment->Offset = Segment->PAddr - LowestPAddr;
1740 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1741 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001742 }
1743
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001744 // TODO: generalize LayoutSections to take a range. Pass a special range
1745 // constructed from an iterator that skips values for which a predicate does
1746 // not hold. Then pass such a range to LayoutSections instead of constructing
1747 // AllocatedSections here.
1748 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001749 for (auto &Section : Obj.sections()) {
1750 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001751 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001752 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001753 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001754 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001755
1756 // Now that every section has been laid out we just need to compute the total
1757 // file size. This might not be the same as the offset returned by
1758 // LayoutSections, because we want to truncate the last segment to the end of
1759 // its last section, to match GNU objcopy's behaviour.
1760 TotalSize = 0;
1761 for (const auto &Section : AllocatedSections) {
1762 if (Section->Type != SHT_NOBITS)
1763 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1764 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001765
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001766 if (Error E = Buf.allocate(TotalSize))
1767 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001768 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001769 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001770}
1771
Jake Ehrlich76e91102018-01-25 22:46:17 +00001772template class ELFBuilder<ELF64LE>;
1773template class ELFBuilder<ELF64BE>;
1774template class ELFBuilder<ELF32LE>;
1775template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001776
Jake Ehrlich76e91102018-01-25 22:46:17 +00001777template class ELFWriter<ELF64LE>;
1778template class ELFWriter<ELF64BE>;
1779template class ELFWriter<ELF32LE>;
1780template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001781
1782} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001783} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001784} // end namespace llvm