blob: afa48e5c8868a20969549f5cb39802d2bf38dce0 [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
Petr Hosek05a04cb2017-08-01 00:33:58 +0000300void StringTableSection::addString(StringRef Name) {
301 StrTabBuilder.add(Name);
302 Size = StrTabBuilder.getSize();
303}
304
305uint32_t StringTableSection::findIndex(StringRef Name) const {
306 return StrTabBuilder.getOffset(Name);
307}
308
309void StringTableSection::finalize() { StrTabBuilder.finalize(); }
310
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
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000460void SymbolTableSection::initialize(SectionTableRef SecTable) {
461 Size = 0;
462 setStrTab(SecTable.getSectionOfType<StringTableSection>(
463 Link,
464 "Symbol table has link index of " + Twine(Link) +
465 " which is not a valid index",
466 "Symbol table has link index of " + Twine(Link) +
467 " which is not a string table"));
468}
469
Petr Hosek79cee9e2017-08-29 02:12:03 +0000470void SymbolTableSection::finalize() {
471 // Make sure SymbolNames is finalized before getting name indexes.
472 SymbolNames->finalize();
473
474 uint32_t MaxLocalIndex = 0;
475 for (auto &Sym : Symbols) {
476 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
477 if (Sym->Binding == STB_LOCAL)
478 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
479 }
480 // Now we need to set the Link and Info fields.
481 Link = SymbolNames->Index;
482 Info = MaxLocalIndex + 1;
483}
484
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000485void SymbolTableSection::prepareForLayout() {
486 // Add all potential section indexes before file layout so that the section
487 // index section has the approprite size.
488 if (SectionIndexTable != nullptr) {
489 for (const auto &Sym : Symbols) {
490 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
491 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
492 else
493 SectionIndexTable->addIndex(SHN_UNDEF);
494 }
495 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000496 // Add all of our strings to SymbolNames so that SymbolNames has the right
497 // size before layout is decided.
498 for (auto &Sym : Symbols)
499 SymbolNames->addString(Sym->Name);
500}
501
502const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
503 if (Symbols.size() <= Index)
504 error("Invalid symbol index: " + Twine(Index));
505 return Symbols[Index].get();
506}
507
Paul Semel99dda0b2018-05-25 11:01:25 +0000508Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
509 return const_cast<Symbol *>(
510 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
511}
512
Petr Hosek79cee9e2017-08-29 02:12:03 +0000513template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000514void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000515 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000516 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000517 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000518 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000519 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000520 Sym->st_name = Symbol->NameIndex;
521 Sym->st_value = Symbol->Value;
522 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000523 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000524 Sym->setBinding(Symbol->Binding);
525 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000526 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000527 ++Sym;
528 }
529}
530
Jake Ehrlich76e91102018-01-25 22:46:17 +0000531void SymbolTableSection::accept(SectionVisitor &Visitor) const {
532 Visitor.visit(*this);
533}
534
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000535void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
536 Visitor.visit(*this);
537}
538
George Rimar79fb8582019-02-27 11:18:27 +0000539Error RelocationSection::removeSectionReferences(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000540 function_ref<bool(const SectionBase *)> ToRemove) {
541 if (ToRemove(Symbols))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000542 return createStringError(llvm::errc::invalid_argument,
543 "Symbol table %s cannot be removed because it is "
544 "referenced by the relocation section %s.",
545 Symbols->Name.data(), this->Name.data());
George Rimar79fb8582019-02-27 11:18:27 +0000546
547 for (const Relocation &R : Relocations) {
548 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
549 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000550 return createStringError(llvm::errc::invalid_argument,
551 "Section %s can't be removed: (%s+0x%" PRIx64
552 ") has relocation against symbol '%s'",
553 R.RelocSymbol->DefinedIn->Name.data(),
554 SecToApplyRel->Name.data(), R.Offset,
555 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000556 }
557
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000558 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000559}
560
561template <class SymTabType>
562void RelocSectionWithSymtabBase<SymTabType>::initialize(
563 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000564 if (Link != SHN_UNDEF)
565 setSymTab(SecTable.getSectionOfType<SymTabType>(
566 Link,
567 "Link field value " + Twine(Link) + " in section " + Name +
568 " is invalid",
569 "Link field value " + Twine(Link) + " in section " + Name +
570 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000571
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000572 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000573 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
574 " in section " + Name +
575 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000576 else
577 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000578}
579
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000580template <class SymTabType>
581void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000582 this->Link = Symbols ? Symbols->Index : 0;
583
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000584 if (SecToApplyRel != nullptr)
585 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000586}
587
588template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000589static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000590
591template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000592static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000593 Rela.r_addend = Addend;
594}
595
Jake Ehrlich76e91102018-01-25 22:46:17 +0000596template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000597static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000598 for (const auto &Reloc : Relocations) {
599 Buf->r_offset = Reloc.Offset;
600 setAddend(*Buf, Reloc.Addend);
601 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
602 ++Buf;
603 }
604}
605
606template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000607void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
608 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
609 if (Sec.Type == SHT_REL)
610 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000611 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000612 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000613}
614
Jake Ehrlich76e91102018-01-25 22:46:17 +0000615void RelocationSection::accept(SectionVisitor &Visitor) const {
616 Visitor.visit(*this);
617}
618
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000619void RelocationSection::accept(MutableSectionVisitor &Visitor) {
620 Visitor.visit(*this);
621}
622
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000623Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000624 function_ref<bool(const Symbol &)> ToRemove) {
625 for (const Relocation &Reloc : Relocations)
626 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000627 return createStringError(
628 llvm::errc::invalid_argument,
629 "not stripping symbol '%s' because it is named in a relocation.",
630 Reloc.RelocSymbol->Name.data());
631 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000632}
633
Paul Semel99dda0b2018-05-25 11:01:25 +0000634void RelocationSection::markSymbols() {
635 for (const Relocation &Reloc : Relocations)
636 Reloc.RelocSymbol->Referenced = true;
637}
638
George Rimard8a5c6c2019-03-11 11:01:24 +0000639void RelocationSection::replaceSectionReferences(
640 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
641 // Update the target section if it was replaced.
642 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
643 SecToApplyRel = To;
644
645 // Change the sections where symbols are defined in if their
646 // original sections were replaced.
647 for (const Relocation &R : Relocations)
648 if (SectionBase *To = FromTo.lookup(R.RelocSymbol->DefinedIn))
649 R.RelocSymbol->DefinedIn = To;
650}
651
Jake Ehrlich76e91102018-01-25 22:46:17 +0000652void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000653 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000654 Out.getBufferStart() + Sec.Offset);
655}
656
657void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
658 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000659}
660
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000661void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
662 Visitor.visit(*this);
663}
664
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000665Error Section::removeSectionReferences(
666 function_ref<bool(const SectionBase *)> ToRemove) {
667 if (ToRemove(LinkSection))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000668 return createStringError(llvm::errc::invalid_argument,
669 "Section %s cannot be removed because it is "
670 "referenced by the section %s",
671 LinkSection->Name.data(), this->Name.data());
672 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000673}
674
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000675void GroupSection::finalize() {
676 this->Info = Sym->Index;
677 this->Link = SymTab->Index;
678}
679
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000680Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
681 if (ToRemove(*Sym))
682 return createStringError(llvm::errc::invalid_argument,
683 "Symbol %s cannot be removed because it is "
684 "referenced by the section %s[%d].",
685 Sym->Name.data(), this->Name.data(), this->Index);
686 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000687}
688
Paul Semel99dda0b2018-05-25 11:01:25 +0000689void GroupSection::markSymbols() {
690 if (Sym)
691 Sym->Referenced = true;
692}
693
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000694void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000695 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000696 LinkSection =
697 SecTable.getSection(Link, "Link field value " + Twine(Link) +
698 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000699 if (LinkSection->Type == ELF::SHT_SYMTAB)
700 LinkSection = nullptr;
701 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000702}
703
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000704void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000705
Jake Ehrlich76e91102018-01-25 22:46:17 +0000706void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000707 FileName = sys::path::filename(File);
708 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000709 // followed by a null terminator and then the CRC32 of the file. The CRC32
710 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
711 // byte, and then finally push the size to alignment and add 4.
712 Size = alignTo(FileName.size() + 1, 4) + 4;
713 // The CRC32 will only be aligned if we align the whole section.
714 Align = 4;
715 Type = ELF::SHT_PROGBITS;
716 Name = ".gnu_debuglink";
717 // For sections not found in segments, OriginalOffset is only used to
718 // establish the order that sections should go in. By using the maximum
719 // possible offset we cause this section to wind up at the end.
720 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000721 JamCRC CRC;
722 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000723 // The CRC32 value needs to be complemented because the JamCRC dosn't
724 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
725 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000726 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000727}
728
Jake Ehrlich76e91102018-01-25 22:46:17 +0000729GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000730 // Read in the file to compute the CRC of it.
731 auto DebugOrErr = MemoryBuffer::getFile(File);
732 if (!DebugOrErr)
733 error("'" + File + "': " + DebugOrErr.getError().message());
734 auto Debug = std::move(*DebugOrErr);
735 init(File, Debug->getBuffer());
736}
737
738template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000739void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
740 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000741 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000742 Elf_Word *CRC =
743 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
744 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000745 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000746}
747
748void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
749 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000750}
751
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000752void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
753 Visitor.visit(*this);
754}
755
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000756template <class ELFT>
757void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
758 ELF::Elf32_Word *Buf =
759 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
760 *Buf++ = Sec.FlagWord;
761 for (const auto *S : Sec.GroupMembers)
762 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
763}
764
765void GroupSection::accept(SectionVisitor &Visitor) const {
766 Visitor.visit(*this);
767}
768
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000769void GroupSection::accept(MutableSectionVisitor &Visitor) {
770 Visitor.visit(*this);
771}
772
Petr Hosek05a04cb2017-08-01 00:33:58 +0000773// Returns true IFF a section is wholly inside the range of a segment
774static bool sectionWithinSegment(const SectionBase &Section,
775 const Segment &Segment) {
776 // If a section is empty it should be treated like it has a size of 1. This is
777 // to clarify the case when an empty section lies on a boundary between two
778 // segments and ensures that the section "belongs" to the second segment and
779 // not the first.
780 uint64_t SecSize = Section.Size ? Section.Size : 1;
781 return Segment.Offset <= Section.OriginalOffset &&
782 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
783}
784
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000785// Returns true IFF a segment's original offset is inside of another segment's
786// range.
787static bool segmentOverlapsSegment(const Segment &Child,
788 const Segment &Parent) {
789
790 return Parent.OriginalOffset <= Child.OriginalOffset &&
791 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
792}
793
Jake Ehrlich46814be2018-01-22 19:27:30 +0000794static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000795 // Any segment without a parent segment should come before a segment
796 // that has a parent segment.
797 if (A->OriginalOffset < B->OriginalOffset)
798 return true;
799 if (A->OriginalOffset > B->OriginalOffset)
800 return false;
801 return A->Index < B->Index;
802}
803
Jake Ehrlich46814be2018-01-22 19:27:30 +0000804static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
805 if (A->PAddr < B->PAddr)
806 return true;
807 if (A->PAddr > B->PAddr)
808 return false;
809 return A->Index < B->Index;
810}
811
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000812void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000813 Obj->Flags = 0x0;
814 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000815 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000816 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000817 Obj->Entry = 0x0;
818 Obj->Machine = EMachine;
819 Obj->Version = 1;
820}
821
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000822void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000823
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000824StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000825 auto &StrTab = Obj->addSection<StringTableSection>();
826 StrTab.Name = ".strtab";
827
828 Obj->SectionNames = &StrTab;
829 return &StrTab;
830}
831
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000832SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000833 auto &SymTab = Obj->addSection<SymbolTableSection>();
834
835 SymTab.Name = ".symtab";
836 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000837
838 // The symbol table always needs a null symbol
839 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
840
841 Obj->SymbolTable = &SymTab;
842 return &SymTab;
843}
844
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000845void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000846 auto Data = ArrayRef<uint8_t>(
847 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
848 MemBuf->getBufferSize());
849 auto &DataSection = Obj->addSection<Section>(Data);
850 DataSection.Name = ".data";
851 DataSection.Type = ELF::SHT_PROGBITS;
852 DataSection.Size = Data.size();
853 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
854
855 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
856 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000857 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000858 Twine Prefix = Twine("_binary_") + SanitizedFilename;
859
860 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
861 /*Value=*/0, STV_DEFAULT, 0, 0);
862 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
863 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
864 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
865 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
866}
867
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000868void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000869 for (auto &Section : Obj->sections()) {
870 Section.initialize(Obj->sections());
871 }
872}
873
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000874std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000875 initFileHeader();
876 initHeaderSegment();
877 StringTableSection *StrTab = addStrTab();
878 SymbolTableSection *SymTab = addSymTab(StrTab);
879 initSections();
880 addData(SymTab);
881
882 return std::move(Obj);
883}
884
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000885template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000886 for (auto &Parent : Obj.segments()) {
887 // Every segment will overlap with itself but we don't want a segment to
888 // be it's own parent so we avoid that situation.
889 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
890 // We want a canonical "most parental" segment but this requires
891 // inspecting the ParentSegment.
892 if (compareSegmentsByOffset(&Parent, &Child))
893 if (Child.ParentSegment == nullptr ||
894 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
895 Child.ParentSegment = &Parent;
896 }
897 }
898 }
899}
900
Jake Ehrlich76e91102018-01-25 22:46:17 +0000901template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000902 uint32_t Index = 0;
903 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Peter Collingbournebf92b3f2019-03-12 02:17:01 +0000904 Segment &Seg = Obj.addSegment();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000905 Seg.Type = Phdr.p_type;
906 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000907 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000908 Seg.Offset = Phdr.p_offset;
909 Seg.VAddr = Phdr.p_vaddr;
910 Seg.PAddr = Phdr.p_paddr;
911 Seg.FileSize = Phdr.p_filesz;
912 Seg.MemSize = Phdr.p_memsz;
913 Seg.Align = Phdr.p_align;
914 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000915 for (auto &Section : Obj.sections()) {
916 if (sectionWithinSegment(Section, Seg)) {
917 Seg.addSection(&Section);
918 if (!Section.ParentSegment ||
919 Section.ParentSegment->Offset > Seg.Offset) {
920 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000921 }
922 }
923 }
924 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000925
926 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000927 ElfHdr.Index = Index++;
928
929 const auto &Ehdr = *ElfFile.getHeader();
930 auto &PrHdr = Obj.ProgramHdrSegment;
931 PrHdr.Type = PT_PHDR;
932 PrHdr.Flags = 0;
933 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
934 // Whereas this works automatically for ElfHdr, here OriginalOffset is
935 // always non-zero and to ensure the equation we assign the same value to
936 // VAddr as well.
937 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
938 PrHdr.PAddr = 0;
939 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000940 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000941 PrHdr.Align = sizeof(Elf_Addr);
942 PrHdr.Index = Index++;
943
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000944 // Now we do an O(n^2) loop through the segments in order to match up
945 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000946 for (auto &Child : Obj.segments())
947 setParentSegment(Child);
948 setParentSegment(ElfHdr);
949 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000950}
951
952template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000953void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
954 auto SecTable = Obj.sections();
955 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
956 GroupSec->Link,
957 "Link field value " + Twine(GroupSec->Link) + " in section " +
958 GroupSec->Name + " is invalid",
959 "Link field value " + Twine(GroupSec->Link) + " in section " +
960 GroupSec->Name + " is not a symbol table");
961 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
962 if (!Sym)
963 error("Info field value " + Twine(GroupSec->Info) + " in section " +
964 GroupSec->Name + " is not a valid symbol index");
965 GroupSec->setSymTab(SymTab);
966 GroupSec->setSymbol(Sym);
967 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
968 GroupSec->Contents.empty())
969 error("The content of the section " + GroupSec->Name + " is malformed");
970 const ELF::Elf32_Word *Word =
971 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
972 const ELF::Elf32_Word *End =
973 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
974 GroupSec->setFlagWord(*Word++);
975 for (; Word != End; ++Word) {
976 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
977 GroupSec->addMember(SecTable.getSection(
978 Index, "Group member index " + Twine(Index) + " in section " +
979 GroupSec->Name + " is invalid"));
980 }
981}
982
983template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000984void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000985 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
986 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000987 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000988
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000989 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
990 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000991 SectionBase *DefSection = nullptr;
992 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000993
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000994 if (Sym.st_shndx == SHN_XINDEX) {
995 if (SymTab->getShndxTable() == nullptr)
996 error("Symbol '" + Name +
997 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
998 if (ShndxData.data() == nullptr) {
999 const Elf_Shdr &ShndxSec =
1000 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1001 ShndxData = unwrapOrError(
1002 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1003 if (ShndxData.size() != Symbols.size())
1004 error("Symbol section index table does not have the same number of "
1005 "entries as the symbol table.");
1006 }
1007 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1008 DefSection = Obj.sections().getSection(
1009 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +00001010 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001011 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001012 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001013 error(
1014 "Symbol '" + Name +
1015 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1016 Twine(Sym.st_shndx));
1017 }
1018 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001019 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001020 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001021 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001022 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001023 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001024
Petr Hosek79cee9e2017-08-29 02:12:03 +00001025 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001026 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001027 }
1028}
1029
1030template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001031static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1032
1033template <class ELFT>
1034static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1035 ToSet = Rela.r_addend;
1036}
1037
Jake Ehrlich76e91102018-01-25 22:46:17 +00001038template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001039static void initRelocations(RelocationSection *Relocs,
1040 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001041 for (const auto &Rel : RelRange) {
1042 Relocation ToAdd;
1043 ToAdd.Offset = Rel.r_offset;
1044 getAddend(ToAdd.Addend, Rel);
1045 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001046 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001047 Relocs->addRelocation(ToAdd);
1048 }
1049}
1050
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001051SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001052 if (Index == SHN_UNDEF || Index > Sections.size())
1053 error(ErrMsg);
1054 return Sections[Index - 1].get();
1055}
1056
1057template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001058T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001059 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001060 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001061 return Sec;
1062 error(TypeErrMsg);
1063}
1064
Petr Hosekd7df9b22017-09-06 23:41:02 +00001065template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001066SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001067 ArrayRef<uint8_t> Data;
1068 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001069 case SHT_REL:
1070 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001071 if (Shdr.sh_flags & SHF_ALLOC) {
1072 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001073 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001074 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001075 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001076 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001077 // If a string table is allocated we don't want to mess with it. That would
1078 // mean altering the memory image. There are no special link types or
1079 // anything so we can just use a Section.
1080 if (Shdr.sh_flags & SHF_ALLOC) {
1081 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001082 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001083 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001084 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001085 case SHT_HASH:
1086 case SHT_GNU_HASH:
1087 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1088 // Because of this we don't need to mess with the hash tables either.
1089 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001090 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001091 case SHT_GROUP:
1092 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1093 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001094 case SHT_DYNSYM:
1095 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001096 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001097 case SHT_DYNAMIC:
1098 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001099 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001100 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001101 auto &SymTab = Obj.addSection<SymbolTableSection>();
1102 Obj.SymbolTable = &SymTab;
1103 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001104 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001105 case SHT_SYMTAB_SHNDX: {
1106 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1107 Obj.SectionIndexTable = &ShndxSection;
1108 return ShndxSection;
1109 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001110 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001111 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001112 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001113 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001114
George Rimarf2eb8ca2019-03-06 14:01:54 +00001115 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1116 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001117 uint64_t DecompressedSize, DecompressedAlign;
1118 std::tie(DecompressedSize, DecompressedAlign) =
1119 getDecompressedSizeAndAlignment<ELFT>(Data);
1120 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1121 DecompressedAlign);
1122 }
1123
Jake Ehrlich76e91102018-01-25 22:46:17 +00001124 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001125 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001126 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001127}
1128
Jake Ehrlich76e91102018-01-25 22:46:17 +00001129template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001130 uint32_t Index = 0;
1131 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1132 if (Index == 0) {
1133 ++Index;
1134 continue;
1135 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001136 auto &Sec = makeSection(Shdr);
1137 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1138 Sec.Type = Shdr.sh_type;
1139 Sec.Flags = Shdr.sh_flags;
1140 Sec.Addr = Shdr.sh_addr;
1141 Sec.Offset = Shdr.sh_offset;
1142 Sec.OriginalOffset = Shdr.sh_offset;
1143 Sec.Size = Shdr.sh_size;
1144 Sec.Link = Shdr.sh_link;
1145 Sec.Info = Shdr.sh_info;
1146 Sec.Align = Shdr.sh_addralign;
1147 Sec.EntrySize = Shdr.sh_entsize;
1148 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001149 Sec.OriginalData =
1150 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1151 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001152 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001153
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001154 // If a section index table exists we'll need to initialize it before we
1155 // initialize the symbol table because the symbol table might need to
1156 // reference it.
1157 if (Obj.SectionIndexTable)
1158 Obj.SectionIndexTable->initialize(Obj.sections());
1159
Petr Hosek79cee9e2017-08-29 02:12:03 +00001160 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001161 // details about symbol tables. We need the symbol table filled out before
1162 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001163 if (Obj.SymbolTable) {
1164 Obj.SymbolTable->initialize(Obj.sections());
1165 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001166 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001167
1168 // Now that all sections and symbols have been added we can add
1169 // relocations that reference symbols and set the link and info fields for
1170 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001171 for (auto &Section : Obj.sections()) {
1172 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001173 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001174 Section.initialize(Obj.sections());
1175 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001176 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1177 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001178 initRelocations(RelSec, Obj.SymbolTable,
1179 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001180 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001182 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001183 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1184 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001185 }
1186 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001187}
1188
Jake Ehrlich76e91102018-01-25 22:46:17 +00001189template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001190 const auto &Ehdr = *ElfFile.getHeader();
1191
George Rimar4ded7732018-12-20 10:51:42 +00001192 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1193 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001194 Obj.Type = Ehdr.e_type;
1195 Obj.Machine = Ehdr.e_machine;
1196 Obj.Version = Ehdr.e_version;
1197 Obj.Entry = Ehdr.e_entry;
1198 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001199
Jake Ehrlich76e91102018-01-25 22:46:17 +00001200 readSectionHeaders();
1201 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001202
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001203 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1204 if (ShstrIndex == SHN_XINDEX)
1205 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1206
Jake Ehrlich76e91102018-01-25 22:46:17 +00001207 Obj.SectionNames =
1208 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001209 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001210 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001211 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001212 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001213 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001214}
1215
Jake Ehrlich76e91102018-01-25 22:46:17 +00001216// A generic size function which computes sizes of any random access range.
1217template <class R> size_t size(R &&Range) {
1218 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1219}
1220
1221Writer::~Writer() {}
1222
1223Reader::~Reader() {}
1224
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001225std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001226 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001227}
1228
1229std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001230 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001231 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1232 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001233 Builder.build();
1234 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001235 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1236 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001237 Builder.build();
1238 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001239 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1240 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001241 Builder.build();
1242 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001243 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1244 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001245 Builder.build();
1246 return Obj;
1247 }
1248 error("Invalid file type");
1249}
1250
1251template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001252 uint8_t *B = Buf.getBufferStart();
1253 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001254 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1255 Ehdr.e_ident[EI_MAG0] = 0x7f;
1256 Ehdr.e_ident[EI_MAG1] = 'E';
1257 Ehdr.e_ident[EI_MAG2] = 'L';
1258 Ehdr.e_ident[EI_MAG3] = 'F';
1259 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1260 Ehdr.e_ident[EI_DATA] =
1261 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1262 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001263 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1264 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001265
Jake Ehrlich76e91102018-01-25 22:46:17 +00001266 Ehdr.e_type = Obj.Type;
1267 Ehdr.e_machine = Obj.Machine;
1268 Ehdr.e_version = Obj.Version;
1269 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001270 // We have to use the fully-qualified name llvm::size
1271 // since some compilers complain on ambiguous resolution.
1272 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001273 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1274 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001275 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001276 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001277 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1278 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001279 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001280 // """
1281 // If the number of sections is greater than or equal to
1282 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1283 // number of section header table entries is contained in the sh_size field
1284 // of the section header at index 0.
1285 // """
1286 auto Shnum = size(Obj.sections()) + 1;
1287 if (Shnum >= SHN_LORESERVE)
1288 Ehdr.e_shnum = 0;
1289 else
1290 Ehdr.e_shnum = Shnum;
1291 // """
1292 // If the section name string table section index is greater than or equal
1293 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1294 // and the actual index of the section name string table section is
1295 // contained in the sh_link field of the section header at index 0.
1296 // """
1297 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1298 Ehdr.e_shstrndx = SHN_XINDEX;
1299 else
1300 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001301 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001302 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001303 Ehdr.e_shoff = 0;
1304 Ehdr.e_shnum = 0;
1305 Ehdr.e_shstrndx = 0;
1306 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001307}
1308
Jake Ehrlich76e91102018-01-25 22:46:17 +00001309template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1310 for (auto &Seg : Obj.segments())
1311 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001312}
1313
Jake Ehrlich76e91102018-01-25 22:46:17 +00001314template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001315 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001316 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001317 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001318 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001319 Shdr.sh_name = 0;
1320 Shdr.sh_type = SHT_NULL;
1321 Shdr.sh_flags = 0;
1322 Shdr.sh_addr = 0;
1323 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001324 // See writeEhdr for why we do this.
1325 uint64_t Shnum = size(Obj.sections()) + 1;
1326 if (Shnum >= SHN_LORESERVE)
1327 Shdr.sh_size = Shnum;
1328 else
1329 Shdr.sh_size = 0;
1330 // See writeEhdr for why we do this.
1331 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1332 Shdr.sh_link = Obj.SectionNames->Index;
1333 else
1334 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001335 Shdr.sh_info = 0;
1336 Shdr.sh_addralign = 0;
1337 Shdr.sh_entsize = 0;
1338
Jake Ehrlich76e91102018-01-25 22:46:17 +00001339 for (auto &Sec : Obj.sections())
1340 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001341}
1342
Jake Ehrlich76e91102018-01-25 22:46:17 +00001343template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1344 for (auto &Sec : Obj.sections())
1345 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001346}
1347
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001348Error Object::removeSections(
1349 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001350
1351 auto Iter = std::stable_partition(
1352 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1353 if (ToRemove(*Sec))
1354 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001355 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1356 if (auto ToRelSec = RelSec->getSection())
1357 return !ToRemove(*ToRelSec);
1358 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001359 return true;
1360 });
1361 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1362 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001363 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001364 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001365 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1366 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001367 // Now make sure there are no remaining references to the sections that will
1368 // be removed. Sometimes it is impossible to remove a reference so we emit
1369 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001370 std::unordered_set<const SectionBase *> RemoveSections;
1371 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001372 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1373 for (auto &Segment : Segments)
1374 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001375 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001376 }
George Rimar79fb8582019-02-27 11:18:27 +00001377
1378 // For each section that remains alive, we want to remove the dead references.
1379 // This either might update the content of the section (e.g. remove symbols
1380 // from symbol table that belongs to removed section) or trigger an error if
1381 // a live section critically depends on a section being removed somehow
1382 // (e.g. the removed section is referenced by a relocation).
1383 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001384 if (Error E = KeepSec->removeSectionReferences(
1385 [&RemoveSections](const SectionBase *Sec) {
1386 return RemoveSections.find(Sec) != RemoveSections.end();
1387 }))
1388 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001389 }
1390
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001391 // Now finally get rid of them all togethor.
1392 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001393 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001394}
1395
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001396Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1397 if (SymbolTable)
1398 for (const SecPtr &Sec : Sections)
1399 if (Error E = Sec->removeSymbols(ToRemove))
1400 return E;
1401 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001402}
1403
Jake Ehrlich76e91102018-01-25 22:46:17 +00001404void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001405 // Put all sections in offset order. Maintain the ordering as closely as
1406 // possible while meeting that demand however.
1407 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1408 return A->OriginalOffset < B->OriginalOffset;
1409 };
1410 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1411 CompareSections);
1412}
1413
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001414static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1415 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1416 if (Align == 0)
1417 Align = 1;
1418 auto Diff =
1419 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1420 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1421 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1422 if (Diff < 0)
1423 Diff += Align;
1424 return Offset + Diff;
1425}
1426
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001427// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001428static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001429 std::stable_sort(std::begin(Segments), std::end(Segments),
1430 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001431}
1432
1433// This function finds a consistent layout for a list of segments starting from
1434// an Offset. It assumes that Segments have been sorted by OrderSegments and
1435// returns an Offset one past the end of the last segment.
1436static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1437 uint64_t Offset) {
1438 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001439 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001440 // The only way a segment should move is if a section was between two
1441 // segments and that section was removed. If that section isn't in a segment
1442 // then it's acceptable, but not ideal, to simply move it to after the
1443 // segments. So we can simply layout segments one after the other accounting
1444 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001445 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001446 // We assume that segments have been ordered by OriginalOffset and Index
1447 // such that a parent segment will always come before a child segment in
1448 // OrderedSegments. This means that the Offset of the ParentSegment should
1449 // already be set and we can set our offset relative to it.
1450 if (Segment->ParentSegment != nullptr) {
1451 auto Parent = Segment->ParentSegment;
1452 Segment->Offset =
1453 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1454 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001455 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001456 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001457 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001458 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001459 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001460 return Offset;
1461}
1462
1463// This function finds a consistent layout for a list of sections. It assumes
1464// that the ->ParentSegment of each section has already been laid out. The
1465// supplied starting Offset is used for the starting offset of any section that
1466// does not have a ParentSegment. It returns either the offset given if all
1467// sections had a ParentSegment or an offset one past the last section if there
1468// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001469template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001470static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001471 // Now the offset of every segment has been set we can assign the offsets
1472 // of each section. For sections that are covered by a segment we should use
1473 // the segment's original offset and the section's original offset to compute
1474 // the offset from the start of the segment. Using the offset from the start
1475 // of the segment we can assign a new offset to the section. For sections not
1476 // covered by segments we can just bump Offset to the next valid location.
1477 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001478 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001479 Section.Index = Index++;
1480 if (Section.ParentSegment != nullptr) {
1481 auto Segment = *Section.ParentSegment;
1482 Section.Offset =
1483 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001484 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001485 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1486 Section.Offset = Offset;
1487 if (Section.Type != SHT_NOBITS)
1488 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001489 }
1490 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001491 return Offset;
1492}
Petr Hosek3f383832017-08-26 01:32:20 +00001493
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001494template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1495 auto &ElfHdr = Obj.ElfHdrSegment;
1496 ElfHdr.Type = PT_PHDR;
1497 ElfHdr.Flags = 0;
1498 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1499 ElfHdr.VAddr = 0;
1500 ElfHdr.PAddr = 0;
1501 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1502 ElfHdr.Align = 0;
1503}
1504
Jake Ehrlich76e91102018-01-25 22:46:17 +00001505template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001506 // We need a temporary list of segments that has a special order to it
1507 // so that we know that anytime ->ParentSegment is set that segment has
1508 // already had its offset properly set.
1509 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001510 for (auto &Segment : Obj.segments())
1511 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001512 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1513 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001514 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001515 // Offset is used as the start offset of the first segment to be laid out.
1516 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1517 // we start at offset 0.
1518 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001519 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001520 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001521 // If we need to write the section header table out then we need to align the
1522 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001523 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001524 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001525 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001526}
1527
Jake Ehrlich76e91102018-01-25 22:46:17 +00001528template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001529 // We already have the section header offset so we can calculate the total
1530 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001531 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1532 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001533 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001534}
1535
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001536template <class ELFT> Error ELFWriter<ELFT>::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001537 writeEhdr();
1538 writePhdrs();
1539 writeSectionData();
1540 if (WriteSectionHeaders)
1541 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001542 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001543}
1544
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001545template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001546 // It could happen that SectionNames has been removed and yet the user wants
1547 // a section header table output. We need to throw an error if a user tries
1548 // to do that.
1549 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001550 return createStringError(llvm::errc::invalid_argument,
1551 "Cannot write section header table because "
1552 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001553
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001554 Obj.sortSections();
1555
1556 // We need to assign indexes before we perform layout because we need to know
1557 // if we need large indexes or not. We can assign indexes first and check as
1558 // we go to see if we will actully need large indexes.
1559 bool NeedsLargeIndexes = false;
1560 if (size(Obj.sections()) >= SHN_LORESERVE) {
1561 auto Sections = Obj.sections();
1562 NeedsLargeIndexes =
1563 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1564 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1565 // TODO: handle case where only one section needs the large index table but
1566 // only needs it because the large index table hasn't been removed yet.
1567 }
1568
1569 if (NeedsLargeIndexes) {
1570 // This means we definitely need to have a section index table but if we
1571 // already have one then we should use it instead of making a new one.
1572 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1573 // Addition of a section to the end does not invalidate the indexes of
1574 // other sections and assigns the correct index to the new section.
1575 auto &Shndx = Obj.addSection<SectionIndexSection>();
1576 Obj.SymbolTable->setShndxTable(&Shndx);
1577 Shndx.setSymTab(Obj.SymbolTable);
1578 }
1579 } else {
1580 // Since we don't need SectionIndexTable we should remove it and all
1581 // references to it.
1582 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001583 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1584 return &Sec == Obj.SectionIndexTable;
1585 }))
1586 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001587 }
1588 }
1589
1590 // Make sure we add the names of all the sections. Importantly this must be
1591 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001592 if (Obj.SectionNames != nullptr)
1593 for (const auto &Section : Obj.sections()) {
1594 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001595 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001596
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001597 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001598
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001599 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001600 // Also, the output arch may not be the same as the input arch, so fix up
1601 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001602 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001603 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1604 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001605 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001606 Sec.accept(*SecSizer);
1607 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001608
1609 // The symbol table does not update all other sections on update. For
1610 // instance, symbol names are not added as new symbols are added. This means
1611 // that some sections, like .strtab, don't yet have their final size.
1612 if (Obj.SymbolTable != nullptr)
1613 Obj.SymbolTable->prepareForLayout();
1614
Petr Hosekc4df10e2017-08-04 21:09:26 +00001615 assignOffsets();
1616
1617 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001618 if (Obj.SectionNames != nullptr)
1619 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001620 // Finally now that all offsets and indexes have been set we can finalize any
1621 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001622 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1623 for (auto &Section : Obj.sections()) {
1624 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001625 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001626 if (WriteSectionHeaders)
1627 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1628 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001629 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001630
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001631 if (Error E = Buf.allocate(totalSize()))
1632 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001633 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001634 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001635}
1636
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001637Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001638 for (auto &Section : Obj.sections()) {
1639 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001640 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001641 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001642 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001643 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001644}
1645
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001646Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001647 // TODO: Create a filter range to construct OrderedSegments from so that this
1648 // code can be deduped with assignOffsets above. This should also solve the
1649 // todo below for LayoutSections.
1650 // We need a temporary list of segments that has a special order to it
1651 // so that we know that anytime ->ParentSegment is set that segment has
1652 // already had it's offset properly set. We only want to consider the segments
1653 // that will affect layout of allocated sections so we only add those.
1654 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001655 for (auto &Section : Obj.sections()) {
1656 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1657 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001658 }
1659 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001660
1661 // For binary output, we're going to use physical addresses instead of
1662 // virtual addresses, since a binary output is used for cases like ROM
1663 // loading and physical addresses are intended for ROM loading.
1664 // However, if no segment has a physical address, we'll fallback to using
1665 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001666 if (all_of(OrderedSegments,
1667 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1668 for (Segment *Seg : OrderedSegments)
1669 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001670
1671 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1672 compareSegmentsByPAddr);
1673
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001674 // Because we add a ParentSegment for each section we might have duplicate
1675 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1676 // would do very strange things.
1677 auto End =
1678 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1679 OrderedSegments.erase(End, std::end(OrderedSegments));
1680
Jake Ehrlich46814be2018-01-22 19:27:30 +00001681 uint64_t Offset = 0;
1682
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001683 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001684 // our layout algorithm to proceed as expected while not writing out the gap
1685 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001686 if (!OrderedSegments.empty()) {
1687 auto Seg = OrderedSegments[0];
1688 auto Sec = Seg->firstSection();
1689 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1690 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001691 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001692 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001693 // The PAddr needs to be increased to remove the gap before the first
1694 // section.
1695 Seg->PAddr += Diff;
1696 uint64_t LowestPAddr = Seg->PAddr;
1697 for (auto &Segment : OrderedSegments) {
1698 Segment->Offset = Segment->PAddr - LowestPAddr;
1699 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1700 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001701 }
1702
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001703 // TODO: generalize LayoutSections to take a range. Pass a special range
1704 // constructed from an iterator that skips values for which a predicate does
1705 // not hold. Then pass such a range to LayoutSections instead of constructing
1706 // AllocatedSections here.
1707 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001708 for (auto &Section : Obj.sections()) {
1709 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001710 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001711 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001712 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001713 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001714
1715 // Now that every section has been laid out we just need to compute the total
1716 // file size. This might not be the same as the offset returned by
1717 // LayoutSections, because we want to truncate the last segment to the end of
1718 // its last section, to match GNU objcopy's behaviour.
1719 TotalSize = 0;
1720 for (const auto &Section : AllocatedSections) {
1721 if (Section->Type != SHT_NOBITS)
1722 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1723 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001724
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001725 if (Error E = Buf.allocate(TotalSize))
1726 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001727 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001728 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001729}
1730
Jake Ehrlich76e91102018-01-25 22:46:17 +00001731template class ELFBuilder<ELF64LE>;
1732template class ELFBuilder<ELF64BE>;
1733template class ELFBuilder<ELF32LE>;
1734template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001735
Jake Ehrlich76e91102018-01-25 22:46:17 +00001736template class ELFWriter<ELF64LE>;
1737template class ELFWriter<ELF64BE>;
1738template class ELFWriter<ELF32LE>;
1739template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001740
1741} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001742} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001743} // end namespace llvm