blob: d859c7e47a6b8a803c1f7517eaf26fa9c2d21609 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Petr Hosek05a04cb2017-08-01 00:33:58 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00008
Petr Hosek05a04cb2017-08-01 00:33:58 +00009#include "Object.h"
10#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/ADT/iterator_range.h"
16#include "llvm/BinaryFormat/ELF.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000017#include "llvm/MC/MCTargetOptions.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000018#include "llvm/Object/ELFObjectFile.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000019#include "llvm/Support/Compression.h"
Jordan Rupprecht971d47622019-02-01 15:20:36 +000020#include "llvm/Support/Errc.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000021#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/FileOutputBuffer.h"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000023#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000024#include <algorithm>
25#include <cstddef>
26#include <cstdint>
27#include <iterator>
Jordan Rupprecht52d57812019-02-21 16:45:42 +000028#include <unordered_set>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include <utility>
30#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000031
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000032namespace llvm {
33namespace objcopy {
34namespace elf {
35
Petr Hosek05a04cb2017-08-01 00:33:58 +000036using namespace object;
37using namespace ELF;
38
Jake Ehrlich76e91102018-01-25 22:46:17 +000039template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000040 uint8_t *B = Buf.getBufferStart();
41 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
42 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000043 Phdr.p_type = Seg.Type;
44 Phdr.p_flags = Seg.Flags;
45 Phdr.p_offset = Seg.Offset;
46 Phdr.p_vaddr = Seg.VAddr;
47 Phdr.p_paddr = Seg.PAddr;
48 Phdr.p_filesz = Seg.FileSize;
49 Phdr.p_memsz = Seg.MemSize;
50 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000051}
52
Jordan Rupprecht52d57812019-02-21 16:45:42 +000053Error SectionBase::removeSectionReferences(
54 function_ref<bool(const SectionBase *)> ToRemove) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +000055 return Error::success();
56}
57
58Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
59 return Error::success();
60}
61
Jake Ehrlichf5a43772017-09-25 20:37:28 +000062void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000063void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000064void SectionBase::markSymbols() {}
George Rimard8a5c6c2019-03-11 11:01:24 +000065void SectionBase::replaceSectionReferences(
66 const DenseMap<SectionBase *, SectionBase *> &) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000067
Jake Ehrlich76e91102018-01-25 22:46:17 +000068template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000069 uint8_t *B = Buf.getBufferStart();
70 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000071 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000072 Shdr.sh_name = Sec.NameIndex;
73 Shdr.sh_type = Sec.Type;
74 Shdr.sh_flags = Sec.Flags;
75 Shdr.sh_addr = Sec.Addr;
76 Shdr.sh_offset = Sec.Offset;
77 Shdr.sh_size = Sec.Size;
78 Shdr.sh_link = Sec.Link;
79 Shdr.sh_info = Sec.Info;
80 Shdr.sh_addralign = Sec.Align;
81 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000082}
83
Jordan Rupprecht1f821762019-01-03 17:45:30 +000084template <class ELFT> void ELFSectionSizer<ELFT>::visit(Section &Sec) {}
85
86template <class ELFT>
87void ELFSectionSizer<ELFT>::visit(OwnedDataSection &Sec) {}
88
89template <class ELFT>
90void ELFSectionSizer<ELFT>::visit(StringTableSection &Sec) {}
91
92template <class ELFT>
93void ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &Sec) {}
94
95template <class ELFT>
96void ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
97 Sec.EntrySize = sizeof(Elf_Sym);
98 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000099 // Align to the largest field in Elf_Sym.
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000100 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000101}
102
103template <class ELFT>
104void ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
105 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
106 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +0000107 // Align to the largest field in Elf_Rel(a).
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000108 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000109}
110
111template <class ELFT>
112void ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &Sec) {}
113
114template <class ELFT> void ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {}
115
116template <class ELFT>
117void ELFSectionSizer<ELFT>::visit(SectionIndexSection &Sec) {}
118
119template <class ELFT>
120void ELFSectionSizer<ELFT>::visit(CompressedSection &Sec) {}
121
122template <class ELFT>
123void ELFSectionSizer<ELFT>::visit(DecompressedSection &Sec) {}
Jake Ehrlich76e91102018-01-25 22:46:17 +0000124
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000125void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
126 error("Cannot write symbol section index table '" + Sec.Name + "' ");
127}
128
Jake Ehrlich76e91102018-01-25 22:46:17 +0000129void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
130 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
131}
132
133void BinarySectionWriter::visit(const RelocationSection &Sec) {
134 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
135}
136
137void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000138 error("Cannot write '" + Sec.Name + "' out to binary");
139}
140
141void BinarySectionWriter::visit(const GroupSection &Sec) {
142 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000143}
144
145void SectionWriter::visit(const Section &Sec) {
146 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000147 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000148 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000149 llvm::copy(Sec.Contents, Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000150}
151
Jake Ehrlich76e91102018-01-25 22:46:17 +0000152void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
153
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000154void Section::accept(MutableSectionVisitor &Visitor) { Visitor.visit(*this); }
155
Jake Ehrlich76e91102018-01-25 22:46:17 +0000156void SectionWriter::visit(const OwnedDataSection &Sec) {
157 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000158 llvm::copy(Sec.Data, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000159}
160
Puyan Lotfiaf048642018-10-01 10:29:41 +0000161static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
162
163static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
164 return Data.size() > ZlibGnuMagic.size() &&
165 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
166}
167
168template <class ELFT>
169static std::tuple<uint64_t, uint64_t>
170getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
171 const bool IsGnuDebug = isDataGnuCompressed(Data);
172 const uint64_t DecompressedSize =
173 IsGnuDebug
174 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
175 Data.data() + ZlibGnuMagic.size()))
176 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
177 const uint64_t DecompressedAlign =
178 IsGnuDebug ? 1
179 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
180 ->ch_addralign;
181
182 return std::make_tuple(DecompressedSize, DecompressedAlign);
183}
184
185template <class ELFT>
186void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
Puyan Lotfiaf048642018-10-01 10:29:41 +0000187 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
188 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
189 : sizeof(Elf_Chdr_Impl<ELFT>);
190
191 StringRef CompressedContent(
192 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
193 Sec.OriginalData.size() - DataOffset);
194
195 SmallVector<char, 128> DecompressedContent;
196 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
197 static_cast<size_t>(Sec.Size)))
198 reportError(Sec.Name, std::move(E));
199
George Rimar281a5be2019-03-06 14:12:18 +0000200 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfiaf048642018-10-01 10:29:41 +0000201 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
202}
203
204void BinarySectionWriter::visit(const DecompressedSection &Sec) {
205 error("Cannot write compressed section '" + Sec.Name + "' ");
206}
207
208void DecompressedSection::accept(SectionVisitor &Visitor) const {
209 Visitor.visit(*this);
210}
211
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000212void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
213 Visitor.visit(*this);
214}
215
Jake Ehrlich76e91102018-01-25 22:46:17 +0000216void OwnedDataSection::accept(SectionVisitor &Visitor) const {
217 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000218}
219
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000220void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
221 Visitor.visit(*this);
222}
223
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000224void BinarySectionWriter::visit(const CompressedSection &Sec) {
225 error("Cannot write compressed section '" + Sec.Name + "' ");
226}
227
228template <class ELFT>
229void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
230 uint8_t *Buf = Out.getBufferStart();
231 Buf += Sec.Offset;
232
233 if (Sec.CompressionType == DebugCompressionType::None) {
234 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
235 return;
236 }
237
238 if (Sec.CompressionType == DebugCompressionType::GNU) {
239 const char *Magic = "ZLIB";
240 memcpy(Buf, Magic, strlen(Magic));
241 Buf += strlen(Magic);
242 const uint64_t DecompressedSize =
243 support::endian::read64be(&Sec.DecompressedSize);
244 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
245 Buf += sizeof(DecompressedSize);
246 } else {
247 Elf_Chdr_Impl<ELFT> Chdr;
248 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
249 Chdr.ch_size = Sec.DecompressedSize;
250 Chdr.ch_addralign = Sec.DecompressedAlign;
251 memcpy(Buf, &Chdr, sizeof(Chdr));
252 Buf += sizeof(Chdr);
253 }
254
255 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
256}
257
258CompressedSection::CompressedSection(const SectionBase &Sec,
259 DebugCompressionType CompressionType)
260 : SectionBase(Sec), CompressionType(CompressionType),
261 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000262 if (Error E = zlib::compress(
263 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
264 OriginalData.size()),
265 CompressedData))
266 reportError(Name, std::move(E));
267
268 size_t ChdrSize;
269 if (CompressionType == DebugCompressionType::GNU) {
270 Name = ".z" + Sec.Name.substr(1);
271 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
272 } else {
273 Flags |= ELF::SHF_COMPRESSED;
274 ChdrSize =
275 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
276 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
277 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
278 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
279 }
280 Size = ChdrSize + CompressedData.size();
281 Align = 8;
282}
283
Puyan Lotfiaf048642018-10-01 10:29:41 +0000284CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
285 uint64_t DecompressedSize,
286 uint64_t DecompressedAlign)
287 : CompressionType(DebugCompressionType::None),
288 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
289 OriginalData = CompressedData;
290}
291
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000292void CompressedSection::accept(SectionVisitor &Visitor) const {
293 Visitor.visit(*this);
294}
295
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000296void CompressedSection::accept(MutableSectionVisitor &Visitor) {
297 Visitor.visit(*this);
298}
299
Petr Hosek05a04cb2017-08-01 00:33:58 +0000300void StringTableSection::addString(StringRef Name) {
301 StrTabBuilder.add(Name);
302 Size = StrTabBuilder.getSize();
303}
304
305uint32_t StringTableSection::findIndex(StringRef Name) const {
306 return StrTabBuilder.getOffset(Name);
307}
308
309void StringTableSection::finalize() { StrTabBuilder.finalize(); }
310
Jake Ehrlich76e91102018-01-25 22:46:17 +0000311void SectionWriter::visit(const StringTableSection &Sec) {
312 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
313}
314
315void StringTableSection::accept(SectionVisitor &Visitor) const {
316 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000317}
318
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000319void StringTableSection::accept(MutableSectionVisitor &Visitor) {
320 Visitor.visit(*this);
321}
322
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000323template <class ELFT>
324void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
325 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000326 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000327 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000328}
329
330void SectionIndexSection::initialize(SectionTableRef SecTable) {
331 Size = 0;
332 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
333 Link,
334 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
335 "Link field value " + Twine(Link) + " in section " + Name +
336 " is not a symbol table"));
337 Symbols->setShndxTable(this);
338}
339
340void SectionIndexSection::finalize() { Link = Symbols->Index; }
341
342void SectionIndexSection::accept(SectionVisitor &Visitor) const {
343 Visitor.visit(*this);
344}
345
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000346void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
347 Visitor.visit(*this);
348}
349
Petr Hosekc1135772017-09-13 03:04:50 +0000350static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000351 switch (Index) {
352 case SHN_ABS:
353 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000354 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000355 }
Petr Hosekc1135772017-09-13 03:04:50 +0000356 if (Machine == EM_HEXAGON) {
357 switch (Index) {
358 case SHN_HEXAGON_SCOMMON:
359 case SHN_HEXAGON_SCOMMON_2:
360 case SHN_HEXAGON_SCOMMON_4:
361 case SHN_HEXAGON_SCOMMON_8:
362 return true;
363 }
364 }
365 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000366}
367
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000368// Large indexes force us to clarify exactly what this function should do. This
369// function should return the value that will appear in st_shndx when written
370// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000371uint16_t Symbol::getShndx() const {
372 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000373 if (DefinedIn->Index >= SHN_LORESERVE)
374 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000375 return DefinedIn->Index;
376 }
377 switch (ShndxType) {
378 // This means that we don't have a defined section but we do need to
379 // output a legitimate section index.
380 case SYMBOL_SIMPLE_INDEX:
381 return SHN_UNDEF;
382 case SYMBOL_ABS:
383 case SYMBOL_COMMON:
384 case SYMBOL_HEXAGON_SCOMMON:
385 case SYMBOL_HEXAGON_SCOMMON_2:
386 case SYMBOL_HEXAGON_SCOMMON_4:
387 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000388 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000389 return static_cast<uint16_t>(ShndxType);
390 }
391 llvm_unreachable("Symbol with invalid ShndxType encountered");
392}
393
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000394bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
395
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000396void SymbolTableSection::assignIndices() {
397 uint32_t Index = 0;
398 for (auto &Sym : Symbols)
399 Sym->Index = Index++;
400}
401
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000402void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000403 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000404 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000405 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000406 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000407 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000408 Sym.Binding = Bind;
409 Sym.Type = Type;
410 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000411 if (DefinedIn != nullptr)
412 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000413 if (DefinedIn == nullptr) {
414 if (Shndx >= SHN_LORESERVE)
415 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
416 else
417 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
418 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000419 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000420 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000421 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000422 Sym.Index = Symbols.size();
423 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
424 Size += this->EntrySize;
425}
426
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000427Error SymbolTableSection::removeSectionReferences(
428 function_ref<bool(const SectionBase *)> ToRemove) {
429 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000430 SectionIndexTable = nullptr;
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000431 if (ToRemove(SymbolNames))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000432 return createStringError(llvm::errc::invalid_argument,
433 "String table %s cannot be removed because it is "
434 "referenced by the symbol table %s",
435 SymbolNames->Name.data(), this->Name.data());
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000436 return removeSymbols(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000437 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000438}
439
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000440void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000441 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
442 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000443 std::stable_partition(
444 std::begin(Symbols), std::end(Symbols),
445 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000446 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000447}
448
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000449Error SymbolTableSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000450 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000451 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000452 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000453 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
454 std::end(Symbols));
455 Size = Symbols.size() * EntrySize;
456 assignIndices();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000457 return Error::success();
Paul Semel41695f82018-05-02 20:19:22 +0000458}
459
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000460void SymbolTableSection::initialize(SectionTableRef SecTable) {
461 Size = 0;
462 setStrTab(SecTable.getSectionOfType<StringTableSection>(
463 Link,
464 "Symbol table has link index of " + Twine(Link) +
465 " which is not a valid index",
466 "Symbol table has link index of " + Twine(Link) +
467 " which is not a string table"));
468}
469
Petr Hosek79cee9e2017-08-29 02:12:03 +0000470void SymbolTableSection::finalize() {
471 // Make sure SymbolNames is finalized before getting name indexes.
472 SymbolNames->finalize();
473
474 uint32_t MaxLocalIndex = 0;
475 for (auto &Sym : Symbols) {
476 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
477 if (Sym->Binding == STB_LOCAL)
478 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
479 }
480 // Now we need to set the Link and Info fields.
481 Link = SymbolNames->Index;
482 Info = MaxLocalIndex + 1;
483}
484
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000485void SymbolTableSection::prepareForLayout() {
486 // Add all potential section indexes before file layout so that the section
487 // index section has the approprite size.
488 if (SectionIndexTable != nullptr) {
489 for (const auto &Sym : Symbols) {
490 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
491 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
492 else
493 SectionIndexTable->addIndex(SHN_UNDEF);
494 }
495 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000496 // Add all of our strings to SymbolNames so that SymbolNames has the right
497 // size before layout is decided.
498 for (auto &Sym : Symbols)
499 SymbolNames->addString(Sym->Name);
500}
501
502const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
503 if (Symbols.size() <= Index)
504 error("Invalid symbol index: " + Twine(Index));
505 return Symbols[Index].get();
506}
507
Paul Semel99dda0b2018-05-25 11:01:25 +0000508Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
509 return const_cast<Symbol *>(
510 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
511}
512
Petr Hosek79cee9e2017-08-29 02:12:03 +0000513template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000514void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000515 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000516 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000517 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000518 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000519 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000520 Sym->st_name = Symbol->NameIndex;
521 Sym->st_value = Symbol->Value;
522 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000523 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000524 Sym->setBinding(Symbol->Binding);
525 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000526 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000527 ++Sym;
528 }
529}
530
Jake Ehrlich76e91102018-01-25 22:46:17 +0000531void SymbolTableSection::accept(SectionVisitor &Visitor) const {
532 Visitor.visit(*this);
533}
534
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000535void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
536 Visitor.visit(*this);
537}
538
George Rimar79fb8582019-02-27 11:18:27 +0000539Error RelocationSection::removeSectionReferences(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000540 function_ref<bool(const SectionBase *)> ToRemove) {
541 if (ToRemove(Symbols))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000542 return createStringError(llvm::errc::invalid_argument,
543 "Symbol table %s cannot be removed because it is "
544 "referenced by the relocation section %s.",
545 Symbols->Name.data(), this->Name.data());
George Rimar79fb8582019-02-27 11:18:27 +0000546
547 for (const Relocation &R : Relocations) {
548 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
549 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000550 return createStringError(llvm::errc::invalid_argument,
551 "Section %s can't be removed: (%s+0x%" PRIx64
552 ") has relocation against symbol '%s'",
553 R.RelocSymbol->DefinedIn->Name.data(),
554 SecToApplyRel->Name.data(), R.Offset,
555 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000556 }
557
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000558 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000559}
560
561template <class SymTabType>
562void RelocSectionWithSymtabBase<SymTabType>::initialize(
563 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000564 if (Link != SHN_UNDEF)
565 setSymTab(SecTable.getSectionOfType<SymTabType>(
566 Link,
567 "Link field value " + Twine(Link) + " in section " + Name +
568 " is invalid",
569 "Link field value " + Twine(Link) + " in section " + Name +
570 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000571
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000572 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000573 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
574 " in section " + Name +
575 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000576 else
577 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000578}
579
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000580template <class SymTabType>
581void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000582 this->Link = Symbols ? Symbols->Index : 0;
583
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000584 if (SecToApplyRel != nullptr)
585 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000586}
587
588template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000589static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000590
591template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000592static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000593 Rela.r_addend = Addend;
594}
595
Jake Ehrlich76e91102018-01-25 22:46:17 +0000596template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000597static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000598 for (const auto &Reloc : Relocations) {
599 Buf->r_offset = Reloc.Offset;
600 setAddend(*Buf, Reloc.Addend);
601 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
602 ++Buf;
603 }
604}
605
606template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000607void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
608 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
609 if (Sec.Type == SHT_REL)
610 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000611 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000612 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000613}
614
Jake Ehrlich76e91102018-01-25 22:46:17 +0000615void RelocationSection::accept(SectionVisitor &Visitor) const {
616 Visitor.visit(*this);
617}
618
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000619void RelocationSection::accept(MutableSectionVisitor &Visitor) {
620 Visitor.visit(*this);
621}
622
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000623Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000624 function_ref<bool(const Symbol &)> ToRemove) {
625 for (const Relocation &Reloc : Relocations)
626 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000627 return createStringError(
628 llvm::errc::invalid_argument,
629 "not stripping symbol '%s' because it is named in a relocation.",
630 Reloc.RelocSymbol->Name.data());
631 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000632}
633
Paul Semel99dda0b2018-05-25 11:01:25 +0000634void RelocationSection::markSymbols() {
635 for (const Relocation &Reloc : Relocations)
636 Reloc.RelocSymbol->Referenced = true;
637}
638
George Rimard8a5c6c2019-03-11 11:01:24 +0000639void RelocationSection::replaceSectionReferences(
640 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
641 // Update the target section if it was replaced.
642 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
643 SecToApplyRel = To;
644
645 // Change the sections where symbols are defined in if their
646 // original sections were replaced.
647 for (const Relocation &R : Relocations)
648 if (SectionBase *To = FromTo.lookup(R.RelocSymbol->DefinedIn))
649 R.RelocSymbol->DefinedIn = To;
650}
651
Jake Ehrlich76e91102018-01-25 22:46:17 +0000652void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000653 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000654 Out.getBufferStart() + Sec.Offset);
655}
656
657void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
658 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000659}
660
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000661void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
662 Visitor.visit(*this);
663}
664
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000665Error Section::removeSectionReferences(
666 function_ref<bool(const SectionBase *)> ToRemove) {
667 if (ToRemove(LinkSection))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000668 return createStringError(llvm::errc::invalid_argument,
669 "Section %s cannot be removed because it is "
670 "referenced by the section %s",
671 LinkSection->Name.data(), this->Name.data());
672 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000673}
674
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000675void GroupSection::finalize() {
676 this->Info = Sym->Index;
677 this->Link = SymTab->Index;
678}
679
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000680Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
681 if (ToRemove(*Sym))
682 return createStringError(llvm::errc::invalid_argument,
683 "Symbol %s cannot be removed because it is "
684 "referenced by the section %s[%d].",
685 Sym->Name.data(), this->Name.data(), this->Index);
686 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000687}
688
Paul Semel99dda0b2018-05-25 11:01:25 +0000689void GroupSection::markSymbols() {
690 if (Sym)
691 Sym->Referenced = true;
692}
693
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000694void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000695 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000696 LinkSection =
697 SecTable.getSection(Link, "Link field value " + Twine(Link) +
698 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000699 if (LinkSection->Type == ELF::SHT_SYMTAB)
700 LinkSection = nullptr;
701 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000702}
703
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000704void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000705
Jake Ehrlich76e91102018-01-25 22:46:17 +0000706void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000707 FileName = sys::path::filename(File);
708 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000709 // followed by a null terminator and then the CRC32 of the file. The CRC32
710 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
711 // byte, and then finally push the size to alignment and add 4.
712 Size = alignTo(FileName.size() + 1, 4) + 4;
713 // The CRC32 will only be aligned if we align the whole section.
714 Align = 4;
715 Type = ELF::SHT_PROGBITS;
716 Name = ".gnu_debuglink";
717 // For sections not found in segments, OriginalOffset is only used to
718 // establish the order that sections should go in. By using the maximum
719 // possible offset we cause this section to wind up at the end.
720 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000721 JamCRC CRC;
722 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000723 // The CRC32 value needs to be complemented because the JamCRC dosn't
724 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
725 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000726 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000727}
728
Jake Ehrlich76e91102018-01-25 22:46:17 +0000729GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000730 // Read in the file to compute the CRC of it.
731 auto DebugOrErr = MemoryBuffer::getFile(File);
732 if (!DebugOrErr)
733 error("'" + File + "': " + DebugOrErr.getError().message());
734 auto Debug = std::move(*DebugOrErr);
735 init(File, Debug->getBuffer());
736}
737
738template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000739void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
740 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000741 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000742 Elf_Word *CRC =
743 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
744 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000745 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000746}
747
748void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
749 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000750}
751
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000752void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
753 Visitor.visit(*this);
754}
755
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000756template <class ELFT>
757void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
758 ELF::Elf32_Word *Buf =
759 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
760 *Buf++ = Sec.FlagWord;
761 for (const auto *S : Sec.GroupMembers)
762 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
763}
764
765void GroupSection::accept(SectionVisitor &Visitor) const {
766 Visitor.visit(*this);
767}
768
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000769void GroupSection::accept(MutableSectionVisitor &Visitor) {
770 Visitor.visit(*this);
771}
772
Petr Hosek05a04cb2017-08-01 00:33:58 +0000773// Returns true IFF a section is wholly inside the range of a segment
774static bool sectionWithinSegment(const SectionBase &Section,
775 const Segment &Segment) {
776 // If a section is empty it should be treated like it has a size of 1. This is
777 // to clarify the case when an empty section lies on a boundary between two
778 // segments and ensures that the section "belongs" to the second segment and
779 // not the first.
780 uint64_t SecSize = Section.Size ? Section.Size : 1;
781 return Segment.Offset <= Section.OriginalOffset &&
782 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
783}
784
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000785// Returns true IFF a segment's original offset is inside of another segment's
786// range.
787static bool segmentOverlapsSegment(const Segment &Child,
788 const Segment &Parent) {
789
790 return Parent.OriginalOffset <= Child.OriginalOffset &&
791 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
792}
793
Jake Ehrlich46814be2018-01-22 19:27:30 +0000794static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000795 // Any segment without a parent segment should come before a segment
796 // that has a parent segment.
797 if (A->OriginalOffset < B->OriginalOffset)
798 return true;
799 if (A->OriginalOffset > B->OriginalOffset)
800 return false;
801 return A->Index < B->Index;
802}
803
Jake Ehrlich46814be2018-01-22 19:27:30 +0000804static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
805 if (A->PAddr < B->PAddr)
806 return true;
807 if (A->PAddr > B->PAddr)
808 return false;
809 return A->Index < B->Index;
810}
811
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000812void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000813 Obj->Flags = 0x0;
814 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000815 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000816 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000817 Obj->Entry = 0x0;
818 Obj->Machine = EMachine;
819 Obj->Version = 1;
820}
821
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000822void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000823
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000824StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000825 auto &StrTab = Obj->addSection<StringTableSection>();
826 StrTab.Name = ".strtab";
827
828 Obj->SectionNames = &StrTab;
829 return &StrTab;
830}
831
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000832SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000833 auto &SymTab = Obj->addSection<SymbolTableSection>();
834
835 SymTab.Name = ".symtab";
836 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000837
838 // The symbol table always needs a null symbol
839 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
840
841 Obj->SymbolTable = &SymTab;
842 return &SymTab;
843}
844
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000845void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000846 auto Data = ArrayRef<uint8_t>(
847 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
848 MemBuf->getBufferSize());
849 auto &DataSection = Obj->addSection<Section>(Data);
850 DataSection.Name = ".data";
851 DataSection.Type = ELF::SHT_PROGBITS;
852 DataSection.Size = Data.size();
853 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
854
855 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
856 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000857 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000858 Twine Prefix = Twine("_binary_") + SanitizedFilename;
859
860 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
861 /*Value=*/0, STV_DEFAULT, 0, 0);
862 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
863 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
864 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
865 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
866}
867
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000868void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000869 for (auto &Section : Obj->sections()) {
870 Section.initialize(Obj->sections());
871 }
872}
873
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000874std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000875 initFileHeader();
876 initHeaderSegment();
877 StringTableSection *StrTab = addStrTab();
878 SymbolTableSection *SymTab = addSymTab(StrTab);
879 initSections();
880 addData(SymTab);
881
882 return std::move(Obj);
883}
884
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000885template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000886 for (auto &Parent : Obj.segments()) {
887 // Every segment will overlap with itself but we don't want a segment to
888 // be it's own parent so we avoid that situation.
889 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
890 // We want a canonical "most parental" segment but this requires
891 // inspecting the ParentSegment.
892 if (compareSegmentsByOffset(&Parent, &Child))
893 if (Child.ParentSegment == nullptr ||
894 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
895 Child.ParentSegment = &Parent;
896 }
897 }
898 }
899}
900
Jake Ehrlich76e91102018-01-25 22:46:17 +0000901template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000902 uint32_t Index = 0;
903 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000904 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
905 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000906 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000907 Seg.Type = Phdr.p_type;
908 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000909 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000910 Seg.Offset = Phdr.p_offset;
911 Seg.VAddr = Phdr.p_vaddr;
912 Seg.PAddr = Phdr.p_paddr;
913 Seg.FileSize = Phdr.p_filesz;
914 Seg.MemSize = Phdr.p_memsz;
915 Seg.Align = Phdr.p_align;
916 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000917 for (auto &Section : Obj.sections()) {
918 if (sectionWithinSegment(Section, Seg)) {
919 Seg.addSection(&Section);
920 if (!Section.ParentSegment ||
921 Section.ParentSegment->Offset > Seg.Offset) {
922 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000923 }
924 }
925 }
926 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000927
928 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000929 ElfHdr.Index = Index++;
930
931 const auto &Ehdr = *ElfFile.getHeader();
932 auto &PrHdr = Obj.ProgramHdrSegment;
933 PrHdr.Type = PT_PHDR;
934 PrHdr.Flags = 0;
935 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
936 // Whereas this works automatically for ElfHdr, here OriginalOffset is
937 // always non-zero and to ensure the equation we assign the same value to
938 // VAddr as well.
939 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
940 PrHdr.PAddr = 0;
941 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000942 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000943 PrHdr.Align = sizeof(Elf_Addr);
944 PrHdr.Index = Index++;
945
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000946 // Now we do an O(n^2) loop through the segments in order to match up
947 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000948 for (auto &Child : Obj.segments())
949 setParentSegment(Child);
950 setParentSegment(ElfHdr);
951 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000952}
953
954template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000955void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
956 auto SecTable = Obj.sections();
957 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
958 GroupSec->Link,
959 "Link field value " + Twine(GroupSec->Link) + " in section " +
960 GroupSec->Name + " is invalid",
961 "Link field value " + Twine(GroupSec->Link) + " in section " +
962 GroupSec->Name + " is not a symbol table");
963 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
964 if (!Sym)
965 error("Info field value " + Twine(GroupSec->Info) + " in section " +
966 GroupSec->Name + " is not a valid symbol index");
967 GroupSec->setSymTab(SymTab);
968 GroupSec->setSymbol(Sym);
969 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
970 GroupSec->Contents.empty())
971 error("The content of the section " + GroupSec->Name + " is malformed");
972 const ELF::Elf32_Word *Word =
973 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
974 const ELF::Elf32_Word *End =
975 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
976 GroupSec->setFlagWord(*Word++);
977 for (; Word != End; ++Word) {
978 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
979 GroupSec->addMember(SecTable.getSection(
980 Index, "Group member index " + Twine(Index) + " in section " +
981 GroupSec->Name + " is invalid"));
982 }
983}
984
985template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000986void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000987 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
988 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000989 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000990
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000991 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
992 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000993 SectionBase *DefSection = nullptr;
994 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000995
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000996 if (Sym.st_shndx == SHN_XINDEX) {
997 if (SymTab->getShndxTable() == nullptr)
998 error("Symbol '" + Name +
999 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
1000 if (ShndxData.data() == nullptr) {
1001 const Elf_Shdr &ShndxSec =
1002 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1003 ShndxData = unwrapOrError(
1004 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1005 if (ShndxData.size() != Symbols.size())
1006 error("Symbol section index table does not have the same number of "
1007 "entries as the symbol table.");
1008 }
1009 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1010 DefSection = Obj.sections().getSection(
1011 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +00001012 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001013 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001014 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001015 error(
1016 "Symbol '" + Name +
1017 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1018 Twine(Sym.st_shndx));
1019 }
1020 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001021 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001022 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001023 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001024 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001025 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001026
Petr Hosek79cee9e2017-08-29 02:12:03 +00001027 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001028 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001029 }
1030}
1031
1032template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001033static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1034
1035template <class ELFT>
1036static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1037 ToSet = Rela.r_addend;
1038}
1039
Jake Ehrlich76e91102018-01-25 22:46:17 +00001040template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001041static void initRelocations(RelocationSection *Relocs,
1042 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001043 for (const auto &Rel : RelRange) {
1044 Relocation ToAdd;
1045 ToAdd.Offset = Rel.r_offset;
1046 getAddend(ToAdd.Addend, Rel);
1047 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001048 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001049 Relocs->addRelocation(ToAdd);
1050 }
1051}
1052
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001053SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001054 if (Index == SHN_UNDEF || Index > Sections.size())
1055 error(ErrMsg);
1056 return Sections[Index - 1].get();
1057}
1058
1059template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001060T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001061 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001062 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001063 return Sec;
1064 error(TypeErrMsg);
1065}
1066
Petr Hosekd7df9b22017-09-06 23:41:02 +00001067template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001069 ArrayRef<uint8_t> Data;
1070 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001071 case SHT_REL:
1072 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001073 if (Shdr.sh_flags & SHF_ALLOC) {
1074 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001075 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001076 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001077 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001078 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001079 // If a string table is allocated we don't want to mess with it. That would
1080 // mean altering the memory image. There are no special link types or
1081 // anything so we can just use a Section.
1082 if (Shdr.sh_flags & SHF_ALLOC) {
1083 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001084 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001085 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001086 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001087 case SHT_HASH:
1088 case SHT_GNU_HASH:
1089 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1090 // Because of this we don't need to mess with the hash tables either.
1091 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001092 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001093 case SHT_GROUP:
1094 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1095 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001096 case SHT_DYNSYM:
1097 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001098 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001099 case SHT_DYNAMIC:
1100 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001101 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001102 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001103 auto &SymTab = Obj.addSection<SymbolTableSection>();
1104 Obj.SymbolTable = &SymTab;
1105 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001106 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001107 case SHT_SYMTAB_SHNDX: {
1108 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1109 Obj.SectionIndexTable = &ShndxSection;
1110 return ShndxSection;
1111 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001112 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001113 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001114 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001115 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001116
George Rimarf2eb8ca2019-03-06 14:01:54 +00001117 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1118 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001119 uint64_t DecompressedSize, DecompressedAlign;
1120 std::tie(DecompressedSize, DecompressedAlign) =
1121 getDecompressedSizeAndAlignment<ELFT>(Data);
1122 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1123 DecompressedAlign);
1124 }
1125
Jake Ehrlich76e91102018-01-25 22:46:17 +00001126 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001127 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001128 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001129}
1130
Jake Ehrlich76e91102018-01-25 22:46:17 +00001131template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001132 uint32_t Index = 0;
1133 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1134 if (Index == 0) {
1135 ++Index;
1136 continue;
1137 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001138 auto &Sec = makeSection(Shdr);
1139 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1140 Sec.Type = Shdr.sh_type;
1141 Sec.Flags = Shdr.sh_flags;
1142 Sec.Addr = Shdr.sh_addr;
1143 Sec.Offset = Shdr.sh_offset;
1144 Sec.OriginalOffset = Shdr.sh_offset;
1145 Sec.Size = Shdr.sh_size;
1146 Sec.Link = Shdr.sh_link;
1147 Sec.Info = Shdr.sh_info;
1148 Sec.Align = Shdr.sh_addralign;
1149 Sec.EntrySize = Shdr.sh_entsize;
1150 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001151 Sec.OriginalData =
1152 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1153 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001154 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001155
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001156 // If a section index table exists we'll need to initialize it before we
1157 // initialize the symbol table because the symbol table might need to
1158 // reference it.
1159 if (Obj.SectionIndexTable)
1160 Obj.SectionIndexTable->initialize(Obj.sections());
1161
Petr Hosek79cee9e2017-08-29 02:12:03 +00001162 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001163 // details about symbol tables. We need the symbol table filled out before
1164 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001165 if (Obj.SymbolTable) {
1166 Obj.SymbolTable->initialize(Obj.sections());
1167 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001168 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001169
1170 // Now that all sections and symbols have been added we can add
1171 // relocations that reference symbols and set the link and info fields for
1172 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001173 for (auto &Section : Obj.sections()) {
1174 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001175 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001176 Section.initialize(Obj.sections());
1177 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001178 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1179 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001180 initRelocations(RelSec, Obj.SymbolTable,
1181 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001182 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001183 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001184 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001185 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1186 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001187 }
1188 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001189}
1190
Jake Ehrlich76e91102018-01-25 22:46:17 +00001191template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001192 const auto &Ehdr = *ElfFile.getHeader();
1193
George Rimar4ded7732018-12-20 10:51:42 +00001194 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1195 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001196 Obj.Type = Ehdr.e_type;
1197 Obj.Machine = Ehdr.e_machine;
1198 Obj.Version = Ehdr.e_version;
1199 Obj.Entry = Ehdr.e_entry;
1200 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001201
Jake Ehrlich76e91102018-01-25 22:46:17 +00001202 readSectionHeaders();
1203 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001204
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001205 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1206 if (ShstrIndex == SHN_XINDEX)
1207 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1208
Jake Ehrlich76e91102018-01-25 22:46:17 +00001209 Obj.SectionNames =
1210 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001211 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001212 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001213 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001214 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001215 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001216}
1217
Jake Ehrlich76e91102018-01-25 22:46:17 +00001218// A generic size function which computes sizes of any random access range.
1219template <class R> size_t size(R &&Range) {
1220 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1221}
1222
1223Writer::~Writer() {}
1224
1225Reader::~Reader() {}
1226
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001227std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001228 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001229}
1230
1231std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001232 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001233 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1234 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001235 Builder.build();
1236 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001237 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1238 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001239 Builder.build();
1240 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001241 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1242 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001243 Builder.build();
1244 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001245 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1246 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001247 Builder.build();
1248 return Obj;
1249 }
1250 error("Invalid file type");
1251}
1252
1253template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001254 uint8_t *B = Buf.getBufferStart();
1255 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001256 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1257 Ehdr.e_ident[EI_MAG0] = 0x7f;
1258 Ehdr.e_ident[EI_MAG1] = 'E';
1259 Ehdr.e_ident[EI_MAG2] = 'L';
1260 Ehdr.e_ident[EI_MAG3] = 'F';
1261 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1262 Ehdr.e_ident[EI_DATA] =
1263 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1264 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001265 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1266 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001267
Jake Ehrlich76e91102018-01-25 22:46:17 +00001268 Ehdr.e_type = Obj.Type;
1269 Ehdr.e_machine = Obj.Machine;
1270 Ehdr.e_version = Obj.Version;
1271 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001272 // We have to use the fully-qualified name llvm::size
1273 // since some compilers complain on ambiguous resolution.
1274 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001275 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1276 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001277 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001278 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001279 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1280 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001281 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001282 // """
1283 // If the number of sections is greater than or equal to
1284 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1285 // number of section header table entries is contained in the sh_size field
1286 // of the section header at index 0.
1287 // """
1288 auto Shnum = size(Obj.sections()) + 1;
1289 if (Shnum >= SHN_LORESERVE)
1290 Ehdr.e_shnum = 0;
1291 else
1292 Ehdr.e_shnum = Shnum;
1293 // """
1294 // If the section name string table section index is greater than or equal
1295 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1296 // and the actual index of the section name string table section is
1297 // contained in the sh_link field of the section header at index 0.
1298 // """
1299 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1300 Ehdr.e_shstrndx = SHN_XINDEX;
1301 else
1302 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001303 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001304 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001305 Ehdr.e_shoff = 0;
1306 Ehdr.e_shnum = 0;
1307 Ehdr.e_shstrndx = 0;
1308 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001309}
1310
Jake Ehrlich76e91102018-01-25 22:46:17 +00001311template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1312 for (auto &Seg : Obj.segments())
1313 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001314}
1315
Jake Ehrlich76e91102018-01-25 22:46:17 +00001316template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001317 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001318 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001319 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001320 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001321 Shdr.sh_name = 0;
1322 Shdr.sh_type = SHT_NULL;
1323 Shdr.sh_flags = 0;
1324 Shdr.sh_addr = 0;
1325 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001326 // See writeEhdr for why we do this.
1327 uint64_t Shnum = size(Obj.sections()) + 1;
1328 if (Shnum >= SHN_LORESERVE)
1329 Shdr.sh_size = Shnum;
1330 else
1331 Shdr.sh_size = 0;
1332 // See writeEhdr for why we do this.
1333 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1334 Shdr.sh_link = Obj.SectionNames->Index;
1335 else
1336 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001337 Shdr.sh_info = 0;
1338 Shdr.sh_addralign = 0;
1339 Shdr.sh_entsize = 0;
1340
Jake Ehrlich76e91102018-01-25 22:46:17 +00001341 for (auto &Sec : Obj.sections())
1342 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001343}
1344
Jake Ehrlich76e91102018-01-25 22:46:17 +00001345template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1346 for (auto &Sec : Obj.sections())
1347 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001348}
1349
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001350Error Object::removeSections(
1351 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001352
1353 auto Iter = std::stable_partition(
1354 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1355 if (ToRemove(*Sec))
1356 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001357 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1358 if (auto ToRelSec = RelSec->getSection())
1359 return !ToRemove(*ToRelSec);
1360 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001361 return true;
1362 });
1363 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1364 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001365 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001366 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001367 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1368 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001369 // Now make sure there are no remaining references to the sections that will
1370 // be removed. Sometimes it is impossible to remove a reference so we emit
1371 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001372 std::unordered_set<const SectionBase *> RemoveSections;
1373 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001374 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1375 for (auto &Segment : Segments)
1376 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001377 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001378 }
George Rimar79fb8582019-02-27 11:18:27 +00001379
1380 // For each section that remains alive, we want to remove the dead references.
1381 // This either might update the content of the section (e.g. remove symbols
1382 // from symbol table that belongs to removed section) or trigger an error if
1383 // a live section critically depends on a section being removed somehow
1384 // (e.g. the removed section is referenced by a relocation).
1385 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001386 if (Error E = KeepSec->removeSectionReferences(
1387 [&RemoveSections](const SectionBase *Sec) {
1388 return RemoveSections.find(Sec) != RemoveSections.end();
1389 }))
1390 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001391 }
1392
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001393 // Now finally get rid of them all togethor.
1394 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001395 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001396}
1397
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001398Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1399 if (SymbolTable)
1400 for (const SecPtr &Sec : Sections)
1401 if (Error E = Sec->removeSymbols(ToRemove))
1402 return E;
1403 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001404}
1405
Jake Ehrlich76e91102018-01-25 22:46:17 +00001406void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001407 // Put all sections in offset order. Maintain the ordering as closely as
1408 // possible while meeting that demand however.
1409 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1410 return A->OriginalOffset < B->OriginalOffset;
1411 };
1412 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1413 CompareSections);
1414}
1415
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001416static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1417 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1418 if (Align == 0)
1419 Align = 1;
1420 auto Diff =
1421 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1422 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1423 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1424 if (Diff < 0)
1425 Diff += Align;
1426 return Offset + Diff;
1427}
1428
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001429// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001430static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001431 std::stable_sort(std::begin(Segments), std::end(Segments),
1432 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001433}
1434
1435// This function finds a consistent layout for a list of segments starting from
1436// an Offset. It assumes that Segments have been sorted by OrderSegments and
1437// returns an Offset one past the end of the last segment.
1438static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1439 uint64_t Offset) {
1440 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001441 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001442 // The only way a segment should move is if a section was between two
1443 // segments and that section was removed. If that section isn't in a segment
1444 // then it's acceptable, but not ideal, to simply move it to after the
1445 // segments. So we can simply layout segments one after the other accounting
1446 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001447 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001448 // We assume that segments have been ordered by OriginalOffset and Index
1449 // such that a parent segment will always come before a child segment in
1450 // OrderedSegments. This means that the Offset of the ParentSegment should
1451 // already be set and we can set our offset relative to it.
1452 if (Segment->ParentSegment != nullptr) {
1453 auto Parent = Segment->ParentSegment;
1454 Segment->Offset =
1455 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1456 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001457 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001458 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001459 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001460 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001461 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001462 return Offset;
1463}
1464
1465// This function finds a consistent layout for a list of sections. It assumes
1466// that the ->ParentSegment of each section has already been laid out. The
1467// supplied starting Offset is used for the starting offset of any section that
1468// does not have a ParentSegment. It returns either the offset given if all
1469// sections had a ParentSegment or an offset one past the last section if there
1470// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001471template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001472static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001473 // Now the offset of every segment has been set we can assign the offsets
1474 // of each section. For sections that are covered by a segment we should use
1475 // the segment's original offset and the section's original offset to compute
1476 // the offset from the start of the segment. Using the offset from the start
1477 // of the segment we can assign a new offset to the section. For sections not
1478 // covered by segments we can just bump Offset to the next valid location.
1479 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001480 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001481 Section.Index = Index++;
1482 if (Section.ParentSegment != nullptr) {
1483 auto Segment = *Section.ParentSegment;
1484 Section.Offset =
1485 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001486 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001487 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1488 Section.Offset = Offset;
1489 if (Section.Type != SHT_NOBITS)
1490 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001491 }
1492 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001493 return Offset;
1494}
Petr Hosek3f383832017-08-26 01:32:20 +00001495
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001496template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1497 auto &ElfHdr = Obj.ElfHdrSegment;
1498 ElfHdr.Type = PT_PHDR;
1499 ElfHdr.Flags = 0;
1500 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1501 ElfHdr.VAddr = 0;
1502 ElfHdr.PAddr = 0;
1503 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1504 ElfHdr.Align = 0;
1505}
1506
Jake Ehrlich76e91102018-01-25 22:46:17 +00001507template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001508 // We need a temporary list of segments that has a special order to it
1509 // so that we know that anytime ->ParentSegment is set that segment has
1510 // already had its offset properly set.
1511 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001512 for (auto &Segment : Obj.segments())
1513 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001514 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1515 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001516 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001517 // Offset is used as the start offset of the first segment to be laid out.
1518 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1519 // we start at offset 0.
1520 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001521 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001522 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001523 // If we need to write the section header table out then we need to align the
1524 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001525 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001526 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001527 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001528}
1529
Jake Ehrlich76e91102018-01-25 22:46:17 +00001530template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001531 // We already have the section header offset so we can calculate the total
1532 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001533 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1534 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001535 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001536}
1537
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001538template <class ELFT> Error ELFWriter<ELFT>::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001539 writeEhdr();
1540 writePhdrs();
1541 writeSectionData();
1542 if (WriteSectionHeaders)
1543 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001544 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001545}
1546
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001547template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001548 // It could happen that SectionNames has been removed and yet the user wants
1549 // a section header table output. We need to throw an error if a user tries
1550 // to do that.
1551 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001552 return createStringError(llvm::errc::invalid_argument,
1553 "Cannot write section header table because "
1554 "section header string table was removed.");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001555
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001556 Obj.sortSections();
1557
1558 // We need to assign indexes before we perform layout because we need to know
1559 // if we need large indexes or not. We can assign indexes first and check as
1560 // we go to see if we will actully need large indexes.
1561 bool NeedsLargeIndexes = false;
1562 if (size(Obj.sections()) >= SHN_LORESERVE) {
1563 auto Sections = Obj.sections();
1564 NeedsLargeIndexes =
1565 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1566 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1567 // TODO: handle case where only one section needs the large index table but
1568 // only needs it because the large index table hasn't been removed yet.
1569 }
1570
1571 if (NeedsLargeIndexes) {
1572 // This means we definitely need to have a section index table but if we
1573 // already have one then we should use it instead of making a new one.
1574 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1575 // Addition of a section to the end does not invalidate the indexes of
1576 // other sections and assigns the correct index to the new section.
1577 auto &Shndx = Obj.addSection<SectionIndexSection>();
1578 Obj.SymbolTable->setShndxTable(&Shndx);
1579 Shndx.setSymTab(Obj.SymbolTable);
1580 }
1581 } else {
1582 // Since we don't need SectionIndexTable we should remove it and all
1583 // references to it.
1584 if (Obj.SectionIndexTable != nullptr) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001585 if (Error E = Obj.removeSections([this](const SectionBase &Sec) {
1586 return &Sec == Obj.SectionIndexTable;
1587 }))
1588 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001589 }
1590 }
1591
1592 // Make sure we add the names of all the sections. Importantly this must be
1593 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001594 if (Obj.SectionNames != nullptr)
1595 for (const auto &Section : Obj.sections()) {
1596 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001597 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001598
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001599 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001600
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001601 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001602 // Also, the output arch may not be the same as the input arch, so fix up
1603 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001604 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001605 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1606 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001607 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001608 Sec.accept(*SecSizer);
1609 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001610
1611 // The symbol table does not update all other sections on update. For
1612 // instance, symbol names are not added as new symbols are added. This means
1613 // that some sections, like .strtab, don't yet have their final size.
1614 if (Obj.SymbolTable != nullptr)
1615 Obj.SymbolTable->prepareForLayout();
1616
Petr Hosekc4df10e2017-08-04 21:09:26 +00001617 assignOffsets();
1618
1619 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001620 if (Obj.SectionNames != nullptr)
1621 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001622 // Finally now that all offsets and indexes have been set we can finalize any
1623 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001624 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1625 for (auto &Section : Obj.sections()) {
1626 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001627 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001628 if (WriteSectionHeaders)
1629 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1630 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001631 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001632
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001633 if (Error E = Buf.allocate(totalSize()))
1634 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001635 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001636 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001637}
1638
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001639Error BinaryWriter::write() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001640 for (auto &Section : Obj.sections()) {
1641 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001642 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001643 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001644 }
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001645 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001646}
1647
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001648Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001649 // TODO: Create a filter range to construct OrderedSegments from so that this
1650 // code can be deduped with assignOffsets above. This should also solve the
1651 // todo below for LayoutSections.
1652 // We need a temporary list of segments that has a special order to it
1653 // so that we know that anytime ->ParentSegment is set that segment has
1654 // already had it's offset properly set. We only want to consider the segments
1655 // that will affect layout of allocated sections so we only add those.
1656 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001657 for (auto &Section : Obj.sections()) {
1658 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1659 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001660 }
1661 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001662
1663 // For binary output, we're going to use physical addresses instead of
1664 // virtual addresses, since a binary output is used for cases like ROM
1665 // loading and physical addresses are intended for ROM loading.
1666 // However, if no segment has a physical address, we'll fallback to using
1667 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001668 if (all_of(OrderedSegments,
1669 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1670 for (Segment *Seg : OrderedSegments)
1671 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001672
1673 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1674 compareSegmentsByPAddr);
1675
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001676 // Because we add a ParentSegment for each section we might have duplicate
1677 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1678 // would do very strange things.
1679 auto End =
1680 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1681 OrderedSegments.erase(End, std::end(OrderedSegments));
1682
Jake Ehrlich46814be2018-01-22 19:27:30 +00001683 uint64_t Offset = 0;
1684
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001685 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001686 // our layout algorithm to proceed as expected while not writing out the gap
1687 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001688 if (!OrderedSegments.empty()) {
1689 auto Seg = OrderedSegments[0];
1690 auto Sec = Seg->firstSection();
1691 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1692 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001693 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001694 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001695 // The PAddr needs to be increased to remove the gap before the first
1696 // section.
1697 Seg->PAddr += Diff;
1698 uint64_t LowestPAddr = Seg->PAddr;
1699 for (auto &Segment : OrderedSegments) {
1700 Segment->Offset = Segment->PAddr - LowestPAddr;
1701 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1702 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001703 }
1704
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001705 // TODO: generalize LayoutSections to take a range. Pass a special range
1706 // constructed from an iterator that skips values for which a predicate does
1707 // not hold. Then pass such a range to LayoutSections instead of constructing
1708 // AllocatedSections here.
1709 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001710 for (auto &Section : Obj.sections()) {
1711 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001712 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001713 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001714 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001715 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001716
1717 // Now that every section has been laid out we just need to compute the total
1718 // file size. This might not be the same as the offset returned by
1719 // LayoutSections, because we want to truncate the last segment to the end of
1720 // its last section, to match GNU objcopy's behaviour.
1721 TotalSize = 0;
1722 for (const auto &Section : AllocatedSections) {
1723 if (Section->Type != SHT_NOBITS)
1724 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1725 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001726
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001727 if (Error E = Buf.allocate(TotalSize))
1728 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001729 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001730 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001731}
1732
Jake Ehrlich76e91102018-01-25 22:46:17 +00001733template class ELFBuilder<ELF64LE>;
1734template class ELFBuilder<ELF64BE>;
1735template class ELFBuilder<ELF32LE>;
1736template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001737
Jake Ehrlich76e91102018-01-25 22:46:17 +00001738template class ELFWriter<ELF64LE>;
1739template class ELFWriter<ELF64BE>;
1740template class ELFWriter<ELF32LE>;
1741template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001742
1743} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001744} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001745} // end namespace llvm