blob: 6a85b95a43fca98e5c8903f8e846d1a8a6c0cc08 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "Object.h"
11#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000012#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/BinaryFormat/ELF.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000018#include "llvm/MC/MCTargetOptions.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000019#include "llvm/Object/ELFObjectFile.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000020#include "llvm/Support/Compression.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>
28#include <utility>
29#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000030
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000031namespace llvm {
32namespace objcopy {
33namespace elf {
34
Petr Hosek05a04cb2017-08-01 00:33:58 +000035using namespace object;
36using namespace ELF;
37
Jake Ehrlich76e91102018-01-25 22:46:17 +000038template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000039 uint8_t *B = Buf.getBufferStart();
40 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
41 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000042 Phdr.p_type = Seg.Type;
43 Phdr.p_flags = Seg.Flags;
44 Phdr.p_offset = Seg.Offset;
45 Phdr.p_vaddr = Seg.VAddr;
46 Phdr.p_paddr = Seg.PAddr;
47 Phdr.p_filesz = Seg.FileSize;
48 Phdr.p_memsz = Seg.MemSize;
49 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000050}
51
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000052void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000053void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000054void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000055void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000056void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000057
Jake Ehrlich76e91102018-01-25 22:46:17 +000058template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000059 uint8_t *B = Buf.getBufferStart();
60 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000061 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000062 Shdr.sh_name = Sec.NameIndex;
63 Shdr.sh_type = Sec.Type;
64 Shdr.sh_flags = Sec.Flags;
65 Shdr.sh_addr = Sec.Addr;
66 Shdr.sh_offset = Sec.Offset;
67 Shdr.sh_size = Sec.Size;
68 Shdr.sh_link = Sec.Link;
69 Shdr.sh_info = Sec.Info;
70 Shdr.sh_addralign = Sec.Align;
71 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000072}
73
Jordan Rupprecht1f821762019-01-03 17:45:30 +000074template <class ELFT> void ELFSectionSizer<ELFT>::visit(Section &Sec) {}
75
76template <class ELFT>
77void ELFSectionSizer<ELFT>::visit(OwnedDataSection &Sec) {}
78
79template <class ELFT>
80void ELFSectionSizer<ELFT>::visit(StringTableSection &Sec) {}
81
82template <class ELFT>
83void ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &Sec) {}
84
85template <class ELFT>
86void ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
87 Sec.EntrySize = sizeof(Elf_Sym);
88 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000089 // Align to the largest field in Elf_Sym.
Jordan Rupprecht1f821762019-01-03 17:45:30 +000090 Sec.Align = sizeof(Elf_Sym::st_size);
91}
92
93template <class ELFT>
94void ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
95 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
96 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000097 // Align to the largest field in Elf_Rel(a).
Jordan Rupprecht1f821762019-01-03 17:45:30 +000098 Sec.Align =
99 Sec.Type == SHT_REL ? sizeof(Elf_Rel::r_info) : sizeof(Elf_Rela::r_info);
100}
101
102template <class ELFT>
103void ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &Sec) {}
104
105template <class ELFT> void ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {}
106
107template <class ELFT>
108void ELFSectionSizer<ELFT>::visit(SectionIndexSection &Sec) {}
109
110template <class ELFT>
111void ELFSectionSizer<ELFT>::visit(CompressedSection &Sec) {}
112
113template <class ELFT>
114void ELFSectionSizer<ELFT>::visit(DecompressedSection &Sec) {}
Jake Ehrlich76e91102018-01-25 22:46:17 +0000115
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000116void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
117 error("Cannot write symbol section index table '" + Sec.Name + "' ");
118}
119
Jake Ehrlich76e91102018-01-25 22:46:17 +0000120void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
121 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
122}
123
124void BinarySectionWriter::visit(const RelocationSection &Sec) {
125 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
126}
127
128void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000129 error("Cannot write '" + Sec.Name + "' out to binary");
130}
131
132void BinarySectionWriter::visit(const GroupSection &Sec) {
133 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000134}
135
136void SectionWriter::visit(const Section &Sec) {
137 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000138 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000139 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000140 llvm::copy(Sec.Contents, Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000141}
142
Jake Ehrlich76e91102018-01-25 22:46:17 +0000143void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
144
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000145void Section::accept(MutableSectionVisitor &Visitor) { Visitor.visit(*this); }
146
Jake Ehrlich76e91102018-01-25 22:46:17 +0000147void SectionWriter::visit(const OwnedDataSection &Sec) {
148 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000149 llvm::copy(Sec.Data, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000150}
151
Puyan Lotfiaf048642018-10-01 10:29:41 +0000152static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
153
154static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
155 return Data.size() > ZlibGnuMagic.size() &&
156 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
157}
158
159template <class ELFT>
160static std::tuple<uint64_t, uint64_t>
161getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
162 const bool IsGnuDebug = isDataGnuCompressed(Data);
163 const uint64_t DecompressedSize =
164 IsGnuDebug
165 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
166 Data.data() + ZlibGnuMagic.size()))
167 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
168 const uint64_t DecompressedAlign =
169 IsGnuDebug ? 1
170 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
171 ->ch_addralign;
172
173 return std::make_tuple(DecompressedSize, DecompressedAlign);
174}
175
176template <class ELFT>
177void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
178 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
179
180 if (!zlib::isAvailable()) {
181 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
182 return;
183 }
184
185 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
186 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
187 : sizeof(Elf_Chdr_Impl<ELFT>);
188
189 StringRef CompressedContent(
190 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
191 Sec.OriginalData.size() - DataOffset);
192
193 SmallVector<char, 128> DecompressedContent;
194 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
195 static_cast<size_t>(Sec.Size)))
196 reportError(Sec.Name, std::move(E));
197
198 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
199}
200
201void BinarySectionWriter::visit(const DecompressedSection &Sec) {
202 error("Cannot write compressed section '" + Sec.Name + "' ");
203}
204
205void DecompressedSection::accept(SectionVisitor &Visitor) const {
206 Visitor.visit(*this);
207}
208
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000209void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
210 Visitor.visit(*this);
211}
212
Jake Ehrlich76e91102018-01-25 22:46:17 +0000213void OwnedDataSection::accept(SectionVisitor &Visitor) const {
214 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000215}
216
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000217void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
218 Visitor.visit(*this);
219}
220
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000221void BinarySectionWriter::visit(const CompressedSection &Sec) {
222 error("Cannot write compressed section '" + Sec.Name + "' ");
223}
224
225template <class ELFT>
226void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
227 uint8_t *Buf = Out.getBufferStart();
228 Buf += Sec.Offset;
229
230 if (Sec.CompressionType == DebugCompressionType::None) {
231 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
232 return;
233 }
234
235 if (Sec.CompressionType == DebugCompressionType::GNU) {
236 const char *Magic = "ZLIB";
237 memcpy(Buf, Magic, strlen(Magic));
238 Buf += strlen(Magic);
239 const uint64_t DecompressedSize =
240 support::endian::read64be(&Sec.DecompressedSize);
241 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
242 Buf += sizeof(DecompressedSize);
243 } else {
244 Elf_Chdr_Impl<ELFT> Chdr;
245 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
246 Chdr.ch_size = Sec.DecompressedSize;
247 Chdr.ch_addralign = Sec.DecompressedAlign;
248 memcpy(Buf, &Chdr, sizeof(Chdr));
249 Buf += sizeof(Chdr);
250 }
251
252 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
253}
254
255CompressedSection::CompressedSection(const SectionBase &Sec,
256 DebugCompressionType CompressionType)
257 : SectionBase(Sec), CompressionType(CompressionType),
258 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
259
260 if (!zlib::isAvailable()) {
261 CompressionType = DebugCompressionType::None;
262 return;
263 }
264
265 if (Error E = zlib::compress(
266 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
267 OriginalData.size()),
268 CompressedData))
269 reportError(Name, std::move(E));
270
271 size_t ChdrSize;
272 if (CompressionType == DebugCompressionType::GNU) {
273 Name = ".z" + Sec.Name.substr(1);
274 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
275 } else {
276 Flags |= ELF::SHF_COMPRESSED;
277 ChdrSize =
278 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
279 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
280 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
281 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
282 }
283 Size = ChdrSize + CompressedData.size();
284 Align = 8;
285}
286
Puyan Lotfiaf048642018-10-01 10:29:41 +0000287CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
288 uint64_t DecompressedSize,
289 uint64_t DecompressedAlign)
290 : CompressionType(DebugCompressionType::None),
291 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
292 OriginalData = CompressedData;
293}
294
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000295void CompressedSection::accept(SectionVisitor &Visitor) const {
296 Visitor.visit(*this);
297}
298
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000299void CompressedSection::accept(MutableSectionVisitor &Visitor) {
300 Visitor.visit(*this);
301}
302
Petr Hosek05a04cb2017-08-01 00:33:58 +0000303void StringTableSection::addString(StringRef Name) {
304 StrTabBuilder.add(Name);
305 Size = StrTabBuilder.getSize();
306}
307
308uint32_t StringTableSection::findIndex(StringRef Name) const {
309 return StrTabBuilder.getOffset(Name);
310}
311
312void StringTableSection::finalize() { StrTabBuilder.finalize(); }
313
Jake Ehrlich76e91102018-01-25 22:46:17 +0000314void SectionWriter::visit(const StringTableSection &Sec) {
315 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
316}
317
318void StringTableSection::accept(SectionVisitor &Visitor) const {
319 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000320}
321
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000322void StringTableSection::accept(MutableSectionVisitor &Visitor) {
323 Visitor.visit(*this);
324}
325
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000326template <class ELFT>
327void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
328 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000329 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000330 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000331}
332
333void SectionIndexSection::initialize(SectionTableRef SecTable) {
334 Size = 0;
335 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
336 Link,
337 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
338 "Link field value " + Twine(Link) + " in section " + Name +
339 " is not a symbol table"));
340 Symbols->setShndxTable(this);
341}
342
343void SectionIndexSection::finalize() { Link = Symbols->Index; }
344
345void SectionIndexSection::accept(SectionVisitor &Visitor) const {
346 Visitor.visit(*this);
347}
348
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000349void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
350 Visitor.visit(*this);
351}
352
Petr Hosekc1135772017-09-13 03:04:50 +0000353static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000354 switch (Index) {
355 case SHN_ABS:
356 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000357 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000358 }
Petr Hosekc1135772017-09-13 03:04:50 +0000359 if (Machine == EM_HEXAGON) {
360 switch (Index) {
361 case SHN_HEXAGON_SCOMMON:
362 case SHN_HEXAGON_SCOMMON_2:
363 case SHN_HEXAGON_SCOMMON_4:
364 case SHN_HEXAGON_SCOMMON_8:
365 return true;
366 }
367 }
368 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000369}
370
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000371// Large indexes force us to clarify exactly what this function should do. This
372// function should return the value that will appear in st_shndx when written
373// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000374uint16_t Symbol::getShndx() const {
375 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000376 if (DefinedIn->Index >= SHN_LORESERVE)
377 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000378 return DefinedIn->Index;
379 }
380 switch (ShndxType) {
381 // This means that we don't have a defined section but we do need to
382 // output a legitimate section index.
383 case SYMBOL_SIMPLE_INDEX:
384 return SHN_UNDEF;
385 case SYMBOL_ABS:
386 case SYMBOL_COMMON:
387 case SYMBOL_HEXAGON_SCOMMON:
388 case SYMBOL_HEXAGON_SCOMMON_2:
389 case SYMBOL_HEXAGON_SCOMMON_4:
390 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000391 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000392 return static_cast<uint16_t>(ShndxType);
393 }
394 llvm_unreachable("Symbol with invalid ShndxType encountered");
395}
396
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000397bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
398
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000399void SymbolTableSection::assignIndices() {
400 uint32_t Index = 0;
401 for (auto &Sym : Symbols)
402 Sym->Index = Index++;
403}
404
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000405void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000406 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000407 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000408 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000409 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000410 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000411 Sym.Binding = Bind;
412 Sym.Type = Type;
413 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000414 if (DefinedIn != nullptr)
415 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000416 if (DefinedIn == nullptr) {
417 if (Shndx >= SHN_LORESERVE)
418 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
419 else
420 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
421 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000422 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000423 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000424 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000425 Sym.Index = Symbols.size();
426 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
427 Size += this->EntrySize;
428}
429
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000430void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000431 if (SectionIndexTable == Sec)
432 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000433 if (SymbolNames == Sec) {
434 error("String table " + SymbolNames->Name +
435 " cannot be removed because it is referenced by the symbol table " +
436 this->Name);
437 }
Paul Semel41695f82018-05-02 20:19:22 +0000438 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000439}
440
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000441void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000442 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
443 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000444 std::stable_partition(
445 std::begin(Symbols), std::end(Symbols),
446 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000447 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000448}
449
Paul Semel4246a462018-05-09 21:36:54 +0000450void SymbolTableSection::removeSymbols(
451 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000452 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000453 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000454 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
455 std::end(Symbols));
456 Size = Symbols.size() * EntrySize;
457 assignIndices();
458}
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
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000539template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000540void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
541 const SectionBase *Sec) {
542 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000543 error("Symbol table " + Symbols->Name +
544 " cannot be removed because it is "
545 "referenced by the relocation "
546 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000547 this->Name);
548 }
549}
550
551template <class SymTabType>
552void RelocSectionWithSymtabBase<SymTabType>::initialize(
553 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000554 if (Link != SHN_UNDEF)
555 setSymTab(SecTable.getSectionOfType<SymTabType>(
556 Link,
557 "Link field value " + Twine(Link) + " in section " + Name +
558 " is invalid",
559 "Link field value " + Twine(Link) + " in section " + Name +
560 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000561
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000562 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000563 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
564 " in section " + Name +
565 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000566 else
567 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000568}
569
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000570template <class SymTabType>
571void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000572 this->Link = Symbols ? Symbols->Index : 0;
573
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000574 if (SecToApplyRel != nullptr)
575 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000576}
577
578template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000579static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000580
581template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000582static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000583 Rela.r_addend = Addend;
584}
585
Jake Ehrlich76e91102018-01-25 22:46:17 +0000586template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000587static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000588 for (const auto &Reloc : Relocations) {
589 Buf->r_offset = Reloc.Offset;
590 setAddend(*Buf, Reloc.Addend);
591 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
592 ++Buf;
593 }
594}
595
596template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000597void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
598 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
599 if (Sec.Type == SHT_REL)
600 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000601 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000602 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000603}
604
Jake Ehrlich76e91102018-01-25 22:46:17 +0000605void RelocationSection::accept(SectionVisitor &Visitor) const {
606 Visitor.visit(*this);
607}
608
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000609void RelocationSection::accept(MutableSectionVisitor &Visitor) {
610 Visitor.visit(*this);
611}
612
Paul Semel4246a462018-05-09 21:36:54 +0000613void RelocationSection::removeSymbols(
614 function_ref<bool(const Symbol &)> ToRemove) {
615 for (const Relocation &Reloc : Relocations)
616 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000617 error("not stripping symbol '" + Reloc.RelocSymbol->Name +
Paul Semel4246a462018-05-09 21:36:54 +0000618 "' because it is named in a relocation");
619}
620
Paul Semel99dda0b2018-05-25 11:01:25 +0000621void RelocationSection::markSymbols() {
622 for (const Relocation &Reloc : Relocations)
623 Reloc.RelocSymbol->Referenced = true;
624}
625
Jake Ehrlich76e91102018-01-25 22:46:17 +0000626void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000627 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000628 Out.getBufferStart() + Sec.Offset);
629}
630
631void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
632 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000633}
634
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000635void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
636 Visitor.visit(*this);
637}
638
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000639void Section::removeSectionReferences(const SectionBase *Sec) {
640 if (LinkSection == Sec) {
641 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000642 " cannot be removed because it is "
643 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000644 this->Name);
645 }
646}
647
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000648void GroupSection::finalize() {
649 this->Info = Sym->Index;
650 this->Link = SymTab->Index;
651}
652
Paul Semel4246a462018-05-09 21:36:54 +0000653void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
654 if (ToRemove(*Sym)) {
655 error("Symbol " + Sym->Name +
656 " cannot be removed because it is "
657 "referenced by the section " +
658 this->Name + "[" + Twine(this->Index) + "]");
659 }
660}
661
Paul Semel99dda0b2018-05-25 11:01:25 +0000662void GroupSection::markSymbols() {
663 if (Sym)
664 Sym->Referenced = true;
665}
666
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000667void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000668 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000669 LinkSection =
670 SecTable.getSection(Link, "Link field value " + Twine(Link) +
671 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000672 if (LinkSection->Type == ELF::SHT_SYMTAB)
673 LinkSection = nullptr;
674 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000675}
676
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000677void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000678
Jake Ehrlich76e91102018-01-25 22:46:17 +0000679void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000680 FileName = sys::path::filename(File);
681 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000682 // followed by a null terminator and then the CRC32 of the file. The CRC32
683 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
684 // byte, and then finally push the size to alignment and add 4.
685 Size = alignTo(FileName.size() + 1, 4) + 4;
686 // The CRC32 will only be aligned if we align the whole section.
687 Align = 4;
688 Type = ELF::SHT_PROGBITS;
689 Name = ".gnu_debuglink";
690 // For sections not found in segments, OriginalOffset is only used to
691 // establish the order that sections should go in. By using the maximum
692 // possible offset we cause this section to wind up at the end.
693 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000694 JamCRC CRC;
695 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000696 // The CRC32 value needs to be complemented because the JamCRC dosn't
697 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
698 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000699 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000700}
701
Jake Ehrlich76e91102018-01-25 22:46:17 +0000702GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000703 // Read in the file to compute the CRC of it.
704 auto DebugOrErr = MemoryBuffer::getFile(File);
705 if (!DebugOrErr)
706 error("'" + File + "': " + DebugOrErr.getError().message());
707 auto Debug = std::move(*DebugOrErr);
708 init(File, Debug->getBuffer());
709}
710
711template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000712void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
713 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000714 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000715 Elf_Word *CRC =
716 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
717 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000718 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000719}
720
721void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
722 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000723}
724
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000725void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
726 Visitor.visit(*this);
727}
728
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000729template <class ELFT>
730void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
731 ELF::Elf32_Word *Buf =
732 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
733 *Buf++ = Sec.FlagWord;
734 for (const auto *S : Sec.GroupMembers)
735 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
736}
737
738void GroupSection::accept(SectionVisitor &Visitor) const {
739 Visitor.visit(*this);
740}
741
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000742void GroupSection::accept(MutableSectionVisitor &Visitor) {
743 Visitor.visit(*this);
744}
745
Petr Hosek05a04cb2017-08-01 00:33:58 +0000746// Returns true IFF a section is wholly inside the range of a segment
747static bool sectionWithinSegment(const SectionBase &Section,
748 const Segment &Segment) {
749 // If a section is empty it should be treated like it has a size of 1. This is
750 // to clarify the case when an empty section lies on a boundary between two
751 // segments and ensures that the section "belongs" to the second segment and
752 // not the first.
753 uint64_t SecSize = Section.Size ? Section.Size : 1;
754 return Segment.Offset <= Section.OriginalOffset &&
755 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
756}
757
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000758// Returns true IFF a segment's original offset is inside of another segment's
759// range.
760static bool segmentOverlapsSegment(const Segment &Child,
761 const Segment &Parent) {
762
763 return Parent.OriginalOffset <= Child.OriginalOffset &&
764 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
765}
766
Jake Ehrlich46814be2018-01-22 19:27:30 +0000767static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000768 // Any segment without a parent segment should come before a segment
769 // that has a parent segment.
770 if (A->OriginalOffset < B->OriginalOffset)
771 return true;
772 if (A->OriginalOffset > B->OriginalOffset)
773 return false;
774 return A->Index < B->Index;
775}
776
Jake Ehrlich46814be2018-01-22 19:27:30 +0000777static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
778 if (A->PAddr < B->PAddr)
779 return true;
780 if (A->PAddr > B->PAddr)
781 return false;
782 return A->Index < B->Index;
783}
784
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000785void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000786 Obj->Flags = 0x0;
787 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +0000788 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +0000789 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000790 Obj->Entry = 0x0;
791 Obj->Machine = EMachine;
792 Obj->Version = 1;
793}
794
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000795void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000796
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000797StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000798 auto &StrTab = Obj->addSection<StringTableSection>();
799 StrTab.Name = ".strtab";
800
801 Obj->SectionNames = &StrTab;
802 return &StrTab;
803}
804
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000805SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000806 auto &SymTab = Obj->addSection<SymbolTableSection>();
807
808 SymTab.Name = ".symtab";
809 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000810
811 // The symbol table always needs a null symbol
812 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
813
814 Obj->SymbolTable = &SymTab;
815 return &SymTab;
816}
817
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000818void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000819 auto Data = ArrayRef<uint8_t>(
820 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
821 MemBuf->getBufferSize());
822 auto &DataSection = Obj->addSection<Section>(Data);
823 DataSection.Name = ".data";
824 DataSection.Type = ELF::SHT_PROGBITS;
825 DataSection.Size = Data.size();
826 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
827
828 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
829 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000830 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000831 Twine Prefix = Twine("_binary_") + SanitizedFilename;
832
833 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
834 /*Value=*/0, STV_DEFAULT, 0, 0);
835 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
836 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
837 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
838 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
839}
840
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000841void BinaryELFBuilder::initSections() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000842 for (auto &Section : Obj->sections()) {
843 Section.initialize(Obj->sections());
844 }
845}
846
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000847std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000848 initFileHeader();
849 initHeaderSegment();
850 StringTableSection *StrTab = addStrTab();
851 SymbolTableSection *SymTab = addSymTab(StrTab);
852 initSections();
853 addData(SymTab);
854
855 return std::move(Obj);
856}
857
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000858template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000859 for (auto &Parent : Obj.segments()) {
860 // Every segment will overlap with itself but we don't want a segment to
861 // be it's own parent so we avoid that situation.
862 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
863 // We want a canonical "most parental" segment but this requires
864 // inspecting the ParentSegment.
865 if (compareSegmentsByOffset(&Parent, &Child))
866 if (Child.ParentSegment == nullptr ||
867 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
868 Child.ParentSegment = &Parent;
869 }
870 }
871 }
872}
873
Jake Ehrlich76e91102018-01-25 22:46:17 +0000874template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000875 uint32_t Index = 0;
876 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000877 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
878 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000879 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000880 Seg.Type = Phdr.p_type;
881 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000882 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000883 Seg.Offset = Phdr.p_offset;
884 Seg.VAddr = Phdr.p_vaddr;
885 Seg.PAddr = Phdr.p_paddr;
886 Seg.FileSize = Phdr.p_filesz;
887 Seg.MemSize = Phdr.p_memsz;
888 Seg.Align = Phdr.p_align;
889 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000890 for (auto &Section : Obj.sections()) {
891 if (sectionWithinSegment(Section, Seg)) {
892 Seg.addSection(&Section);
893 if (!Section.ParentSegment ||
894 Section.ParentSegment->Offset > Seg.Offset) {
895 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000896 }
897 }
898 }
899 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000900
901 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000902 ElfHdr.Index = Index++;
903
904 const auto &Ehdr = *ElfFile.getHeader();
905 auto &PrHdr = Obj.ProgramHdrSegment;
906 PrHdr.Type = PT_PHDR;
907 PrHdr.Flags = 0;
908 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
909 // Whereas this works automatically for ElfHdr, here OriginalOffset is
910 // always non-zero and to ensure the equation we assign the same value to
911 // VAddr as well.
912 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
913 PrHdr.PAddr = 0;
914 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000915 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000916 PrHdr.Align = sizeof(Elf_Addr);
917 PrHdr.Index = Index++;
918
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000919 // Now we do an O(n^2) loop through the segments in order to match up
920 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000921 for (auto &Child : Obj.segments())
922 setParentSegment(Child);
923 setParentSegment(ElfHdr);
924 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000925}
926
927template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000928void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
929 auto SecTable = Obj.sections();
930 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
931 GroupSec->Link,
932 "Link field value " + Twine(GroupSec->Link) + " in section " +
933 GroupSec->Name + " is invalid",
934 "Link field value " + Twine(GroupSec->Link) + " in section " +
935 GroupSec->Name + " is not a symbol table");
936 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
937 if (!Sym)
938 error("Info field value " + Twine(GroupSec->Info) + " in section " +
939 GroupSec->Name + " is not a valid symbol index");
940 GroupSec->setSymTab(SymTab);
941 GroupSec->setSymbol(Sym);
942 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
943 GroupSec->Contents.empty())
944 error("The content of the section " + GroupSec->Name + " is malformed");
945 const ELF::Elf32_Word *Word =
946 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
947 const ELF::Elf32_Word *End =
948 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
949 GroupSec->setFlagWord(*Word++);
950 for (; Word != End; ++Word) {
951 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
952 GroupSec->addMember(SecTable.getSection(
953 Index, "Group member index " + Twine(Index) + " in section " +
954 GroupSec->Name + " is invalid"));
955 }
956}
957
958template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000959void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000960 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
961 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000962 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000963
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000964 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
965 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000966 SectionBase *DefSection = nullptr;
967 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000968
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000969 if (Sym.st_shndx == SHN_XINDEX) {
970 if (SymTab->getShndxTable() == nullptr)
971 error("Symbol '" + Name +
972 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
973 if (ShndxData.data() == nullptr) {
974 const Elf_Shdr &ShndxSec =
975 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
976 ShndxData = unwrapOrError(
977 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
978 if (ShndxData.size() != Symbols.size())
979 error("Symbol section index table does not have the same number of "
980 "entries as the symbol table.");
981 }
982 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
983 DefSection = Obj.sections().getSection(
984 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000985 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000986 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000987 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000988 error(
989 "Symbol '" + Name +
990 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
991 Twine(Sym.st_shndx));
992 }
993 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000994 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000995 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000996 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000997 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000998 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000999
Petr Hosek79cee9e2017-08-29 02:12:03 +00001000 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001001 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001002 }
1003}
1004
1005template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001006static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1007
1008template <class ELFT>
1009static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1010 ToSet = Rela.r_addend;
1011}
1012
Jake Ehrlich76e91102018-01-25 22:46:17 +00001013template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001014static void initRelocations(RelocationSection *Relocs,
1015 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001016 for (const auto &Rel : RelRange) {
1017 Relocation ToAdd;
1018 ToAdd.Offset = Rel.r_offset;
1019 getAddend(ToAdd.Addend, Rel);
1020 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001021 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001022 Relocs->addRelocation(ToAdd);
1023 }
1024}
1025
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001026SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001027 if (Index == SHN_UNDEF || Index > Sections.size())
1028 error(ErrMsg);
1029 return Sections[Index - 1].get();
1030}
1031
1032template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001033T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001034 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001035 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001036 return Sec;
1037 error(TypeErrMsg);
1038}
1039
Petr Hosekd7df9b22017-09-06 23:41:02 +00001040template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001041SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001042 ArrayRef<uint8_t> Data;
1043 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001044 case SHT_REL:
1045 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001046 if (Shdr.sh_flags & SHF_ALLOC) {
1047 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001048 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001049 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001050 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001051 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001052 // If a string table is allocated we don't want to mess with it. That would
1053 // mean altering the memory image. There are no special link types or
1054 // anything so we can just use a Section.
1055 if (Shdr.sh_flags & SHF_ALLOC) {
1056 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001057 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001058 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001059 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001060 case SHT_HASH:
1061 case SHT_GNU_HASH:
1062 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1063 // Because of this we don't need to mess with the hash tables either.
1064 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001065 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001066 case SHT_GROUP:
1067 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1068 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001069 case SHT_DYNSYM:
1070 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001071 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001072 case SHT_DYNAMIC:
1073 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001074 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001075 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001076 auto &SymTab = Obj.addSection<SymbolTableSection>();
1077 Obj.SymbolTable = &SymTab;
1078 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001079 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001080 case SHT_SYMTAB_SHNDX: {
1081 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1082 Obj.SectionIndexTable = &ShndxSection;
1083 return ShndxSection;
1084 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001085 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001086 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001087 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001088 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001089
1090 if (isDataGnuCompressed(Data) || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
1091 uint64_t DecompressedSize, DecompressedAlign;
1092 std::tie(DecompressedSize, DecompressedAlign) =
1093 getDecompressedSizeAndAlignment<ELFT>(Data);
1094 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1095 DecompressedAlign);
1096 }
1097
Jake Ehrlich76e91102018-01-25 22:46:17 +00001098 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001099 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001100 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001101}
1102
Jake Ehrlich76e91102018-01-25 22:46:17 +00001103template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001104 uint32_t Index = 0;
1105 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1106 if (Index == 0) {
1107 ++Index;
1108 continue;
1109 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001110 auto &Sec = makeSection(Shdr);
1111 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1112 Sec.Type = Shdr.sh_type;
1113 Sec.Flags = Shdr.sh_flags;
1114 Sec.Addr = Shdr.sh_addr;
1115 Sec.Offset = Shdr.sh_offset;
1116 Sec.OriginalOffset = Shdr.sh_offset;
1117 Sec.Size = Shdr.sh_size;
1118 Sec.Link = Shdr.sh_link;
1119 Sec.Info = Shdr.sh_info;
1120 Sec.Align = Shdr.sh_addralign;
1121 Sec.EntrySize = Shdr.sh_entsize;
1122 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001123 Sec.OriginalData =
1124 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1125 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001126 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001127
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001128 // If a section index table exists we'll need to initialize it before we
1129 // initialize the symbol table because the symbol table might need to
1130 // reference it.
1131 if (Obj.SectionIndexTable)
1132 Obj.SectionIndexTable->initialize(Obj.sections());
1133
Petr Hosek79cee9e2017-08-29 02:12:03 +00001134 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001135 // details about symbol tables. We need the symbol table filled out before
1136 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001137 if (Obj.SymbolTable) {
1138 Obj.SymbolTable->initialize(Obj.sections());
1139 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001140 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001141
1142 // Now that all sections and symbols have been added we can add
1143 // relocations that reference symbols and set the link and info fields for
1144 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001145 for (auto &Section : Obj.sections()) {
1146 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001147 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001148 Section.initialize(Obj.sections());
1149 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001150 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1151 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001152 initRelocations(RelSec, Obj.SymbolTable,
1153 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001154 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001155 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001156 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001157 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1158 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001159 }
1160 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001161}
1162
Jake Ehrlich76e91102018-01-25 22:46:17 +00001163template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001164 const auto &Ehdr = *ElfFile.getHeader();
1165
George Rimar4ded7732018-12-20 10:51:42 +00001166 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1167 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001168 Obj.Type = Ehdr.e_type;
1169 Obj.Machine = Ehdr.e_machine;
1170 Obj.Version = Ehdr.e_version;
1171 Obj.Entry = Ehdr.e_entry;
1172 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001173
Jake Ehrlich76e91102018-01-25 22:46:17 +00001174 readSectionHeaders();
1175 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001176
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001177 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1178 if (ShstrIndex == SHN_XINDEX)
1179 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1180
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181 Obj.SectionNames =
1182 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001183 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001184 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001185 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001186 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001187 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001188}
1189
Jake Ehrlich76e91102018-01-25 22:46:17 +00001190// A generic size function which computes sizes of any random access range.
1191template <class R> size_t size(R &&Range) {
1192 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1193}
1194
1195Writer::~Writer() {}
1196
1197Reader::~Reader() {}
1198
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001199std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001200 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001201}
1202
1203std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001204 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001205 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1206 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001207 Builder.build();
1208 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001209 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1210 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001211 Builder.build();
1212 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001213 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1214 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001215 Builder.build();
1216 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001217 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1218 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001219 Builder.build();
1220 return Obj;
1221 }
1222 error("Invalid file type");
1223}
1224
1225template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001226 uint8_t *B = Buf.getBufferStart();
1227 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001228 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1229 Ehdr.e_ident[EI_MAG0] = 0x7f;
1230 Ehdr.e_ident[EI_MAG1] = 'E';
1231 Ehdr.e_ident[EI_MAG2] = 'L';
1232 Ehdr.e_ident[EI_MAG3] = 'F';
1233 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1234 Ehdr.e_ident[EI_DATA] =
1235 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1236 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001237 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1238 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001239
Jake Ehrlich76e91102018-01-25 22:46:17 +00001240 Ehdr.e_type = Obj.Type;
1241 Ehdr.e_machine = Obj.Machine;
1242 Ehdr.e_version = Obj.Version;
1243 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001244 // We have to use the fully-qualified name llvm::size
1245 // since some compilers complain on ambiguous resolution.
1246 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001247 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1248 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001249 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001250 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001251 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1252 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001253 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001254 // """
1255 // If the number of sections is greater than or equal to
1256 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1257 // number of section header table entries is contained in the sh_size field
1258 // of the section header at index 0.
1259 // """
1260 auto Shnum = size(Obj.sections()) + 1;
1261 if (Shnum >= SHN_LORESERVE)
1262 Ehdr.e_shnum = 0;
1263 else
1264 Ehdr.e_shnum = Shnum;
1265 // """
1266 // If the section name string table section index is greater than or equal
1267 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1268 // and the actual index of the section name string table section is
1269 // contained in the sh_link field of the section header at index 0.
1270 // """
1271 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1272 Ehdr.e_shstrndx = SHN_XINDEX;
1273 else
1274 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001275 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001276 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001277 Ehdr.e_shoff = 0;
1278 Ehdr.e_shnum = 0;
1279 Ehdr.e_shstrndx = 0;
1280 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001281}
1282
Jake Ehrlich76e91102018-01-25 22:46:17 +00001283template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1284 for (auto &Seg : Obj.segments())
1285 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001286}
1287
Jake Ehrlich76e91102018-01-25 22:46:17 +00001288template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001289 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001290 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001291 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001292 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001293 Shdr.sh_name = 0;
1294 Shdr.sh_type = SHT_NULL;
1295 Shdr.sh_flags = 0;
1296 Shdr.sh_addr = 0;
1297 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001298 // See writeEhdr for why we do this.
1299 uint64_t Shnum = size(Obj.sections()) + 1;
1300 if (Shnum >= SHN_LORESERVE)
1301 Shdr.sh_size = Shnum;
1302 else
1303 Shdr.sh_size = 0;
1304 // See writeEhdr for why we do this.
1305 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1306 Shdr.sh_link = Obj.SectionNames->Index;
1307 else
1308 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001309 Shdr.sh_info = 0;
1310 Shdr.sh_addralign = 0;
1311 Shdr.sh_entsize = 0;
1312
Jake Ehrlich76e91102018-01-25 22:46:17 +00001313 for (auto &Sec : Obj.sections())
1314 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001315}
1316
Jake Ehrlich76e91102018-01-25 22:46:17 +00001317template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1318 for (auto &Sec : Obj.sections())
1319 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001320}
1321
Jake Ehrlich76e91102018-01-25 22:46:17 +00001322void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001323
1324 auto Iter = std::stable_partition(
1325 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1326 if (ToRemove(*Sec))
1327 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001328 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1329 if (auto ToRelSec = RelSec->getSection())
1330 return !ToRemove(*ToRelSec);
1331 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001332 return true;
1333 });
1334 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1335 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001336 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001337 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001338 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1339 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001340 // Now make sure there are no remaining references to the sections that will
1341 // be removed. Sometimes it is impossible to remove a reference so we emit
1342 // an error here instead.
1343 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1344 for (auto &Segment : Segments)
1345 Segment->removeSection(RemoveSec.get());
1346 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1347 KeepSec->removeSectionReferences(RemoveSec.get());
1348 }
1349 // Now finally get rid of them all togethor.
1350 Sections.erase(Iter, std::end(Sections));
1351}
1352
Paul Semel4246a462018-05-09 21:36:54 +00001353void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1354 if (!SymbolTable)
1355 return;
1356
1357 for (const SecPtr &Sec : Sections)
1358 Sec->removeSymbols(ToRemove);
1359}
1360
Jake Ehrlich76e91102018-01-25 22:46:17 +00001361void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001362 // Put all sections in offset order. Maintain the ordering as closely as
1363 // possible while meeting that demand however.
1364 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1365 return A->OriginalOffset < B->OriginalOffset;
1366 };
1367 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1368 CompareSections);
1369}
1370
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001371static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1372 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1373 if (Align == 0)
1374 Align = 1;
1375 auto Diff =
1376 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1377 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1378 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1379 if (Diff < 0)
1380 Diff += Align;
1381 return Offset + Diff;
1382}
1383
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001384// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001385static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001386 std::stable_sort(std::begin(Segments), std::end(Segments),
1387 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001388}
1389
1390// This function finds a consistent layout for a list of segments starting from
1391// an Offset. It assumes that Segments have been sorted by OrderSegments and
1392// returns an Offset one past the end of the last segment.
1393static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1394 uint64_t Offset) {
1395 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001396 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001397 // The only way a segment should move is if a section was between two
1398 // segments and that section was removed. If that section isn't in a segment
1399 // then it's acceptable, but not ideal, to simply move it to after the
1400 // segments. So we can simply layout segments one after the other accounting
1401 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001402 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001403 // We assume that segments have been ordered by OriginalOffset and Index
1404 // such that a parent segment will always come before a child segment in
1405 // OrderedSegments. This means that the Offset of the ParentSegment should
1406 // already be set and we can set our offset relative to it.
1407 if (Segment->ParentSegment != nullptr) {
1408 auto Parent = Segment->ParentSegment;
1409 Segment->Offset =
1410 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1411 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001412 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001413 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001414 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001415 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001416 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001417 return Offset;
1418}
1419
1420// This function finds a consistent layout for a list of sections. It assumes
1421// that the ->ParentSegment of each section has already been laid out. The
1422// supplied starting Offset is used for the starting offset of any section that
1423// does not have a ParentSegment. It returns either the offset given if all
1424// sections had a ParentSegment or an offset one past the last section if there
1425// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001426template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001427static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001428 // Now the offset of every segment has been set we can assign the offsets
1429 // of each section. For sections that are covered by a segment we should use
1430 // the segment's original offset and the section's original offset to compute
1431 // the offset from the start of the segment. Using the offset from the start
1432 // of the segment we can assign a new offset to the section. For sections not
1433 // covered by segments we can just bump Offset to the next valid location.
1434 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001435 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001436 Section.Index = Index++;
1437 if (Section.ParentSegment != nullptr) {
1438 auto Segment = *Section.ParentSegment;
1439 Section.Offset =
1440 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001441 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001442 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1443 Section.Offset = Offset;
1444 if (Section.Type != SHT_NOBITS)
1445 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001446 }
1447 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001448 return Offset;
1449}
Petr Hosek3f383832017-08-26 01:32:20 +00001450
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001451template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1452 auto &ElfHdr = Obj.ElfHdrSegment;
1453 ElfHdr.Type = PT_PHDR;
1454 ElfHdr.Flags = 0;
1455 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1456 ElfHdr.VAddr = 0;
1457 ElfHdr.PAddr = 0;
1458 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1459 ElfHdr.Align = 0;
1460}
1461
Jake Ehrlich76e91102018-01-25 22:46:17 +00001462template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001463 // We need a temporary list of segments that has a special order to it
1464 // so that we know that anytime ->ParentSegment is set that segment has
1465 // already had its offset properly set.
1466 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001467 for (auto &Segment : Obj.segments())
1468 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001469 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1470 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001471 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001472 // Offset is used as the start offset of the first segment to be laid out.
1473 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1474 // we start at offset 0.
1475 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001476 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001477 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001478 // If we need to write the section header table out then we need to align the
1479 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001480 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001481 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001482 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001483}
1484
Jake Ehrlich76e91102018-01-25 22:46:17 +00001485template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001486 // We already have the section header offset so we can calculate the total
1487 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001488 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1489 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001490 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001491}
1492
Jake Ehrlich76e91102018-01-25 22:46:17 +00001493template <class ELFT> void ELFWriter<ELFT>::write() {
1494 writeEhdr();
1495 writePhdrs();
1496 writeSectionData();
1497 if (WriteSectionHeaders)
1498 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001499 if (auto E = Buf.commit())
1500 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001501}
1502
1503template <class ELFT> void ELFWriter<ELFT>::finalize() {
1504 // It could happen that SectionNames has been removed and yet the user wants
1505 // a section header table output. We need to throw an error if a user tries
1506 // to do that.
1507 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1508 error("Cannot write section header table because section header string "
1509 "table was removed.");
1510
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001511 Obj.sortSections();
1512
1513 // We need to assign indexes before we perform layout because we need to know
1514 // if we need large indexes or not. We can assign indexes first and check as
1515 // we go to see if we will actully need large indexes.
1516 bool NeedsLargeIndexes = false;
1517 if (size(Obj.sections()) >= SHN_LORESERVE) {
1518 auto Sections = Obj.sections();
1519 NeedsLargeIndexes =
1520 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1521 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1522 // TODO: handle case where only one section needs the large index table but
1523 // only needs it because the large index table hasn't been removed yet.
1524 }
1525
1526 if (NeedsLargeIndexes) {
1527 // This means we definitely need to have a section index table but if we
1528 // already have one then we should use it instead of making a new one.
1529 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1530 // Addition of a section to the end does not invalidate the indexes of
1531 // other sections and assigns the correct index to the new section.
1532 auto &Shndx = Obj.addSection<SectionIndexSection>();
1533 Obj.SymbolTable->setShndxTable(&Shndx);
1534 Shndx.setSymTab(Obj.SymbolTable);
1535 }
1536 } else {
1537 // Since we don't need SectionIndexTable we should remove it and all
1538 // references to it.
1539 if (Obj.SectionIndexTable != nullptr) {
1540 Obj.removeSections([this](const SectionBase &Sec) {
1541 return &Sec == Obj.SectionIndexTable;
1542 });
1543 }
1544 }
1545
1546 // Make sure we add the names of all the sections. Importantly this must be
1547 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001548 if (Obj.SectionNames != nullptr)
1549 for (const auto &Section : Obj.sections()) {
1550 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001551 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001552
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001553 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001554
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001555 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001556 // Also, the output arch may not be the same as the input arch, so fix up
1557 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001558 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001559 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1560 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001561 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001562 Sec.accept(*SecSizer);
1563 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001564
1565 // The symbol table does not update all other sections on update. For
1566 // instance, symbol names are not added as new symbols are added. This means
1567 // that some sections, like .strtab, don't yet have their final size.
1568 if (Obj.SymbolTable != nullptr)
1569 Obj.SymbolTable->prepareForLayout();
1570
Petr Hosekc4df10e2017-08-04 21:09:26 +00001571 assignOffsets();
1572
1573 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001574 if (Obj.SectionNames != nullptr)
1575 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001576 // Finally now that all offsets and indexes have been set we can finalize any
1577 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001578 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1579 for (auto &Section : Obj.sections()) {
1580 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001581 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001582 if (WriteSectionHeaders)
1583 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1584 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001585 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001586
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001587 Buf.allocate(totalSize());
1588 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001589}
1590
Jake Ehrlich76e91102018-01-25 22:46:17 +00001591void BinaryWriter::write() {
1592 for (auto &Section : Obj.sections()) {
1593 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001594 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001595 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001596 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001597 if (auto E = Buf.commit())
1598 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001599}
1600
Jake Ehrlich76e91102018-01-25 22:46:17 +00001601void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001602 // TODO: Create a filter range to construct OrderedSegments from so that this
1603 // code can be deduped with assignOffsets above. This should also solve the
1604 // todo below for LayoutSections.
1605 // We need a temporary list of segments that has a special order to it
1606 // so that we know that anytime ->ParentSegment is set that segment has
1607 // already had it's offset properly set. We only want to consider the segments
1608 // that will affect layout of allocated sections so we only add those.
1609 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001610 for (auto &Section : Obj.sections()) {
1611 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1612 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001613 }
1614 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001615
1616 // For binary output, we're going to use physical addresses instead of
1617 // virtual addresses, since a binary output is used for cases like ROM
1618 // loading and physical addresses are intended for ROM loading.
1619 // However, if no segment has a physical address, we'll fallback to using
1620 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001621 if (all_of(OrderedSegments,
1622 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1623 for (Segment *Seg : OrderedSegments)
1624 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001625
1626 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1627 compareSegmentsByPAddr);
1628
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001629 // Because we add a ParentSegment for each section we might have duplicate
1630 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1631 // would do very strange things.
1632 auto End =
1633 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1634 OrderedSegments.erase(End, std::end(OrderedSegments));
1635
Jake Ehrlich46814be2018-01-22 19:27:30 +00001636 uint64_t Offset = 0;
1637
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001638 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001639 // our layout algorithm to proceed as expected while not writing out the gap
1640 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001641 if (!OrderedSegments.empty()) {
1642 auto Seg = OrderedSegments[0];
1643 auto Sec = Seg->firstSection();
1644 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1645 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001646 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001647 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001648 // The PAddr needs to be increased to remove the gap before the first
1649 // section.
1650 Seg->PAddr += Diff;
1651 uint64_t LowestPAddr = Seg->PAddr;
1652 for (auto &Segment : OrderedSegments) {
1653 Segment->Offset = Segment->PAddr - LowestPAddr;
1654 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1655 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001656 }
1657
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001658 // TODO: generalize LayoutSections to take a range. Pass a special range
1659 // constructed from an iterator that skips values for which a predicate does
1660 // not hold. Then pass such a range to LayoutSections instead of constructing
1661 // AllocatedSections here.
1662 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001663 for (auto &Section : Obj.sections()) {
1664 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001665 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001666 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001667 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001668 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001669
1670 // Now that every section has been laid out we just need to compute the total
1671 // file size. This might not be the same as the offset returned by
1672 // LayoutSections, because we want to truncate the last segment to the end of
1673 // its last section, to match GNU objcopy's behaviour.
1674 TotalSize = 0;
1675 for (const auto &Section : AllocatedSections) {
1676 if (Section->Type != SHT_NOBITS)
1677 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1678 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001679
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001680 Buf.allocate(TotalSize);
1681 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001682}
1683
Jake Ehrlich76e91102018-01-25 22:46:17 +00001684template class ELFBuilder<ELF64LE>;
1685template class ELFBuilder<ELF64BE>;
1686template class ELFBuilder<ELF32LE>;
1687template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001688
Jake Ehrlich76e91102018-01-25 22:46:17 +00001689template class ELFWriter<ELF64LE>;
1690template class ELFWriter<ELF64BE>;
1691template class ELFWriter<ELF32LE>;
1692template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001693
1694} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001695} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001696} // end namespace llvm