blob: 0c80bad6c102d063b385b7d7e0b31777ddc5249b [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;
812 return Segment.Offset <= Section.OriginalOffset &&
813 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
814}
815
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000816// Returns true IFF a segment's original offset is inside of another segment's
817// range.
818static bool segmentOverlapsSegment(const Segment &Child,
819 const Segment &Parent) {
820
821 return Parent.OriginalOffset <= Child.OriginalOffset &&
822 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
823}
824
Jake Ehrlich46814be2018-01-22 19:27:30 +0000825static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000826 // Any segment without a parent segment should come before a segment
827 // that has a parent segment.
828 if (A->OriginalOffset < B->OriginalOffset)
829 return true;
830 if (A->OriginalOffset > B->OriginalOffset)
831 return false;
832 return A->Index < B->Index;
833}
834
Jake Ehrlich46814be2018-01-22 19:27:30 +0000835static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
836 if (A->PAddr < B->PAddr)
837 return true;
838 if (A->PAddr > B->PAddr)
839 return false;
840 return A->Index < B->Index;
841}
842
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000843void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000844 Obj->Flags = 0x0;
845 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000846 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000847 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000848 Obj->Entry = 0x0;
849 Obj->Machine = EMachine;
850 Obj->Version = 1;
851}
852
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000853void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000854
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000855StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000856 auto &StrTab = Obj->addSection<StringTableSection>();
857 StrTab.Name = ".strtab";
858
859 Obj->SectionNames = &StrTab;
860 return &StrTab;
861}
862
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000863SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000864 auto &SymTab = Obj->addSection<SymbolTableSection>();
865
866 SymTab.Name = ".symtab";
867 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000868
869 // The symbol table always needs a null symbol
870 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
871
872 Obj->SymbolTable = &SymTab;
873 return &SymTab;
874}
875
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000876void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000877 auto Data = ArrayRef<uint8_t>(
878 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
879 MemBuf->getBufferSize());
880 auto &DataSection = Obj->addSection<Section>(Data);
881 DataSection.Name = ".data";
882 DataSection.Type = ELF::SHT_PROGBITS;
883 DataSection.Size = Data.size();
884 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
885
886 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
887 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000888 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000889 Twine Prefix = Twine("_binary_") + SanitizedFilename;
890
891 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
892 /*Value=*/0, STV_DEFAULT, 0, 0);
893 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
894 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
895 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
896 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
897}
898
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000899void BinaryELFBuilder::initSections() {
George Rimare98a8f72019-05-23 09:18:57 +0000900 for (SectionBase &Section : Obj->sections())
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000901 Section.initialize(Obj->sections());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000902}
903
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000904std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000905 initFileHeader();
906 initHeaderSegment();
George Rimare98a8f72019-05-23 09:18:57 +0000907
908 SymbolTableSection *SymTab = addSymTab(addStrTab());
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000909 initSections();
910 addData(SymTab);
911
912 return std::move(Obj);
913}
914
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000915template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
George Rimare98a8f72019-05-23 09:18:57 +0000916 for (Segment &Parent : Obj.segments()) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000917 // Every segment will overlap with itself but we don't want a segment to
918 // be it's own parent so we avoid that situation.
919 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
920 // We want a canonical "most parental" segment but this requires
921 // inspecting the ParentSegment.
922 if (compareSegmentsByOffset(&Parent, &Child))
923 if (Child.ParentSegment == nullptr ||
924 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
925 Child.ParentSegment = &Parent;
926 }
927 }
928 }
929}
930
Jake Ehrlich76e91102018-01-25 22:46:17 +0000931template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000932 uint32_t Index = 0;
933 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
James Henderson1f448142019-03-25 16:36:26 +0000934 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
935 (size_t)Phdr.p_filesz};
936 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000937 Seg.Type = Phdr.p_type;
938 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000939 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000940 Seg.Offset = Phdr.p_offset;
941 Seg.VAddr = Phdr.p_vaddr;
942 Seg.PAddr = Phdr.p_paddr;
943 Seg.FileSize = Phdr.p_filesz;
944 Seg.MemSize = Phdr.p_memsz;
945 Seg.Align = Phdr.p_align;
946 Seg.Index = Index++;
George Rimare98a8f72019-05-23 09:18:57 +0000947 for (SectionBase &Section : Obj.sections()) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000948 if (sectionWithinSegment(Section, Seg)) {
949 Seg.addSection(&Section);
950 if (!Section.ParentSegment ||
951 Section.ParentSegment->Offset > Seg.Offset) {
952 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000953 }
954 }
955 }
956 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000957
958 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000959 ElfHdr.Index = Index++;
960
961 const auto &Ehdr = *ElfFile.getHeader();
962 auto &PrHdr = Obj.ProgramHdrSegment;
963 PrHdr.Type = PT_PHDR;
964 PrHdr.Flags = 0;
965 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
966 // Whereas this works automatically for ElfHdr, here OriginalOffset is
967 // always non-zero and to ensure the equation we assign the same value to
968 // VAddr as well.
969 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
970 PrHdr.PAddr = 0;
971 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000972 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000973 PrHdr.Align = sizeof(Elf_Addr);
974 PrHdr.Index = Index++;
975
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000976 // Now we do an O(n^2) loop through the segments in order to match up
977 // segments.
George Rimare98a8f72019-05-23 09:18:57 +0000978 for (Segment &Child : Obj.segments())
Jake Ehrlich6452b112018-02-14 23:31:33 +0000979 setParentSegment(Child);
980 setParentSegment(ElfHdr);
981 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000982}
983
984template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000985void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
George Rimar0a5d4b82019-03-24 13:31:08 +0000986 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
James Henderson5316a0d2019-05-22 13:23:26 +0000987 error("invalid alignment " + Twine(GroupSec->Align) + " of group section '" +
988 GroupSec->Name + "'");
George Rimare98a8f72019-05-23 09:18:57 +0000989 SectionTableRef SecTable = Obj.sections();
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000990 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
991 GroupSec->Link,
James Henderson5316a0d2019-05-22 13:23:26 +0000992 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
993 GroupSec->Name + "' is invalid",
994 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
995 GroupSec->Name + "' is not a symbol table");
George Rimare98a8f72019-05-23 09:18:57 +0000996 Symbol *Sym = SymTab->getSymbolByIndex(GroupSec->Info);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000997 if (!Sym)
James Henderson5316a0d2019-05-22 13:23:26 +0000998 error("info field value '" + Twine(GroupSec->Info) + "' in section '" +
999 GroupSec->Name + "' is not a valid symbol index");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001000 GroupSec->setSymTab(SymTab);
1001 GroupSec->setSymbol(Sym);
1002 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1003 GroupSec->Contents.empty())
James Henderson5316a0d2019-05-22 13:23:26 +00001004 error("the content of the section " + GroupSec->Name + " is malformed");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001005 const ELF::Elf32_Word *Word =
1006 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1007 const ELF::Elf32_Word *End =
1008 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1009 GroupSec->setFlagWord(*Word++);
1010 for (; Word != End; ++Word) {
1011 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
1012 GroupSec->addMember(SecTable.getSection(
James Henderson5316a0d2019-05-22 13:23:26 +00001013 Index, "group member index " + Twine(Index) + " in section '" +
1014 GroupSec->Name + "' is invalid"));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001015 }
1016}
1017
1018template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001019void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001020 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
1021 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001022 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001023
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001024 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
1025 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001026 SectionBase *DefSection = nullptr;
1027 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001028
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001029 if (Sym.st_shndx == SHN_XINDEX) {
1030 if (SymTab->getShndxTable() == nullptr)
James Henderson5316a0d2019-05-22 13:23:26 +00001031 error("symbol '" + Name +
1032 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001033 if (ShndxData.data() == nullptr) {
1034 const Elf_Shdr &ShndxSec =
1035 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1036 ShndxData = unwrapOrError(
1037 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1038 if (ShndxData.size() != Symbols.size())
James Henderson5316a0d2019-05-22 13:23:26 +00001039 error("symbol section index table does not have the same number of "
1040 "entries as the symbol table");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001041 }
1042 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1043 DefSection = Obj.sections().getSection(
1044 Index,
James Henderson5316a0d2019-05-22 13:23:26 +00001045 "symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001046 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001047 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001048 error(
James Henderson5316a0d2019-05-22 13:23:26 +00001049 "symbol '" + Name +
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001050 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1051 Twine(Sym.st_shndx));
1052 }
1053 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001054 DefSection = Obj.sections().getSection(
James Henderson5316a0d2019-05-22 13:23:26 +00001055 Sym.st_shndx, "symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001056 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001057 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001058 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001059
Petr Hosek79cee9e2017-08-29 02:12:03 +00001060 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001061 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001062 }
1063}
1064
1065template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001066static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1067
1068template <class ELFT>
1069static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1070 ToSet = Rela.r_addend;
1071}
1072
Jake Ehrlich76e91102018-01-25 22:46:17 +00001073template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001074static void initRelocations(RelocationSection *Relocs,
1075 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001076 for (const auto &Rel : RelRange) {
1077 Relocation ToAdd;
1078 ToAdd.Offset = Rel.r_offset;
1079 getAddend(ToAdd.Addend, Rel);
1080 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001081 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001082 Relocs->addRelocation(ToAdd);
1083 }
1084}
1085
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001086SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001087 if (Index == SHN_UNDEF || Index > Sections.size())
1088 error(ErrMsg);
1089 return Sections[Index - 1].get();
1090}
1091
1092template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001093T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001094 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001095 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001096 return Sec;
1097 error(TypeErrMsg);
1098}
1099
Petr Hosekd7df9b22017-09-06 23:41:02 +00001100template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001101SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001102 ArrayRef<uint8_t> Data;
1103 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001104 case SHT_REL:
1105 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001106 if (Shdr.sh_flags & SHF_ALLOC) {
1107 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001108 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001109 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001110 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001111 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001112 // If a string table is allocated we don't want to mess with it. That would
1113 // mean altering the memory image. There are no special link types or
1114 // anything so we can just use a Section.
1115 if (Shdr.sh_flags & SHF_ALLOC) {
1116 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001117 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001118 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001119 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001120 case SHT_HASH:
1121 case SHT_GNU_HASH:
1122 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1123 // Because of this we don't need to mess with the hash tables either.
1124 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001125 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001126 case SHT_GROUP:
1127 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1128 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001129 case SHT_DYNSYM:
1130 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001131 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001132 case SHT_DYNAMIC:
1133 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001134 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001135 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001136 auto &SymTab = Obj.addSection<SymbolTableSection>();
1137 Obj.SymbolTable = &SymTab;
1138 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001139 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001140 case SHT_SYMTAB_SHNDX: {
1141 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1142 Obj.SectionIndexTable = &ShndxSection;
1143 return ShndxSection;
1144 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001145 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001146 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001147 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001148 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001149
George Rimarf2eb8ca2019-03-06 14:01:54 +00001150 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1151 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001152 uint64_t DecompressedSize, DecompressedAlign;
1153 std::tie(DecompressedSize, DecompressedAlign) =
1154 getDecompressedSizeAndAlignment<ELFT>(Data);
1155 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1156 DecompressedAlign);
1157 }
1158
Jake Ehrlich76e91102018-01-25 22:46:17 +00001159 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001160 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001161 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001162}
1163
Jake Ehrlich76e91102018-01-25 22:46:17 +00001164template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001165 uint32_t Index = 0;
1166 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1167 if (Index == 0) {
1168 ++Index;
1169 continue;
1170 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001171 auto &Sec = makeSection(Shdr);
1172 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1173 Sec.Type = Shdr.sh_type;
1174 Sec.Flags = Shdr.sh_flags;
1175 Sec.Addr = Shdr.sh_addr;
1176 Sec.Offset = Shdr.sh_offset;
1177 Sec.OriginalOffset = Shdr.sh_offset;
1178 Sec.Size = Shdr.sh_size;
1179 Sec.Link = Shdr.sh_link;
1180 Sec.Info = Shdr.sh_info;
1181 Sec.Align = Shdr.sh_addralign;
1182 Sec.EntrySize = Shdr.sh_entsize;
1183 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001184 Sec.OriginalData =
1185 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1186 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001187 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001188
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001189 // If a section index table exists we'll need to initialize it before we
1190 // initialize the symbol table because the symbol table might need to
1191 // reference it.
1192 if (Obj.SectionIndexTable)
1193 Obj.SectionIndexTable->initialize(Obj.sections());
1194
Petr Hosek79cee9e2017-08-29 02:12:03 +00001195 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001196 // details about symbol tables. We need the symbol table filled out before
1197 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001198 if (Obj.SymbolTable) {
1199 Obj.SymbolTable->initialize(Obj.sections());
1200 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001201 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001202
1203 // Now that all sections and symbols have been added we can add
1204 // relocations that reference symbols and set the link and info fields for
1205 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001206 for (auto &Section : Obj.sections()) {
1207 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001208 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001209 Section.initialize(Obj.sections());
1210 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001211 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1212 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001213 initRelocations(RelSec, Obj.SymbolTable,
1214 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001215 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001216 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001217 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001218 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1219 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001220 }
1221 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001222}
1223
Jake Ehrlich76e91102018-01-25 22:46:17 +00001224template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001225 const auto &Ehdr = *ElfFile.getHeader();
1226
George Rimar4ded7732018-12-20 10:51:42 +00001227 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1228 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001229 Obj.Type = Ehdr.e_type;
1230 Obj.Machine = Ehdr.e_machine;
1231 Obj.Version = Ehdr.e_version;
1232 Obj.Entry = Ehdr.e_entry;
1233 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001234
Jake Ehrlich76e91102018-01-25 22:46:17 +00001235 readSectionHeaders();
1236 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001237
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001238 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1239 if (ShstrIndex == SHN_XINDEX)
1240 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1241
James Henderson38cb2382019-04-02 14:11:13 +00001242 if (ShstrIndex == SHN_UNDEF)
1243 Obj.HadShdrs = false;
1244 else
1245 Obj.SectionNames =
1246 Obj.sections().template getSectionOfType<StringTableSection>(
1247 ShstrIndex,
1248 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1249 " in elf header is invalid",
1250 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1251 " in elf header is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001252}
1253
Jake Ehrlich76e91102018-01-25 22:46:17 +00001254Writer::~Writer() {}
1255
1256Reader::~Reader() {}
1257
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001258std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001259 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001260}
1261
1262std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001263 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001264 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1265 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001266 Builder.build();
1267 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001268 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1269 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001270 Builder.build();
1271 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001272 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1273 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001274 Builder.build();
1275 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001276 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1277 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001278 Builder.build();
1279 return Obj;
1280 }
James Henderson5316a0d2019-05-22 13:23:26 +00001281 error("invalid file type");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001282}
1283
1284template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
George Rimare98a8f72019-05-23 09:18:57 +00001285 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf.getBufferStart());
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001286 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1287 Ehdr.e_ident[EI_MAG0] = 0x7f;
1288 Ehdr.e_ident[EI_MAG1] = 'E';
1289 Ehdr.e_ident[EI_MAG2] = 'L';
1290 Ehdr.e_ident[EI_MAG3] = 'F';
1291 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1292 Ehdr.e_ident[EI_DATA] =
1293 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1294 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001295 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1296 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001297
Jake Ehrlich76e91102018-01-25 22:46:17 +00001298 Ehdr.e_type = Obj.Type;
1299 Ehdr.e_machine = Obj.Machine;
1300 Ehdr.e_version = Obj.Version;
1301 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001302 // We have to use the fully-qualified name llvm::size
1303 // since some compilers complain on ambiguous resolution.
1304 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001305 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1306 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001307 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001308 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Fangrui Song82b01e02019-03-30 14:08:59 +00001309 if (WriteSectionHeaders && Obj.sections().size() != 0) {
Julie Hockett468722e2018-09-12 17:56:31 +00001310 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001311 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001312 // """
1313 // If the number of sections is greater than or equal to
1314 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1315 // number of section header table entries is contained in the sh_size field
1316 // of the section header at index 0.
1317 // """
Fangrui Song82b01e02019-03-30 14:08:59 +00001318 auto Shnum = Obj.sections().size() + 1;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001319 if (Shnum >= SHN_LORESERVE)
1320 Ehdr.e_shnum = 0;
1321 else
1322 Ehdr.e_shnum = Shnum;
1323 // """
1324 // If the section name string table section index is greater than or equal
1325 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1326 // and the actual index of the section name string table section is
1327 // contained in the sh_link field of the section header at index 0.
1328 // """
1329 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1330 Ehdr.e_shstrndx = SHN_XINDEX;
1331 else
1332 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001333 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001334 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001335 Ehdr.e_shoff = 0;
1336 Ehdr.e_shnum = 0;
1337 Ehdr.e_shstrndx = 0;
1338 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001339}
1340
Jake Ehrlich76e91102018-01-25 22:46:17 +00001341template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1342 for (auto &Seg : Obj.segments())
1343 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001344}
1345
Jake Ehrlich76e91102018-01-25 22:46:17 +00001346template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001347 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001348 // of the file. It is not used for anything else
George Rimare98a8f72019-05-23 09:18:57 +00001349 Elf_Shdr &Shdr =
1350 *reinterpret_cast<Elf_Shdr *>(Buf.getBufferStart() + Obj.SHOffset);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001351 Shdr.sh_name = 0;
1352 Shdr.sh_type = SHT_NULL;
1353 Shdr.sh_flags = 0;
1354 Shdr.sh_addr = 0;
1355 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001356 // See writeEhdr for why we do this.
Fangrui Song82b01e02019-03-30 14:08:59 +00001357 uint64_t Shnum = Obj.sections().size() + 1;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001358 if (Shnum >= SHN_LORESERVE)
1359 Shdr.sh_size = Shnum;
1360 else
1361 Shdr.sh_size = 0;
1362 // See writeEhdr for why we do this.
1363 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1364 Shdr.sh_link = Obj.SectionNames->Index;
1365 else
1366 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001367 Shdr.sh_info = 0;
1368 Shdr.sh_addralign = 0;
1369 Shdr.sh_entsize = 0;
1370
George Rimare98a8f72019-05-23 09:18:57 +00001371 for (SectionBase &Sec : Obj.sections())
Jake Ehrlich76e91102018-01-25 22:46:17 +00001372 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001373}
1374
Jake Ehrlich76e91102018-01-25 22:46:17 +00001375template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
George Rimare98a8f72019-05-23 09:18:57 +00001376 for (SectionBase &Sec : Obj.sections())
James Henderson1f448142019-03-25 16:36:26 +00001377 // Segments are responsible for writing their contents, so only write the
1378 // section data if the section is not in a segment. Note that this renders
1379 // sections in segments effectively immutable.
1380 if (Sec.ParentSegment == nullptr)
1381 Sec.accept(*SecWriter);
1382}
1383
1384template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
1385 for (Segment &Seg : Obj.segments()) {
1386 uint8_t *B = Buf.getBufferStart() + Seg.Offset;
1387 assert(Seg.FileSize == Seg.getContents().size() &&
1388 "Segment size must match contents size");
1389 std::memcpy(B, Seg.getContents().data(), Seg.FileSize);
1390 }
1391
1392 // Iterate over removed sections and overwrite their old data with zeroes.
1393 for (auto &Sec : Obj.removedSections()) {
1394 Segment *Parent = Sec.ParentSegment;
1395 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
1396 continue;
1397 uint64_t Offset =
1398 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
George Rimare98a8f72019-05-23 09:18:57 +00001399 std::memset(Buf.getBufferStart() + Offset, 0, Sec.Size);
James Henderson1f448142019-03-25 16:36:26 +00001400 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001401}
1402
James Henderson38cb2382019-04-02 14:11:13 +00001403template <class ELFT>
1404ELFWriter<ELFT>::ELFWriter(Object &Obj, Buffer &Buf, bool WSH)
1405 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs) {}
1406
James Henderson66a9d0f2019-04-18 09:13:30 +00001407Error Object::removeSections(bool AllowBrokenLinks,
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001408 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001409
1410 auto Iter = std::stable_partition(
1411 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1412 if (ToRemove(*Sec))
1413 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001414 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1415 if (auto ToRelSec = RelSec->getSection())
1416 return !ToRemove(*ToRelSec);
1417 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001418 return true;
1419 });
1420 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1421 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001422 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001423 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001424 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1425 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001426 // Now make sure there are no remaining references to the sections that will
1427 // be removed. Sometimes it is impossible to remove a reference so we emit
1428 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001429 std::unordered_set<const SectionBase *> RemoveSections;
1430 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001431 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1432 for (auto &Segment : Segments)
1433 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001434 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001435 }
George Rimar79fb8582019-02-27 11:18:27 +00001436
1437 // For each section that remains alive, we want to remove the dead references.
1438 // This either might update the content of the section (e.g. remove symbols
1439 // from symbol table that belongs to removed section) or trigger an error if
1440 // a live section critically depends on a section being removed somehow
1441 // (e.g. the removed section is referenced by a relocation).
1442 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
James Henderson66a9d0f2019-04-18 09:13:30 +00001443 if (Error E = KeepSec->removeSectionReferences(AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001444 [&RemoveSections](const SectionBase *Sec) {
1445 return RemoveSections.find(Sec) != RemoveSections.end();
1446 }))
1447 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001448 }
1449
James Henderson1f448142019-03-25 16:36:26 +00001450 // Transfer removed sections into the Object RemovedSections container for use
1451 // later.
1452 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
1453 // Now finally get rid of them all together.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001454 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001455 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001456}
1457
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001458Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1459 if (SymbolTable)
1460 for (const SecPtr &Sec : Sections)
1461 if (Error E = Sec->removeSymbols(ToRemove))
1462 return E;
1463 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001464}
1465
Jake Ehrlich76e91102018-01-25 22:46:17 +00001466void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001467 // Put all sections in offset order. Maintain the ordering as closely as
1468 // possible while meeting that demand however.
Fangrui Songa5355a52019-04-22 15:53:43 +00001469 llvm::stable_sort(Sections, [](const SecPtr &A, const SecPtr &B) {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001470 return A->OriginalOffset < B->OriginalOffset;
Fangrui Songa5355a52019-04-22 15:53:43 +00001471 });
Petr Hosekc4df10e2017-08-04 21:09:26 +00001472}
1473
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001474static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1475 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1476 if (Align == 0)
1477 Align = 1;
1478 auto Diff =
1479 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1480 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1481 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1482 if (Diff < 0)
1483 Diff += Align;
1484 return Offset + Diff;
1485}
1486
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001487// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001488static void orderSegments(std::vector<Segment *> &Segments) {
Fangrui Songa5355a52019-04-22 15:53:43 +00001489 llvm::stable_sort(Segments, compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001490}
1491
1492// This function finds a consistent layout for a list of segments starting from
1493// an Offset. It assumes that Segments have been sorted by OrderSegments and
1494// returns an Offset one past the end of the last segment.
Fangrui Song8da6a6c2019-03-29 15:27:58 +00001495static uint64_t layoutSegments(std::vector<Segment *> &Segments,
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001496 uint64_t Offset) {
1497 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001498 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001499 // The only way a segment should move is if a section was between two
1500 // segments and that section was removed. If that section isn't in a segment
1501 // then it's acceptable, but not ideal, to simply move it to after the
1502 // segments. So we can simply layout segments one after the other accounting
1503 // for alignment.
George Rimare98a8f72019-05-23 09:18:57 +00001504 for (Segment *Seg : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001505 // We assume that segments have been ordered by OriginalOffset and Index
1506 // such that a parent segment will always come before a child segment in
1507 // OrderedSegments. This means that the Offset of the ParentSegment should
1508 // already be set and we can set our offset relative to it.
George Rimare98a8f72019-05-23 09:18:57 +00001509 if (Seg->ParentSegment != nullptr) {
1510 Segment *Parent = Seg->ParentSegment;
1511 Seg->Offset =
1512 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001513 } else {
George Rimare98a8f72019-05-23 09:18:57 +00001514 Offset = alignToAddr(Offset, Seg->VAddr, Seg->Align);
1515 Seg->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001516 }
George Rimare98a8f72019-05-23 09:18:57 +00001517 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001518 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001519 return Offset;
1520}
1521
1522// This function finds a consistent layout for a list of sections. It assumes
1523// that the ->ParentSegment of each section has already been laid out. The
1524// supplied starting Offset is used for the starting offset of any section that
1525// does not have a ParentSegment. It returns either the offset given if all
1526// sections had a ParentSegment or an offset one past the last section if there
1527// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001528template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001529static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001530 // Now the offset of every segment has been set we can assign the offsets
1531 // of each section. For sections that are covered by a segment we should use
1532 // the segment's original offset and the section's original offset to compute
1533 // the offset from the start of the segment. Using the offset from the start
1534 // of the segment we can assign a new offset to the section. For sections not
1535 // covered by segments we can just bump Offset to the next valid location.
1536 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001537 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001538 Section.Index = Index++;
1539 if (Section.ParentSegment != nullptr) {
1540 auto Segment = *Section.ParentSegment;
1541 Section.Offset =
1542 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001543 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001544 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1545 Section.Offset = Offset;
1546 if (Section.Type != SHT_NOBITS)
1547 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001548 }
1549 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001550 return Offset;
1551}
Petr Hosek3f383832017-08-26 01:32:20 +00001552
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001553template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
George Rimare98a8f72019-05-23 09:18:57 +00001554 Segment &ElfHdr = Obj.ElfHdrSegment;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001555 ElfHdr.Type = PT_PHDR;
1556 ElfHdr.Flags = 0;
1557 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1558 ElfHdr.VAddr = 0;
1559 ElfHdr.PAddr = 0;
1560 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1561 ElfHdr.Align = 0;
1562}
1563
Jake Ehrlich76e91102018-01-25 22:46:17 +00001564template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001565 // We need a temporary list of segments that has a special order to it
1566 // so that we know that anytime ->ParentSegment is set that segment has
1567 // already had its offset properly set.
1568 std::vector<Segment *> OrderedSegments;
George Rimare98a8f72019-05-23 09:18:57 +00001569 for (Segment &Segment : Obj.segments())
Jake Ehrlich76e91102018-01-25 22:46:17 +00001570 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001571 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1572 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001573 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001574 // Offset is used as the start offset of the first segment to be laid out.
1575 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1576 // we start at offset 0.
1577 uint64_t Offset = 0;
Fangrui Song8da6a6c2019-03-29 15:27:58 +00001578 Offset = layoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001579 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001580 // If we need to write the section header table out then we need to align the
1581 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001582 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001583 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001584 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001585}
1586
Jake Ehrlich76e91102018-01-25 22:46:17 +00001587template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001588 // We already have the section header offset so we can calculate the total
1589 // size by just adding up the size of each section header.
James Henderson38cb2382019-04-02 14:11:13 +00001590 if (!WriteSectionHeaders)
1591 return Obj.SHOffset;
1592 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
1593 return Obj.SHOffset + ShdrCount * sizeof(Elf_Shdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001594}
1595
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001596template <class ELFT> Error ELFWriter<ELFT>::write() {
James Henderson1f448142019-03-25 16:36:26 +00001597 // Segment data must be written first, so that the ELF header and program
1598 // header tables can overwrite it, if covered by a segment.
1599 writeSegmentData();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001600 writeEhdr();
1601 writePhdrs();
1602 writeSectionData();
1603 if (WriteSectionHeaders)
1604 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001605 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001606}
1607
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001608template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001609 // It could happen that SectionNames has been removed and yet the user wants
1610 // a section header table output. We need to throw an error if a user tries
1611 // to do that.
1612 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001613 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +00001614 "cannot write section header table because "
1615 "section header string table was removed");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001616
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001617 Obj.sortSections();
1618
1619 // We need to assign indexes before we perform layout because we need to know
1620 // if we need large indexes or not. We can assign indexes first and check as
1621 // we go to see if we will actully need large indexes.
1622 bool NeedsLargeIndexes = false;
Fangrui Song82b01e02019-03-30 14:08:59 +00001623 if (Obj.sections().size() >= SHN_LORESERVE) {
George Rimare98a8f72019-05-23 09:18:57 +00001624 SectionTableRef Sections = Obj.sections();
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001625 NeedsLargeIndexes =
1626 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1627 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1628 // TODO: handle case where only one section needs the large index table but
1629 // only needs it because the large index table hasn't been removed yet.
1630 }
1631
1632 if (NeedsLargeIndexes) {
1633 // This means we definitely need to have a section index table but if we
1634 // already have one then we should use it instead of making a new one.
1635 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1636 // Addition of a section to the end does not invalidate the indexes of
1637 // other sections and assigns the correct index to the new section.
1638 auto &Shndx = Obj.addSection<SectionIndexSection>();
1639 Obj.SymbolTable->setShndxTable(&Shndx);
1640 Shndx.setSymTab(Obj.SymbolTable);
1641 }
1642 } else {
1643 // Since we don't need SectionIndexTable we should remove it and all
1644 // references to it.
1645 if (Obj.SectionIndexTable != nullptr) {
James Henderson66a9d0f2019-04-18 09:13:30 +00001646 // We do not support sections referring to the section index table.
1647 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
1648 [this](const SectionBase &Sec) {
1649 return &Sec == Obj.SectionIndexTable;
1650 }))
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001651 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001652 }
1653 }
1654
1655 // Make sure we add the names of all the sections. Importantly this must be
1656 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001657 if (Obj.SectionNames != nullptr)
1658 for (const auto &Section : Obj.sections()) {
1659 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001660 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001661
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001662 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001663
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001664 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001665 // Also, the output arch may not be the same as the input arch, so fix up
1666 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001667 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001668 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1669 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001670 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001671 Sec.accept(*SecSizer);
1672 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001673
1674 // The symbol table does not update all other sections on update. For
1675 // instance, symbol names are not added as new symbols are added. This means
1676 // that some sections, like .strtab, don't yet have their final size.
1677 if (Obj.SymbolTable != nullptr)
1678 Obj.SymbolTable->prepareForLayout();
1679
George Rimarfaf308b2019-03-18 14:27:41 +00001680 // Now that all strings are added we want to finalize string table builders,
1681 // because that affects section sizes which in turn affects section offsets.
George Rimare98a8f72019-05-23 09:18:57 +00001682 for (SectionBase &Sec : Obj.sections())
George Rimarfaf308b2019-03-18 14:27:41 +00001683 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
1684 StrTab->prepareForLayout();
1685
Petr Hosekc4df10e2017-08-04 21:09:26 +00001686 assignOffsets();
1687
Eugene Leviant88089fe2019-04-12 11:59:30 +00001688 // layoutSections could have modified section indexes, so we need
1689 // to fill the index table after assignOffsets.
1690 if (Obj.SymbolTable != nullptr)
1691 Obj.SymbolTable->fillShndxTable();
1692
Petr Hosekc4df10e2017-08-04 21:09:26 +00001693 // Finally now that all offsets and indexes have been set we can finalize any
1694 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001695 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
George Rimare98a8f72019-05-23 09:18:57 +00001696 for (SectionBase &Section : Obj.sections()) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001697 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001698 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001699 if (WriteSectionHeaders)
1700 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1701 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001702 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001703
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001704 if (Error E = Buf.allocate(totalSize()))
1705 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001706 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001707 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001708}
1709
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001710Error BinaryWriter::write() {
George Rimare98a8f72019-05-23 09:18:57 +00001711 for (auto &Section : Obj.sections())
1712 if (Section.Flags & SHF_ALLOC)
1713 Section.accept(*SecWriter);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001714 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001715}
1716
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001717Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001718 // TODO: Create a filter range to construct OrderedSegments from so that this
1719 // code can be deduped with assignOffsets above. This should also solve the
1720 // todo below for LayoutSections.
1721 // We need a temporary list of segments that has a special order to it
1722 // so that we know that anytime ->ParentSegment is set that segment has
1723 // already had it's offset properly set. We only want to consider the segments
1724 // that will affect layout of allocated sections so we only add those.
1725 std::vector<Segment *> OrderedSegments;
George Rimare98a8f72019-05-23 09:18:57 +00001726 for (SectionBase &Section : Obj.sections())
1727 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001728 OrderedSegments.push_back(Section.ParentSegment);
Jake Ehrlich46814be2018-01-22 19:27:30 +00001729
1730 // For binary output, we're going to use physical addresses instead of
1731 // virtual addresses, since a binary output is used for cases like ROM
1732 // loading and physical addresses are intended for ROM loading.
1733 // However, if no segment has a physical address, we'll fallback to using
1734 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001735 if (all_of(OrderedSegments,
1736 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1737 for (Segment *Seg : OrderedSegments)
1738 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001739
Fangrui Songa5355a52019-04-22 15:53:43 +00001740 llvm::stable_sort(OrderedSegments, compareSegmentsByPAddr);
Jake Ehrlich46814be2018-01-22 19:27:30 +00001741
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001742 // Because we add a ParentSegment for each section we might have duplicate
1743 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1744 // would do very strange things.
1745 auto End =
1746 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1747 OrderedSegments.erase(End, std::end(OrderedSegments));
1748
Jake Ehrlich46814be2018-01-22 19:27:30 +00001749 uint64_t Offset = 0;
1750
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001751 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001752 // our layout algorithm to proceed as expected while not writing out the gap
1753 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001754 if (!OrderedSegments.empty()) {
George Rimare98a8f72019-05-23 09:18:57 +00001755 Segment *Seg = OrderedSegments[0];
1756 const SectionBase *Sec = Seg->firstSection();
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001757 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1758 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001759 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001760 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001761 // The PAddr needs to be increased to remove the gap before the first
1762 // section.
1763 Seg->PAddr += Diff;
1764 uint64_t LowestPAddr = Seg->PAddr;
George Rimare98a8f72019-05-23 09:18:57 +00001765 for (Segment *Segment : OrderedSegments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001766 Segment->Offset = Segment->PAddr - LowestPAddr;
1767 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1768 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001769 }
1770
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001771 // TODO: generalize LayoutSections to take a range. Pass a special range
1772 // constructed from an iterator that skips values for which a predicate does
1773 // not hold. Then pass such a range to LayoutSections instead of constructing
1774 // AllocatedSections here.
1775 std::vector<SectionBase *> AllocatedSections;
George Rimare98a8f72019-05-23 09:18:57 +00001776 for (SectionBase &Section : Obj.sections())
1777 if (Section.Flags & SHF_ALLOC)
1778 AllocatedSections.push_back(&Section);
Fangrui Song32a34e62018-11-01 16:02:12 +00001779 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001780
1781 // Now that every section has been laid out we just need to compute the total
1782 // file size. This might not be the same as the offset returned by
1783 // LayoutSections, because we want to truncate the last segment to the end of
1784 // its last section, to match GNU objcopy's behaviour.
1785 TotalSize = 0;
George Rimare98a8f72019-05-23 09:18:57 +00001786 for (SectionBase *Section : AllocatedSections)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001787 if (Section->Type != SHT_NOBITS)
1788 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001789
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001790 if (Error E = Buf.allocate(TotalSize))
1791 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001792 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001793 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001794}
1795
Jake Ehrlich76e91102018-01-25 22:46:17 +00001796template class ELFBuilder<ELF64LE>;
1797template class ELFBuilder<ELF64BE>;
1798template class ELFBuilder<ELF32LE>;
1799template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001800
Jake Ehrlich76e91102018-01-25 22:46:17 +00001801template class ELFWriter<ELF64LE>;
1802template class ELFWriter<ELF64BE>;
1803template class ELFWriter<ELF32LE>;
1804template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001805
1806} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001807} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001808} // end namespace llvm