blob: 7cceb70ca63bbc58588b417947c0af29936d779c [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
George Rimar27257172019-03-24 14:41:45 +0000692void GroupSection::replaceSectionReferences(
693 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
694 for (SectionBase *&Sec : GroupMembers)
695 if (SectionBase *To = FromTo.lookup(Sec))
696 Sec = To;
697}
698
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000699void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000700 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000701 LinkSection =
702 SecTable.getSection(Link, "Link field value " + Twine(Link) +
703 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000704 if (LinkSection->Type == ELF::SHT_SYMTAB)
705 LinkSection = nullptr;
706 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000707}
708
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000709void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000710
Jake Ehrlich76e91102018-01-25 22:46:17 +0000711void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000712 FileName = sys::path::filename(File);
713 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000714 // followed by a null terminator and then the CRC32 of the file. The CRC32
715 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
716 // byte, and then finally push the size to alignment and add 4.
717 Size = alignTo(FileName.size() + 1, 4) + 4;
718 // The CRC32 will only be aligned if we align the whole section.
719 Align = 4;
720 Type = ELF::SHT_PROGBITS;
721 Name = ".gnu_debuglink";
722 // For sections not found in segments, OriginalOffset is only used to
723 // establish the order that sections should go in. By using the maximum
724 // possible offset we cause this section to wind up at the end.
725 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000726 JamCRC CRC;
727 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000728 // The CRC32 value needs to be complemented because the JamCRC dosn't
729 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
730 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000731 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000732}
733
Jake Ehrlich76e91102018-01-25 22:46:17 +0000734GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000735 // Read in the file to compute the CRC of it.
736 auto DebugOrErr = MemoryBuffer::getFile(File);
737 if (!DebugOrErr)
738 error("'" + File + "': " + DebugOrErr.getError().message());
739 auto Debug = std::move(*DebugOrErr);
740 init(File, Debug->getBuffer());
741}
742
743template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000744void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
745 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000746 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000747 Elf_Word *CRC =
748 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
749 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000750 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000751}
752
753void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
754 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000755}
756
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000757void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
758 Visitor.visit(*this);
759}
760
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000761template <class ELFT>
762void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
763 ELF::Elf32_Word *Buf =
764 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
765 *Buf++ = Sec.FlagWord;
766 for (const auto *S : Sec.GroupMembers)
767 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
768}
769
770void GroupSection::accept(SectionVisitor &Visitor) const {
771 Visitor.visit(*this);
772}
773
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000774void GroupSection::accept(MutableSectionVisitor &Visitor) {
775 Visitor.visit(*this);
776}
777
Petr Hosek05a04cb2017-08-01 00:33:58 +0000778// Returns true IFF a section is wholly inside the range of a segment
779static bool sectionWithinSegment(const SectionBase &Section,
780 const Segment &Segment) {
781 // If a section is empty it should be treated like it has a size of 1. This is
782 // to clarify the case when an empty section lies on a boundary between two
783 // segments and ensures that the section "belongs" to the second segment and
784 // not the first.
785 uint64_t SecSize = Section.Size ? Section.Size : 1;
786 return Segment.Offset <= Section.OriginalOffset &&
787 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
788}
789
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000790// Returns true IFF a segment's original offset is inside of another segment's
791// range.
792static bool segmentOverlapsSegment(const Segment &Child,
793 const Segment &Parent) {
794
795 return Parent.OriginalOffset <= Child.OriginalOffset &&
796 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
797}
798
Jake Ehrlich46814be2018-01-22 19:27:30 +0000799static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000800 // Any segment without a parent segment should come before a segment
801 // that has a parent segment.
802 if (A->OriginalOffset < B->OriginalOffset)
803 return true;
804 if (A->OriginalOffset > B->OriginalOffset)
805 return false;
806 return A->Index < B->Index;
807}
808
Jake Ehrlich46814be2018-01-22 19:27:30 +0000809static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
810 if (A->PAddr < B->PAddr)
811 return true;
812 if (A->PAddr > B->PAddr)
813 return false;
814 return A->Index < B->Index;
815}
816
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000817void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000818 Obj->Flags = 0x0;
819 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000820 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000821 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000822 Obj->Entry = 0x0;
823 Obj->Machine = EMachine;
824 Obj->Version = 1;
825}
826
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000827void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000828
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000829StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000830 auto &StrTab = Obj->addSection<StringTableSection>();
831 StrTab.Name = ".strtab";
832
833 Obj->SectionNames = &StrTab;
834 return &StrTab;
835}
836
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000837SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000838 auto &SymTab = Obj->addSection<SymbolTableSection>();
839
840 SymTab.Name = ".symtab";
841 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000842
843 // The symbol table always needs a null symbol
844 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
845
846 Obj->SymbolTable = &SymTab;
847 return &SymTab;
848}
849
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000850void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000851 auto Data = ArrayRef<uint8_t>(
852 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
853 MemBuf->getBufferSize());
854 auto &DataSection = Obj->addSection<Section>(Data);
855 DataSection.Name = ".data";
856 DataSection.Type = ELF::SHT_PROGBITS;
857 DataSection.Size = Data.size();
858 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
859
860 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
861 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000862 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000863 Twine Prefix = Twine("_binary_") + SanitizedFilename;
864
865 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
866 /*Value=*/0, STV_DEFAULT, 0, 0);
867 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
868 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
869 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
870 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
871}
872
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000873void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000874 for (auto &Section : Obj->sections()) {
875 Section.initialize(Obj->sections());
876 }
877}
878
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000879std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000880 initFileHeader();
881 initHeaderSegment();
882 StringTableSection *StrTab = addStrTab();
883 SymbolTableSection *SymTab = addSymTab(StrTab);
884 initSections();
885 addData(SymTab);
886
887 return std::move(Obj);
888}
889
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000890template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000891 for (auto &Parent : Obj.segments()) {
892 // Every segment will overlap with itself but we don't want a segment to
893 // be it's own parent so we avoid that situation.
894 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
895 // We want a canonical "most parental" segment but this requires
896 // inspecting the ParentSegment.
897 if (compareSegmentsByOffset(&Parent, &Child))
898 if (Child.ParentSegment == nullptr ||
899 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
900 Child.ParentSegment = &Parent;
901 }
902 }
903 }
904}
905
Jake Ehrlich76e91102018-01-25 22:46:17 +0000906template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000907 uint32_t Index = 0;
908 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
James Henderson1f448142019-03-25 16:36:26 +0000909 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
910 (size_t)Phdr.p_filesz};
911 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000912 Seg.Type = Phdr.p_type;
913 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000914 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000915 Seg.Offset = Phdr.p_offset;
916 Seg.VAddr = Phdr.p_vaddr;
917 Seg.PAddr = Phdr.p_paddr;
918 Seg.FileSize = Phdr.p_filesz;
919 Seg.MemSize = Phdr.p_memsz;
920 Seg.Align = Phdr.p_align;
921 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000922 for (auto &Section : Obj.sections()) {
923 if (sectionWithinSegment(Section, Seg)) {
924 Seg.addSection(&Section);
925 if (!Section.ParentSegment ||
926 Section.ParentSegment->Offset > Seg.Offset) {
927 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000928 }
929 }
930 }
931 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000932
933 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000934 ElfHdr.Index = Index++;
935
936 const auto &Ehdr = *ElfFile.getHeader();
937 auto &PrHdr = Obj.ProgramHdrSegment;
938 PrHdr.Type = PT_PHDR;
939 PrHdr.Flags = 0;
940 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
941 // Whereas this works automatically for ElfHdr, here OriginalOffset is
942 // always non-zero and to ensure the equation we assign the same value to
943 // VAddr as well.
944 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
945 PrHdr.PAddr = 0;
946 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000947 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000948 PrHdr.Align = sizeof(Elf_Addr);
949 PrHdr.Index = Index++;
950
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000951 // Now we do an O(n^2) loop through the segments in order to match up
952 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000953 for (auto &Child : Obj.segments())
954 setParentSegment(Child);
955 setParentSegment(ElfHdr);
956 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000957}
958
959template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000960void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
George Rimar0a5d4b82019-03-24 13:31:08 +0000961 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
962 error("Invalid alignment " + Twine(GroupSec->Align) + " of group section " +
963 GroupSec->Name);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000964 auto SecTable = Obj.sections();
965 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
966 GroupSec->Link,
967 "Link field value " + Twine(GroupSec->Link) + " in section " +
968 GroupSec->Name + " is invalid",
969 "Link field value " + Twine(GroupSec->Link) + " in section " +
970 GroupSec->Name + " is not a symbol table");
971 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
972 if (!Sym)
973 error("Info field value " + Twine(GroupSec->Info) + " in section " +
974 GroupSec->Name + " is not a valid symbol index");
975 GroupSec->setSymTab(SymTab);
976 GroupSec->setSymbol(Sym);
977 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
978 GroupSec->Contents.empty())
979 error("The content of the section " + GroupSec->Name + " is malformed");
980 const ELF::Elf32_Word *Word =
981 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
982 const ELF::Elf32_Word *End =
983 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
984 GroupSec->setFlagWord(*Word++);
985 for (; Word != End; ++Word) {
986 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
987 GroupSec->addMember(SecTable.getSection(
988 Index, "Group member index " + Twine(Index) + " in section " +
989 GroupSec->Name + " is invalid"));
990 }
991}
992
993template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000994void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000995 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
996 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000997 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000998
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000999 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
1000 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001001 SectionBase *DefSection = nullptr;
1002 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001003
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001004 if (Sym.st_shndx == SHN_XINDEX) {
1005 if (SymTab->getShndxTable() == nullptr)
1006 error("Symbol '" + Name +
1007 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
1008 if (ShndxData.data() == nullptr) {
1009 const Elf_Shdr &ShndxSec =
1010 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1011 ShndxData = unwrapOrError(
1012 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1013 if (ShndxData.size() != Symbols.size())
1014 error("Symbol section index table does not have the same number of "
1015 "entries as the symbol table.");
1016 }
1017 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1018 DefSection = Obj.sections().getSection(
1019 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +00001020 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001021 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001022 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001023 error(
1024 "Symbol '" + Name +
1025 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1026 Twine(Sym.st_shndx));
1027 }
1028 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001029 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001030 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001031 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001032 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001033 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001034
Petr Hosek79cee9e2017-08-29 02:12:03 +00001035 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001036 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001037 }
1038}
1039
1040template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001041static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1042
1043template <class ELFT>
1044static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1045 ToSet = Rela.r_addend;
1046}
1047
Jake Ehrlich76e91102018-01-25 22:46:17 +00001048template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001049static void initRelocations(RelocationSection *Relocs,
1050 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001051 for (const auto &Rel : RelRange) {
1052 Relocation ToAdd;
1053 ToAdd.Offset = Rel.r_offset;
1054 getAddend(ToAdd.Addend, Rel);
1055 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001056 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001057 Relocs->addRelocation(ToAdd);
1058 }
1059}
1060
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001061SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001062 if (Index == SHN_UNDEF || Index > Sections.size())
1063 error(ErrMsg);
1064 return Sections[Index - 1].get();
1065}
1066
1067template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001068T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001069 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001070 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001071 return Sec;
1072 error(TypeErrMsg);
1073}
1074
Petr Hosekd7df9b22017-09-06 23:41:02 +00001075template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001076SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001077 ArrayRef<uint8_t> Data;
1078 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001079 case SHT_REL:
1080 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001081 if (Shdr.sh_flags & SHF_ALLOC) {
1082 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001084 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001085 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001086 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001087 // If a string table is allocated we don't want to mess with it. That would
1088 // mean altering the memory image. There are no special link types or
1089 // anything so we can just use a Section.
1090 if (Shdr.sh_flags & SHF_ALLOC) {
1091 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001092 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001093 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001094 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001095 case SHT_HASH:
1096 case SHT_GNU_HASH:
1097 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1098 // Because of this we don't need to mess with the hash tables either.
1099 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001100 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001101 case SHT_GROUP:
1102 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1103 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001104 case SHT_DYNSYM:
1105 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001106 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001107 case SHT_DYNAMIC:
1108 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001109 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001110 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001111 auto &SymTab = Obj.addSection<SymbolTableSection>();
1112 Obj.SymbolTable = &SymTab;
1113 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001114 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001115 case SHT_SYMTAB_SHNDX: {
1116 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1117 Obj.SectionIndexTable = &ShndxSection;
1118 return ShndxSection;
1119 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001120 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001121 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001122 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001123 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001124
George Rimarf2eb8ca2019-03-06 14:01:54 +00001125 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1126 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001127 uint64_t DecompressedSize, DecompressedAlign;
1128 std::tie(DecompressedSize, DecompressedAlign) =
1129 getDecompressedSizeAndAlignment<ELFT>(Data);
1130 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1131 DecompressedAlign);
1132 }
1133
Jake Ehrlich76e91102018-01-25 22:46:17 +00001134 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001135 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001136 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001137}
1138
Jake Ehrlich76e91102018-01-25 22:46:17 +00001139template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001140 uint32_t Index = 0;
1141 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1142 if (Index == 0) {
1143 ++Index;
1144 continue;
1145 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001146 auto &Sec = makeSection(Shdr);
1147 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1148 Sec.Type = Shdr.sh_type;
1149 Sec.Flags = Shdr.sh_flags;
1150 Sec.Addr = Shdr.sh_addr;
1151 Sec.Offset = Shdr.sh_offset;
1152 Sec.OriginalOffset = Shdr.sh_offset;
1153 Sec.Size = Shdr.sh_size;
1154 Sec.Link = Shdr.sh_link;
1155 Sec.Info = Shdr.sh_info;
1156 Sec.Align = Shdr.sh_addralign;
1157 Sec.EntrySize = Shdr.sh_entsize;
1158 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001159 Sec.OriginalData =
1160 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1161 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001162 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001163
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001164 // If a section index table exists we'll need to initialize it before we
1165 // initialize the symbol table because the symbol table might need to
1166 // reference it.
1167 if (Obj.SectionIndexTable)
1168 Obj.SectionIndexTable->initialize(Obj.sections());
1169
Petr Hosek79cee9e2017-08-29 02:12:03 +00001170 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001171 // details about symbol tables. We need the symbol table filled out before
1172 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001173 if (Obj.SymbolTable) {
1174 Obj.SymbolTable->initialize(Obj.sections());
1175 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001176 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001177
1178 // Now that all sections and symbols have been added we can add
1179 // relocations that reference symbols and set the link and info fields for
1180 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181 for (auto &Section : Obj.sections()) {
1182 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001183 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001184 Section.initialize(Obj.sections());
1185 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001186 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1187 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001188 initRelocations(RelSec, Obj.SymbolTable,
1189 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001190 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001191 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001192 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001193 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1194 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001195 }
1196 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001197}
1198
Jake Ehrlich76e91102018-01-25 22:46:17 +00001199template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001200 const auto &Ehdr = *ElfFile.getHeader();
1201
George Rimar4ded7732018-12-20 10:51:42 +00001202 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1203 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001204 Obj.Type = Ehdr.e_type;
1205 Obj.Machine = Ehdr.e_machine;
1206 Obj.Version = Ehdr.e_version;
1207 Obj.Entry = Ehdr.e_entry;
1208 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001209
Jake Ehrlich76e91102018-01-25 22:46:17 +00001210 readSectionHeaders();
1211 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001212
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001213 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1214 if (ShstrIndex == SHN_XINDEX)
1215 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1216
Jake Ehrlich76e91102018-01-25 22:46:17 +00001217 Obj.SectionNames =
1218 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001219 ShstrIndex,
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 invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001222 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001223 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001224}
1225
Jake Ehrlich76e91102018-01-25 22:46:17 +00001226// A generic size function which computes sizes of any random access range.
1227template <class R> size_t size(R &&Range) {
1228 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1229}
1230
1231Writer::~Writer() {}
1232
1233Reader::~Reader() {}
1234
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001235std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001236 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001237}
1238
1239std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001240 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001241 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1242 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001243 Builder.build();
1244 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001245 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1246 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001247 Builder.build();
1248 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001249 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1250 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001251 Builder.build();
1252 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001253 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1254 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001255 Builder.build();
1256 return Obj;
1257 }
1258 error("Invalid file type");
1259}
1260
1261template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001262 uint8_t *B = Buf.getBufferStart();
1263 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001264 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1265 Ehdr.e_ident[EI_MAG0] = 0x7f;
1266 Ehdr.e_ident[EI_MAG1] = 'E';
1267 Ehdr.e_ident[EI_MAG2] = 'L';
1268 Ehdr.e_ident[EI_MAG3] = 'F';
1269 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1270 Ehdr.e_ident[EI_DATA] =
1271 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1272 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001273 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1274 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001275
Jake Ehrlich76e91102018-01-25 22:46:17 +00001276 Ehdr.e_type = Obj.Type;
1277 Ehdr.e_machine = Obj.Machine;
1278 Ehdr.e_version = Obj.Version;
1279 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001280 // We have to use the fully-qualified name llvm::size
1281 // since some compilers complain on ambiguous resolution.
1282 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001283 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1284 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001285 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001286 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001287 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1288 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001289 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001290 // """
1291 // If the number of sections is greater than or equal to
1292 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1293 // number of section header table entries is contained in the sh_size field
1294 // of the section header at index 0.
1295 // """
1296 auto Shnum = size(Obj.sections()) + 1;
1297 if (Shnum >= SHN_LORESERVE)
1298 Ehdr.e_shnum = 0;
1299 else
1300 Ehdr.e_shnum = Shnum;
1301 // """
1302 // If the section name string table section index is greater than or equal
1303 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1304 // and the actual index of the section name string table section is
1305 // contained in the sh_link field of the section header at index 0.
1306 // """
1307 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1308 Ehdr.e_shstrndx = SHN_XINDEX;
1309 else
1310 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001311 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001312 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001313 Ehdr.e_shoff = 0;
1314 Ehdr.e_shnum = 0;
1315 Ehdr.e_shstrndx = 0;
1316 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001317}
1318
Jake Ehrlich76e91102018-01-25 22:46:17 +00001319template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1320 for (auto &Seg : Obj.segments())
1321 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001322}
1323
Jake Ehrlich76e91102018-01-25 22:46:17 +00001324template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001325 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001326 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001327 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001328 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001329 Shdr.sh_name = 0;
1330 Shdr.sh_type = SHT_NULL;
1331 Shdr.sh_flags = 0;
1332 Shdr.sh_addr = 0;
1333 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001334 // See writeEhdr for why we do this.
1335 uint64_t Shnum = size(Obj.sections()) + 1;
1336 if (Shnum >= SHN_LORESERVE)
1337 Shdr.sh_size = Shnum;
1338 else
1339 Shdr.sh_size = 0;
1340 // See writeEhdr for why we do this.
1341 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1342 Shdr.sh_link = Obj.SectionNames->Index;
1343 else
1344 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001345 Shdr.sh_info = 0;
1346 Shdr.sh_addralign = 0;
1347 Shdr.sh_entsize = 0;
1348
Jake Ehrlich76e91102018-01-25 22:46:17 +00001349 for (auto &Sec : Obj.sections())
1350 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001351}
1352
Jake Ehrlich76e91102018-01-25 22:46:17 +00001353template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1354 for (auto &Sec : Obj.sections())
James Henderson1f448142019-03-25 16:36:26 +00001355 // Segments are responsible for writing their contents, so only write the
1356 // section data if the section is not in a segment. Note that this renders
1357 // sections in segments effectively immutable.
1358 if (Sec.ParentSegment == nullptr)
1359 Sec.accept(*SecWriter);
1360}
1361
1362template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
1363 for (Segment &Seg : Obj.segments()) {
1364 uint8_t *B = Buf.getBufferStart() + Seg.Offset;
1365 assert(Seg.FileSize == Seg.getContents().size() &&
1366 "Segment size must match contents size");
1367 std::memcpy(B, Seg.getContents().data(), Seg.FileSize);
1368 }
1369
1370 // Iterate over removed sections and overwrite their old data with zeroes.
1371 for (auto &Sec : Obj.removedSections()) {
1372 Segment *Parent = Sec.ParentSegment;
1373 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
1374 continue;
1375 uint64_t Offset =
1376 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
1377 uint8_t *B = Buf.getBufferStart();
1378 std::memset(B + Offset, 0, Sec.Size);
1379 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001380}
1381
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001382Error Object::removeSections(
1383 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001384
1385 auto Iter = std::stable_partition(
1386 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1387 if (ToRemove(*Sec))
1388 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001389 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1390 if (auto ToRelSec = RelSec->getSection())
1391 return !ToRemove(*ToRelSec);
1392 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001393 return true;
1394 });
1395 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1396 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001397 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001398 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001399 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1400 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001401 // Now make sure there are no remaining references to the sections that will
1402 // be removed. Sometimes it is impossible to remove a reference so we emit
1403 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001404 std::unordered_set<const SectionBase *> RemoveSections;
1405 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001406 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1407 for (auto &Segment : Segments)
1408 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001409 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001410 }
George Rimar79fb8582019-02-27 11:18:27 +00001411
1412 // For each section that remains alive, we want to remove the dead references.
1413 // This either might update the content of the section (e.g. remove symbols
1414 // from symbol table that belongs to removed section) or trigger an error if
1415 // a live section critically depends on a section being removed somehow
1416 // (e.g. the removed section is referenced by a relocation).
1417 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001418 if (Error E = KeepSec->removeSectionReferences(
1419 [&RemoveSections](const SectionBase *Sec) {
1420 return RemoveSections.find(Sec) != RemoveSections.end();
1421 }))
1422 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001423 }
1424
James Henderson1f448142019-03-25 16:36:26 +00001425 // Transfer removed sections into the Object RemovedSections container for use
1426 // later.
1427 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
1428 // Now finally get rid of them all together.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001429 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001430 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001431}
1432
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001433Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1434 if (SymbolTable)
1435 for (const SecPtr &Sec : Sections)
1436 if (Error E = Sec->removeSymbols(ToRemove))
1437 return E;
1438 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001439}
1440
Jake Ehrlich76e91102018-01-25 22:46:17 +00001441void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001442 // Put all sections in offset order. Maintain the ordering as closely as
1443 // possible while meeting that demand however.
1444 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1445 return A->OriginalOffset < B->OriginalOffset;
1446 };
1447 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1448 CompareSections);
1449}
1450
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001451static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1452 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1453 if (Align == 0)
1454 Align = 1;
1455 auto Diff =
1456 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1457 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1458 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1459 if (Diff < 0)
1460 Diff += Align;
1461 return Offset + Diff;
1462}
1463
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001464// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001465static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001466 std::stable_sort(std::begin(Segments), std::end(Segments),
1467 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001468}
1469
1470// This function finds a consistent layout for a list of segments starting from
1471// an Offset. It assumes that Segments have been sorted by OrderSegments and
1472// returns an Offset one past the end of the last segment.
1473static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1474 uint64_t Offset) {
1475 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001476 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001477 // The only way a segment should move is if a section was between two
1478 // segments and that section was removed. If that section isn't in a segment
1479 // then it's acceptable, but not ideal, to simply move it to after the
1480 // segments. So we can simply layout segments one after the other accounting
1481 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001482 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001483 // We assume that segments have been ordered by OriginalOffset and Index
1484 // such that a parent segment will always come before a child segment in
1485 // OrderedSegments. This means that the Offset of the ParentSegment should
1486 // already be set and we can set our offset relative to it.
1487 if (Segment->ParentSegment != nullptr) {
1488 auto Parent = Segment->ParentSegment;
1489 Segment->Offset =
1490 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1491 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001492 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001493 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001494 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001495 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001496 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001497 return Offset;
1498}
1499
1500// This function finds a consistent layout for a list of sections. It assumes
1501// that the ->ParentSegment of each section has already been laid out. The
1502// supplied starting Offset is used for the starting offset of any section that
1503// does not have a ParentSegment. It returns either the offset given if all
1504// sections had a ParentSegment or an offset one past the last section if there
1505// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001506template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001507static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001508 // Now the offset of every segment has been set we can assign the offsets
1509 // of each section. For sections that are covered by a segment we should use
1510 // the segment's original offset and the section's original offset to compute
1511 // the offset from the start of the segment. Using the offset from the start
1512 // of the segment we can assign a new offset to the section. For sections not
1513 // covered by segments we can just bump Offset to the next valid location.
1514 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001515 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001516 Section.Index = Index++;
1517 if (Section.ParentSegment != nullptr) {
1518 auto Segment = *Section.ParentSegment;
1519 Section.Offset =
1520 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001521 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001522 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1523 Section.Offset = Offset;
1524 if (Section.Type != SHT_NOBITS)
1525 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001526 }
1527 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001528 return Offset;
1529}
Petr Hosek3f383832017-08-26 01:32:20 +00001530
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001531template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1532 auto &ElfHdr = Obj.ElfHdrSegment;
1533 ElfHdr.Type = PT_PHDR;
1534 ElfHdr.Flags = 0;
1535 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1536 ElfHdr.VAddr = 0;
1537 ElfHdr.PAddr = 0;
1538 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1539 ElfHdr.Align = 0;
1540}
1541
Jake Ehrlich76e91102018-01-25 22:46:17 +00001542template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001543 // We need a temporary list of segments that has a special order to it
1544 // so that we know that anytime ->ParentSegment is set that segment has
1545 // already had its offset properly set.
1546 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001547 for (auto &Segment : Obj.segments())
1548 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001549 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1550 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001551 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001552 // Offset is used as the start offset of the first segment to be laid out.
1553 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1554 // we start at offset 0.
1555 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001556 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001557 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001558 // If we need to write the section header table out then we need to align the
1559 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001560 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001561 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001562 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001563}
1564
Jake Ehrlich76e91102018-01-25 22:46:17 +00001565template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001566 // We already have the section header offset so we can calculate the total
1567 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001568 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1569 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001570 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001571}
1572
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001573template <class ELFT> Error ELFWriter<ELFT>::write() {
James Henderson1f448142019-03-25 16:36:26 +00001574 // Segment data must be written first, so that the ELF header and program
1575 // header tables can overwrite it, if covered by a segment.
1576 writeSegmentData();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001577 writeEhdr();
1578 writePhdrs();
1579 writeSectionData();
1580 if (WriteSectionHeaders)
1581 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001582 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001583}
1584
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001585template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001586 // It could happen that SectionNames has been removed and yet the user wants
1587 // a section header table output. We need to throw an error if a user tries
1588 // to do that.
1589 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001590 return createStringError(llvm::errc::invalid_argument,
1591 "Cannot write section header table because "
1592 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001593
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001594 Obj.sortSections();
1595
1596 // We need to assign indexes before we perform layout because we need to know
1597 // if we need large indexes or not. We can assign indexes first and check as
1598 // we go to see if we will actully need large indexes.
1599 bool NeedsLargeIndexes = false;
1600 if (size(Obj.sections()) >= SHN_LORESERVE) {
1601 auto Sections = Obj.sections();
1602 NeedsLargeIndexes =
1603 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1604 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1605 // TODO: handle case where only one section needs the large index table but
1606 // only needs it because the large index table hasn't been removed yet.
1607 }
1608
1609 if (NeedsLargeIndexes) {
1610 // This means we definitely need to have a section index table but if we
1611 // already have one then we should use it instead of making a new one.
1612 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1613 // Addition of a section to the end does not invalidate the indexes of
1614 // other sections and assigns the correct index to the new section.
1615 auto &Shndx = Obj.addSection<SectionIndexSection>();
1616 Obj.SymbolTable->setShndxTable(&Shndx);
1617 Shndx.setSymTab(Obj.SymbolTable);
1618 }
1619 } else {
1620 // Since we don't need SectionIndexTable we should remove it and all
1621 // references to it.
1622 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001623 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1624 return &Sec == Obj.SectionIndexTable;
1625 }))
1626 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001627 }
1628 }
1629
1630 // Make sure we add the names of all the sections. Importantly this must be
1631 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001632 if (Obj.SectionNames != nullptr)
1633 for (const auto &Section : Obj.sections()) {
1634 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001635 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001636
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001637 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001638
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001639 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001640 // Also, the output arch may not be the same as the input arch, so fix up
1641 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001642 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001643 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1644 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001645 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001646 Sec.accept(*SecSizer);
1647 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001648
1649 // The symbol table does not update all other sections on update. For
1650 // instance, symbol names are not added as new symbols are added. This means
1651 // that some sections, like .strtab, don't yet have their final size.
1652 if (Obj.SymbolTable != nullptr)
1653 Obj.SymbolTable->prepareForLayout();
1654
George Rimarfaf308b2019-03-18 14:27:41 +00001655 // Now that all strings are added we want to finalize string table builders,
1656 // because that affects section sizes which in turn affects section offsets.
1657 for (auto &Sec : Obj.sections())
1658 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
1659 StrTab->prepareForLayout();
1660
Petr Hosekc4df10e2017-08-04 21:09:26 +00001661 assignOffsets();
1662
Petr Hosekc4df10e2017-08-04 21:09:26 +00001663 // Finally now that all offsets and indexes have been set we can finalize any
1664 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001665 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1666 for (auto &Section : Obj.sections()) {
1667 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001668 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001669 if (WriteSectionHeaders)
1670 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1671 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001672 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001673
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001674 if (Error E = Buf.allocate(totalSize()))
1675 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001676 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001677 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001678}
1679
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001680Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001681 for (auto &Section : Obj.sections()) {
1682 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001683 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001684 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001685 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001686 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001687}
1688
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001689Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001690 // TODO: Create a filter range to construct OrderedSegments from so that this
1691 // code can be deduped with assignOffsets above. This should also solve the
1692 // todo below for LayoutSections.
1693 // We need a temporary list of segments that has a special order to it
1694 // so that we know that anytime ->ParentSegment is set that segment has
1695 // already had it's offset properly set. We only want to consider the segments
1696 // that will affect layout of allocated sections so we only add those.
1697 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001698 for (auto &Section : Obj.sections()) {
1699 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1700 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001701 }
1702 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001703
1704 // For binary output, we're going to use physical addresses instead of
1705 // virtual addresses, since a binary output is used for cases like ROM
1706 // loading and physical addresses are intended for ROM loading.
1707 // However, if no segment has a physical address, we'll fallback to using
1708 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001709 if (all_of(OrderedSegments,
1710 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1711 for (Segment *Seg : OrderedSegments)
1712 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001713
1714 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1715 compareSegmentsByPAddr);
1716
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001717 // Because we add a ParentSegment for each section we might have duplicate
1718 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1719 // would do very strange things.
1720 auto End =
1721 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1722 OrderedSegments.erase(End, std::end(OrderedSegments));
1723
Jake Ehrlich46814be2018-01-22 19:27:30 +00001724 uint64_t Offset = 0;
1725
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001726 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001727 // our layout algorithm to proceed as expected while not writing out the gap
1728 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001729 if (!OrderedSegments.empty()) {
1730 auto Seg = OrderedSegments[0];
1731 auto Sec = Seg->firstSection();
1732 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1733 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001734 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001735 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001736 // The PAddr needs to be increased to remove the gap before the first
1737 // section.
1738 Seg->PAddr += Diff;
1739 uint64_t LowestPAddr = Seg->PAddr;
1740 for (auto &Segment : OrderedSegments) {
1741 Segment->Offset = Segment->PAddr - LowestPAddr;
1742 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1743 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001744 }
1745
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001746 // TODO: generalize LayoutSections to take a range. Pass a special range
1747 // constructed from an iterator that skips values for which a predicate does
1748 // not hold. Then pass such a range to LayoutSections instead of constructing
1749 // AllocatedSections here.
1750 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001751 for (auto &Section : Obj.sections()) {
1752 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001753 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001754 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001755 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001756 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001757
1758 // Now that every section has been laid out we just need to compute the total
1759 // file size. This might not be the same as the offset returned by
1760 // LayoutSections, because we want to truncate the last segment to the end of
1761 // its last section, to match GNU objcopy's behaviour.
1762 TotalSize = 0;
1763 for (const auto &Section : AllocatedSections) {
1764 if (Section->Type != SHT_NOBITS)
1765 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1766 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001767
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001768 if (Error E = Buf.allocate(TotalSize))
1769 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001770 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001771 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001772}
1773
Jake Ehrlich76e91102018-01-25 22:46:17 +00001774template class ELFBuilder<ELF64LE>;
1775template class ELFBuilder<ELF64BE>;
1776template class ELFBuilder<ELF32LE>;
1777template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001778
Jake Ehrlich76e91102018-01-25 22:46:17 +00001779template class ELFWriter<ELF64LE>;
1780template class ELFWriter<ELF64BE>;
1781template class ELFWriter<ELF32LE>;
1782template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001783
1784} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001785} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001786} // end namespace llvm