blob: ead2a88943845bc663b8b0fe03f69ee7853b8bd1 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Petr Hosek05a04cb2017-08-01 00:33:58 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00008
Petr Hosek05a04cb2017-08-01 00:33:58 +00009#include "Object.h"
10#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/ADT/iterator_range.h"
16#include "llvm/BinaryFormat/ELF.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000017#include "llvm/MC/MCTargetOptions.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000018#include "llvm/Object/ELFObjectFile.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000019#include "llvm/Support/Compression.h"
Jordan Rupprecht971d47622019-02-01 15:20:36 +000020#include "llvm/Support/Errc.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000021#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/FileOutputBuffer.h"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000023#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000024#include <algorithm>
25#include <cstddef>
26#include <cstdint>
27#include <iterator>
Jordan Rupprecht52d57812019-02-21 16:45:42 +000028#include <unordered_set>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include <utility>
30#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000031
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000032namespace llvm {
33namespace objcopy {
34namespace elf {
35
Petr Hosek05a04cb2017-08-01 00:33:58 +000036using namespace object;
37using namespace ELF;
38
Jake Ehrlich76e91102018-01-25 22:46:17 +000039template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000040 uint8_t *B = Buf.getBufferStart();
41 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
42 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000043 Phdr.p_type = Seg.Type;
44 Phdr.p_flags = Seg.Flags;
45 Phdr.p_offset = Seg.Offset;
46 Phdr.p_vaddr = Seg.VAddr;
47 Phdr.p_paddr = Seg.PAddr;
48 Phdr.p_filesz = Seg.FileSize;
49 Phdr.p_memsz = Seg.MemSize;
50 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000051}
52
Jordan Rupprecht52d57812019-02-21 16:45:42 +000053Error SectionBase::removeSectionReferences(
54 function_ref<bool(const SectionBase *)> ToRemove) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +000055 return Error::success();
56}
57
58Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
59 return Error::success();
60}
61
Jake Ehrlichf5a43772017-09-25 20:37:28 +000062void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000063void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000064void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000065
Jake Ehrlich76e91102018-01-25 22:46:17 +000066template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000067 uint8_t *B = Buf.getBufferStart();
68 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000069 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000070 Shdr.sh_name = Sec.NameIndex;
71 Shdr.sh_type = Sec.Type;
72 Shdr.sh_flags = Sec.Flags;
73 Shdr.sh_addr = Sec.Addr;
74 Shdr.sh_offset = Sec.Offset;
75 Shdr.sh_size = Sec.Size;
76 Shdr.sh_link = Sec.Link;
77 Shdr.sh_info = Sec.Info;
78 Shdr.sh_addralign = Sec.Align;
79 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000080}
81
Jordan Rupprecht1f821762019-01-03 17:45:30 +000082template <class ELFT> void ELFSectionSizer<ELFT>::visit(Section &Sec) {}
83
84template <class ELFT>
85void ELFSectionSizer<ELFT>::visit(OwnedDataSection &Sec) {}
86
87template <class ELFT>
88void ELFSectionSizer<ELFT>::visit(StringTableSection &Sec) {}
89
90template <class ELFT>
91void ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &Sec) {}
92
93template <class ELFT>
94void ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
95 Sec.EntrySize = sizeof(Elf_Sym);
96 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000097 // Align to the largest field in Elf_Sym.
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +000098 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +000099}
100
101template <class ELFT>
102void ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
103 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
104 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +0000105 // Align to the largest field in Elf_Rel(a).
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000106 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000107}
108
109template <class ELFT>
110void ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &Sec) {}
111
112template <class ELFT> void ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {}
113
114template <class ELFT>
115void ELFSectionSizer<ELFT>::visit(SectionIndexSection &Sec) {}
116
117template <class ELFT>
118void ELFSectionSizer<ELFT>::visit(CompressedSection &Sec) {}
119
120template <class ELFT>
121void ELFSectionSizer<ELFT>::visit(DecompressedSection &Sec) {}
Jake Ehrlich76e91102018-01-25 22:46:17 +0000122
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000123void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
124 error("Cannot write symbol section index table '" + Sec.Name + "' ");
125}
126
Jake Ehrlich76e91102018-01-25 22:46:17 +0000127void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
128 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
129}
130
131void BinarySectionWriter::visit(const RelocationSection &Sec) {
132 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
133}
134
135void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000136 error("Cannot write '" + Sec.Name + "' out to binary");
137}
138
139void BinarySectionWriter::visit(const GroupSection &Sec) {
140 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000141}
142
143void SectionWriter::visit(const Section &Sec) {
144 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000145 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000146 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000147 llvm::copy(Sec.Contents, Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000148}
149
Jake Ehrlich76e91102018-01-25 22:46:17 +0000150void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
151
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000152void Section::accept(MutableSectionVisitor &Visitor) { Visitor.visit(*this); }
153
Jake Ehrlich76e91102018-01-25 22:46:17 +0000154void SectionWriter::visit(const OwnedDataSection &Sec) {
155 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000156 llvm::copy(Sec.Data, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000157}
158
Puyan Lotfiaf048642018-10-01 10:29:41 +0000159static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
160
161static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
162 return Data.size() > ZlibGnuMagic.size() &&
163 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
164}
165
166template <class ELFT>
167static std::tuple<uint64_t, uint64_t>
168getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
169 const bool IsGnuDebug = isDataGnuCompressed(Data);
170 const uint64_t DecompressedSize =
171 IsGnuDebug
172 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
173 Data.data() + ZlibGnuMagic.size()))
174 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
175 const uint64_t DecompressedAlign =
176 IsGnuDebug ? 1
177 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
178 ->ch_addralign;
179
180 return std::make_tuple(DecompressedSize, DecompressedAlign);
181}
182
183template <class ELFT>
184void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
Puyan Lotfiaf048642018-10-01 10:29:41 +0000185 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
186 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
187 : sizeof(Elf_Chdr_Impl<ELFT>);
188
189 StringRef CompressedContent(
190 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
191 Sec.OriginalData.size() - DataOffset);
192
193 SmallVector<char, 128> DecompressedContent;
194 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
195 static_cast<size_t>(Sec.Size)))
196 reportError(Sec.Name, std::move(E));
197
George Rimar281a5be2019-03-06 14:12:18 +0000198 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfiaf048642018-10-01 10:29:41 +0000199 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
200}
201
202void BinarySectionWriter::visit(const DecompressedSection &Sec) {
203 error("Cannot write compressed section '" + Sec.Name + "' ");
204}
205
206void DecompressedSection::accept(SectionVisitor &Visitor) const {
207 Visitor.visit(*this);
208}
209
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000210void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
211 Visitor.visit(*this);
212}
213
Jake Ehrlich76e91102018-01-25 22:46:17 +0000214void OwnedDataSection::accept(SectionVisitor &Visitor) const {
215 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000216}
217
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000218void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
219 Visitor.visit(*this);
220}
221
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000222void BinarySectionWriter::visit(const CompressedSection &Sec) {
223 error("Cannot write compressed section '" + Sec.Name + "' ");
224}
225
226template <class ELFT>
227void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
228 uint8_t *Buf = Out.getBufferStart();
229 Buf += Sec.Offset;
230
231 if (Sec.CompressionType == DebugCompressionType::None) {
232 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
233 return;
234 }
235
236 if (Sec.CompressionType == DebugCompressionType::GNU) {
237 const char *Magic = "ZLIB";
238 memcpy(Buf, Magic, strlen(Magic));
239 Buf += strlen(Magic);
240 const uint64_t DecompressedSize =
241 support::endian::read64be(&Sec.DecompressedSize);
242 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
243 Buf += sizeof(DecompressedSize);
244 } else {
245 Elf_Chdr_Impl<ELFT> Chdr;
246 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
247 Chdr.ch_size = Sec.DecompressedSize;
248 Chdr.ch_addralign = Sec.DecompressedAlign;
249 memcpy(Buf, &Chdr, sizeof(Chdr));
250 Buf += sizeof(Chdr);
251 }
252
253 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
254}
255
256CompressedSection::CompressedSection(const SectionBase &Sec,
257 DebugCompressionType CompressionType)
258 : SectionBase(Sec), CompressionType(CompressionType),
259 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000260 if (Error E = zlib::compress(
261 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
262 OriginalData.size()),
263 CompressedData))
264 reportError(Name, std::move(E));
265
266 size_t ChdrSize;
267 if (CompressionType == DebugCompressionType::GNU) {
268 Name = ".z" + Sec.Name.substr(1);
269 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
270 } else {
271 Flags |= ELF::SHF_COMPRESSED;
272 ChdrSize =
273 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
274 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
275 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
276 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
277 }
278 Size = ChdrSize + CompressedData.size();
279 Align = 8;
280}
281
Puyan Lotfiaf048642018-10-01 10:29:41 +0000282CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
283 uint64_t DecompressedSize,
284 uint64_t DecompressedAlign)
285 : CompressionType(DebugCompressionType::None),
286 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
287 OriginalData = CompressedData;
288}
289
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000290void CompressedSection::accept(SectionVisitor &Visitor) const {
291 Visitor.visit(*this);
292}
293
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000294void CompressedSection::accept(MutableSectionVisitor &Visitor) {
295 Visitor.visit(*this);
296}
297
Petr Hosek05a04cb2017-08-01 00:33:58 +0000298void StringTableSection::addString(StringRef Name) {
299 StrTabBuilder.add(Name);
300 Size = StrTabBuilder.getSize();
301}
302
303uint32_t StringTableSection::findIndex(StringRef Name) const {
304 return StrTabBuilder.getOffset(Name);
305}
306
307void StringTableSection::finalize() { StrTabBuilder.finalize(); }
308
Jake Ehrlich76e91102018-01-25 22:46:17 +0000309void SectionWriter::visit(const StringTableSection &Sec) {
310 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
311}
312
313void StringTableSection::accept(SectionVisitor &Visitor) const {
314 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000315}
316
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000317void StringTableSection::accept(MutableSectionVisitor &Visitor) {
318 Visitor.visit(*this);
319}
320
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000321template <class ELFT>
322void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
323 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000324 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000325 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000326}
327
328void SectionIndexSection::initialize(SectionTableRef SecTable) {
329 Size = 0;
330 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
331 Link,
332 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
333 "Link field value " + Twine(Link) + " in section " + Name +
334 " is not a symbol table"));
335 Symbols->setShndxTable(this);
336}
337
338void SectionIndexSection::finalize() { Link = Symbols->Index; }
339
340void SectionIndexSection::accept(SectionVisitor &Visitor) const {
341 Visitor.visit(*this);
342}
343
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000344void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
345 Visitor.visit(*this);
346}
347
Petr Hosekc1135772017-09-13 03:04:50 +0000348static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000349 switch (Index) {
350 case SHN_ABS:
351 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000352 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000353 }
Petr Hosekc1135772017-09-13 03:04:50 +0000354 if (Machine == EM_HEXAGON) {
355 switch (Index) {
356 case SHN_HEXAGON_SCOMMON:
357 case SHN_HEXAGON_SCOMMON_2:
358 case SHN_HEXAGON_SCOMMON_4:
359 case SHN_HEXAGON_SCOMMON_8:
360 return true;
361 }
362 }
363 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000364}
365
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000366// Large indexes force us to clarify exactly what this function should do. This
367// function should return the value that will appear in st_shndx when written
368// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000369uint16_t Symbol::getShndx() const {
370 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000371 if (DefinedIn->Index >= SHN_LORESERVE)
372 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000373 return DefinedIn->Index;
374 }
375 switch (ShndxType) {
376 // This means that we don't have a defined section but we do need to
377 // output a legitimate section index.
378 case SYMBOL_SIMPLE_INDEX:
379 return SHN_UNDEF;
380 case SYMBOL_ABS:
381 case SYMBOL_COMMON:
382 case SYMBOL_HEXAGON_SCOMMON:
383 case SYMBOL_HEXAGON_SCOMMON_2:
384 case SYMBOL_HEXAGON_SCOMMON_4:
385 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000386 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000387 return static_cast<uint16_t>(ShndxType);
388 }
389 llvm_unreachable("Symbol with invalid ShndxType encountered");
390}
391
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000392bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
393
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000394void SymbolTableSection::assignIndices() {
395 uint32_t Index = 0;
396 for (auto &Sym : Symbols)
397 Sym->Index = Index++;
398}
399
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000400void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000401 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000402 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000403 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000404 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000405 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000406 Sym.Binding = Bind;
407 Sym.Type = Type;
408 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000409 if (DefinedIn != nullptr)
410 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000411 if (DefinedIn == nullptr) {
412 if (Shndx >= SHN_LORESERVE)
413 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
414 else
415 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
416 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000417 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000418 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000419 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000420 Sym.Index = Symbols.size();
421 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
422 Size += this->EntrySize;
423}
424
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000425Error SymbolTableSection::removeSectionReferences(
426 function_ref<bool(const SectionBase *)> ToRemove) {
427 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000428 SectionIndexTable = nullptr;
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000429 if (ToRemove(SymbolNames))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000430 return createStringError(llvm::errc::invalid_argument,
431 "String table %s cannot be removed because it is "
432 "referenced by the symbol table %s",
433 SymbolNames->Name.data(), this->Name.data());
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000434 return removeSymbols(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000435 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000436}
437
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000438void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000439 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
440 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000441 std::stable_partition(
442 std::begin(Symbols), std::end(Symbols),
443 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000444 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000445}
446
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000447Error SymbolTableSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000448 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000449 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000450 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000451 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
452 std::end(Symbols));
453 Size = Symbols.size() * EntrySize;
454 assignIndices();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000455 return Error::success();
Paul Semel41695f82018-05-02 20:19:22 +0000456}
457
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000458void SymbolTableSection::initialize(SectionTableRef SecTable) {
459 Size = 0;
460 setStrTab(SecTable.getSectionOfType<StringTableSection>(
461 Link,
462 "Symbol table has link index of " + Twine(Link) +
463 " which is not a valid index",
464 "Symbol table has link index of " + Twine(Link) +
465 " which is not a string table"));
466}
467
Petr Hosek79cee9e2017-08-29 02:12:03 +0000468void SymbolTableSection::finalize() {
469 // Make sure SymbolNames is finalized before getting name indexes.
470 SymbolNames->finalize();
471
472 uint32_t MaxLocalIndex = 0;
473 for (auto &Sym : Symbols) {
474 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
475 if (Sym->Binding == STB_LOCAL)
476 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
477 }
478 // Now we need to set the Link and Info fields.
479 Link = SymbolNames->Index;
480 Info = MaxLocalIndex + 1;
481}
482
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000483void SymbolTableSection::prepareForLayout() {
484 // Add all potential section indexes before file layout so that the section
485 // index section has the approprite size.
486 if (SectionIndexTable != nullptr) {
487 for (const auto &Sym : Symbols) {
488 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
489 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
490 else
491 SectionIndexTable->addIndex(SHN_UNDEF);
492 }
493 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000494 // Add all of our strings to SymbolNames so that SymbolNames has the right
495 // size before layout is decided.
496 for (auto &Sym : Symbols)
497 SymbolNames->addString(Sym->Name);
498}
499
500const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
501 if (Symbols.size() <= Index)
502 error("Invalid symbol index: " + Twine(Index));
503 return Symbols[Index].get();
504}
505
Paul Semel99dda0b2018-05-25 11:01:25 +0000506Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
507 return const_cast<Symbol *>(
508 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
509}
510
Petr Hosek79cee9e2017-08-29 02:12:03 +0000511template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000512void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000513 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000514 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000515 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000516 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000517 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000518 Sym->st_name = Symbol->NameIndex;
519 Sym->st_value = Symbol->Value;
520 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000521 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000522 Sym->setBinding(Symbol->Binding);
523 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000524 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000525 ++Sym;
526 }
527}
528
Jake Ehrlich76e91102018-01-25 22:46:17 +0000529void SymbolTableSection::accept(SectionVisitor &Visitor) const {
530 Visitor.visit(*this);
531}
532
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000533void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
534 Visitor.visit(*this);
535}
536
George Rimar79fb8582019-02-27 11:18:27 +0000537Error RelocationSection::removeSectionReferences(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000538 function_ref<bool(const SectionBase *)> ToRemove) {
539 if (ToRemove(Symbols))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000540 return createStringError(llvm::errc::invalid_argument,
541 "Symbol table %s cannot be removed because it is "
542 "referenced by the relocation section %s.",
543 Symbols->Name.data(), this->Name.data());
George Rimar79fb8582019-02-27 11:18:27 +0000544
545 for (const Relocation &R : Relocations) {
546 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
547 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000548 return createStringError(llvm::errc::invalid_argument,
549 "Section %s can't be removed: (%s+0x%" PRIx64
550 ") has relocation against symbol '%s'",
551 R.RelocSymbol->DefinedIn->Name.data(),
552 SecToApplyRel->Name.data(), R.Offset,
553 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000554 }
555
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000556 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000557}
558
559template <class SymTabType>
560void RelocSectionWithSymtabBase<SymTabType>::initialize(
561 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000562 if (Link != SHN_UNDEF)
563 setSymTab(SecTable.getSectionOfType<SymTabType>(
564 Link,
565 "Link field value " + Twine(Link) + " in section " + Name +
566 " is invalid",
567 "Link field value " + Twine(Link) + " in section " + Name +
568 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000569
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000570 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000571 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
572 " in section " + Name +
573 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000574 else
575 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000576}
577
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000578template <class SymTabType>
579void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000580 this->Link = Symbols ? Symbols->Index : 0;
581
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000582 if (SecToApplyRel != nullptr)
583 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000584}
585
586template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000587static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000588
589template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000590static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000591 Rela.r_addend = Addend;
592}
593
Jake Ehrlich76e91102018-01-25 22:46:17 +0000594template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000595static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000596 for (const auto &Reloc : Relocations) {
597 Buf->r_offset = Reloc.Offset;
598 setAddend(*Buf, Reloc.Addend);
599 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
600 ++Buf;
601 }
602}
603
604template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000605void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
606 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
607 if (Sec.Type == SHT_REL)
608 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000609 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000610 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000611}
612
Jake Ehrlich76e91102018-01-25 22:46:17 +0000613void RelocationSection::accept(SectionVisitor &Visitor) const {
614 Visitor.visit(*this);
615}
616
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000617void RelocationSection::accept(MutableSectionVisitor &Visitor) {
618 Visitor.visit(*this);
619}
620
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000621Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000622 function_ref<bool(const Symbol &)> ToRemove) {
623 for (const Relocation &Reloc : Relocations)
624 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000625 return createStringError(
626 llvm::errc::invalid_argument,
627 "not stripping symbol '%s' because it is named in a relocation.",
628 Reloc.RelocSymbol->Name.data());
629 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000630}
631
Paul Semel99dda0b2018-05-25 11:01:25 +0000632void RelocationSection::markSymbols() {
633 for (const Relocation &Reloc : Relocations)
634 Reloc.RelocSymbol->Referenced = true;
635}
636
Jake Ehrlich76e91102018-01-25 22:46:17 +0000637void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000638 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000639 Out.getBufferStart() + Sec.Offset);
640}
641
642void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
643 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000644}
645
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000646void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
647 Visitor.visit(*this);
648}
649
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000650Error Section::removeSectionReferences(
651 function_ref<bool(const SectionBase *)> ToRemove) {
652 if (ToRemove(LinkSection))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000653 return createStringError(llvm::errc::invalid_argument,
654 "Section %s cannot be removed because it is "
655 "referenced by the section %s",
656 LinkSection->Name.data(), this->Name.data());
657 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000658}
659
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000660void GroupSection::finalize() {
661 this->Info = Sym->Index;
662 this->Link = SymTab->Index;
663}
664
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000665Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
666 if (ToRemove(*Sym))
667 return createStringError(llvm::errc::invalid_argument,
668 "Symbol %s cannot be removed because it is "
669 "referenced by the section %s[%d].",
670 Sym->Name.data(), this->Name.data(), this->Index);
671 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000672}
673
Paul Semel99dda0b2018-05-25 11:01:25 +0000674void GroupSection::markSymbols() {
675 if (Sym)
676 Sym->Referenced = true;
677}
678
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000679void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000680 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000681 LinkSection =
682 SecTable.getSection(Link, "Link field value " + Twine(Link) +
683 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000684 if (LinkSection->Type == ELF::SHT_SYMTAB)
685 LinkSection = nullptr;
686 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000687}
688
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000689void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000690
Jake Ehrlich76e91102018-01-25 22:46:17 +0000691void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000692 FileName = sys::path::filename(File);
693 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000694 // followed by a null terminator and then the CRC32 of the file. The CRC32
695 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
696 // byte, and then finally push the size to alignment and add 4.
697 Size = alignTo(FileName.size() + 1, 4) + 4;
698 // The CRC32 will only be aligned if we align the whole section.
699 Align = 4;
700 Type = ELF::SHT_PROGBITS;
701 Name = ".gnu_debuglink";
702 // For sections not found in segments, OriginalOffset is only used to
703 // establish the order that sections should go in. By using the maximum
704 // possible offset we cause this section to wind up at the end.
705 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000706 JamCRC CRC;
707 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000708 // The CRC32 value needs to be complemented because the JamCRC dosn't
709 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
710 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000711 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000712}
713
Jake Ehrlich76e91102018-01-25 22:46:17 +0000714GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000715 // Read in the file to compute the CRC of it.
716 auto DebugOrErr = MemoryBuffer::getFile(File);
717 if (!DebugOrErr)
718 error("'" + File + "': " + DebugOrErr.getError().message());
719 auto Debug = std::move(*DebugOrErr);
720 init(File, Debug->getBuffer());
721}
722
723template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000724void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
725 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000726 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000727 Elf_Word *CRC =
728 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
729 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000730 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000731}
732
733void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
734 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000735}
736
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000737void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
738 Visitor.visit(*this);
739}
740
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000741template <class ELFT>
742void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
743 ELF::Elf32_Word *Buf =
744 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
745 *Buf++ = Sec.FlagWord;
746 for (const auto *S : Sec.GroupMembers)
747 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
748}
749
750void GroupSection::accept(SectionVisitor &Visitor) const {
751 Visitor.visit(*this);
752}
753
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000754void GroupSection::accept(MutableSectionVisitor &Visitor) {
755 Visitor.visit(*this);
756}
757
Petr Hosek05a04cb2017-08-01 00:33:58 +0000758// Returns true IFF a section is wholly inside the range of a segment
759static bool sectionWithinSegment(const SectionBase &Section,
760 const Segment &Segment) {
761 // If a section is empty it should be treated like it has a size of 1. This is
762 // to clarify the case when an empty section lies on a boundary between two
763 // segments and ensures that the section "belongs" to the second segment and
764 // not the first.
765 uint64_t SecSize = Section.Size ? Section.Size : 1;
766 return Segment.Offset <= Section.OriginalOffset &&
767 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
768}
769
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000770// Returns true IFF a segment's original offset is inside of another segment's
771// range.
772static bool segmentOverlapsSegment(const Segment &Child,
773 const Segment &Parent) {
774
775 return Parent.OriginalOffset <= Child.OriginalOffset &&
776 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
777}
778
Jake Ehrlich46814be2018-01-22 19:27:30 +0000779static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000780 // Any segment without a parent segment should come before a segment
781 // that has a parent segment.
782 if (A->OriginalOffset < B->OriginalOffset)
783 return true;
784 if (A->OriginalOffset > B->OriginalOffset)
785 return false;
786 return A->Index < B->Index;
787}
788
Jake Ehrlich46814be2018-01-22 19:27:30 +0000789static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
790 if (A->PAddr < B->PAddr)
791 return true;
792 if (A->PAddr > B->PAddr)
793 return false;
794 return A->Index < B->Index;
795}
796
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000797void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000798 Obj->Flags = 0x0;
799 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000800 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000801 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000802 Obj->Entry = 0x0;
803 Obj->Machine = EMachine;
804 Obj->Version = 1;
805}
806
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000807void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000808
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000809StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000810 auto &StrTab = Obj->addSection<StringTableSection>();
811 StrTab.Name = ".strtab";
812
813 Obj->SectionNames = &StrTab;
814 return &StrTab;
815}
816
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000817SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000818 auto &SymTab = Obj->addSection<SymbolTableSection>();
819
820 SymTab.Name = ".symtab";
821 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000822
823 // The symbol table always needs a null symbol
824 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
825
826 Obj->SymbolTable = &SymTab;
827 return &SymTab;
828}
829
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000830void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000831 auto Data = ArrayRef<uint8_t>(
832 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
833 MemBuf->getBufferSize());
834 auto &DataSection = Obj->addSection<Section>(Data);
835 DataSection.Name = ".data";
836 DataSection.Type = ELF::SHT_PROGBITS;
837 DataSection.Size = Data.size();
838 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
839
840 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
841 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000842 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000843 Twine Prefix = Twine("_binary_") + SanitizedFilename;
844
845 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
846 /*Value=*/0, STV_DEFAULT, 0, 0);
847 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
848 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
849 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
850 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
851}
852
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000853void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000854 for (auto &Section : Obj->sections()) {
855 Section.initialize(Obj->sections());
856 }
857}
858
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000859std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000860 initFileHeader();
861 initHeaderSegment();
862 StringTableSection *StrTab = addStrTab();
863 SymbolTableSection *SymTab = addSymTab(StrTab);
864 initSections();
865 addData(SymTab);
866
867 return std::move(Obj);
868}
869
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000870template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000871 for (auto &Parent : Obj.segments()) {
872 // Every segment will overlap with itself but we don't want a segment to
873 // be it's own parent so we avoid that situation.
874 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
875 // We want a canonical "most parental" segment but this requires
876 // inspecting the ParentSegment.
877 if (compareSegmentsByOffset(&Parent, &Child))
878 if (Child.ParentSegment == nullptr ||
879 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
880 Child.ParentSegment = &Parent;
881 }
882 }
883 }
884}
885
Jake Ehrlich76e91102018-01-25 22:46:17 +0000886template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000887 uint32_t Index = 0;
888 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000889 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
890 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000891 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000892 Seg.Type = Phdr.p_type;
893 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000894 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000895 Seg.Offset = Phdr.p_offset;
896 Seg.VAddr = Phdr.p_vaddr;
897 Seg.PAddr = Phdr.p_paddr;
898 Seg.FileSize = Phdr.p_filesz;
899 Seg.MemSize = Phdr.p_memsz;
900 Seg.Align = Phdr.p_align;
901 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000902 for (auto &Section : Obj.sections()) {
903 if (sectionWithinSegment(Section, Seg)) {
904 Seg.addSection(&Section);
905 if (!Section.ParentSegment ||
906 Section.ParentSegment->Offset > Seg.Offset) {
907 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000908 }
909 }
910 }
911 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000912
913 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000914 ElfHdr.Index = Index++;
915
916 const auto &Ehdr = *ElfFile.getHeader();
917 auto &PrHdr = Obj.ProgramHdrSegment;
918 PrHdr.Type = PT_PHDR;
919 PrHdr.Flags = 0;
920 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
921 // Whereas this works automatically for ElfHdr, here OriginalOffset is
922 // always non-zero and to ensure the equation we assign the same value to
923 // VAddr as well.
924 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
925 PrHdr.PAddr = 0;
926 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000927 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000928 PrHdr.Align = sizeof(Elf_Addr);
929 PrHdr.Index = Index++;
930
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000931 // Now we do an O(n^2) loop through the segments in order to match up
932 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000933 for (auto &Child : Obj.segments())
934 setParentSegment(Child);
935 setParentSegment(ElfHdr);
936 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000937}
938
939template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000940void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
941 auto SecTable = Obj.sections();
942 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
943 GroupSec->Link,
944 "Link field value " + Twine(GroupSec->Link) + " in section " +
945 GroupSec->Name + " is invalid",
946 "Link field value " + Twine(GroupSec->Link) + " in section " +
947 GroupSec->Name + " is not a symbol table");
948 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
949 if (!Sym)
950 error("Info field value " + Twine(GroupSec->Info) + " in section " +
951 GroupSec->Name + " is not a valid symbol index");
952 GroupSec->setSymTab(SymTab);
953 GroupSec->setSymbol(Sym);
954 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
955 GroupSec->Contents.empty())
956 error("The content of the section " + GroupSec->Name + " is malformed");
957 const ELF::Elf32_Word *Word =
958 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
959 const ELF::Elf32_Word *End =
960 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
961 GroupSec->setFlagWord(*Word++);
962 for (; Word != End; ++Word) {
963 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
964 GroupSec->addMember(SecTable.getSection(
965 Index, "Group member index " + Twine(Index) + " in section " +
966 GroupSec->Name + " is invalid"));
967 }
968}
969
970template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000971void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000972 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
973 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000974 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000975
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000976 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
977 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000978 SectionBase *DefSection = nullptr;
979 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000980
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000981 if (Sym.st_shndx == SHN_XINDEX) {
982 if (SymTab->getShndxTable() == nullptr)
983 error("Symbol '" + Name +
984 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
985 if (ShndxData.data() == nullptr) {
986 const Elf_Shdr &ShndxSec =
987 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
988 ShndxData = unwrapOrError(
989 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
990 if (ShndxData.size() != Symbols.size())
991 error("Symbol section index table does not have the same number of "
992 "entries as the symbol table.");
993 }
994 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
995 DefSection = Obj.sections().getSection(
996 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000997 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000998 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000999 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001000 error(
1001 "Symbol '" + Name +
1002 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1003 Twine(Sym.st_shndx));
1004 }
1005 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001006 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001007 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001008 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001009 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001010 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001011
Petr Hosek79cee9e2017-08-29 02:12:03 +00001012 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001013 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001014 }
1015}
1016
1017template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001018static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1019
1020template <class ELFT>
1021static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1022 ToSet = Rela.r_addend;
1023}
1024
Jake Ehrlich76e91102018-01-25 22:46:17 +00001025template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001026static void initRelocations(RelocationSection *Relocs,
1027 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001028 for (const auto &Rel : RelRange) {
1029 Relocation ToAdd;
1030 ToAdd.Offset = Rel.r_offset;
1031 getAddend(ToAdd.Addend, Rel);
1032 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001033 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001034 Relocs->addRelocation(ToAdd);
1035 }
1036}
1037
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001038SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001039 if (Index == SHN_UNDEF || Index > Sections.size())
1040 error(ErrMsg);
1041 return Sections[Index - 1].get();
1042}
1043
1044template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001045T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001046 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001047 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001048 return Sec;
1049 error(TypeErrMsg);
1050}
1051
Petr Hosekd7df9b22017-09-06 23:41:02 +00001052template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001053SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001054 ArrayRef<uint8_t> Data;
1055 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001056 case SHT_REL:
1057 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001058 if (Shdr.sh_flags & SHF_ALLOC) {
1059 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001060 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001061 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001062 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001063 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001064 // If a string table is allocated we don't want to mess with it. That would
1065 // mean altering the memory image. There are no special link types or
1066 // anything so we can just use a Section.
1067 if (Shdr.sh_flags & SHF_ALLOC) {
1068 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001069 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001070 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001071 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001072 case SHT_HASH:
1073 case SHT_GNU_HASH:
1074 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1075 // Because of this we don't need to mess with the hash tables either.
1076 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001077 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001078 case SHT_GROUP:
1079 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1080 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001081 case SHT_DYNSYM:
1082 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001083 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001084 case SHT_DYNAMIC:
1085 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001086 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001087 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001088 auto &SymTab = Obj.addSection<SymbolTableSection>();
1089 Obj.SymbolTable = &SymTab;
1090 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001091 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001092 case SHT_SYMTAB_SHNDX: {
1093 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1094 Obj.SectionIndexTable = &ShndxSection;
1095 return ShndxSection;
1096 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001097 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001098 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001099 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001100 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001101
George Rimarf2eb8ca2019-03-06 14:01:54 +00001102 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1103 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001104 uint64_t DecompressedSize, DecompressedAlign;
1105 std::tie(DecompressedSize, DecompressedAlign) =
1106 getDecompressedSizeAndAlignment<ELFT>(Data);
1107 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1108 DecompressedAlign);
1109 }
1110
Jake Ehrlich76e91102018-01-25 22:46:17 +00001111 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001112 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001113 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001114}
1115
Jake Ehrlich76e91102018-01-25 22:46:17 +00001116template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001117 uint32_t Index = 0;
1118 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1119 if (Index == 0) {
1120 ++Index;
1121 continue;
1122 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001123 auto &Sec = makeSection(Shdr);
1124 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1125 Sec.Type = Shdr.sh_type;
1126 Sec.Flags = Shdr.sh_flags;
1127 Sec.Addr = Shdr.sh_addr;
1128 Sec.Offset = Shdr.sh_offset;
1129 Sec.OriginalOffset = Shdr.sh_offset;
1130 Sec.Size = Shdr.sh_size;
1131 Sec.Link = Shdr.sh_link;
1132 Sec.Info = Shdr.sh_info;
1133 Sec.Align = Shdr.sh_addralign;
1134 Sec.EntrySize = Shdr.sh_entsize;
1135 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001136 Sec.OriginalData =
1137 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1138 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001139 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001140
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001141 // If a section index table exists we'll need to initialize it before we
1142 // initialize the symbol table because the symbol table might need to
1143 // reference it.
1144 if (Obj.SectionIndexTable)
1145 Obj.SectionIndexTable->initialize(Obj.sections());
1146
Petr Hosek79cee9e2017-08-29 02:12:03 +00001147 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001148 // details about symbol tables. We need the symbol table filled out before
1149 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001150 if (Obj.SymbolTable) {
1151 Obj.SymbolTable->initialize(Obj.sections());
1152 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001153 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001154
1155 // Now that all sections and symbols have been added we can add
1156 // relocations that reference symbols and set the link and info fields for
1157 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001158 for (auto &Section : Obj.sections()) {
1159 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001160 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001161 Section.initialize(Obj.sections());
1162 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001163 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1164 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001165 initRelocations(RelSec, Obj.SymbolTable,
1166 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001167 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001168 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001169 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001170 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1171 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001172 }
1173 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001174}
1175
Jake Ehrlich76e91102018-01-25 22:46:17 +00001176template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001177 const auto &Ehdr = *ElfFile.getHeader();
1178
George Rimar4ded7732018-12-20 10:51:42 +00001179 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1180 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181 Obj.Type = Ehdr.e_type;
1182 Obj.Machine = Ehdr.e_machine;
1183 Obj.Version = Ehdr.e_version;
1184 Obj.Entry = Ehdr.e_entry;
1185 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001186
Jake Ehrlich76e91102018-01-25 22:46:17 +00001187 readSectionHeaders();
1188 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001189
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001190 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1191 if (ShstrIndex == SHN_XINDEX)
1192 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1193
Jake Ehrlich76e91102018-01-25 22:46:17 +00001194 Obj.SectionNames =
1195 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001196 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001197 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001198 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001199 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001200 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001201}
1202
Jake Ehrlich76e91102018-01-25 22:46:17 +00001203// A generic size function which computes sizes of any random access range.
1204template <class R> size_t size(R &&Range) {
1205 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1206}
1207
1208Writer::~Writer() {}
1209
1210Reader::~Reader() {}
1211
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001212std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001213 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001214}
1215
1216std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001217 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001218 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1219 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001220 Builder.build();
1221 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001222 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1223 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001224 Builder.build();
1225 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001226 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1227 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001228 Builder.build();
1229 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001230 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1231 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001232 Builder.build();
1233 return Obj;
1234 }
1235 error("Invalid file type");
1236}
1237
1238template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001239 uint8_t *B = Buf.getBufferStart();
1240 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001241 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1242 Ehdr.e_ident[EI_MAG0] = 0x7f;
1243 Ehdr.e_ident[EI_MAG1] = 'E';
1244 Ehdr.e_ident[EI_MAG2] = 'L';
1245 Ehdr.e_ident[EI_MAG3] = 'F';
1246 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1247 Ehdr.e_ident[EI_DATA] =
1248 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1249 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001250 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1251 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001252
Jake Ehrlich76e91102018-01-25 22:46:17 +00001253 Ehdr.e_type = Obj.Type;
1254 Ehdr.e_machine = Obj.Machine;
1255 Ehdr.e_version = Obj.Version;
1256 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001257 // We have to use the fully-qualified name llvm::size
1258 // since some compilers complain on ambiguous resolution.
1259 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001260 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1261 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001262 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001263 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001264 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1265 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001266 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001267 // """
1268 // If the number of sections is greater than or equal to
1269 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1270 // number of section header table entries is contained in the sh_size field
1271 // of the section header at index 0.
1272 // """
1273 auto Shnum = size(Obj.sections()) + 1;
1274 if (Shnum >= SHN_LORESERVE)
1275 Ehdr.e_shnum = 0;
1276 else
1277 Ehdr.e_shnum = Shnum;
1278 // """
1279 // If the section name string table section index is greater than or equal
1280 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1281 // and the actual index of the section name string table section is
1282 // contained in the sh_link field of the section header at index 0.
1283 // """
1284 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1285 Ehdr.e_shstrndx = SHN_XINDEX;
1286 else
1287 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001288 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001289 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001290 Ehdr.e_shoff = 0;
1291 Ehdr.e_shnum = 0;
1292 Ehdr.e_shstrndx = 0;
1293 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001294}
1295
Jake Ehrlich76e91102018-01-25 22:46:17 +00001296template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1297 for (auto &Seg : Obj.segments())
1298 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001299}
1300
Jake Ehrlich76e91102018-01-25 22:46:17 +00001301template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001302 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001303 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001304 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001305 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001306 Shdr.sh_name = 0;
1307 Shdr.sh_type = SHT_NULL;
1308 Shdr.sh_flags = 0;
1309 Shdr.sh_addr = 0;
1310 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001311 // See writeEhdr for why we do this.
1312 uint64_t Shnum = size(Obj.sections()) + 1;
1313 if (Shnum >= SHN_LORESERVE)
1314 Shdr.sh_size = Shnum;
1315 else
1316 Shdr.sh_size = 0;
1317 // See writeEhdr for why we do this.
1318 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1319 Shdr.sh_link = Obj.SectionNames->Index;
1320 else
1321 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001322 Shdr.sh_info = 0;
1323 Shdr.sh_addralign = 0;
1324 Shdr.sh_entsize = 0;
1325
Jake Ehrlich76e91102018-01-25 22:46:17 +00001326 for (auto &Sec : Obj.sections())
1327 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001328}
1329
Jake Ehrlich76e91102018-01-25 22:46:17 +00001330template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1331 for (auto &Sec : Obj.sections())
1332 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001333}
1334
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001335Error Object::removeSections(
1336 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001337
1338 auto Iter = std::stable_partition(
1339 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1340 if (ToRemove(*Sec))
1341 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001342 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1343 if (auto ToRelSec = RelSec->getSection())
1344 return !ToRemove(*ToRelSec);
1345 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001346 return true;
1347 });
1348 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1349 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001350 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001351 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001352 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1353 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001354 // Now make sure there are no remaining references to the sections that will
1355 // be removed. Sometimes it is impossible to remove a reference so we emit
1356 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001357 std::unordered_set<const SectionBase *> RemoveSections;
1358 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001359 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1360 for (auto &Segment : Segments)
1361 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001362 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001363 }
George Rimar79fb8582019-02-27 11:18:27 +00001364
1365 // For each section that remains alive, we want to remove the dead references.
1366 // This either might update the content of the section (e.g. remove symbols
1367 // from symbol table that belongs to removed section) or trigger an error if
1368 // a live section critically depends on a section being removed somehow
1369 // (e.g. the removed section is referenced by a relocation).
1370 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001371 if (Error E = KeepSec->removeSectionReferences(
1372 [&RemoveSections](const SectionBase *Sec) {
1373 return RemoveSections.find(Sec) != RemoveSections.end();
1374 }))
1375 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001376 }
1377
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001378 // Now finally get rid of them all togethor.
1379 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001380 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001381}
1382
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001383Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1384 if (SymbolTable)
1385 for (const SecPtr &Sec : Sections)
1386 if (Error E = Sec->removeSymbols(ToRemove))
1387 return E;
1388 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001389}
1390
Jake Ehrlich76e91102018-01-25 22:46:17 +00001391void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001392 // Put all sections in offset order. Maintain the ordering as closely as
1393 // possible while meeting that demand however.
1394 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1395 return A->OriginalOffset < B->OriginalOffset;
1396 };
1397 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1398 CompareSections);
1399}
1400
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001401static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1402 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1403 if (Align == 0)
1404 Align = 1;
1405 auto Diff =
1406 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1407 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1408 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1409 if (Diff < 0)
1410 Diff += Align;
1411 return Offset + Diff;
1412}
1413
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001414// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001415static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001416 std::stable_sort(std::begin(Segments), std::end(Segments),
1417 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001418}
1419
1420// This function finds a consistent layout for a list of segments starting from
1421// an Offset. It assumes that Segments have been sorted by OrderSegments and
1422// returns an Offset one past the end of the last segment.
1423static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1424 uint64_t Offset) {
1425 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001426 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001427 // The only way a segment should move is if a section was between two
1428 // segments and that section was removed. If that section isn't in a segment
1429 // then it's acceptable, but not ideal, to simply move it to after the
1430 // segments. So we can simply layout segments one after the other accounting
1431 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001432 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001433 // We assume that segments have been ordered by OriginalOffset and Index
1434 // such that a parent segment will always come before a child segment in
1435 // OrderedSegments. This means that the Offset of the ParentSegment should
1436 // already be set and we can set our offset relative to it.
1437 if (Segment->ParentSegment != nullptr) {
1438 auto Parent = Segment->ParentSegment;
1439 Segment->Offset =
1440 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1441 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001442 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001443 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001444 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001445 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001446 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001447 return Offset;
1448}
1449
1450// This function finds a consistent layout for a list of sections. It assumes
1451// that the ->ParentSegment of each section has already been laid out. The
1452// supplied starting Offset is used for the starting offset of any section that
1453// does not have a ParentSegment. It returns either the offset given if all
1454// sections had a ParentSegment or an offset one past the last section if there
1455// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001456template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001457static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001458 // Now the offset of every segment has been set we can assign the offsets
1459 // of each section. For sections that are covered by a segment we should use
1460 // the segment's original offset and the section's original offset to compute
1461 // the offset from the start of the segment. Using the offset from the start
1462 // of the segment we can assign a new offset to the section. For sections not
1463 // covered by segments we can just bump Offset to the next valid location.
1464 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001465 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001466 Section.Index = Index++;
1467 if (Section.ParentSegment != nullptr) {
1468 auto Segment = *Section.ParentSegment;
1469 Section.Offset =
1470 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001471 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001472 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1473 Section.Offset = Offset;
1474 if (Section.Type != SHT_NOBITS)
1475 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001476 }
1477 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001478 return Offset;
1479}
Petr Hosek3f383832017-08-26 01:32:20 +00001480
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001481template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1482 auto &ElfHdr = Obj.ElfHdrSegment;
1483 ElfHdr.Type = PT_PHDR;
1484 ElfHdr.Flags = 0;
1485 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1486 ElfHdr.VAddr = 0;
1487 ElfHdr.PAddr = 0;
1488 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1489 ElfHdr.Align = 0;
1490}
1491
Jake Ehrlich76e91102018-01-25 22:46:17 +00001492template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001493 // We need a temporary list of segments that has a special order to it
1494 // so that we know that anytime ->ParentSegment is set that segment has
1495 // already had its offset properly set.
1496 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001497 for (auto &Segment : Obj.segments())
1498 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001499 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1500 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001501 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001502 // Offset is used as the start offset of the first segment to be laid out.
1503 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1504 // we start at offset 0.
1505 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001506 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001507 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001508 // If we need to write the section header table out then we need to align the
1509 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001510 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001511 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001512 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001513}
1514
Jake Ehrlich76e91102018-01-25 22:46:17 +00001515template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001516 // We already have the section header offset so we can calculate the total
1517 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001518 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1519 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001520 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001521}
1522
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001523template <class ELFT> Error ELFWriter<ELFT>::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001524 writeEhdr();
1525 writePhdrs();
1526 writeSectionData();
1527 if (WriteSectionHeaders)
1528 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001529 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001530}
1531
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001532template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001533 // It could happen that SectionNames has been removed and yet the user wants
1534 // a section header table output. We need to throw an error if a user tries
1535 // to do that.
1536 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001537 return createStringError(llvm::errc::invalid_argument,
1538 "Cannot write section header table because "
1539 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001540
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001541 Obj.sortSections();
1542
1543 // We need to assign indexes before we perform layout because we need to know
1544 // if we need large indexes or not. We can assign indexes first and check as
1545 // we go to see if we will actully need large indexes.
1546 bool NeedsLargeIndexes = false;
1547 if (size(Obj.sections()) >= SHN_LORESERVE) {
1548 auto Sections = Obj.sections();
1549 NeedsLargeIndexes =
1550 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1551 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1552 // TODO: handle case where only one section needs the large index table but
1553 // only needs it because the large index table hasn't been removed yet.
1554 }
1555
1556 if (NeedsLargeIndexes) {
1557 // This means we definitely need to have a section index table but if we
1558 // already have one then we should use it instead of making a new one.
1559 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1560 // Addition of a section to the end does not invalidate the indexes of
1561 // other sections and assigns the correct index to the new section.
1562 auto &Shndx = Obj.addSection<SectionIndexSection>();
1563 Obj.SymbolTable->setShndxTable(&Shndx);
1564 Shndx.setSymTab(Obj.SymbolTable);
1565 }
1566 } else {
1567 // Since we don't need SectionIndexTable we should remove it and all
1568 // references to it.
1569 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001570 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1571 return &Sec == Obj.SectionIndexTable;
1572 }))
1573 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001574 }
1575 }
1576
1577 // Make sure we add the names of all the sections. Importantly this must be
1578 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001579 if (Obj.SectionNames != nullptr)
1580 for (const auto &Section : Obj.sections()) {
1581 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001582 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001583
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001584 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001585
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001586 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001587 // Also, the output arch may not be the same as the input arch, so fix up
1588 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001589 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001590 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1591 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001592 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001593 Sec.accept(*SecSizer);
1594 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001595
1596 // The symbol table does not update all other sections on update. For
1597 // instance, symbol names are not added as new symbols are added. This means
1598 // that some sections, like .strtab, don't yet have their final size.
1599 if (Obj.SymbolTable != nullptr)
1600 Obj.SymbolTable->prepareForLayout();
1601
Petr Hosekc4df10e2017-08-04 21:09:26 +00001602 assignOffsets();
1603
1604 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001605 if (Obj.SectionNames != nullptr)
1606 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001607 // Finally now that all offsets and indexes have been set we can finalize any
1608 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001609 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1610 for (auto &Section : Obj.sections()) {
1611 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001612 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001613 if (WriteSectionHeaders)
1614 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1615 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001616 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001617
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001618 if (Error E = Buf.allocate(totalSize()))
1619 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001620 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001621 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001622}
1623
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001624Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001625 for (auto &Section : Obj.sections()) {
1626 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001627 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001628 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001629 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001630 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001631}
1632
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001633Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001634 // TODO: Create a filter range to construct OrderedSegments from so that this
1635 // code can be deduped with assignOffsets above. This should also solve the
1636 // todo below for LayoutSections.
1637 // We need a temporary list of segments that has a special order to it
1638 // so that we know that anytime ->ParentSegment is set that segment has
1639 // already had it's offset properly set. We only want to consider the segments
1640 // that will affect layout of allocated sections so we only add those.
1641 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001642 for (auto &Section : Obj.sections()) {
1643 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1644 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001645 }
1646 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001647
1648 // For binary output, we're going to use physical addresses instead of
1649 // virtual addresses, since a binary output is used for cases like ROM
1650 // loading and physical addresses are intended for ROM loading.
1651 // However, if no segment has a physical address, we'll fallback to using
1652 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001653 if (all_of(OrderedSegments,
1654 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1655 for (Segment *Seg : OrderedSegments)
1656 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001657
1658 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1659 compareSegmentsByPAddr);
1660
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001661 // Because we add a ParentSegment for each section we might have duplicate
1662 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1663 // would do very strange things.
1664 auto End =
1665 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1666 OrderedSegments.erase(End, std::end(OrderedSegments));
1667
Jake Ehrlich46814be2018-01-22 19:27:30 +00001668 uint64_t Offset = 0;
1669
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001670 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001671 // our layout algorithm to proceed as expected while not writing out the gap
1672 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001673 if (!OrderedSegments.empty()) {
1674 auto Seg = OrderedSegments[0];
1675 auto Sec = Seg->firstSection();
1676 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1677 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001678 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001679 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001680 // The PAddr needs to be increased to remove the gap before the first
1681 // section.
1682 Seg->PAddr += Diff;
1683 uint64_t LowestPAddr = Seg->PAddr;
1684 for (auto &Segment : OrderedSegments) {
1685 Segment->Offset = Segment->PAddr - LowestPAddr;
1686 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1687 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001688 }
1689
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001690 // TODO: generalize LayoutSections to take a range. Pass a special range
1691 // constructed from an iterator that skips values for which a predicate does
1692 // not hold. Then pass such a range to LayoutSections instead of constructing
1693 // AllocatedSections here.
1694 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001695 for (auto &Section : Obj.sections()) {
1696 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001697 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001698 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001699 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001700 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001701
1702 // Now that every section has been laid out we just need to compute the total
1703 // file size. This might not be the same as the offset returned by
1704 // LayoutSections, because we want to truncate the last segment to the end of
1705 // its last section, to match GNU objcopy's behaviour.
1706 TotalSize = 0;
1707 for (const auto &Section : AllocatedSections) {
1708 if (Section->Type != SHT_NOBITS)
1709 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1710 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001711
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001712 if (Error E = Buf.allocate(TotalSize))
1713 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001714 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001715 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001716}
1717
Jake Ehrlich76e91102018-01-25 22:46:17 +00001718template class ELFBuilder<ELF64LE>;
1719template class ELFBuilder<ELF64BE>;
1720template class ELFBuilder<ELF32LE>;
1721template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001722
Jake Ehrlich76e91102018-01-25 22:46:17 +00001723template class ELFWriter<ELF64LE>;
1724template class ELFWriter<ELF64BE>;
1725template class ELFWriter<ELF32LE>;
1726template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001727
1728} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001729} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001730} // end namespace llvm