blob: 39bee8579459cb5f0da84cdc8d42216c6aeb707c [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
174 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
175 Data.data() + ZlibGnuMagic.size()))
176 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
177 const uint64_t DecompressedAlign =
178 IsGnuDebug ? 1
179 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
180 ->ch_addralign;
181
182 return std::make_tuple(DecompressedSize, DecompressedAlign);
183}
184
185template <class ELFT>
186void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
Puyan Lotfiaf048642018-10-01 10:29:41 +0000187 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
188 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
189 : sizeof(Elf_Chdr_Impl<ELFT>);
190
191 StringRef CompressedContent(
192 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
193 Sec.OriginalData.size() - DataOffset);
194
195 SmallVector<char, 128> DecompressedContent;
196 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
197 static_cast<size_t>(Sec.Size)))
198 reportError(Sec.Name, std::move(E));
199
George Rimar281a5be2019-03-06 14:12:18 +0000200 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfiaf048642018-10-01 10:29:41 +0000201 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
202}
203
204void BinarySectionWriter::visit(const DecompressedSection &Sec) {
205 error("Cannot write compressed section '" + Sec.Name + "' ");
206}
207
208void DecompressedSection::accept(SectionVisitor &Visitor) const {
209 Visitor.visit(*this);
210}
211
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000212void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
213 Visitor.visit(*this);
214}
215
Jake Ehrlich76e91102018-01-25 22:46:17 +0000216void OwnedDataSection::accept(SectionVisitor &Visitor) const {
217 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000218}
219
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000220void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
221 Visitor.visit(*this);
222}
223
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000224void BinarySectionWriter::visit(const CompressedSection &Sec) {
225 error("Cannot write compressed section '" + Sec.Name + "' ");
226}
227
228template <class ELFT>
229void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
230 uint8_t *Buf = Out.getBufferStart();
231 Buf += Sec.Offset;
232
233 if (Sec.CompressionType == DebugCompressionType::None) {
234 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
235 return;
236 }
237
238 if (Sec.CompressionType == DebugCompressionType::GNU) {
239 const char *Magic = "ZLIB";
240 memcpy(Buf, Magic, strlen(Magic));
241 Buf += strlen(Magic);
242 const uint64_t DecompressedSize =
243 support::endian::read64be(&Sec.DecompressedSize);
244 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
245 Buf += sizeof(DecompressedSize);
246 } else {
247 Elf_Chdr_Impl<ELFT> Chdr;
248 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
249 Chdr.ch_size = Sec.DecompressedSize;
250 Chdr.ch_addralign = Sec.DecompressedAlign;
251 memcpy(Buf, &Chdr, sizeof(Chdr));
252 Buf += sizeof(Chdr);
253 }
254
255 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
256}
257
258CompressedSection::CompressedSection(const SectionBase &Sec,
259 DebugCompressionType CompressionType)
260 : SectionBase(Sec), CompressionType(CompressionType),
261 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000262 if (Error E = zlib::compress(
263 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
264 OriginalData.size()),
265 CompressedData))
266 reportError(Name, std::move(E));
267
268 size_t ChdrSize;
269 if (CompressionType == DebugCompressionType::GNU) {
270 Name = ".z" + Sec.Name.substr(1);
271 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
272 } else {
273 Flags |= ELF::SHF_COMPRESSED;
274 ChdrSize =
275 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
276 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
277 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
278 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
279 }
280 Size = ChdrSize + CompressedData.size();
281 Align = 8;
282}
283
Puyan Lotfiaf048642018-10-01 10:29:41 +0000284CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
285 uint64_t DecompressedSize,
286 uint64_t DecompressedAlign)
287 : CompressionType(DebugCompressionType::None),
288 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
289 OriginalData = CompressedData;
290}
291
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000292void CompressedSection::accept(SectionVisitor &Visitor) const {
293 Visitor.visit(*this);
294}
295
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000296void CompressedSection::accept(MutableSectionVisitor &Visitor) {
297 Visitor.visit(*this);
298}
299
George Rimarfaf308b2019-03-18 14:27:41 +0000300void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000301
302uint32_t StringTableSection::findIndex(StringRef Name) const {
303 return StrTabBuilder.getOffset(Name);
304}
305
George Rimarfaf308b2019-03-18 14:27:41 +0000306void StringTableSection::prepareForLayout() {
307 StrTabBuilder.finalize();
308 Size = StrTabBuilder.getSize();
309}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000310
Jake Ehrlich76e91102018-01-25 22:46:17 +0000311void SectionWriter::visit(const StringTableSection &Sec) {
312 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
313}
314
315void StringTableSection::accept(SectionVisitor &Visitor) const {
316 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000317}
318
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000319void StringTableSection::accept(MutableSectionVisitor &Visitor) {
320 Visitor.visit(*this);
321}
322
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000323template <class ELFT>
324void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
325 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000326 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000327 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000328}
329
330void SectionIndexSection::initialize(SectionTableRef SecTable) {
331 Size = 0;
332 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
333 Link,
334 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
335 "Link field value " + Twine(Link) + " in section " + Name +
336 " is not a symbol table"));
337 Symbols->setShndxTable(this);
338}
339
340void SectionIndexSection::finalize() { Link = Symbols->Index; }
341
342void SectionIndexSection::accept(SectionVisitor &Visitor) const {
343 Visitor.visit(*this);
344}
345
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000346void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
347 Visitor.visit(*this);
348}
349
Petr Hosekc1135772017-09-13 03:04:50 +0000350static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000351 switch (Index) {
352 case SHN_ABS:
353 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000354 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000355 }
Petr Hosekc1135772017-09-13 03:04:50 +0000356 if (Machine == EM_HEXAGON) {
357 switch (Index) {
358 case SHN_HEXAGON_SCOMMON:
359 case SHN_HEXAGON_SCOMMON_2:
360 case SHN_HEXAGON_SCOMMON_4:
361 case SHN_HEXAGON_SCOMMON_8:
362 return true;
363 }
364 }
365 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000366}
367
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000368// Large indexes force us to clarify exactly what this function should do. This
369// function should return the value that will appear in st_shndx when written
370// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000371uint16_t Symbol::getShndx() const {
372 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000373 if (DefinedIn->Index >= SHN_LORESERVE)
374 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000375 return DefinedIn->Index;
376 }
377 switch (ShndxType) {
378 // This means that we don't have a defined section but we do need to
379 // output a legitimate section index.
380 case SYMBOL_SIMPLE_INDEX:
381 return SHN_UNDEF;
382 case SYMBOL_ABS:
383 case SYMBOL_COMMON:
384 case SYMBOL_HEXAGON_SCOMMON:
385 case SYMBOL_HEXAGON_SCOMMON_2:
386 case SYMBOL_HEXAGON_SCOMMON_4:
387 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000388 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000389 return static_cast<uint16_t>(ShndxType);
390 }
391 llvm_unreachable("Symbol with invalid ShndxType encountered");
392}
393
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000394bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
395
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000396void SymbolTableSection::assignIndices() {
397 uint32_t Index = 0;
398 for (auto &Sym : Symbols)
399 Sym->Index = Index++;
400}
401
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000402void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000403 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000404 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000405 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000406 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000407 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000408 Sym.Binding = Bind;
409 Sym.Type = Type;
410 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000411 if (DefinedIn != nullptr)
412 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000413 if (DefinedIn == nullptr) {
414 if (Shndx >= SHN_LORESERVE)
415 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
416 else
417 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
418 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000419 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000420 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000421 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000422 Sym.Index = Symbols.size();
423 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
424 Size += this->EntrySize;
425}
426
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000427Error SymbolTableSection::removeSectionReferences(
428 function_ref<bool(const SectionBase *)> ToRemove) {
429 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000430 SectionIndexTable = nullptr;
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000431 if (ToRemove(SymbolNames))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000432 return createStringError(llvm::errc::invalid_argument,
433 "String table %s cannot be removed because it is "
434 "referenced by the symbol table %s",
435 SymbolNames->Name.data(), this->Name.data());
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000436 return removeSymbols(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000437 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000438}
439
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000440void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000441 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
442 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000443 std::stable_partition(
444 std::begin(Symbols), std::end(Symbols),
445 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000446 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000447}
448
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000449Error SymbolTableSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000450 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000451 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000452 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000453 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
454 std::end(Symbols));
455 Size = Symbols.size() * EntrySize;
456 assignIndices();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000457 return Error::success();
Paul Semel41695f82018-05-02 20:19:22 +0000458}
459
George Rimar0373bed2019-03-20 13:57:47 +0000460void SymbolTableSection::replaceSectionReferences(
461 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
462 for (std::unique_ptr<Symbol> &Sym : Symbols)
463 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
464 Sym->DefinedIn = To;
465}
466
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000467void SymbolTableSection::initialize(SectionTableRef SecTable) {
468 Size = 0;
469 setStrTab(SecTable.getSectionOfType<StringTableSection>(
470 Link,
471 "Symbol table has link index of " + Twine(Link) +
472 " which is not a valid index",
473 "Symbol table has link index of " + Twine(Link) +
474 " which is not a string table"));
475}
476
Petr Hosek79cee9e2017-08-29 02:12:03 +0000477void SymbolTableSection::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000478 uint32_t MaxLocalIndex = 0;
479 for (auto &Sym : Symbols) {
480 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
481 if (Sym->Binding == STB_LOCAL)
482 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
483 }
484 // Now we need to set the Link and Info fields.
485 Link = SymbolNames->Index;
486 Info = MaxLocalIndex + 1;
487}
488
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000489void SymbolTableSection::prepareForLayout() {
490 // Add all potential section indexes before file layout so that the section
491 // index section has the approprite size.
492 if (SectionIndexTable != nullptr) {
493 for (const auto &Sym : Symbols) {
494 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
495 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
496 else
497 SectionIndexTable->addIndex(SHN_UNDEF);
498 }
499 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000500 // Add all of our strings to SymbolNames so that SymbolNames has the right
501 // size before layout is decided.
502 for (auto &Sym : Symbols)
503 SymbolNames->addString(Sym->Name);
504}
505
506const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
507 if (Symbols.size() <= Index)
508 error("Invalid symbol index: " + Twine(Index));
509 return Symbols[Index].get();
510}
511
Paul Semel99dda0b2018-05-25 11:01:25 +0000512Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
513 return const_cast<Symbol *>(
514 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
515}
516
Petr Hosek79cee9e2017-08-29 02:12:03 +0000517template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000518void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000519 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000520 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000521 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000522 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000523 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000524 Sym->st_name = Symbol->NameIndex;
525 Sym->st_value = Symbol->Value;
526 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000527 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000528 Sym->setBinding(Symbol->Binding);
529 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000530 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000531 ++Sym;
532 }
533}
534
Jake Ehrlich76e91102018-01-25 22:46:17 +0000535void SymbolTableSection::accept(SectionVisitor &Visitor) const {
536 Visitor.visit(*this);
537}
538
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000539void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
540 Visitor.visit(*this);
541}
542
George Rimar79fb8582019-02-27 11:18:27 +0000543Error RelocationSection::removeSectionReferences(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000544 function_ref<bool(const SectionBase *)> ToRemove) {
545 if (ToRemove(Symbols))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000546 return createStringError(llvm::errc::invalid_argument,
547 "Symbol table %s cannot be removed because it is "
548 "referenced by the relocation section %s.",
549 Symbols->Name.data(), this->Name.data());
George Rimar79fb8582019-02-27 11:18:27 +0000550
551 for (const Relocation &R : Relocations) {
552 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
553 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000554 return createStringError(llvm::errc::invalid_argument,
555 "Section %s can't be removed: (%s+0x%" PRIx64
556 ") has relocation against symbol '%s'",
557 R.RelocSymbol->DefinedIn->Name.data(),
558 SecToApplyRel->Name.data(), R.Offset,
559 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000560 }
561
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000562 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000563}
564
565template <class SymTabType>
566void RelocSectionWithSymtabBase<SymTabType>::initialize(
567 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000568 if (Link != SHN_UNDEF)
569 setSymTab(SecTable.getSectionOfType<SymTabType>(
570 Link,
571 "Link field value " + Twine(Link) + " in section " + Name +
572 " is invalid",
573 "Link field value " + Twine(Link) + " in section " + Name +
574 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000575
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000576 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000577 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
578 " in section " + Name +
579 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000580 else
581 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000582}
583
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000584template <class SymTabType>
585void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000586 this->Link = Symbols ? Symbols->Index : 0;
587
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000588 if (SecToApplyRel != nullptr)
589 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000590}
591
592template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000593static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000594
595template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000596static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000597 Rela.r_addend = Addend;
598}
599
Jake Ehrlich76e91102018-01-25 22:46:17 +0000600template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000601static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000602 for (const auto &Reloc : Relocations) {
603 Buf->r_offset = Reloc.Offset;
604 setAddend(*Buf, Reloc.Addend);
605 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
606 ++Buf;
607 }
608}
609
610template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000611void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
612 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
613 if (Sec.Type == SHT_REL)
614 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000615 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000616 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000617}
618
Jake Ehrlich76e91102018-01-25 22:46:17 +0000619void RelocationSection::accept(SectionVisitor &Visitor) const {
620 Visitor.visit(*this);
621}
622
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000623void RelocationSection::accept(MutableSectionVisitor &Visitor) {
624 Visitor.visit(*this);
625}
626
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000627Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000628 function_ref<bool(const Symbol &)> ToRemove) {
629 for (const Relocation &Reloc : Relocations)
630 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000631 return createStringError(
632 llvm::errc::invalid_argument,
633 "not stripping symbol '%s' because it is named in a relocation.",
634 Reloc.RelocSymbol->Name.data());
635 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000636}
637
Paul Semel99dda0b2018-05-25 11:01:25 +0000638void RelocationSection::markSymbols() {
639 for (const Relocation &Reloc : Relocations)
640 Reloc.RelocSymbol->Referenced = true;
641}
642
George Rimard8a5c6c2019-03-11 11:01:24 +0000643void RelocationSection::replaceSectionReferences(
644 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
645 // Update the target section if it was replaced.
646 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
647 SecToApplyRel = To;
George Rimard8a5c6c2019-03-11 11:01:24 +0000648}
649
Jake Ehrlich76e91102018-01-25 22:46:17 +0000650void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000651 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000652 Out.getBufferStart() + Sec.Offset);
653}
654
655void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
656 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000657}
658
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000659void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
660 Visitor.visit(*this);
661}
662
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000663Error Section::removeSectionReferences(
664 function_ref<bool(const SectionBase *)> ToRemove) {
665 if (ToRemove(LinkSection))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000666 return createStringError(llvm::errc::invalid_argument,
667 "Section %s cannot be removed because it is "
668 "referenced by the section %s",
669 LinkSection->Name.data(), this->Name.data());
670 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000671}
672
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000673void GroupSection::finalize() {
674 this->Info = Sym->Index;
675 this->Link = SymTab->Index;
676}
677
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000678Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
679 if (ToRemove(*Sym))
680 return createStringError(llvm::errc::invalid_argument,
681 "Symbol %s cannot be removed because it is "
682 "referenced by the section %s[%d].",
683 Sym->Name.data(), this->Name.data(), this->Index);
684 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000685}
686
Paul Semel99dda0b2018-05-25 11:01:25 +0000687void GroupSection::markSymbols() {
688 if (Sym)
689 Sym->Referenced = true;
690}
691
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000692void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000693 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000694 LinkSection =
695 SecTable.getSection(Link, "Link field value " + Twine(Link) +
696 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000697 if (LinkSection->Type == ELF::SHT_SYMTAB)
698 LinkSection = nullptr;
699 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000700}
701
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000702void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000703
Jake Ehrlich76e91102018-01-25 22:46:17 +0000704void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000705 FileName = sys::path::filename(File);
706 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000707 // followed by a null terminator and then the CRC32 of the file. The CRC32
708 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
709 // byte, and then finally push the size to alignment and add 4.
710 Size = alignTo(FileName.size() + 1, 4) + 4;
711 // The CRC32 will only be aligned if we align the whole section.
712 Align = 4;
713 Type = ELF::SHT_PROGBITS;
714 Name = ".gnu_debuglink";
715 // For sections not found in segments, OriginalOffset is only used to
716 // establish the order that sections should go in. By using the maximum
717 // possible offset we cause this section to wind up at the end.
718 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000719 JamCRC CRC;
720 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000721 // The CRC32 value needs to be complemented because the JamCRC dosn't
722 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
723 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000724 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000725}
726
Jake Ehrlich76e91102018-01-25 22:46:17 +0000727GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000728 // Read in the file to compute the CRC of it.
729 auto DebugOrErr = MemoryBuffer::getFile(File);
730 if (!DebugOrErr)
731 error("'" + File + "': " + DebugOrErr.getError().message());
732 auto Debug = std::move(*DebugOrErr);
733 init(File, Debug->getBuffer());
734}
735
736template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000737void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
738 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000739 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000740 Elf_Word *CRC =
741 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
742 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000743 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000744}
745
746void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
747 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000748}
749
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000750void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
751 Visitor.visit(*this);
752}
753
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000754template <class ELFT>
755void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
756 ELF::Elf32_Word *Buf =
757 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
758 *Buf++ = Sec.FlagWord;
759 for (const auto *S : Sec.GroupMembers)
760 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
761}
762
763void GroupSection::accept(SectionVisitor &Visitor) const {
764 Visitor.visit(*this);
765}
766
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000767void GroupSection::accept(MutableSectionVisitor &Visitor) {
768 Visitor.visit(*this);
769}
770
Petr Hosek05a04cb2017-08-01 00:33:58 +0000771// Returns true IFF a section is wholly inside the range of a segment
772static bool sectionWithinSegment(const SectionBase &Section,
773 const Segment &Segment) {
774 // If a section is empty it should be treated like it has a size of 1. This is
775 // to clarify the case when an empty section lies on a boundary between two
776 // segments and ensures that the section "belongs" to the second segment and
777 // not the first.
778 uint64_t SecSize = Section.Size ? Section.Size : 1;
779 return Segment.Offset <= Section.OriginalOffset &&
780 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
781}
782
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000783// Returns true IFF a segment's original offset is inside of another segment's
784// range.
785static bool segmentOverlapsSegment(const Segment &Child,
786 const Segment &Parent) {
787
788 return Parent.OriginalOffset <= Child.OriginalOffset &&
789 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
790}
791
Jake Ehrlich46814be2018-01-22 19:27:30 +0000792static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000793 // Any segment without a parent segment should come before a segment
794 // that has a parent segment.
795 if (A->OriginalOffset < B->OriginalOffset)
796 return true;
797 if (A->OriginalOffset > B->OriginalOffset)
798 return false;
799 return A->Index < B->Index;
800}
801
Jake Ehrlich46814be2018-01-22 19:27:30 +0000802static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
803 if (A->PAddr < B->PAddr)
804 return true;
805 if (A->PAddr > B->PAddr)
806 return false;
807 return A->Index < B->Index;
808}
809
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000810void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000811 Obj->Flags = 0x0;
812 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000813 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000814 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000815 Obj->Entry = 0x0;
816 Obj->Machine = EMachine;
817 Obj->Version = 1;
818}
819
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000820void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000821
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000822StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000823 auto &StrTab = Obj->addSection<StringTableSection>();
824 StrTab.Name = ".strtab";
825
826 Obj->SectionNames = &StrTab;
827 return &StrTab;
828}
829
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000830SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000831 auto &SymTab = Obj->addSection<SymbolTableSection>();
832
833 SymTab.Name = ".symtab";
834 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000835
836 // The symbol table always needs a null symbol
837 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
838
839 Obj->SymbolTable = &SymTab;
840 return &SymTab;
841}
842
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000843void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000844 auto Data = ArrayRef<uint8_t>(
845 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
846 MemBuf->getBufferSize());
847 auto &DataSection = Obj->addSection<Section>(Data);
848 DataSection.Name = ".data";
849 DataSection.Type = ELF::SHT_PROGBITS;
850 DataSection.Size = Data.size();
851 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
852
853 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
854 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000855 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000856 Twine Prefix = Twine("_binary_") + SanitizedFilename;
857
858 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
859 /*Value=*/0, STV_DEFAULT, 0, 0);
860 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
861 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
862 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
863 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
864}
865
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000866void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000867 for (auto &Section : Obj->sections()) {
868 Section.initialize(Obj->sections());
869 }
870}
871
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000872std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000873 initFileHeader();
874 initHeaderSegment();
875 StringTableSection *StrTab = addStrTab();
876 SymbolTableSection *SymTab = addSymTab(StrTab);
877 initSections();
878 addData(SymTab);
879
880 return std::move(Obj);
881}
882
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000883template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000884 for (auto &Parent : Obj.segments()) {
885 // Every segment will overlap with itself but we don't want a segment to
886 // be it's own parent so we avoid that situation.
887 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
888 // We want a canonical "most parental" segment but this requires
889 // inspecting the ParentSegment.
890 if (compareSegmentsByOffset(&Parent, &Child))
891 if (Child.ParentSegment == nullptr ||
892 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
893 Child.ParentSegment = &Parent;
894 }
895 }
896 }
897}
898
Jake Ehrlich76e91102018-01-25 22:46:17 +0000899template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000900 uint32_t Index = 0;
901 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Peter Collingbournebf92b3f2019-03-12 02:17:01 +0000902 Segment &Seg = Obj.addSegment();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000903 Seg.Type = Phdr.p_type;
904 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000905 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000906 Seg.Offset = Phdr.p_offset;
907 Seg.VAddr = Phdr.p_vaddr;
908 Seg.PAddr = Phdr.p_paddr;
909 Seg.FileSize = Phdr.p_filesz;
910 Seg.MemSize = Phdr.p_memsz;
911 Seg.Align = Phdr.p_align;
912 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000913 for (auto &Section : Obj.sections()) {
914 if (sectionWithinSegment(Section, Seg)) {
915 Seg.addSection(&Section);
916 if (!Section.ParentSegment ||
917 Section.ParentSegment->Offset > Seg.Offset) {
918 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000919 }
920 }
921 }
922 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000923
924 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000925 ElfHdr.Index = Index++;
926
927 const auto &Ehdr = *ElfFile.getHeader();
928 auto &PrHdr = Obj.ProgramHdrSegment;
929 PrHdr.Type = PT_PHDR;
930 PrHdr.Flags = 0;
931 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
932 // Whereas this works automatically for ElfHdr, here OriginalOffset is
933 // always non-zero and to ensure the equation we assign the same value to
934 // VAddr as well.
935 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
936 PrHdr.PAddr = 0;
937 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000938 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000939 PrHdr.Align = sizeof(Elf_Addr);
940 PrHdr.Index = Index++;
941
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000942 // Now we do an O(n^2) loop through the segments in order to match up
943 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000944 for (auto &Child : Obj.segments())
945 setParentSegment(Child);
946 setParentSegment(ElfHdr);
947 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000948}
949
950template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000951void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
George Rimar0a5d4b82019-03-24 13:31:08 +0000952 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
953 error("Invalid alignment " + Twine(GroupSec->Align) + " of group section " +
954 GroupSec->Name);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000955 auto SecTable = Obj.sections();
956 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
957 GroupSec->Link,
958 "Link field value " + Twine(GroupSec->Link) + " in section " +
959 GroupSec->Name + " is invalid",
960 "Link field value " + Twine(GroupSec->Link) + " in section " +
961 GroupSec->Name + " is not a symbol table");
962 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
963 if (!Sym)
964 error("Info field value " + Twine(GroupSec->Info) + " in section " +
965 GroupSec->Name + " is not a valid symbol index");
966 GroupSec->setSymTab(SymTab);
967 GroupSec->setSymbol(Sym);
968 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
969 GroupSec->Contents.empty())
970 error("The content of the section " + GroupSec->Name + " is malformed");
971 const ELF::Elf32_Word *Word =
972 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
973 const ELF::Elf32_Word *End =
974 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
975 GroupSec->setFlagWord(*Word++);
976 for (; Word != End; ++Word) {
977 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
978 GroupSec->addMember(SecTable.getSection(
979 Index, "Group member index " + Twine(Index) + " in section " +
980 GroupSec->Name + " is invalid"));
981 }
982}
983
984template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000985void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000986 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
987 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000988 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000989
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000990 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
991 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000992 SectionBase *DefSection = nullptr;
993 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000994
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000995 if (Sym.st_shndx == SHN_XINDEX) {
996 if (SymTab->getShndxTable() == nullptr)
997 error("Symbol '" + Name +
998 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
999 if (ShndxData.data() == nullptr) {
1000 const Elf_Shdr &ShndxSec =
1001 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1002 ShndxData = unwrapOrError(
1003 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1004 if (ShndxData.size() != Symbols.size())
1005 error("Symbol section index table does not have the same number of "
1006 "entries as the symbol table.");
1007 }
1008 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1009 DefSection = Obj.sections().getSection(
1010 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +00001011 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001012 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001013 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001014 error(
1015 "Symbol '" + Name +
1016 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1017 Twine(Sym.st_shndx));
1018 }
1019 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001020 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001021 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001022 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001023 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001024 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001025
Petr Hosek79cee9e2017-08-29 02:12:03 +00001026 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001027 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001028 }
1029}
1030
1031template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001032static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1033
1034template <class ELFT>
1035static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1036 ToSet = Rela.r_addend;
1037}
1038
Jake Ehrlich76e91102018-01-25 22:46:17 +00001039template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001040static void initRelocations(RelocationSection *Relocs,
1041 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001042 for (const auto &Rel : RelRange) {
1043 Relocation ToAdd;
1044 ToAdd.Offset = Rel.r_offset;
1045 getAddend(ToAdd.Addend, Rel);
1046 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001047 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001048 Relocs->addRelocation(ToAdd);
1049 }
1050}
1051
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001052SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001053 if (Index == SHN_UNDEF || Index > Sections.size())
1054 error(ErrMsg);
1055 return Sections[Index - 1].get();
1056}
1057
1058template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001059T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001060 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001061 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001062 return Sec;
1063 error(TypeErrMsg);
1064}
1065
Petr Hosekd7df9b22017-09-06 23:41:02 +00001066template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001067SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001068 ArrayRef<uint8_t> Data;
1069 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001070 case SHT_REL:
1071 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001072 if (Shdr.sh_flags & SHF_ALLOC) {
1073 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001074 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001075 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001076 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001077 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001078 // If a string table is allocated we don't want to mess with it. That would
1079 // mean altering the memory image. There are no special link types or
1080 // anything so we can just use a Section.
1081 if (Shdr.sh_flags & SHF_ALLOC) {
1082 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001084 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001085 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001086 case SHT_HASH:
1087 case SHT_GNU_HASH:
1088 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1089 // Because of this we don't need to mess with the hash tables either.
1090 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001091 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001092 case SHT_GROUP:
1093 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1094 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001095 case SHT_DYNSYM:
1096 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001097 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001098 case SHT_DYNAMIC:
1099 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001100 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001101 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001102 auto &SymTab = Obj.addSection<SymbolTableSection>();
1103 Obj.SymbolTable = &SymTab;
1104 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001105 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001106 case SHT_SYMTAB_SHNDX: {
1107 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1108 Obj.SectionIndexTable = &ShndxSection;
1109 return ShndxSection;
1110 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001111 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001112 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001113 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001114 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001115
George Rimarf2eb8ca2019-03-06 14:01:54 +00001116 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1117 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001118 uint64_t DecompressedSize, DecompressedAlign;
1119 std::tie(DecompressedSize, DecompressedAlign) =
1120 getDecompressedSizeAndAlignment<ELFT>(Data);
1121 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1122 DecompressedAlign);
1123 }
1124
Jake Ehrlich76e91102018-01-25 22:46:17 +00001125 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001126 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001127 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001128}
1129
Jake Ehrlich76e91102018-01-25 22:46:17 +00001130template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001131 uint32_t Index = 0;
1132 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1133 if (Index == 0) {
1134 ++Index;
1135 continue;
1136 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001137 auto &Sec = makeSection(Shdr);
1138 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1139 Sec.Type = Shdr.sh_type;
1140 Sec.Flags = Shdr.sh_flags;
1141 Sec.Addr = Shdr.sh_addr;
1142 Sec.Offset = Shdr.sh_offset;
1143 Sec.OriginalOffset = Shdr.sh_offset;
1144 Sec.Size = Shdr.sh_size;
1145 Sec.Link = Shdr.sh_link;
1146 Sec.Info = Shdr.sh_info;
1147 Sec.Align = Shdr.sh_addralign;
1148 Sec.EntrySize = Shdr.sh_entsize;
1149 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001150 Sec.OriginalData =
1151 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1152 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001153 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001154
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001155 // If a section index table exists we'll need to initialize it before we
1156 // initialize the symbol table because the symbol table might need to
1157 // reference it.
1158 if (Obj.SectionIndexTable)
1159 Obj.SectionIndexTable->initialize(Obj.sections());
1160
Petr Hosek79cee9e2017-08-29 02:12:03 +00001161 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001162 // details about symbol tables. We need the symbol table filled out before
1163 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001164 if (Obj.SymbolTable) {
1165 Obj.SymbolTable->initialize(Obj.sections());
1166 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001167 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001168
1169 // Now that all sections and symbols have been added we can add
1170 // relocations that reference symbols and set the link and info fields for
1171 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001172 for (auto &Section : Obj.sections()) {
1173 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001174 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001175 Section.initialize(Obj.sections());
1176 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001177 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1178 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001179 initRelocations(RelSec, Obj.SymbolTable,
1180 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001181 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001182 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001183 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001184 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1185 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001186 }
1187 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001188}
1189
Jake Ehrlich76e91102018-01-25 22:46:17 +00001190template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001191 const auto &Ehdr = *ElfFile.getHeader();
1192
George Rimar4ded7732018-12-20 10:51:42 +00001193 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1194 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001195 Obj.Type = Ehdr.e_type;
1196 Obj.Machine = Ehdr.e_machine;
1197 Obj.Version = Ehdr.e_version;
1198 Obj.Entry = Ehdr.e_entry;
1199 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001200
Jake Ehrlich76e91102018-01-25 22:46:17 +00001201 readSectionHeaders();
1202 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001203
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001204 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1205 if (ShstrIndex == SHN_XINDEX)
1206 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1207
Jake Ehrlich76e91102018-01-25 22:46:17 +00001208 Obj.SectionNames =
1209 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001210 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001211 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001212 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001213 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001214 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001215}
1216
Jake Ehrlich76e91102018-01-25 22:46:17 +00001217// A generic size function which computes sizes of any random access range.
1218template <class R> size_t size(R &&Range) {
1219 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1220}
1221
1222Writer::~Writer() {}
1223
1224Reader::~Reader() {}
1225
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001226std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001227 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001228}
1229
1230std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001231 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001232 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1233 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001234 Builder.build();
1235 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001236 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1237 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001238 Builder.build();
1239 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001240 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1241 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001242 Builder.build();
1243 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001244 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1245 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001246 Builder.build();
1247 return Obj;
1248 }
1249 error("Invalid file type");
1250}
1251
1252template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001253 uint8_t *B = Buf.getBufferStart();
1254 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001255 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1256 Ehdr.e_ident[EI_MAG0] = 0x7f;
1257 Ehdr.e_ident[EI_MAG1] = 'E';
1258 Ehdr.e_ident[EI_MAG2] = 'L';
1259 Ehdr.e_ident[EI_MAG3] = 'F';
1260 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1261 Ehdr.e_ident[EI_DATA] =
1262 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1263 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001264 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1265 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001266
Jake Ehrlich76e91102018-01-25 22:46:17 +00001267 Ehdr.e_type = Obj.Type;
1268 Ehdr.e_machine = Obj.Machine;
1269 Ehdr.e_version = Obj.Version;
1270 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001271 // We have to use the fully-qualified name llvm::size
1272 // since some compilers complain on ambiguous resolution.
1273 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001274 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1275 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001276 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001277 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001278 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1279 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001280 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001281 // """
1282 // If the number of sections is greater than or equal to
1283 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1284 // number of section header table entries is contained in the sh_size field
1285 // of the section header at index 0.
1286 // """
1287 auto Shnum = size(Obj.sections()) + 1;
1288 if (Shnum >= SHN_LORESERVE)
1289 Ehdr.e_shnum = 0;
1290 else
1291 Ehdr.e_shnum = Shnum;
1292 // """
1293 // If the section name string table section index is greater than or equal
1294 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1295 // and the actual index of the section name string table section is
1296 // contained in the sh_link field of the section header at index 0.
1297 // """
1298 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1299 Ehdr.e_shstrndx = SHN_XINDEX;
1300 else
1301 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001302 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001303 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001304 Ehdr.e_shoff = 0;
1305 Ehdr.e_shnum = 0;
1306 Ehdr.e_shstrndx = 0;
1307 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001308}
1309
Jake Ehrlich76e91102018-01-25 22:46:17 +00001310template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1311 for (auto &Seg : Obj.segments())
1312 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001313}
1314
Jake Ehrlich76e91102018-01-25 22:46:17 +00001315template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001316 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001317 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001318 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001319 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001320 Shdr.sh_name = 0;
1321 Shdr.sh_type = SHT_NULL;
1322 Shdr.sh_flags = 0;
1323 Shdr.sh_addr = 0;
1324 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001325 // See writeEhdr for why we do this.
1326 uint64_t Shnum = size(Obj.sections()) + 1;
1327 if (Shnum >= SHN_LORESERVE)
1328 Shdr.sh_size = Shnum;
1329 else
1330 Shdr.sh_size = 0;
1331 // See writeEhdr for why we do this.
1332 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1333 Shdr.sh_link = Obj.SectionNames->Index;
1334 else
1335 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001336 Shdr.sh_info = 0;
1337 Shdr.sh_addralign = 0;
1338 Shdr.sh_entsize = 0;
1339
Jake Ehrlich76e91102018-01-25 22:46:17 +00001340 for (auto &Sec : Obj.sections())
1341 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001342}
1343
Jake Ehrlich76e91102018-01-25 22:46:17 +00001344template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1345 for (auto &Sec : Obj.sections())
1346 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001347}
1348
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001349Error Object::removeSections(
1350 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001351
1352 auto Iter = std::stable_partition(
1353 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1354 if (ToRemove(*Sec))
1355 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001356 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1357 if (auto ToRelSec = RelSec->getSection())
1358 return !ToRemove(*ToRelSec);
1359 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001360 return true;
1361 });
1362 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1363 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001364 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001365 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001366 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1367 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001368 // Now make sure there are no remaining references to the sections that will
1369 // be removed. Sometimes it is impossible to remove a reference so we emit
1370 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001371 std::unordered_set<const SectionBase *> RemoveSections;
1372 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001373 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1374 for (auto &Segment : Segments)
1375 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001376 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001377 }
George Rimar79fb8582019-02-27 11:18:27 +00001378
1379 // For each section that remains alive, we want to remove the dead references.
1380 // This either might update the content of the section (e.g. remove symbols
1381 // from symbol table that belongs to removed section) or trigger an error if
1382 // a live section critically depends on a section being removed somehow
1383 // (e.g. the removed section is referenced by a relocation).
1384 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001385 if (Error E = KeepSec->removeSectionReferences(
1386 [&RemoveSections](const SectionBase *Sec) {
1387 return RemoveSections.find(Sec) != RemoveSections.end();
1388 }))
1389 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001390 }
1391
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001392 // Now finally get rid of them all togethor.
1393 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001394 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001395}
1396
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001397Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1398 if (SymbolTable)
1399 for (const SecPtr &Sec : Sections)
1400 if (Error E = Sec->removeSymbols(ToRemove))
1401 return E;
1402 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001403}
1404
Jake Ehrlich76e91102018-01-25 22:46:17 +00001405void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001406 // Put all sections in offset order. Maintain the ordering as closely as
1407 // possible while meeting that demand however.
1408 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1409 return A->OriginalOffset < B->OriginalOffset;
1410 };
1411 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1412 CompareSections);
1413}
1414
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001415static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1416 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1417 if (Align == 0)
1418 Align = 1;
1419 auto Diff =
1420 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1421 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1422 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1423 if (Diff < 0)
1424 Diff += Align;
1425 return Offset + Diff;
1426}
1427
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001428// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001429static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001430 std::stable_sort(std::begin(Segments), std::end(Segments),
1431 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001432}
1433
1434// This function finds a consistent layout for a list of segments starting from
1435// an Offset. It assumes that Segments have been sorted by OrderSegments and
1436// returns an Offset one past the end of the last segment.
1437static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1438 uint64_t Offset) {
1439 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001440 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001441 // The only way a segment should move is if a section was between two
1442 // segments and that section was removed. If that section isn't in a segment
1443 // then it's acceptable, but not ideal, to simply move it to after the
1444 // segments. So we can simply layout segments one after the other accounting
1445 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001446 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001447 // We assume that segments have been ordered by OriginalOffset and Index
1448 // such that a parent segment will always come before a child segment in
1449 // OrderedSegments. This means that the Offset of the ParentSegment should
1450 // already be set and we can set our offset relative to it.
1451 if (Segment->ParentSegment != nullptr) {
1452 auto Parent = Segment->ParentSegment;
1453 Segment->Offset =
1454 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1455 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001456 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001457 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001458 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001459 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001460 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001461 return Offset;
1462}
1463
1464// This function finds a consistent layout for a list of sections. It assumes
1465// that the ->ParentSegment of each section has already been laid out. The
1466// supplied starting Offset is used for the starting offset of any section that
1467// does not have a ParentSegment. It returns either the offset given if all
1468// sections had a ParentSegment or an offset one past the last section if there
1469// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001470template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001471static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001472 // Now the offset of every segment has been set we can assign the offsets
1473 // of each section. For sections that are covered by a segment we should use
1474 // the segment's original offset and the section's original offset to compute
1475 // the offset from the start of the segment. Using the offset from the start
1476 // of the segment we can assign a new offset to the section. For sections not
1477 // covered by segments we can just bump Offset to the next valid location.
1478 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001479 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001480 Section.Index = Index++;
1481 if (Section.ParentSegment != nullptr) {
1482 auto Segment = *Section.ParentSegment;
1483 Section.Offset =
1484 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001485 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001486 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1487 Section.Offset = Offset;
1488 if (Section.Type != SHT_NOBITS)
1489 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001490 }
1491 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001492 return Offset;
1493}
Petr Hosek3f383832017-08-26 01:32:20 +00001494
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001495template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1496 auto &ElfHdr = Obj.ElfHdrSegment;
1497 ElfHdr.Type = PT_PHDR;
1498 ElfHdr.Flags = 0;
1499 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1500 ElfHdr.VAddr = 0;
1501 ElfHdr.PAddr = 0;
1502 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1503 ElfHdr.Align = 0;
1504}
1505
Jake Ehrlich76e91102018-01-25 22:46:17 +00001506template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001507 // We need a temporary list of segments that has a special order to it
1508 // so that we know that anytime ->ParentSegment is set that segment has
1509 // already had its offset properly set.
1510 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001511 for (auto &Segment : Obj.segments())
1512 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001513 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1514 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001515 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001516 // Offset is used as the start offset of the first segment to be laid out.
1517 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1518 // we start at offset 0.
1519 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001520 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001521 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001522 // If we need to write the section header table out then we need to align the
1523 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001524 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001525 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001526 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001527}
1528
Jake Ehrlich76e91102018-01-25 22:46:17 +00001529template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001530 // We already have the section header offset so we can calculate the total
1531 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001532 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1533 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001534 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001535}
1536
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001537template <class ELFT> Error ELFWriter<ELFT>::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001538 writeEhdr();
1539 writePhdrs();
1540 writeSectionData();
1541 if (WriteSectionHeaders)
1542 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001543 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001544}
1545
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001546template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001547 // It could happen that SectionNames has been removed and yet the user wants
1548 // a section header table output. We need to throw an error if a user tries
1549 // to do that.
1550 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001551 return createStringError(llvm::errc::invalid_argument,
1552 "Cannot write section header table because "
1553 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001554
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001555 Obj.sortSections();
1556
1557 // We need to assign indexes before we perform layout because we need to know
1558 // if we need large indexes or not. We can assign indexes first and check as
1559 // we go to see if we will actully need large indexes.
1560 bool NeedsLargeIndexes = false;
1561 if (size(Obj.sections()) >= SHN_LORESERVE) {
1562 auto Sections = Obj.sections();
1563 NeedsLargeIndexes =
1564 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1565 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1566 // TODO: handle case where only one section needs the large index table but
1567 // only needs it because the large index table hasn't been removed yet.
1568 }
1569
1570 if (NeedsLargeIndexes) {
1571 // This means we definitely need to have a section index table but if we
1572 // already have one then we should use it instead of making a new one.
1573 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1574 // Addition of a section to the end does not invalidate the indexes of
1575 // other sections and assigns the correct index to the new section.
1576 auto &Shndx = Obj.addSection<SectionIndexSection>();
1577 Obj.SymbolTable->setShndxTable(&Shndx);
1578 Shndx.setSymTab(Obj.SymbolTable);
1579 }
1580 } else {
1581 // Since we don't need SectionIndexTable we should remove it and all
1582 // references to it.
1583 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001584 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1585 return &Sec == Obj.SectionIndexTable;
1586 }))
1587 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001588 }
1589 }
1590
1591 // Make sure we add the names of all the sections. Importantly this must be
1592 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001593 if (Obj.SectionNames != nullptr)
1594 for (const auto &Section : Obj.sections()) {
1595 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001596 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001597
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001598 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001599
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001600 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001601 // Also, the output arch may not be the same as the input arch, so fix up
1602 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001603 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001604 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1605 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001606 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001607 Sec.accept(*SecSizer);
1608 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001609
1610 // The symbol table does not update all other sections on update. For
1611 // instance, symbol names are not added as new symbols are added. This means
1612 // that some sections, like .strtab, don't yet have their final size.
1613 if (Obj.SymbolTable != nullptr)
1614 Obj.SymbolTable->prepareForLayout();
1615
George Rimarfaf308b2019-03-18 14:27:41 +00001616 // Now that all strings are added we want to finalize string table builders,
1617 // because that affects section sizes which in turn affects section offsets.
1618 for (auto &Sec : Obj.sections())
1619 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
1620 StrTab->prepareForLayout();
1621
Petr Hosekc4df10e2017-08-04 21:09:26 +00001622 assignOffsets();
1623
Petr Hosekc4df10e2017-08-04 21:09:26 +00001624 // Finally now that all offsets and indexes have been set we can finalize any
1625 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001626 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1627 for (auto &Section : Obj.sections()) {
1628 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001629 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001630 if (WriteSectionHeaders)
1631 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1632 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001633 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001634
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001635 if (Error E = Buf.allocate(totalSize()))
1636 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001637 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001638 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001639}
1640
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001641Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001642 for (auto &Section : Obj.sections()) {
1643 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001644 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001645 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001646 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001647 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001648}
1649
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001650Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001651 // TODO: Create a filter range to construct OrderedSegments from so that this
1652 // code can be deduped with assignOffsets above. This should also solve the
1653 // todo below for LayoutSections.
1654 // We need a temporary list of segments that has a special order to it
1655 // so that we know that anytime ->ParentSegment is set that segment has
1656 // already had it's offset properly set. We only want to consider the segments
1657 // that will affect layout of allocated sections so we only add those.
1658 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001659 for (auto &Section : Obj.sections()) {
1660 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1661 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001662 }
1663 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001664
1665 // For binary output, we're going to use physical addresses instead of
1666 // virtual addresses, since a binary output is used for cases like ROM
1667 // loading and physical addresses are intended for ROM loading.
1668 // However, if no segment has a physical address, we'll fallback to using
1669 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001670 if (all_of(OrderedSegments,
1671 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1672 for (Segment *Seg : OrderedSegments)
1673 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001674
1675 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1676 compareSegmentsByPAddr);
1677
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001678 // Because we add a ParentSegment for each section we might have duplicate
1679 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1680 // would do very strange things.
1681 auto End =
1682 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1683 OrderedSegments.erase(End, std::end(OrderedSegments));
1684
Jake Ehrlich46814be2018-01-22 19:27:30 +00001685 uint64_t Offset = 0;
1686
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001687 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001688 // our layout algorithm to proceed as expected while not writing out the gap
1689 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001690 if (!OrderedSegments.empty()) {
1691 auto Seg = OrderedSegments[0];
1692 auto Sec = Seg->firstSection();
1693 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1694 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001695 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001696 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001697 // The PAddr needs to be increased to remove the gap before the first
1698 // section.
1699 Seg->PAddr += Diff;
1700 uint64_t LowestPAddr = Seg->PAddr;
1701 for (auto &Segment : OrderedSegments) {
1702 Segment->Offset = Segment->PAddr - LowestPAddr;
1703 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1704 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001705 }
1706
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001707 // TODO: generalize LayoutSections to take a range. Pass a special range
1708 // constructed from an iterator that skips values for which a predicate does
1709 // not hold. Then pass such a range to LayoutSections instead of constructing
1710 // AllocatedSections here.
1711 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001712 for (auto &Section : Obj.sections()) {
1713 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001714 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001715 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001716 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001717 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001718
1719 // Now that every section has been laid out we just need to compute the total
1720 // file size. This might not be the same as the offset returned by
1721 // LayoutSections, because we want to truncate the last segment to the end of
1722 // its last section, to match GNU objcopy's behaviour.
1723 TotalSize = 0;
1724 for (const auto &Section : AllocatedSections) {
1725 if (Section->Type != SHT_NOBITS)
1726 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1727 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001728
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001729 if (Error E = Buf.allocate(TotalSize))
1730 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001731 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001732 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001733}
1734
Jake Ehrlich76e91102018-01-25 22:46:17 +00001735template class ELFBuilder<ELF64LE>;
1736template class ELFBuilder<ELF64BE>;
1737template class ELFBuilder<ELF32LE>;
1738template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001739
Jake Ehrlich76e91102018-01-25 22:46:17 +00001740template class ELFWriter<ELF64LE>;
1741template class ELFWriter<ELF64BE>;
1742template class ELFWriter<ELF32LE>;
1743template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001744
1745} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001746} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001747} // end namespace llvm