blob: 85e7ffa6d8ecb0f612e1e046eab0b68ae8b5cbe8 [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) {
George Rimare98a8f72019-05-23 09:18:57 +000040 uint8_t *B = Buf.getBufferStart() + Obj.ProgramHdrSegment.Offset +
41 Seg.Index * sizeof(Elf_Phdr);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000042 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(
James Henderson66a9d0f2019-04-18 09:13:30 +000054 bool AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +000055 function_ref<bool(const SectionBase *)> ToRemove) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +000056 return Error::success();
57}
58
59Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
60 return Error::success();
61}
62
Jake Ehrlichf5a43772017-09-25 20:37:28 +000063void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000064void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000065void SectionBase::markSymbols() {}
George Rimard8a5c6c2019-03-11 11:01:24 +000066void SectionBase::replaceSectionReferences(
67 const DenseMap<SectionBase *, SectionBase *> &) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000068
Jake Ehrlich76e91102018-01-25 22:46:17 +000069template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +000070 uint8_t *B = Buf.getBufferStart() + 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) {
James Henderson5316a0d2019-05-22 13:23:26 +0000126 error("cannot write symbol section index table '" + Sec.Name + "' ");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000127}
128
Jake Ehrlich76e91102018-01-25 22:46:17 +0000129void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000130 error("cannot write symbol table '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000131}
132
133void BinarySectionWriter::visit(const RelocationSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000134 error("cannot write relocation section '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000135}
136
137void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000138 error("cannot write '" + Sec.Name + "' out to binary");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000139}
140
141void BinarySectionWriter::visit(const GroupSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000142 error("cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000143}
144
145void SectionWriter::visit(const Section &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000146 if (Sec.Type != SHT_NOBITS)
147 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
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) {
George Rimare98a8f72019-05-23 09:18:57 +0000155 llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000156}
157
Puyan Lotfiaf048642018-10-01 10:29:41 +0000158static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
159
160static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
161 return Data.size() > ZlibGnuMagic.size() &&
162 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
163}
164
165template <class ELFT>
166static std::tuple<uint64_t, uint64_t>
167getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
168 const bool IsGnuDebug = isDataGnuCompressed(Data);
169 const uint64_t DecompressedSize =
170 IsGnuDebug
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000171 ? support::endian::read64be(Data.data() + ZlibGnuMagic.size())
Puyan Lotfiaf048642018-10-01 10:29:41 +0000172 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
173 const uint64_t DecompressedAlign =
174 IsGnuDebug ? 1
175 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
176 ->ch_addralign;
177
178 return std::make_tuple(DecompressedSize, DecompressedAlign);
179}
180
181template <class ELFT>
182void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
Puyan Lotfiaf048642018-10-01 10:29:41 +0000183 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
184 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
185 : sizeof(Elf_Chdr_Impl<ELFT>);
186
187 StringRef CompressedContent(
188 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
189 Sec.OriginalData.size() - DataOffset);
190
191 SmallVector<char, 128> DecompressedContent;
192 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
193 static_cast<size_t>(Sec.Size)))
194 reportError(Sec.Name, std::move(E));
195
George Rimar281a5be2019-03-06 14:12:18 +0000196 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfiaf048642018-10-01 10:29:41 +0000197 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
198}
199
200void BinarySectionWriter::visit(const DecompressedSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000201 error("cannot write compressed section '" + Sec.Name + "' ");
Puyan Lotfiaf048642018-10-01 10:29:41 +0000202}
203
204void DecompressedSection::accept(SectionVisitor &Visitor) const {
205 Visitor.visit(*this);
206}
207
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000208void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
209 Visitor.visit(*this);
210}
211
Jake Ehrlich76e91102018-01-25 22:46:17 +0000212void OwnedDataSection::accept(SectionVisitor &Visitor) const {
213 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000214}
215
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000216void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
217 Visitor.visit(*this);
218}
219
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000220void BinarySectionWriter::visit(const CompressedSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000221 error("cannot write compressed section '" + Sec.Name + "' ");
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000222}
223
224template <class ELFT>
225void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000226 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000227 if (Sec.CompressionType == DebugCompressionType::None) {
228 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
229 return;
230 }
231
232 if (Sec.CompressionType == DebugCompressionType::GNU) {
233 const char *Magic = "ZLIB";
234 memcpy(Buf, Magic, strlen(Magic));
235 Buf += strlen(Magic);
236 const uint64_t DecompressedSize =
237 support::endian::read64be(&Sec.DecompressedSize);
238 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
239 Buf += sizeof(DecompressedSize);
240 } else {
241 Elf_Chdr_Impl<ELFT> Chdr;
242 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
243 Chdr.ch_size = Sec.DecompressedSize;
244 Chdr.ch_addralign = Sec.DecompressedAlign;
245 memcpy(Buf, &Chdr, sizeof(Chdr));
246 Buf += sizeof(Chdr);
247 }
248
249 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
250}
251
252CompressedSection::CompressedSection(const SectionBase &Sec,
253 DebugCompressionType CompressionType)
254 : SectionBase(Sec), CompressionType(CompressionType),
255 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000256 if (Error E = zlib::compress(
257 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
258 OriginalData.size()),
259 CompressedData))
260 reportError(Name, std::move(E));
261
262 size_t ChdrSize;
263 if (CompressionType == DebugCompressionType::GNU) {
264 Name = ".z" + Sec.Name.substr(1);
265 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
266 } else {
267 Flags |= ELF::SHF_COMPRESSED;
268 ChdrSize =
269 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
270 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
271 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
272 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
273 }
274 Size = ChdrSize + CompressedData.size();
275 Align = 8;
276}
277
Puyan Lotfiaf048642018-10-01 10:29:41 +0000278CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
279 uint64_t DecompressedSize,
280 uint64_t DecompressedAlign)
281 : CompressionType(DebugCompressionType::None),
282 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
283 OriginalData = CompressedData;
284}
285
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000286void CompressedSection::accept(SectionVisitor &Visitor) const {
287 Visitor.visit(*this);
288}
289
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000290void CompressedSection::accept(MutableSectionVisitor &Visitor) {
291 Visitor.visit(*this);
292}
293
George Rimarfaf308b2019-03-18 14:27:41 +0000294void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000295
296uint32_t StringTableSection::findIndex(StringRef Name) const {
297 return StrTabBuilder.getOffset(Name);
298}
299
George Rimarfaf308b2019-03-18 14:27:41 +0000300void StringTableSection::prepareForLayout() {
301 StrTabBuilder.finalize();
302 Size = StrTabBuilder.getSize();
303}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000304
Jake Ehrlich76e91102018-01-25 22:46:17 +0000305void SectionWriter::visit(const StringTableSection &Sec) {
306 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
307}
308
309void StringTableSection::accept(SectionVisitor &Visitor) const {
310 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000311}
312
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000313void StringTableSection::accept(MutableSectionVisitor &Visitor) {
314 Visitor.visit(*this);
315}
316
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000317template <class ELFT>
318void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
319 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
George Rimare98a8f72019-05-23 09:18:57 +0000320 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000321}
322
323void SectionIndexSection::initialize(SectionTableRef SecTable) {
324 Size = 0;
325 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
326 Link,
327 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
328 "Link field value " + Twine(Link) + " in section " + Name +
329 " is not a symbol table"));
330 Symbols->setShndxTable(this);
331}
332
333void SectionIndexSection::finalize() { Link = Symbols->Index; }
334
335void SectionIndexSection::accept(SectionVisitor &Visitor) const {
336 Visitor.visit(*this);
337}
338
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000339void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
340 Visitor.visit(*this);
341}
342
Petr Hosekc1135772017-09-13 03:04:50 +0000343static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000344 switch (Index) {
345 case SHN_ABS:
346 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000347 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000348 }
Petr Hosekc1135772017-09-13 03:04:50 +0000349 if (Machine == EM_HEXAGON) {
350 switch (Index) {
351 case SHN_HEXAGON_SCOMMON:
352 case SHN_HEXAGON_SCOMMON_2:
353 case SHN_HEXAGON_SCOMMON_4:
354 case SHN_HEXAGON_SCOMMON_8:
355 return true;
356 }
357 }
358 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000359}
360
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000361// Large indexes force us to clarify exactly what this function should do. This
362// function should return the value that will appear in st_shndx when written
363// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000364uint16_t Symbol::getShndx() const {
365 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000366 if (DefinedIn->Index >= SHN_LORESERVE)
367 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000368 return DefinedIn->Index;
369 }
370 switch (ShndxType) {
371 // This means that we don't have a defined section but we do need to
372 // output a legitimate section index.
373 case SYMBOL_SIMPLE_INDEX:
374 return SHN_UNDEF;
375 case SYMBOL_ABS:
376 case SYMBOL_COMMON:
377 case SYMBOL_HEXAGON_SCOMMON:
378 case SYMBOL_HEXAGON_SCOMMON_2:
379 case SYMBOL_HEXAGON_SCOMMON_4:
380 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000381 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000382 return static_cast<uint16_t>(ShndxType);
383 }
384 llvm_unreachable("Symbol with invalid ShndxType encountered");
385}
386
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000387bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
388
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000389void SymbolTableSection::assignIndices() {
390 uint32_t Index = 0;
391 for (auto &Sym : Symbols)
392 Sym->Index = Index++;
393}
394
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000395void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000396 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000397 uint8_t Visibility, uint16_t Shndx,
George Rimar17dbb192019-05-08 07:31:05 +0000398 uint64_t SymbolSize) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000399 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000400 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000401 Sym.Binding = Bind;
402 Sym.Type = Type;
403 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000404 if (DefinedIn != nullptr)
405 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000406 if (DefinedIn == nullptr) {
407 if (Shndx >= SHN_LORESERVE)
408 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
409 else
410 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
411 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000412 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000413 Sym.Visibility = Visibility;
George Rimar17dbb192019-05-08 07:31:05 +0000414 Sym.Size = SymbolSize;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000415 Sym.Index = Symbols.size();
416 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
417 Size += this->EntrySize;
418}
419
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000420Error SymbolTableSection::removeSectionReferences(
James Henderson66a9d0f2019-04-18 09:13:30 +0000421 bool AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000422 function_ref<bool(const SectionBase *)> ToRemove) {
423 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000424 SectionIndexTable = nullptr;
James Henderson66a9d0f2019-04-18 09:13:30 +0000425 if (ToRemove(SymbolNames)) {
426 if (!AllowBrokenLinks)
427 return createStringError(
428 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000429 "string table '%s' cannot be removed because it is "
430 "referenced by the symbol table '%s'",
James Henderson66a9d0f2019-04-18 09:13:30 +0000431 SymbolNames->Name.data(), this->Name.data());
432 SymbolNames = nullptr;
433 }
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
George Rimar0373bed2019-03-20 13:57:47 +0000458void SymbolTableSection::replaceSectionReferences(
459 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
460 for (std::unique_ptr<Symbol> &Sym : Symbols)
461 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
462 Sym->DefinedIn = To;
463}
464
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000465void SymbolTableSection::initialize(SectionTableRef SecTable) {
466 Size = 0;
467 setStrTab(SecTable.getSectionOfType<StringTableSection>(
468 Link,
469 "Symbol table has link index of " + Twine(Link) +
470 " which is not a valid index",
471 "Symbol table has link index of " + Twine(Link) +
472 " which is not a string table"));
473}
474
Petr Hosek79cee9e2017-08-29 02:12:03 +0000475void SymbolTableSection::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000476 uint32_t MaxLocalIndex = 0;
George Rimare98a8f72019-05-23 09:18:57 +0000477 for (std::unique_ptr<Symbol> &Sym : Symbols) {
James Henderson66a9d0f2019-04-18 09:13:30 +0000478 Sym->NameIndex =
479 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000480 if (Sym->Binding == STB_LOCAL)
481 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
482 }
483 // Now we need to set the Link and Info fields.
James Henderson66a9d0f2019-04-18 09:13:30 +0000484 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000485 Info = MaxLocalIndex + 1;
486}
487
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000488void SymbolTableSection::prepareForLayout() {
Eugene Leviant88089fe2019-04-12 11:59:30 +0000489 // Reserve proper amount of space in section index table, so we can
490 // layout sections correctly. We will fill the table with correct
491 // indexes later in fillShdnxTable.
492 if (SectionIndexTable)
493 SectionIndexTable->reserve(Symbols.size());
James Henderson66a9d0f2019-04-18 09:13:30 +0000494
Petr Hosek79cee9e2017-08-29 02:12:03 +0000495 // Add all of our strings to SymbolNames so that SymbolNames has the right
496 // size before layout is decided.
James Henderson66a9d0f2019-04-18 09:13:30 +0000497 // If the symbol names section has been removed, don't try to add strings to
498 // the table.
499 if (SymbolNames != nullptr)
George Rimare98a8f72019-05-23 09:18:57 +0000500 for (std::unique_ptr<Symbol> &Sym : Symbols)
James Henderson66a9d0f2019-04-18 09:13:30 +0000501 SymbolNames->addString(Sym->Name);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000502}
503
Eugene Leviant88089fe2019-04-12 11:59:30 +0000504void SymbolTableSection::fillShndxTable() {
505 if (SectionIndexTable == nullptr)
506 return;
507 // Fill section index table with real section indexes. This function must
508 // be called after assignOffsets.
George Rimare98a8f72019-05-23 09:18:57 +0000509 for (const std::unique_ptr<Symbol> &Sym : Symbols) {
Eugene Leviant88089fe2019-04-12 11:59:30 +0000510 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
511 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
512 else
513 SectionIndexTable->addIndex(SHN_UNDEF);
514 }
515}
516
Petr Hosek79cee9e2017-08-29 02:12:03 +0000517const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
518 if (Symbols.size() <= Index)
James Henderson5316a0d2019-05-22 13:23:26 +0000519 error("invalid symbol index: " + Twine(Index));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000520 return Symbols[Index].get();
521}
522
Paul Semel99dda0b2018-05-25 11:01:25 +0000523Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
524 return const_cast<Symbol *>(
525 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
526}
527
Petr Hosek79cee9e2017-08-29 02:12:03 +0000528template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000529void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000530 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000531 // Loop though symbols setting each entry of the symbol table.
George Rimare98a8f72019-05-23 09:18:57 +0000532 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000533 Sym->st_name = Symbol->NameIndex;
534 Sym->st_value = Symbol->Value;
535 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000536 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000537 Sym->setBinding(Symbol->Binding);
538 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000539 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000540 ++Sym;
541 }
542}
543
Jake Ehrlich76e91102018-01-25 22:46:17 +0000544void SymbolTableSection::accept(SectionVisitor &Visitor) const {
545 Visitor.visit(*this);
546}
547
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000548void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
549 Visitor.visit(*this);
550}
551
George Rimar79fb8582019-02-27 11:18:27 +0000552Error RelocationSection::removeSectionReferences(
James Henderson66a9d0f2019-04-18 09:13:30 +0000553 bool AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000554 function_ref<bool(const SectionBase *)> ToRemove) {
James Henderson66a9d0f2019-04-18 09:13:30 +0000555 if (ToRemove(Symbols)) {
556 if (!AllowBrokenLinks)
557 return createStringError(
558 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000559 "symbol table '%s' cannot be removed because it is "
560 "referenced by the relocation section '%s'",
James Henderson66a9d0f2019-04-18 09:13:30 +0000561 Symbols->Name.data(), this->Name.data());
562 Symbols = nullptr;
563 }
George Rimar79fb8582019-02-27 11:18:27 +0000564
565 for (const Relocation &R : Relocations) {
566 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
567 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000568 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000569 "section '%s' cannot be removed: (%s+0x%" PRIx64
George Rimarbf447a52019-02-28 08:21:50 +0000570 ") has relocation against symbol '%s'",
571 R.RelocSymbol->DefinedIn->Name.data(),
572 SecToApplyRel->Name.data(), R.Offset,
573 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000574 }
575
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000576 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000577}
578
579template <class SymTabType>
580void RelocSectionWithSymtabBase<SymTabType>::initialize(
581 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000582 if (Link != SHN_UNDEF)
583 setSymTab(SecTable.getSectionOfType<SymTabType>(
584 Link,
585 "Link field value " + Twine(Link) + " in section " + Name +
586 " is invalid",
587 "Link field value " + Twine(Link) + " in section " + Name +
588 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000589
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000590 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000591 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
592 " in section " + Name +
593 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000594 else
595 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000596}
597
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000598template <class SymTabType>
599void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000600 this->Link = Symbols ? Symbols->Index : 0;
601
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000602 if (SecToApplyRel != nullptr)
603 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000604}
605
606template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000607static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000608
609template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000610static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000611 Rela.r_addend = Addend;
612}
613
Jake Ehrlich76e91102018-01-25 22:46:17 +0000614template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000615static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000616 for (const auto &Reloc : Relocations) {
617 Buf->r_offset = Reloc.Offset;
618 setAddend(*Buf, Reloc.Addend);
619 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
620 ++Buf;
621 }
622}
623
624template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000625void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
626 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
627 if (Sec.Type == SHT_REL)
628 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000629 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000630 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000631}
632
Jake Ehrlich76e91102018-01-25 22:46:17 +0000633void RelocationSection::accept(SectionVisitor &Visitor) const {
634 Visitor.visit(*this);
635}
636
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000637void RelocationSection::accept(MutableSectionVisitor &Visitor) {
638 Visitor.visit(*this);
639}
640
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000641Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000642 function_ref<bool(const Symbol &)> ToRemove) {
643 for (const Relocation &Reloc : Relocations)
644 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000645 return createStringError(
646 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000647 "not stripping symbol '%s' because it is named in a relocation",
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000648 Reloc.RelocSymbol->Name.data());
649 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000650}
651
Paul Semel99dda0b2018-05-25 11:01:25 +0000652void RelocationSection::markSymbols() {
653 for (const Relocation &Reloc : Relocations)
654 Reloc.RelocSymbol->Referenced = true;
655}
656
George Rimard8a5c6c2019-03-11 11:01:24 +0000657void RelocationSection::replaceSectionReferences(
658 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
659 // Update the target section if it was replaced.
660 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
661 SecToApplyRel = To;
George Rimard8a5c6c2019-03-11 11:01:24 +0000662}
663
Jake Ehrlich76e91102018-01-25 22:46:17 +0000664void SectionWriter::visit(const DynamicRelocationSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000665 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000666}
667
668void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
669 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000670}
671
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000672void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
George Rimare98a8f72019-05-23 09:18:57 +0000673 Visitor.visit(*this);
674}
675
676Error DynamicRelocationSection::removeSectionReferences(
677 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
678 if (ToRemove(Symbols)) {
679 if (!AllowBrokenLinks)
680 return createStringError(
681 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000682 "symbol table '%s' cannot be removed because it is "
683 "referenced by the relocation section '%s'",
George Rimare98a8f72019-05-23 09:18:57 +0000684 Symbols->Name.data(), this->Name.data());
685 Symbols = nullptr;
686 }
687
688 // SecToApplyRel contains a section referenced by sh_info field. It keeps
689 // a section to which the relocation section applies. When we remove any
690 // sections we also remove their relocation sections. Since we do that much
691 // earlier, this assert should never be triggered.
692 assert(!SecToApplyRel || !ToRemove(SecToApplyRel));
693 return Error::success();
694}
695
696Error Section::removeSectionReferences(bool AllowBrokenDependency,
697 function_ref<bool(const SectionBase *)> ToRemove) {
698 if (ToRemove(LinkSection)) {
James Henderson66a9d0f2019-04-18 09:13:30 +0000699 if (!AllowBrokenDependency)
700 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000701 "section '%s' cannot be removed because it is "
702 "referenced by the section '%s'",
James Henderson66a9d0f2019-04-18 09:13:30 +0000703 LinkSection->Name.data(), this->Name.data());
704 LinkSection = nullptr;
705 }
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000706 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000707}
708
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000709void GroupSection::finalize() {
710 this->Info = Sym->Index;
711 this->Link = SymTab->Index;
712}
713
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000714Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
715 if (ToRemove(*Sym))
716 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000717 "symbol '%s' cannot be removed because it is "
718 "referenced by the section '%s[%d]'",
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000719 Sym->Name.data(), this->Name.data(), this->Index);
720 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000721}
722
Paul Semel99dda0b2018-05-25 11:01:25 +0000723void GroupSection::markSymbols() {
724 if (Sym)
725 Sym->Referenced = true;
726}
727
George Rimar27257172019-03-24 14:41:45 +0000728void GroupSection::replaceSectionReferences(
729 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
730 for (SectionBase *&Sec : GroupMembers)
731 if (SectionBase *To = FromTo.lookup(Sec))
732 Sec = To;
733}
734
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000735void Section::initialize(SectionTableRef SecTable) {
George Rimare98a8f72019-05-23 09:18:57 +0000736 if (Link == ELF::SHN_UNDEF)
737 return;
738 LinkSection =
739 SecTable.getSection(Link, "Link field value " + Twine(Link) +
740 " in section " + Name + " is invalid");
741 if (LinkSection->Type == ELF::SHT_SYMTAB)
742 LinkSection = nullptr;
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000743}
744
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000745void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000746
James Henderson9df38832019-05-14 10:59:04 +0000747void GnuDebugLinkSection::init(StringRef File) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000748 FileName = sys::path::filename(File);
749 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000750 // followed by a null terminator and then the CRC32 of the file. The CRC32
751 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
752 // byte, and then finally push the size to alignment and add 4.
753 Size = alignTo(FileName.size() + 1, 4) + 4;
754 // The CRC32 will only be aligned if we align the whole section.
755 Align = 4;
756 Type = ELF::SHT_PROGBITS;
757 Name = ".gnu_debuglink";
758 // For sections not found in segments, OriginalOffset is only used to
759 // establish the order that sections should go in. By using the maximum
760 // possible offset we cause this section to wind up at the end.
761 OriginalOffset = std::numeric_limits<uint64_t>::max();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000762}
763
James Henderson9df38832019-05-14 10:59:04 +0000764GnuDebugLinkSection::GnuDebugLinkSection(StringRef File,
765 uint32_t PrecomputedCRC)
766 : FileName(File), CRC32(PrecomputedCRC) {
767 init(File);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000768}
769
770template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000771void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000772 unsigned char *Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000773 Elf_Word *CRC =
774 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
775 *CRC = Sec.CRC32;
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000776 llvm::copy(Sec.FileName, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000777}
778
779void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
780 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000781}
782
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000783void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
784 Visitor.visit(*this);
785}
786
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000787template <class ELFT>
788void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
789 ELF::Elf32_Word *Buf =
790 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
791 *Buf++ = Sec.FlagWord;
George Rimare98a8f72019-05-23 09:18:57 +0000792 for (SectionBase *S : Sec.GroupMembers)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000793 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
794}
795
796void GroupSection::accept(SectionVisitor &Visitor) const {
797 Visitor.visit(*this);
798}
799
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000800void GroupSection::accept(MutableSectionVisitor &Visitor) {
801 Visitor.visit(*this);
802}
803
Petr Hosek05a04cb2017-08-01 00:33:58 +0000804// Returns true IFF a section is wholly inside the range of a segment
805static bool sectionWithinSegment(const SectionBase &Section,
806 const Segment &Segment) {
807 // If a section is empty it should be treated like it has a size of 1. This is
808 // to clarify the case when an empty section lies on a boundary between two
809 // segments and ensures that the section "belongs" to the second segment and
810 // not the first.
811 uint64_t SecSize = Section.Size ? Section.Size : 1;
Peter Collingbourneab09cca2019-05-24 00:21:46 +0000812
813 if (Section.Type == SHT_NOBITS) {
814 if (!(Section.Flags & SHF_ALLOC))
815 return false;
816
817 bool SectionIsTLS = Section.Flags & SHF_TLS;
818 bool SegmentIsTLS = Segment.Type == PT_TLS;
819 if (SectionIsTLS != SegmentIsTLS)
820 return false;
821
822 return Segment.VAddr <= Section.Addr &&
823 Segment.VAddr + Segment.MemSize >= Section.Addr + SecSize;
824 }
825
Petr Hosek05a04cb2017-08-01 00:33:58 +0000826 return Segment.Offset <= Section.OriginalOffset &&
827 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
828}
829
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000830// Returns true IFF a segment's original offset is inside of another segment's
831// range.
832static bool segmentOverlapsSegment(const Segment &Child,
833 const Segment &Parent) {
834
835 return Parent.OriginalOffset <= Child.OriginalOffset &&
836 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
837}
838
Jake Ehrlich46814be2018-01-22 19:27:30 +0000839static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000840 // Any segment without a parent segment should come before a segment
841 // that has a parent segment.
842 if (A->OriginalOffset < B->OriginalOffset)
843 return true;
844 if (A->OriginalOffset > B->OriginalOffset)
845 return false;
846 return A->Index < B->Index;
847}
848
Jake Ehrlich46814be2018-01-22 19:27:30 +0000849static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
850 if (A->PAddr < B->PAddr)
851 return true;
852 if (A->PAddr > B->PAddr)
853 return false;
854 return A->Index < B->Index;
855}
856
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000857void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000858 Obj->Flags = 0x0;
859 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000860 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000861 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000862 Obj->Entry = 0x0;
863 Obj->Machine = EMachine;
864 Obj->Version = 1;
865}
866
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000867void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000868
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000869StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000870 auto &StrTab = Obj->addSection<StringTableSection>();
871 StrTab.Name = ".strtab";
872
873 Obj->SectionNames = &StrTab;
874 return &StrTab;
875}
876
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000877SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000878 auto &SymTab = Obj->addSection<SymbolTableSection>();
879
880 SymTab.Name = ".symtab";
881 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000882
883 // The symbol table always needs a null symbol
884 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
885
886 Obj->SymbolTable = &SymTab;
887 return &SymTab;
888}
889
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000890void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000891 auto Data = ArrayRef<uint8_t>(
892 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
893 MemBuf->getBufferSize());
894 auto &DataSection = Obj->addSection<Section>(Data);
895 DataSection.Name = ".data";
896 DataSection.Type = ELF::SHT_PROGBITS;
897 DataSection.Size = Data.size();
898 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
899
900 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
901 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000902 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000903 Twine Prefix = Twine("_binary_") + SanitizedFilename;
904
905 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
906 /*Value=*/0, STV_DEFAULT, 0, 0);
907 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
908 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
909 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
910 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
911}
912
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000913void BinaryELFBuilder::initSections() {
George Rimare98a8f72019-05-23 09:18:57 +0000914 for (SectionBase &Section : Obj->sections())
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000915 Section.initialize(Obj->sections());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000916}
917
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000918std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000919 initFileHeader();
920 initHeaderSegment();
George Rimare98a8f72019-05-23 09:18:57 +0000921
922 SymbolTableSection *SymTab = addSymTab(addStrTab());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000923 initSections();
924 addData(SymTab);
925
926 return std::move(Obj);
927}
928
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000929template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
George Rimare98a8f72019-05-23 09:18:57 +0000930 for (Segment &Parent : Obj.segments()) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000931 // Every segment will overlap with itself but we don't want a segment to
932 // be it's own parent so we avoid that situation.
933 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
934 // We want a canonical "most parental" segment but this requires
935 // inspecting the ParentSegment.
936 if (compareSegmentsByOffset(&Parent, &Child))
937 if (Child.ParentSegment == nullptr ||
938 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
939 Child.ParentSegment = &Parent;
940 }
941 }
942 }
943}
944
Jake Ehrlich76e91102018-01-25 22:46:17 +0000945template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000946 uint32_t Index = 0;
947 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
James Henderson1f448142019-03-25 16:36:26 +0000948 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
949 (size_t)Phdr.p_filesz};
950 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000951 Seg.Type = Phdr.p_type;
952 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000953 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000954 Seg.Offset = Phdr.p_offset;
955 Seg.VAddr = Phdr.p_vaddr;
956 Seg.PAddr = Phdr.p_paddr;
957 Seg.FileSize = Phdr.p_filesz;
958 Seg.MemSize = Phdr.p_memsz;
959 Seg.Align = Phdr.p_align;
960 Seg.Index = Index++;
George Rimare98a8f72019-05-23 09:18:57 +0000961 for (SectionBase &Section : Obj.sections()) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000962 if (sectionWithinSegment(Section, Seg)) {
963 Seg.addSection(&Section);
964 if (!Section.ParentSegment ||
965 Section.ParentSegment->Offset > Seg.Offset) {
966 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000967 }
968 }
969 }
970 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000971
972 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000973 ElfHdr.Index = Index++;
974
975 const auto &Ehdr = *ElfFile.getHeader();
976 auto &PrHdr = Obj.ProgramHdrSegment;
977 PrHdr.Type = PT_PHDR;
978 PrHdr.Flags = 0;
979 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
980 // Whereas this works automatically for ElfHdr, here OriginalOffset is
981 // always non-zero and to ensure the equation we assign the same value to
982 // VAddr as well.
983 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
984 PrHdr.PAddr = 0;
985 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000986 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000987 PrHdr.Align = sizeof(Elf_Addr);
988 PrHdr.Index = Index++;
989
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000990 // Now we do an O(n^2) loop through the segments in order to match up
991 // segments.
George Rimare98a8f72019-05-23 09:18:57 +0000992 for (Segment &Child : Obj.segments())
Jake Ehrlich6452b112018-02-14 23:31:33 +0000993 setParentSegment(Child);
994 setParentSegment(ElfHdr);
995 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000996}
997
998template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000999void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
George Rimar0a5d4b82019-03-24 13:31:08 +00001000 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
James Henderson5316a0d2019-05-22 13:23:26 +00001001 error("invalid alignment " + Twine(GroupSec->Align) + " of group section '" +
1002 GroupSec->Name + "'");
George Rimare98a8f72019-05-23 09:18:57 +00001003 SectionTableRef SecTable = Obj.sections();
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001004 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1005 GroupSec->Link,
James Henderson5316a0d2019-05-22 13:23:26 +00001006 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1007 GroupSec->Name + "' is invalid",
1008 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1009 GroupSec->Name + "' is not a symbol table");
George Rimare98a8f72019-05-23 09:18:57 +00001010 Symbol *Sym = SymTab->getSymbolByIndex(GroupSec->Info);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001011 if (!Sym)
James Henderson5316a0d2019-05-22 13:23:26 +00001012 error("info field value '" + Twine(GroupSec->Info) + "' in section '" +
1013 GroupSec->Name + "' is not a valid symbol index");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001014 GroupSec->setSymTab(SymTab);
1015 GroupSec->setSymbol(Sym);
1016 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1017 GroupSec->Contents.empty())
James Henderson5316a0d2019-05-22 13:23:26 +00001018 error("the content of the section " + GroupSec->Name + " is malformed");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001019 const ELF::Elf32_Word *Word =
1020 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1021 const ELF::Elf32_Word *End =
1022 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1023 GroupSec->setFlagWord(*Word++);
1024 for (; Word != End; ++Word) {
1025 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
1026 GroupSec->addMember(SecTable.getSection(
James Henderson5316a0d2019-05-22 13:23:26 +00001027 Index, "group member index " + Twine(Index) + " in section '" +
1028 GroupSec->Name + "' is invalid"));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001029 }
1030}
1031
1032template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001033void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001034 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
1035 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001036 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001037
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001038 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
1039 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001040 SectionBase *DefSection = nullptr;
1041 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001042
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001043 if (Sym.st_shndx == SHN_XINDEX) {
1044 if (SymTab->getShndxTable() == nullptr)
James Henderson5316a0d2019-05-22 13:23:26 +00001045 error("symbol '" + Name +
1046 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001047 if (ShndxData.data() == nullptr) {
1048 const Elf_Shdr &ShndxSec =
1049 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1050 ShndxData = unwrapOrError(
1051 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1052 if (ShndxData.size() != Symbols.size())
James Henderson5316a0d2019-05-22 13:23:26 +00001053 error("symbol section index table does not have the same number of "
1054 "entries as the symbol table");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001055 }
1056 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1057 DefSection = Obj.sections().getSection(
1058 Index,
James Henderson5316a0d2019-05-22 13:23:26 +00001059 "symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001060 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001061 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001062 error(
James Henderson5316a0d2019-05-22 13:23:26 +00001063 "symbol '" + Name +
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001064 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1065 Twine(Sym.st_shndx));
1066 }
1067 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068 DefSection = Obj.sections().getSection(
James Henderson5316a0d2019-05-22 13:23:26 +00001069 Sym.st_shndx, "symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001070 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001071 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001072 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001073
Petr Hosek79cee9e2017-08-29 02:12:03 +00001074 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001075 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001076 }
1077}
1078
1079template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001080static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1081
1082template <class ELFT>
1083static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1084 ToSet = Rela.r_addend;
1085}
1086
Jake Ehrlich76e91102018-01-25 22:46:17 +00001087template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001088static void initRelocations(RelocationSection *Relocs,
1089 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001090 for (const auto &Rel : RelRange) {
1091 Relocation ToAdd;
1092 ToAdd.Offset = Rel.r_offset;
1093 getAddend(ToAdd.Addend, Rel);
1094 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001095 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001096 Relocs->addRelocation(ToAdd);
1097 }
1098}
1099
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001100SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001101 if (Index == SHN_UNDEF || Index > Sections.size())
1102 error(ErrMsg);
1103 return Sections[Index - 1].get();
1104}
1105
1106template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001107T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001108 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001109 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001110 return Sec;
1111 error(TypeErrMsg);
1112}
1113
Petr Hosekd7df9b22017-09-06 23:41:02 +00001114template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001115SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001116 ArrayRef<uint8_t> Data;
1117 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001118 case SHT_REL:
1119 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001120 if (Shdr.sh_flags & SHF_ALLOC) {
1121 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001122 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001123 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001124 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001125 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001126 // If a string table is allocated we don't want to mess with it. That would
1127 // mean altering the memory image. There are no special link types or
1128 // anything so we can just use a Section.
1129 if (Shdr.sh_flags & SHF_ALLOC) {
1130 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001131 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001132 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001133 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001134 case SHT_HASH:
1135 case SHT_GNU_HASH:
1136 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1137 // Because of this we don't need to mess with the hash tables either.
1138 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001139 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001140 case SHT_GROUP:
1141 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1142 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001143 case SHT_DYNSYM:
1144 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001145 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001146 case SHT_DYNAMIC:
1147 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001148 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001149 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001150 auto &SymTab = Obj.addSection<SymbolTableSection>();
1151 Obj.SymbolTable = &SymTab;
1152 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001153 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001154 case SHT_SYMTAB_SHNDX: {
1155 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1156 Obj.SectionIndexTable = &ShndxSection;
1157 return ShndxSection;
1158 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001159 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001160 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001161 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001162 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001163
George Rimarf2eb8ca2019-03-06 14:01:54 +00001164 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1165 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001166 uint64_t DecompressedSize, DecompressedAlign;
1167 std::tie(DecompressedSize, DecompressedAlign) =
1168 getDecompressedSizeAndAlignment<ELFT>(Data);
1169 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1170 DecompressedAlign);
1171 }
1172
Jake Ehrlich76e91102018-01-25 22:46:17 +00001173 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001174 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001175 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001176}
1177
Jake Ehrlich76e91102018-01-25 22:46:17 +00001178template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001179 uint32_t Index = 0;
1180 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1181 if (Index == 0) {
1182 ++Index;
1183 continue;
1184 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001185 auto &Sec = makeSection(Shdr);
1186 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1187 Sec.Type = Shdr.sh_type;
1188 Sec.Flags = Shdr.sh_flags;
1189 Sec.Addr = Shdr.sh_addr;
1190 Sec.Offset = Shdr.sh_offset;
1191 Sec.OriginalOffset = Shdr.sh_offset;
1192 Sec.Size = Shdr.sh_size;
1193 Sec.Link = Shdr.sh_link;
1194 Sec.Info = Shdr.sh_info;
1195 Sec.Align = Shdr.sh_addralign;
1196 Sec.EntrySize = Shdr.sh_entsize;
1197 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001198 Sec.OriginalData =
1199 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1200 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001201 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001202
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001203 // If a section index table exists we'll need to initialize it before we
1204 // initialize the symbol table because the symbol table might need to
1205 // reference it.
1206 if (Obj.SectionIndexTable)
1207 Obj.SectionIndexTable->initialize(Obj.sections());
1208
Petr Hosek79cee9e2017-08-29 02:12:03 +00001209 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001210 // details about symbol tables. We need the symbol table filled out before
1211 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001212 if (Obj.SymbolTable) {
1213 Obj.SymbolTable->initialize(Obj.sections());
1214 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001215 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001216
1217 // Now that all sections and symbols have been added we can add
1218 // relocations that reference symbols and set the link and info fields for
1219 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001220 for (auto &Section : Obj.sections()) {
1221 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001222 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001223 Section.initialize(Obj.sections());
1224 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001225 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1226 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001227 initRelocations(RelSec, Obj.SymbolTable,
1228 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001229 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001230 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001231 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001232 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1233 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001234 }
1235 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001236}
1237
Jake Ehrlich76e91102018-01-25 22:46:17 +00001238template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001239 const auto &Ehdr = *ElfFile.getHeader();
1240
George Rimar4ded7732018-12-20 10:51:42 +00001241 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1242 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001243 Obj.Type = Ehdr.e_type;
1244 Obj.Machine = Ehdr.e_machine;
1245 Obj.Version = Ehdr.e_version;
1246 Obj.Entry = Ehdr.e_entry;
1247 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001248
Jake Ehrlich76e91102018-01-25 22:46:17 +00001249 readSectionHeaders();
1250 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001251
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001252 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1253 if (ShstrIndex == SHN_XINDEX)
1254 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1255
James Henderson38cb2382019-04-02 14:11:13 +00001256 if (ShstrIndex == SHN_UNDEF)
1257 Obj.HadShdrs = false;
1258 else
1259 Obj.SectionNames =
1260 Obj.sections().template getSectionOfType<StringTableSection>(
1261 ShstrIndex,
1262 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1263 " in elf header is invalid",
1264 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1265 " in elf header is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001266}
1267
Jake Ehrlich76e91102018-01-25 22:46:17 +00001268Writer::~Writer() {}
1269
1270Reader::~Reader() {}
1271
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001272std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001273 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001274}
1275
1276std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001277 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001278 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1279 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001280 Builder.build();
1281 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001282 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1283 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001284 Builder.build();
1285 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001286 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1287 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001288 Builder.build();
1289 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001290 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1291 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001292 Builder.build();
1293 return Obj;
1294 }
James Henderson5316a0d2019-05-22 13:23:26 +00001295 error("invalid file type");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001296}
1297
1298template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
George Rimare98a8f72019-05-23 09:18:57 +00001299 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf.getBufferStart());
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001300 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1301 Ehdr.e_ident[EI_MAG0] = 0x7f;
1302 Ehdr.e_ident[EI_MAG1] = 'E';
1303 Ehdr.e_ident[EI_MAG2] = 'L';
1304 Ehdr.e_ident[EI_MAG3] = 'F';
1305 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1306 Ehdr.e_ident[EI_DATA] =
1307 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1308 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001309 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1310 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001311
Jake Ehrlich76e91102018-01-25 22:46:17 +00001312 Ehdr.e_type = Obj.Type;
1313 Ehdr.e_machine = Obj.Machine;
1314 Ehdr.e_version = Obj.Version;
1315 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001316 // We have to use the fully-qualified name llvm::size
1317 // since some compilers complain on ambiguous resolution.
1318 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001319 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1320 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001321 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001322 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Fangrui Song82b01e02019-03-30 14:08:59 +00001323 if (WriteSectionHeaders && Obj.sections().size() != 0) {
Julie Hockett468722e2018-09-12 17:56:31 +00001324 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001325 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001326 // """
1327 // If the number of sections is greater than or equal to
1328 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1329 // number of section header table entries is contained in the sh_size field
1330 // of the section header at index 0.
1331 // """
Fangrui Song82b01e02019-03-30 14:08:59 +00001332 auto Shnum = Obj.sections().size() + 1;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001333 if (Shnum >= SHN_LORESERVE)
1334 Ehdr.e_shnum = 0;
1335 else
1336 Ehdr.e_shnum = Shnum;
1337 // """
1338 // If the section name string table section index is greater than or equal
1339 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1340 // and the actual index of the section name string table section is
1341 // contained in the sh_link field of the section header at index 0.
1342 // """
1343 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1344 Ehdr.e_shstrndx = SHN_XINDEX;
1345 else
1346 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001347 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001348 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001349 Ehdr.e_shoff = 0;
1350 Ehdr.e_shnum = 0;
1351 Ehdr.e_shstrndx = 0;
1352 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001353}
1354
Jake Ehrlich76e91102018-01-25 22:46:17 +00001355template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1356 for (auto &Seg : Obj.segments())
1357 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001358}
1359
Jake Ehrlich76e91102018-01-25 22:46:17 +00001360template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001361 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001362 // of the file. It is not used for anything else
George Rimare98a8f72019-05-23 09:18:57 +00001363 Elf_Shdr &Shdr =
1364 *reinterpret_cast<Elf_Shdr *>(Buf.getBufferStart() + Obj.SHOffset);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001365 Shdr.sh_name = 0;
1366 Shdr.sh_type = SHT_NULL;
1367 Shdr.sh_flags = 0;
1368 Shdr.sh_addr = 0;
1369 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001370 // See writeEhdr for why we do this.
Fangrui Song82b01e02019-03-30 14:08:59 +00001371 uint64_t Shnum = Obj.sections().size() + 1;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001372 if (Shnum >= SHN_LORESERVE)
1373 Shdr.sh_size = Shnum;
1374 else
1375 Shdr.sh_size = 0;
1376 // See writeEhdr for why we do this.
1377 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1378 Shdr.sh_link = Obj.SectionNames->Index;
1379 else
1380 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001381 Shdr.sh_info = 0;
1382 Shdr.sh_addralign = 0;
1383 Shdr.sh_entsize = 0;
1384
George Rimare98a8f72019-05-23 09:18:57 +00001385 for (SectionBase &Sec : Obj.sections())
Jake Ehrlich76e91102018-01-25 22:46:17 +00001386 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001387}
1388
Jake Ehrlich76e91102018-01-25 22:46:17 +00001389template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
George Rimare98a8f72019-05-23 09:18:57 +00001390 for (SectionBase &Sec : Obj.sections())
James Henderson1f448142019-03-25 16:36:26 +00001391 // Segments are responsible for writing their contents, so only write the
1392 // section data if the section is not in a segment. Note that this renders
1393 // sections in segments effectively immutable.
1394 if (Sec.ParentSegment == nullptr)
1395 Sec.accept(*SecWriter);
1396}
1397
1398template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
1399 for (Segment &Seg : Obj.segments()) {
1400 uint8_t *B = Buf.getBufferStart() + Seg.Offset;
1401 assert(Seg.FileSize == Seg.getContents().size() &&
1402 "Segment size must match contents size");
1403 std::memcpy(B, Seg.getContents().data(), Seg.FileSize);
1404 }
1405
1406 // Iterate over removed sections and overwrite their old data with zeroes.
1407 for (auto &Sec : Obj.removedSections()) {
1408 Segment *Parent = Sec.ParentSegment;
1409 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
1410 continue;
1411 uint64_t Offset =
1412 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
George Rimare98a8f72019-05-23 09:18:57 +00001413 std::memset(Buf.getBufferStart() + Offset, 0, Sec.Size);
James Henderson1f448142019-03-25 16:36:26 +00001414 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001415}
1416
James Henderson38cb2382019-04-02 14:11:13 +00001417template <class ELFT>
1418ELFWriter<ELFT>::ELFWriter(Object &Obj, Buffer &Buf, bool WSH)
1419 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs) {}
1420
James Henderson66a9d0f2019-04-18 09:13:30 +00001421Error Object::removeSections(bool AllowBrokenLinks,
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001422 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001423
1424 auto Iter = std::stable_partition(
1425 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1426 if (ToRemove(*Sec))
1427 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001428 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1429 if (auto ToRelSec = RelSec->getSection())
1430 return !ToRemove(*ToRelSec);
1431 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001432 return true;
1433 });
1434 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1435 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001436 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001437 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001438 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1439 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001440 // Now make sure there are no remaining references to the sections that will
1441 // be removed. Sometimes it is impossible to remove a reference so we emit
1442 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001443 std::unordered_set<const SectionBase *> RemoveSections;
1444 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001445 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1446 for (auto &Segment : Segments)
1447 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001448 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001449 }
George Rimar79fb8582019-02-27 11:18:27 +00001450
1451 // For each section that remains alive, we want to remove the dead references.
1452 // This either might update the content of the section (e.g. remove symbols
1453 // from symbol table that belongs to removed section) or trigger an error if
1454 // a live section critically depends on a section being removed somehow
1455 // (e.g. the removed section is referenced by a relocation).
1456 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
James Henderson66a9d0f2019-04-18 09:13:30 +00001457 if (Error E = KeepSec->removeSectionReferences(AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001458 [&RemoveSections](const SectionBase *Sec) {
1459 return RemoveSections.find(Sec) != RemoveSections.end();
1460 }))
1461 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001462 }
1463
James Henderson1f448142019-03-25 16:36:26 +00001464 // Transfer removed sections into the Object RemovedSections container for use
1465 // later.
1466 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
1467 // Now finally get rid of them all together.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001468 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001469 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001470}
1471
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001472Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1473 if (SymbolTable)
1474 for (const SecPtr &Sec : Sections)
1475 if (Error E = Sec->removeSymbols(ToRemove))
1476 return E;
1477 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001478}
1479
Jake Ehrlich76e91102018-01-25 22:46:17 +00001480void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001481 // Put all sections in offset order. Maintain the ordering as closely as
1482 // possible while meeting that demand however.
Fangrui Songa5355a52019-04-22 15:53:43 +00001483 llvm::stable_sort(Sections, [](const SecPtr &A, const SecPtr &B) {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001484 return A->OriginalOffset < B->OriginalOffset;
Fangrui Songa5355a52019-04-22 15:53:43 +00001485 });
Petr Hosekc4df10e2017-08-04 21:09:26 +00001486}
1487
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001488static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1489 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1490 if (Align == 0)
1491 Align = 1;
1492 auto Diff =
1493 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1494 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1495 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1496 if (Diff < 0)
1497 Diff += Align;
1498 return Offset + Diff;
1499}
1500
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001501// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001502static void orderSegments(std::vector<Segment *> &Segments) {
Fangrui Songa5355a52019-04-22 15:53:43 +00001503 llvm::stable_sort(Segments, compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001504}
1505
1506// This function finds a consistent layout for a list of segments starting from
1507// an Offset. It assumes that Segments have been sorted by OrderSegments and
1508// returns an Offset one past the end of the last segment.
Fangrui Song8da6a6c2019-03-29 15:27:58 +00001509static uint64_t layoutSegments(std::vector<Segment *> &Segments,
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001510 uint64_t Offset) {
1511 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001512 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001513 // The only way a segment should move is if a section was between two
1514 // segments and that section was removed. If that section isn't in a segment
1515 // then it's acceptable, but not ideal, to simply move it to after the
1516 // segments. So we can simply layout segments one after the other accounting
1517 // for alignment.
George Rimare98a8f72019-05-23 09:18:57 +00001518 for (Segment *Seg : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001519 // We assume that segments have been ordered by OriginalOffset and Index
1520 // such that a parent segment will always come before a child segment in
1521 // OrderedSegments. This means that the Offset of the ParentSegment should
1522 // already be set and we can set our offset relative to it.
George Rimare98a8f72019-05-23 09:18:57 +00001523 if (Seg->ParentSegment != nullptr) {
1524 Segment *Parent = Seg->ParentSegment;
1525 Seg->Offset =
1526 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001527 } else {
George Rimare98a8f72019-05-23 09:18:57 +00001528 Offset = alignToAddr(Offset, Seg->VAddr, Seg->Align);
1529 Seg->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001530 }
George Rimare98a8f72019-05-23 09:18:57 +00001531 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001532 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001533 return Offset;
1534}
1535
1536// This function finds a consistent layout for a list of sections. It assumes
1537// that the ->ParentSegment of each section has already been laid out. The
1538// supplied starting Offset is used for the starting offset of any section that
1539// does not have a ParentSegment. It returns either the offset given if all
1540// sections had a ParentSegment or an offset one past the last section if there
1541// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001542template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001543static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001544 // Now the offset of every segment has been set we can assign the offsets
1545 // of each section. For sections that are covered by a segment we should use
1546 // the segment's original offset and the section's original offset to compute
1547 // the offset from the start of the segment. Using the offset from the start
1548 // of the segment we can assign a new offset to the section. For sections not
1549 // covered by segments we can just bump Offset to the next valid location.
1550 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001551 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001552 Section.Index = Index++;
1553 if (Section.ParentSegment != nullptr) {
1554 auto Segment = *Section.ParentSegment;
1555 Section.Offset =
1556 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001557 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001558 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1559 Section.Offset = Offset;
1560 if (Section.Type != SHT_NOBITS)
1561 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001562 }
1563 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001564 return Offset;
1565}
Petr Hosek3f383832017-08-26 01:32:20 +00001566
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001567template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
George Rimare98a8f72019-05-23 09:18:57 +00001568 Segment &ElfHdr = Obj.ElfHdrSegment;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001569 ElfHdr.Type = PT_PHDR;
1570 ElfHdr.Flags = 0;
1571 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1572 ElfHdr.VAddr = 0;
1573 ElfHdr.PAddr = 0;
1574 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1575 ElfHdr.Align = 0;
1576}
1577
Jake Ehrlich76e91102018-01-25 22:46:17 +00001578template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001579 // We need a temporary list of segments that has a special order to it
1580 // so that we know that anytime ->ParentSegment is set that segment has
1581 // already had its offset properly set.
1582 std::vector<Segment *> OrderedSegments;
George Rimare98a8f72019-05-23 09:18:57 +00001583 for (Segment &Segment : Obj.segments())
Jake Ehrlich76e91102018-01-25 22:46:17 +00001584 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001585 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1586 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001587 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001588 // Offset is used as the start offset of the first segment to be laid out.
1589 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1590 // we start at offset 0.
1591 uint64_t Offset = 0;
Fangrui Song8da6a6c2019-03-29 15:27:58 +00001592 Offset = layoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001593 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001594 // If we need to write the section header table out then we need to align the
1595 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001596 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001597 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001598 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001599}
1600
Jake Ehrlich76e91102018-01-25 22:46:17 +00001601template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001602 // We already have the section header offset so we can calculate the total
1603 // size by just adding up the size of each section header.
James Henderson38cb2382019-04-02 14:11:13 +00001604 if (!WriteSectionHeaders)
1605 return Obj.SHOffset;
1606 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
1607 return Obj.SHOffset + ShdrCount * sizeof(Elf_Shdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001608}
1609
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001610template <class ELFT> Error ELFWriter<ELFT>::write() {
James Henderson1f448142019-03-25 16:36:26 +00001611 // Segment data must be written first, so that the ELF header and program
1612 // header tables can overwrite it, if covered by a segment.
1613 writeSegmentData();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001614 writeEhdr();
1615 writePhdrs();
1616 writeSectionData();
1617 if (WriteSectionHeaders)
1618 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001619 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001620}
1621
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001622template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001623 // It could happen that SectionNames has been removed and yet the user wants
1624 // a section header table output. We need to throw an error if a user tries
1625 // to do that.
1626 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001627 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +00001628 "cannot write section header table because "
1629 "section header string table was removed");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001630
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001631 Obj.sortSections();
1632
1633 // We need to assign indexes before we perform layout because we need to know
1634 // if we need large indexes or not. We can assign indexes first and check as
1635 // we go to see if we will actully need large indexes.
1636 bool NeedsLargeIndexes = false;
Fangrui Song82b01e02019-03-30 14:08:59 +00001637 if (Obj.sections().size() >= SHN_LORESERVE) {
George Rimare98a8f72019-05-23 09:18:57 +00001638 SectionTableRef Sections = Obj.sections();
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001639 NeedsLargeIndexes =
1640 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1641 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1642 // TODO: handle case where only one section needs the large index table but
1643 // only needs it because the large index table hasn't been removed yet.
1644 }
1645
1646 if (NeedsLargeIndexes) {
1647 // This means we definitely need to have a section index table but if we
1648 // already have one then we should use it instead of making a new one.
1649 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1650 // Addition of a section to the end does not invalidate the indexes of
1651 // other sections and assigns the correct index to the new section.
1652 auto &Shndx = Obj.addSection<SectionIndexSection>();
1653 Obj.SymbolTable->setShndxTable(&Shndx);
1654 Shndx.setSymTab(Obj.SymbolTable);
1655 }
1656 } else {
1657 // Since we don't need SectionIndexTable we should remove it and all
1658 // references to it.
1659 if (Obj.SectionIndexTable != nullptr) {
James Henderson66a9d0f2019-04-18 09:13:30 +00001660 // We do not support sections referring to the section index table.
1661 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
1662 [this](const SectionBase &Sec) {
1663 return &Sec == Obj.SectionIndexTable;
1664 }))
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001665 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001666 }
1667 }
1668
1669 // Make sure we add the names of all the sections. Importantly this must be
1670 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001671 if (Obj.SectionNames != nullptr)
1672 for (const auto &Section : Obj.sections()) {
1673 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001674 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001675
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001676 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001677
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001678 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001679 // Also, the output arch may not be the same as the input arch, so fix up
1680 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001681 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001682 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1683 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001684 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001685 Sec.accept(*SecSizer);
1686 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001687
1688 // The symbol table does not update all other sections on update. For
1689 // instance, symbol names are not added as new symbols are added. This means
1690 // that some sections, like .strtab, don't yet have their final size.
1691 if (Obj.SymbolTable != nullptr)
1692 Obj.SymbolTable->prepareForLayout();
1693
George Rimarfaf308b2019-03-18 14:27:41 +00001694 // Now that all strings are added we want to finalize string table builders,
1695 // because that affects section sizes which in turn affects section offsets.
George Rimare98a8f72019-05-23 09:18:57 +00001696 for (SectionBase &Sec : Obj.sections())
George Rimarfaf308b2019-03-18 14:27:41 +00001697 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
1698 StrTab->prepareForLayout();
1699
Petr Hosekc4df10e2017-08-04 21:09:26 +00001700 assignOffsets();
1701
Eugene Leviant88089fe2019-04-12 11:59:30 +00001702 // layoutSections could have modified section indexes, so we need
1703 // to fill the index table after assignOffsets.
1704 if (Obj.SymbolTable != nullptr)
1705 Obj.SymbolTable->fillShndxTable();
1706
Petr Hosekc4df10e2017-08-04 21:09:26 +00001707 // Finally now that all offsets and indexes have been set we can finalize any
1708 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001709 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
George Rimare98a8f72019-05-23 09:18:57 +00001710 for (SectionBase &Section : Obj.sections()) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001711 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001712 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001713 if (WriteSectionHeaders)
1714 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1715 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001716 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001717
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001718 if (Error E = Buf.allocate(totalSize()))
1719 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001720 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001721 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001722}
1723
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001724Error BinaryWriter::write() {
George Rimare98a8f72019-05-23 09:18:57 +00001725 for (auto &Section : Obj.sections())
1726 if (Section.Flags & SHF_ALLOC)
1727 Section.accept(*SecWriter);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001728 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001729}
1730
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001731Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001732 // TODO: Create a filter range to construct OrderedSegments from so that this
1733 // code can be deduped with assignOffsets above. This should also solve the
1734 // todo below for LayoutSections.
1735 // We need a temporary list of segments that has a special order to it
1736 // so that we know that anytime ->ParentSegment is set that segment has
1737 // already had it's offset properly set. We only want to consider the segments
1738 // that will affect layout of allocated sections so we only add those.
1739 std::vector<Segment *> OrderedSegments;
George Rimare98a8f72019-05-23 09:18:57 +00001740 for (SectionBase &Section : Obj.sections())
1741 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001742 OrderedSegments.push_back(Section.ParentSegment);
Jake Ehrlich46814be2018-01-22 19:27:30 +00001743
1744 // For binary output, we're going to use physical addresses instead of
1745 // virtual addresses, since a binary output is used for cases like ROM
1746 // loading and physical addresses are intended for ROM loading.
1747 // However, if no segment has a physical address, we'll fallback to using
1748 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001749 if (all_of(OrderedSegments,
1750 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1751 for (Segment *Seg : OrderedSegments)
1752 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001753
Fangrui Songa5355a52019-04-22 15:53:43 +00001754 llvm::stable_sort(OrderedSegments, compareSegmentsByPAddr);
Jake Ehrlich46814be2018-01-22 19:27:30 +00001755
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001756 // Because we add a ParentSegment for each section we might have duplicate
1757 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1758 // would do very strange things.
1759 auto End =
1760 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1761 OrderedSegments.erase(End, std::end(OrderedSegments));
1762
Jake Ehrlich46814be2018-01-22 19:27:30 +00001763 uint64_t Offset = 0;
1764
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001765 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001766 // our layout algorithm to proceed as expected while not writing out the gap
1767 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001768 if (!OrderedSegments.empty()) {
George Rimare98a8f72019-05-23 09:18:57 +00001769 Segment *Seg = OrderedSegments[0];
1770 const SectionBase *Sec = Seg->firstSection();
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001771 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1772 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001773 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001774 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001775 // The PAddr needs to be increased to remove the gap before the first
1776 // section.
1777 Seg->PAddr += Diff;
1778 uint64_t LowestPAddr = Seg->PAddr;
George Rimare98a8f72019-05-23 09:18:57 +00001779 for (Segment *Segment : OrderedSegments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001780 Segment->Offset = Segment->PAddr - LowestPAddr;
1781 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1782 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001783 }
1784
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001785 // TODO: generalize LayoutSections to take a range. Pass a special range
1786 // constructed from an iterator that skips values for which a predicate does
1787 // not hold. Then pass such a range to LayoutSections instead of constructing
1788 // AllocatedSections here.
1789 std::vector<SectionBase *> AllocatedSections;
George Rimare98a8f72019-05-23 09:18:57 +00001790 for (SectionBase &Section : Obj.sections())
1791 if (Section.Flags & SHF_ALLOC)
1792 AllocatedSections.push_back(&Section);
Fangrui Song32a34e62018-11-01 16:02:12 +00001793 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001794
1795 // Now that every section has been laid out we just need to compute the total
1796 // file size. This might not be the same as the offset returned by
1797 // LayoutSections, because we want to truncate the last segment to the end of
1798 // its last section, to match GNU objcopy's behaviour.
1799 TotalSize = 0;
George Rimare98a8f72019-05-23 09:18:57 +00001800 for (SectionBase *Section : AllocatedSections)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001801 if (Section->Type != SHT_NOBITS)
1802 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001803
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001804 if (Error E = Buf.allocate(TotalSize))
1805 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001806 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001807 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001808}
1809
Jake Ehrlich76e91102018-01-25 22:46:17 +00001810template class ELFBuilder<ELF64LE>;
1811template class ELFBuilder<ELF64BE>;
1812template class ELFBuilder<ELF32LE>;
1813template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001814
Jake Ehrlich76e91102018-01-25 22:46:17 +00001815template class ELFWriter<ELF64LE>;
1816template class ELFWriter<ELF64BE>;
1817template class ELFWriter<ELF32LE>;
1818template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001819
1820} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001821} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001822} // end namespace llvm