blob: ae02966b730841acf5161d969085c0f462f4a521 [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
Jake Ehrlich76e91102018-01-25 22:46:17 +000074SectionVisitor::~SectionVisitor() {}
75
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +000076void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
77 error("Cannot write symbol section index table '" + Sec.Name + "' ");
78}
79
Jake Ehrlich76e91102018-01-25 22:46:17 +000080void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
81 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
82}
83
84void BinarySectionWriter::visit(const RelocationSection &Sec) {
85 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
86}
87
88void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +000089 error("Cannot write '" + Sec.Name + "' out to binary");
90}
91
92void BinarySectionWriter::visit(const GroupSection &Sec) {
93 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +000094}
95
96void SectionWriter::visit(const Section &Sec) {
97 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +000098 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +000099 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000100 llvm::copy(Sec.Contents, Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000101}
102
Jake Ehrlich76e91102018-01-25 22:46:17 +0000103void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
104
105void SectionWriter::visit(const OwnedDataSection &Sec) {
106 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Fangrui Song75709322018-11-17 01:44:25 +0000107 llvm::copy(Sec.Data, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000108}
109
Puyan Lotfiaf048642018-10-01 10:29:41 +0000110static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
111
112static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
113 return Data.size() > ZlibGnuMagic.size() &&
114 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
115}
116
117template <class ELFT>
118static std::tuple<uint64_t, uint64_t>
119getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
120 const bool IsGnuDebug = isDataGnuCompressed(Data);
121 const uint64_t DecompressedSize =
122 IsGnuDebug
123 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
124 Data.data() + ZlibGnuMagic.size()))
125 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
126 const uint64_t DecompressedAlign =
127 IsGnuDebug ? 1
128 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
129 ->ch_addralign;
130
131 return std::make_tuple(DecompressedSize, DecompressedAlign);
132}
133
134template <class ELFT>
135void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
136 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
137
138 if (!zlib::isAvailable()) {
139 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
140 return;
141 }
142
143 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
144 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
145 : sizeof(Elf_Chdr_Impl<ELFT>);
146
147 StringRef CompressedContent(
148 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
149 Sec.OriginalData.size() - DataOffset);
150
151 SmallVector<char, 128> DecompressedContent;
152 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
153 static_cast<size_t>(Sec.Size)))
154 reportError(Sec.Name, std::move(E));
155
156 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
157}
158
159void BinarySectionWriter::visit(const DecompressedSection &Sec) {
160 error("Cannot write compressed section '" + Sec.Name + "' ");
161}
162
163void DecompressedSection::accept(SectionVisitor &Visitor) const {
164 Visitor.visit(*this);
165}
166
Jake Ehrlich76e91102018-01-25 22:46:17 +0000167void OwnedDataSection::accept(SectionVisitor &Visitor) const {
168 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000169}
170
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000171void BinarySectionWriter::visit(const CompressedSection &Sec) {
172 error("Cannot write compressed section '" + Sec.Name + "' ");
173}
174
175template <class ELFT>
176void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
177 uint8_t *Buf = Out.getBufferStart();
178 Buf += Sec.Offset;
179
180 if (Sec.CompressionType == DebugCompressionType::None) {
181 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
182 return;
183 }
184
185 if (Sec.CompressionType == DebugCompressionType::GNU) {
186 const char *Magic = "ZLIB";
187 memcpy(Buf, Magic, strlen(Magic));
188 Buf += strlen(Magic);
189 const uint64_t DecompressedSize =
190 support::endian::read64be(&Sec.DecompressedSize);
191 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
192 Buf += sizeof(DecompressedSize);
193 } else {
194 Elf_Chdr_Impl<ELFT> Chdr;
195 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
196 Chdr.ch_size = Sec.DecompressedSize;
197 Chdr.ch_addralign = Sec.DecompressedAlign;
198 memcpy(Buf, &Chdr, sizeof(Chdr));
199 Buf += sizeof(Chdr);
200 }
201
202 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
203}
204
205CompressedSection::CompressedSection(const SectionBase &Sec,
206 DebugCompressionType CompressionType)
207 : SectionBase(Sec), CompressionType(CompressionType),
208 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
209
210 if (!zlib::isAvailable()) {
211 CompressionType = DebugCompressionType::None;
212 return;
213 }
214
215 if (Error E = zlib::compress(
216 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
217 OriginalData.size()),
218 CompressedData))
219 reportError(Name, std::move(E));
220
221 size_t ChdrSize;
222 if (CompressionType == DebugCompressionType::GNU) {
223 Name = ".z" + Sec.Name.substr(1);
224 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
225 } else {
226 Flags |= ELF::SHF_COMPRESSED;
227 ChdrSize =
228 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
229 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
230 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
231 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
232 }
233 Size = ChdrSize + CompressedData.size();
234 Align = 8;
235}
236
Puyan Lotfiaf048642018-10-01 10:29:41 +0000237CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
238 uint64_t DecompressedSize,
239 uint64_t DecompressedAlign)
240 : CompressionType(DebugCompressionType::None),
241 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
242 OriginalData = CompressedData;
243}
244
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000245void CompressedSection::accept(SectionVisitor &Visitor) const {
246 Visitor.visit(*this);
247}
248
Petr Hosek05a04cb2017-08-01 00:33:58 +0000249void StringTableSection::addString(StringRef Name) {
250 StrTabBuilder.add(Name);
251 Size = StrTabBuilder.getSize();
252}
253
254uint32_t StringTableSection::findIndex(StringRef Name) const {
255 return StrTabBuilder.getOffset(Name);
256}
257
258void StringTableSection::finalize() { StrTabBuilder.finalize(); }
259
Jake Ehrlich76e91102018-01-25 22:46:17 +0000260void SectionWriter::visit(const StringTableSection &Sec) {
261 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
262}
263
264void StringTableSection::accept(SectionVisitor &Visitor) const {
265 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000266}
267
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000268template <class ELFT>
269void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
270 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000271 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Fangrui Song75709322018-11-17 01:44:25 +0000272 llvm::copy(Sec.Indexes, IndexesBuffer);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000273}
274
275void SectionIndexSection::initialize(SectionTableRef SecTable) {
276 Size = 0;
277 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
278 Link,
279 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
280 "Link field value " + Twine(Link) + " in section " + Name +
281 " is not a symbol table"));
282 Symbols->setShndxTable(this);
283}
284
285void SectionIndexSection::finalize() { Link = Symbols->Index; }
286
287void SectionIndexSection::accept(SectionVisitor &Visitor) const {
288 Visitor.visit(*this);
289}
290
Petr Hosekc1135772017-09-13 03:04:50 +0000291static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000292 switch (Index) {
293 case SHN_ABS:
294 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000295 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000296 }
Petr Hosekc1135772017-09-13 03:04:50 +0000297 if (Machine == EM_HEXAGON) {
298 switch (Index) {
299 case SHN_HEXAGON_SCOMMON:
300 case SHN_HEXAGON_SCOMMON_2:
301 case SHN_HEXAGON_SCOMMON_4:
302 case SHN_HEXAGON_SCOMMON_8:
303 return true;
304 }
305 }
306 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000307}
308
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000309// Large indexes force us to clarify exactly what this function should do. This
310// function should return the value that will appear in st_shndx when written
311// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000312uint16_t Symbol::getShndx() const {
313 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000314 if (DefinedIn->Index >= SHN_LORESERVE)
315 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000316 return DefinedIn->Index;
317 }
318 switch (ShndxType) {
319 // This means that we don't have a defined section but we do need to
320 // output a legitimate section index.
321 case SYMBOL_SIMPLE_INDEX:
322 return SHN_UNDEF;
323 case SYMBOL_ABS:
324 case SYMBOL_COMMON:
325 case SYMBOL_HEXAGON_SCOMMON:
326 case SYMBOL_HEXAGON_SCOMMON_2:
327 case SYMBOL_HEXAGON_SCOMMON_4:
328 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000329 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000330 return static_cast<uint16_t>(ShndxType);
331 }
332 llvm_unreachable("Symbol with invalid ShndxType encountered");
333}
334
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000335bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
336
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000337void SymbolTableSection::assignIndices() {
338 uint32_t Index = 0;
339 for (auto &Sym : Symbols)
340 Sym->Index = Index++;
341}
342
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000343void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000344 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000345 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000346 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000347 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000348 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000349 Sym.Binding = Bind;
350 Sym.Type = Type;
351 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000352 if (DefinedIn != nullptr)
353 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000354 if (DefinedIn == nullptr) {
355 if (Shndx >= SHN_LORESERVE)
356 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
357 else
358 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
359 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000360 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000361 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000362 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000363 Sym.Index = Symbols.size();
364 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
365 Size += this->EntrySize;
366}
367
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000368void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000369 if (SectionIndexTable == Sec)
370 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000371 if (SymbolNames == Sec) {
372 error("String table " + SymbolNames->Name +
373 " cannot be removed because it is referenced by the symbol table " +
374 this->Name);
375 }
Paul Semel41695f82018-05-02 20:19:22 +0000376 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000377}
378
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000379void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000380 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
381 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000382 std::stable_partition(
383 std::begin(Symbols), std::end(Symbols),
384 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000385 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000386}
387
Paul Semel4246a462018-05-09 21:36:54 +0000388void SymbolTableSection::removeSymbols(
389 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000390 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000391 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000392 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
393 std::end(Symbols));
394 Size = Symbols.size() * EntrySize;
395 assignIndices();
396}
397
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000398void SymbolTableSection::initialize(SectionTableRef SecTable) {
399 Size = 0;
400 setStrTab(SecTable.getSectionOfType<StringTableSection>(
401 Link,
402 "Symbol table has link index of " + Twine(Link) +
403 " which is not a valid index",
404 "Symbol table has link index of " + Twine(Link) +
405 " which is not a string table"));
406}
407
Petr Hosek79cee9e2017-08-29 02:12:03 +0000408void SymbolTableSection::finalize() {
409 // Make sure SymbolNames is finalized before getting name indexes.
410 SymbolNames->finalize();
411
412 uint32_t MaxLocalIndex = 0;
413 for (auto &Sym : Symbols) {
414 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
415 if (Sym->Binding == STB_LOCAL)
416 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
417 }
418 // Now we need to set the Link and Info fields.
419 Link = SymbolNames->Index;
420 Info = MaxLocalIndex + 1;
421}
422
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000423void SymbolTableSection::prepareForLayout() {
424 // Add all potential section indexes before file layout so that the section
425 // index section has the approprite size.
426 if (SectionIndexTable != nullptr) {
427 for (const auto &Sym : Symbols) {
428 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
429 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
430 else
431 SectionIndexTable->addIndex(SHN_UNDEF);
432 }
433 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000434 // Add all of our strings to SymbolNames so that SymbolNames has the right
435 // size before layout is decided.
436 for (auto &Sym : Symbols)
437 SymbolNames->addString(Sym->Name);
438}
439
440const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
441 if (Symbols.size() <= Index)
442 error("Invalid symbol index: " + Twine(Index));
443 return Symbols[Index].get();
444}
445
Paul Semel99dda0b2018-05-25 11:01:25 +0000446Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
447 return const_cast<Symbol *>(
448 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
449}
450
Petr Hosek79cee9e2017-08-29 02:12:03 +0000451template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000452void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000453 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000454 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000455 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000456 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000457 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000458 Sym->st_name = Symbol->NameIndex;
459 Sym->st_value = Symbol->Value;
460 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000461 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000462 Sym->setBinding(Symbol->Binding);
463 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000464 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000465 ++Sym;
466 }
467}
468
Jake Ehrlich76e91102018-01-25 22:46:17 +0000469void SymbolTableSection::accept(SectionVisitor &Visitor) const {
470 Visitor.visit(*this);
471}
472
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000473template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000474void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
475 const SectionBase *Sec) {
476 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000477 error("Symbol table " + Symbols->Name +
478 " cannot be removed because it is "
479 "referenced by the relocation "
480 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000481 this->Name);
482 }
483}
484
485template <class SymTabType>
486void RelocSectionWithSymtabBase<SymTabType>::initialize(
487 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000488 if (Link != SHN_UNDEF)
489 setSymTab(SecTable.getSectionOfType<SymTabType>(
490 Link,
491 "Link field value " + Twine(Link) + " in section " + Name +
492 " is invalid",
493 "Link field value " + Twine(Link) + " in section " + Name +
494 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000495
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000496 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000497 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
498 " in section " + Name +
499 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000500 else
501 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000502}
503
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000504template <class SymTabType>
505void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000506 this->Link = Symbols ? Symbols->Index : 0;
507
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000508 if (SecToApplyRel != nullptr)
509 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000510}
511
512template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000513static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000514
515template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000516static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000517 Rela.r_addend = Addend;
518}
519
Jake Ehrlich76e91102018-01-25 22:46:17 +0000520template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000521static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000522 for (const auto &Reloc : Relocations) {
523 Buf->r_offset = Reloc.Offset;
524 setAddend(*Buf, Reloc.Addend);
525 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
526 ++Buf;
527 }
528}
529
530template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000531void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
532 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
533 if (Sec.Type == SHT_REL)
534 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000535 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000536 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000537}
538
Jake Ehrlich76e91102018-01-25 22:46:17 +0000539void RelocationSection::accept(SectionVisitor &Visitor) const {
540 Visitor.visit(*this);
541}
542
Paul Semel4246a462018-05-09 21:36:54 +0000543void RelocationSection::removeSymbols(
544 function_ref<bool(const Symbol &)> ToRemove) {
545 for (const Relocation &Reloc : Relocations)
546 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000547 error("not stripping symbol '" + Reloc.RelocSymbol->Name +
Paul Semel4246a462018-05-09 21:36:54 +0000548 "' because it is named in a relocation");
549}
550
Paul Semel99dda0b2018-05-25 11:01:25 +0000551void RelocationSection::markSymbols() {
552 for (const Relocation &Reloc : Relocations)
553 Reloc.RelocSymbol->Referenced = true;
554}
555
Jake Ehrlich76e91102018-01-25 22:46:17 +0000556void SectionWriter::visit(const DynamicRelocationSection &Sec) {
Fangrui Song75709322018-11-17 01:44:25 +0000557 llvm::copy(Sec.Contents,
Jake Ehrlich76e91102018-01-25 22:46:17 +0000558 Out.getBufferStart() + Sec.Offset);
559}
560
561void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
562 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000563}
564
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000565void Section::removeSectionReferences(const SectionBase *Sec) {
566 if (LinkSection == Sec) {
567 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000568 " cannot be removed because it is "
569 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000570 this->Name);
571 }
572}
573
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000574void GroupSection::finalize() {
575 this->Info = Sym->Index;
576 this->Link = SymTab->Index;
577}
578
Paul Semel4246a462018-05-09 21:36:54 +0000579void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
580 if (ToRemove(*Sym)) {
581 error("Symbol " + Sym->Name +
582 " cannot be removed because it is "
583 "referenced by the section " +
584 this->Name + "[" + Twine(this->Index) + "]");
585 }
586}
587
Paul Semel99dda0b2018-05-25 11:01:25 +0000588void GroupSection::markSymbols() {
589 if (Sym)
590 Sym->Referenced = true;
591}
592
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000593void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000594 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000595 LinkSection =
596 SecTable.getSection(Link, "Link field value " + Twine(Link) +
597 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000598 if (LinkSection->Type == ELF::SHT_SYMTAB)
599 LinkSection = nullptr;
600 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000601}
602
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000603void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000604
Jake Ehrlich76e91102018-01-25 22:46:17 +0000605void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000606 FileName = sys::path::filename(File);
607 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000608 // followed by a null terminator and then the CRC32 of the file. The CRC32
609 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
610 // byte, and then finally push the size to alignment and add 4.
611 Size = alignTo(FileName.size() + 1, 4) + 4;
612 // The CRC32 will only be aligned if we align the whole section.
613 Align = 4;
614 Type = ELF::SHT_PROGBITS;
615 Name = ".gnu_debuglink";
616 // For sections not found in segments, OriginalOffset is only used to
617 // establish the order that sections should go in. By using the maximum
618 // possible offset we cause this section to wind up at the end.
619 OriginalOffset = std::numeric_limits<uint64_t>::max();
Fangrui Song32a34e62018-11-01 16:02:12 +0000620 JamCRC CRC;
621 CRC.update(ArrayRef<char>(Data.data(), Data.size()));
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000622 // The CRC32 value needs to be complemented because the JamCRC dosn't
623 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
624 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
Fangrui Song32a34e62018-11-01 16:02:12 +0000625 CRC32 = ~CRC.getCRC();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000626}
627
Jake Ehrlich76e91102018-01-25 22:46:17 +0000628GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000629 // Read in the file to compute the CRC of it.
630 auto DebugOrErr = MemoryBuffer::getFile(File);
631 if (!DebugOrErr)
632 error("'" + File + "': " + DebugOrErr.getError().message());
633 auto Debug = std::move(*DebugOrErr);
634 init(File, Debug->getBuffer());
635}
636
637template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000638void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
639 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000640 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000641 Elf_Word *CRC =
642 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
643 *CRC = Sec.CRC32;
Fangrui Song75709322018-11-17 01:44:25 +0000644 llvm::copy(Sec.FileName, File);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000645}
646
647void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
648 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000649}
650
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000651template <class ELFT>
652void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
653 ELF::Elf32_Word *Buf =
654 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
655 *Buf++ = Sec.FlagWord;
656 for (const auto *S : Sec.GroupMembers)
657 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
658}
659
660void GroupSection::accept(SectionVisitor &Visitor) const {
661 Visitor.visit(*this);
662}
663
Petr Hosek05a04cb2017-08-01 00:33:58 +0000664// Returns true IFF a section is wholly inside the range of a segment
665static bool sectionWithinSegment(const SectionBase &Section,
666 const Segment &Segment) {
667 // If a section is empty it should be treated like it has a size of 1. This is
668 // to clarify the case when an empty section lies on a boundary between two
669 // segments and ensures that the section "belongs" to the second segment and
670 // not the first.
671 uint64_t SecSize = Section.Size ? Section.Size : 1;
672 return Segment.Offset <= Section.OriginalOffset &&
673 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
674}
675
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000676// Returns true IFF a segment's original offset is inside of another segment's
677// range.
678static bool segmentOverlapsSegment(const Segment &Child,
679 const Segment &Parent) {
680
681 return Parent.OriginalOffset <= Child.OriginalOffset &&
682 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
683}
684
Jake Ehrlich46814be2018-01-22 19:27:30 +0000685static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000686 // Any segment without a parent segment should come before a segment
687 // that has a parent segment.
688 if (A->OriginalOffset < B->OriginalOffset)
689 return true;
690 if (A->OriginalOffset > B->OriginalOffset)
691 return false;
692 return A->Index < B->Index;
693}
694
Jake Ehrlich46814be2018-01-22 19:27:30 +0000695static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
696 if (A->PAddr < B->PAddr)
697 return true;
698 if (A->PAddr > B->PAddr)
699 return false;
700 return A->Index < B->Index;
701}
702
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000703template <class ELFT> void BinaryELFBuilder<ELFT>::initFileHeader() {
704 Obj->Flags = 0x0;
705 Obj->Type = ET_REL;
706 Obj->Entry = 0x0;
707 Obj->Machine = EMachine;
708 Obj->Version = 1;
709}
710
711template <class ELFT> void BinaryELFBuilder<ELFT>::initHeaderSegment() {
712 Obj->ElfHdrSegment.Index = 0;
713}
714
715template <class ELFT> StringTableSection *BinaryELFBuilder<ELFT>::addStrTab() {
716 auto &StrTab = Obj->addSection<StringTableSection>();
717 StrTab.Name = ".strtab";
718
719 Obj->SectionNames = &StrTab;
720 return &StrTab;
721}
722
723template <class ELFT>
724SymbolTableSection *
725BinaryELFBuilder<ELFT>::addSymTab(StringTableSection *StrTab) {
726 auto &SymTab = Obj->addSection<SymbolTableSection>();
727
728 SymTab.Name = ".symtab";
729 SymTab.Link = StrTab->Index;
730 // TODO: Factor out dependence on ElfType here.
731 SymTab.EntrySize = sizeof(Elf_Sym);
732
733 // The symbol table always needs a null symbol
734 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
735
736 Obj->SymbolTable = &SymTab;
737 return &SymTab;
738}
739
740template <class ELFT>
741void BinaryELFBuilder<ELFT>::addData(SymbolTableSection *SymTab) {
742 auto Data = ArrayRef<uint8_t>(
743 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
744 MemBuf->getBufferSize());
745 auto &DataSection = Obj->addSection<Section>(Data);
746 DataSection.Name = ".data";
747 DataSection.Type = ELF::SHT_PROGBITS;
748 DataSection.Size = Data.size();
749 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
750
751 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
752 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +0000753 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000754 Twine Prefix = Twine("_binary_") + SanitizedFilename;
755
756 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
757 /*Value=*/0, STV_DEFAULT, 0, 0);
758 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
759 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
760 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
761 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
762}
763
764template <class ELFT> void BinaryELFBuilder<ELFT>::initSections() {
765 for (auto &Section : Obj->sections()) {
766 Section.initialize(Obj->sections());
767 }
768}
769
770template <class ELFT> std::unique_ptr<Object> BinaryELFBuilder<ELFT>::build() {
771 initFileHeader();
772 initHeaderSegment();
773 StringTableSection *StrTab = addStrTab();
774 SymbolTableSection *SymTab = addSymTab(StrTab);
775 initSections();
776 addData(SymTab);
777
778 return std::move(Obj);
779}
780
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000781template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000782 for (auto &Parent : Obj.segments()) {
783 // Every segment will overlap with itself but we don't want a segment to
784 // be it's own parent so we avoid that situation.
785 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
786 // We want a canonical "most parental" segment but this requires
787 // inspecting the ParentSegment.
788 if (compareSegmentsByOffset(&Parent, &Child))
789 if (Child.ParentSegment == nullptr ||
790 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
791 Child.ParentSegment = &Parent;
792 }
793 }
794 }
795}
796
Jake Ehrlich76e91102018-01-25 22:46:17 +0000797template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000798 uint32_t Index = 0;
799 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000800 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
801 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000802 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000803 Seg.Type = Phdr.p_type;
804 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000805 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000806 Seg.Offset = Phdr.p_offset;
807 Seg.VAddr = Phdr.p_vaddr;
808 Seg.PAddr = Phdr.p_paddr;
809 Seg.FileSize = Phdr.p_filesz;
810 Seg.MemSize = Phdr.p_memsz;
811 Seg.Align = Phdr.p_align;
812 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000813 for (auto &Section : Obj.sections()) {
814 if (sectionWithinSegment(Section, Seg)) {
815 Seg.addSection(&Section);
816 if (!Section.ParentSegment ||
817 Section.ParentSegment->Offset > Seg.Offset) {
818 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000819 }
820 }
821 }
822 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000823
824 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000825 ElfHdr.Index = Index++;
826
827 const auto &Ehdr = *ElfFile.getHeader();
828 auto &PrHdr = Obj.ProgramHdrSegment;
829 PrHdr.Type = PT_PHDR;
830 PrHdr.Flags = 0;
831 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
832 // Whereas this works automatically for ElfHdr, here OriginalOffset is
833 // always non-zero and to ensure the equation we assign the same value to
834 // VAddr as well.
835 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
836 PrHdr.PAddr = 0;
837 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000838 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000839 PrHdr.Align = sizeof(Elf_Addr);
840 PrHdr.Index = Index++;
841
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000842 // Now we do an O(n^2) loop through the segments in order to match up
843 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000844 for (auto &Child : Obj.segments())
845 setParentSegment(Child);
846 setParentSegment(ElfHdr);
847 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000848}
849
850template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000851void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
852 auto SecTable = Obj.sections();
853 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
854 GroupSec->Link,
855 "Link field value " + Twine(GroupSec->Link) + " in section " +
856 GroupSec->Name + " is invalid",
857 "Link field value " + Twine(GroupSec->Link) + " in section " +
858 GroupSec->Name + " is not a symbol table");
859 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
860 if (!Sym)
861 error("Info field value " + Twine(GroupSec->Info) + " in section " +
862 GroupSec->Name + " is not a valid symbol index");
863 GroupSec->setSymTab(SymTab);
864 GroupSec->setSymbol(Sym);
865 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
866 GroupSec->Contents.empty())
867 error("The content of the section " + GroupSec->Name + " is malformed");
868 const ELF::Elf32_Word *Word =
869 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
870 const ELF::Elf32_Word *End =
871 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
872 GroupSec->setFlagWord(*Word++);
873 for (; Word != End; ++Word) {
874 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
875 GroupSec->addMember(SecTable.getSection(
876 Index, "Group member index " + Twine(Index) + " in section " +
877 GroupSec->Name + " is invalid"));
878 }
879}
880
881template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000882void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000883 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
884 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000885 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000886
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000887 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
888 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000889 SectionBase *DefSection = nullptr;
890 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000891
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000892 if (Sym.st_shndx == SHN_XINDEX) {
893 if (SymTab->getShndxTable() == nullptr)
894 error("Symbol '" + Name +
895 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
896 if (ShndxData.data() == nullptr) {
897 const Elf_Shdr &ShndxSec =
898 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
899 ShndxData = unwrapOrError(
900 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
901 if (ShndxData.size() != Symbols.size())
902 error("Symbol section index table does not have the same number of "
903 "entries as the symbol table.");
904 }
905 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
906 DefSection = Obj.sections().getSection(
907 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000908 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000909 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000910 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000911 error(
912 "Symbol '" + Name +
913 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
914 Twine(Sym.st_shndx));
915 }
916 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000917 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000918 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000919 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000920 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000921 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000922
Petr Hosek79cee9e2017-08-29 02:12:03 +0000923 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000924 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000925 }
926}
927
928template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000929static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
930
931template <class ELFT>
932static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
933 ToSet = Rela.r_addend;
934}
935
Jake Ehrlich76e91102018-01-25 22:46:17 +0000936template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000937static void initRelocations(RelocationSection *Relocs,
938 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000939 for (const auto &Rel : RelRange) {
940 Relocation ToAdd;
941 ToAdd.Offset = Rel.r_offset;
942 getAddend(ToAdd.Addend, Rel);
943 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000944 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000945 Relocs->addRelocation(ToAdd);
946 }
947}
948
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000949SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000950 if (Index == SHN_UNDEF || Index > Sections.size())
951 error(ErrMsg);
952 return Sections[Index - 1].get();
953}
954
955template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000956T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000957 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000958 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000959 return Sec;
960 error(TypeErrMsg);
961}
962
Petr Hosekd7df9b22017-09-06 23:41:02 +0000963template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000964SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000965 ArrayRef<uint8_t> Data;
966 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000967 case SHT_REL:
968 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000969 if (Shdr.sh_flags & SHF_ALLOC) {
970 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000971 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000972 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000973 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000974 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000975 // If a string table is allocated we don't want to mess with it. That would
976 // mean altering the memory image. There are no special link types or
977 // anything so we can just use a Section.
978 if (Shdr.sh_flags & SHF_ALLOC) {
979 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000980 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000981 }
Jake Ehrlich76e91102018-01-25 22:46:17 +0000982 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000983 case SHT_HASH:
984 case SHT_GNU_HASH:
985 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
986 // Because of this we don't need to mess with the hash tables either.
987 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000988 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000989 case SHT_GROUP:
990 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
991 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000992 case SHT_DYNSYM:
993 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000994 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000995 case SHT_DYNAMIC:
996 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000997 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000998 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000999 auto &SymTab = Obj.addSection<SymbolTableSection>();
1000 Obj.SymbolTable = &SymTab;
1001 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001002 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001003 case SHT_SYMTAB_SHNDX: {
1004 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1005 Obj.SectionIndexTable = &ShndxSection;
1006 return ShndxSection;
1007 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001008 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001009 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001010 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001011 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001012
1013 if (isDataGnuCompressed(Data) || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
1014 uint64_t DecompressedSize, DecompressedAlign;
1015 std::tie(DecompressedSize, DecompressedAlign) =
1016 getDecompressedSizeAndAlignment<ELFT>(Data);
1017 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1018 DecompressedAlign);
1019 }
1020
Jake Ehrlich76e91102018-01-25 22:46:17 +00001021 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001022 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001023 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001024}
1025
Jake Ehrlich76e91102018-01-25 22:46:17 +00001026template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001027 uint32_t Index = 0;
1028 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1029 if (Index == 0) {
1030 ++Index;
1031 continue;
1032 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001033 auto &Sec = makeSection(Shdr);
1034 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1035 Sec.Type = Shdr.sh_type;
1036 Sec.Flags = Shdr.sh_flags;
1037 Sec.Addr = Shdr.sh_addr;
1038 Sec.Offset = Shdr.sh_offset;
1039 Sec.OriginalOffset = Shdr.sh_offset;
1040 Sec.Size = Shdr.sh_size;
1041 Sec.Link = Shdr.sh_link;
1042 Sec.Info = Shdr.sh_info;
1043 Sec.Align = Shdr.sh_addralign;
1044 Sec.EntrySize = Shdr.sh_entsize;
1045 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001046 Sec.OriginalData =
1047 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1048 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001049 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001050
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001051 // If a section index table exists we'll need to initialize it before we
1052 // initialize the symbol table because the symbol table might need to
1053 // reference it.
1054 if (Obj.SectionIndexTable)
1055 Obj.SectionIndexTable->initialize(Obj.sections());
1056
Petr Hosek79cee9e2017-08-29 02:12:03 +00001057 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001058 // details about symbol tables. We need the symbol table filled out before
1059 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001060 if (Obj.SymbolTable) {
1061 Obj.SymbolTable->initialize(Obj.sections());
1062 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001063 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001064
1065 // Now that all sections and symbols have been added we can add
1066 // relocations that reference symbols and set the link and info fields for
1067 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001068 for (auto &Section : Obj.sections()) {
1069 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001070 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001071 Section.initialize(Obj.sections());
1072 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001073 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1074 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001075 initRelocations(RelSec, Obj.SymbolTable,
1076 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001077 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001078 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001079 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001080 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1081 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001082 }
1083 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001084}
1085
Jake Ehrlich76e91102018-01-25 22:46:17 +00001086template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001087 const auto &Ehdr = *ElfFile.getHeader();
1088
Jake Ehrlich76e91102018-01-25 22:46:17 +00001089 Obj.Type = Ehdr.e_type;
1090 Obj.Machine = Ehdr.e_machine;
1091 Obj.Version = Ehdr.e_version;
1092 Obj.Entry = Ehdr.e_entry;
1093 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001094
Jake Ehrlich76e91102018-01-25 22:46:17 +00001095 readSectionHeaders();
1096 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001097
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001098 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1099 if (ShstrIndex == SHN_XINDEX)
1100 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1101
Jake Ehrlich76e91102018-01-25 22:46:17 +00001102 Obj.SectionNames =
1103 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001104 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001105 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001106 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001107 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001108 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001109}
1110
Jake Ehrlich76e91102018-01-25 22:46:17 +00001111// A generic size function which computes sizes of any random access range.
1112template <class R> size_t size(R &&Range) {
1113 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1114}
1115
1116Writer::~Writer() {}
1117
1118Reader::~Reader() {}
1119
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001120std::unique_ptr<Object> BinaryReader::create() const {
1121 if (MInfo.Is64Bit)
1122 return MInfo.IsLittleEndian
1123 ? BinaryELFBuilder<ELF64LE>(MInfo.EMachine, MemBuf).build()
1124 : BinaryELFBuilder<ELF64BE>(MInfo.EMachine, MemBuf).build();
1125 else
1126 return MInfo.IsLittleEndian
1127 ? BinaryELFBuilder<ELF32LE>(MInfo.EMachine, MemBuf).build()
1128 : BinaryELFBuilder<ELF32BE>(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001129}
1130
1131std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001132 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001133 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1134 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001135 Builder.build();
1136 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001137 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1138 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001139 Builder.build();
1140 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001141 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1142 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001143 Builder.build();
1144 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001145 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1146 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001147 Builder.build();
1148 return Obj;
1149 }
1150 error("Invalid file type");
1151}
1152
1153template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001154 uint8_t *B = Buf.getBufferStart();
1155 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001156 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1157 Ehdr.e_ident[EI_MAG0] = 0x7f;
1158 Ehdr.e_ident[EI_MAG1] = 'E';
1159 Ehdr.e_ident[EI_MAG2] = 'L';
1160 Ehdr.e_ident[EI_MAG3] = 'F';
1161 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1162 Ehdr.e_ident[EI_DATA] =
1163 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1164 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1165 Ehdr.e_ident[EI_OSABI] = ELFOSABI_NONE;
1166 Ehdr.e_ident[EI_ABIVERSION] = 0;
1167
Jake Ehrlich76e91102018-01-25 22:46:17 +00001168 Ehdr.e_type = Obj.Type;
1169 Ehdr.e_machine = Obj.Machine;
1170 Ehdr.e_version = Obj.Version;
1171 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001172 // We have to use the fully-qualified name llvm::size
1173 // since some compilers complain on ambiguous resolution.
1174 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001175 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1176 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001177 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001178 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001179 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1180 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001181 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001182 // """
1183 // If the number of sections is greater than or equal to
1184 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1185 // number of section header table entries is contained in the sh_size field
1186 // of the section header at index 0.
1187 // """
1188 auto Shnum = size(Obj.sections()) + 1;
1189 if (Shnum >= SHN_LORESERVE)
1190 Ehdr.e_shnum = 0;
1191 else
1192 Ehdr.e_shnum = Shnum;
1193 // """
1194 // If the section name string table section index is greater than or equal
1195 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1196 // and the actual index of the section name string table section is
1197 // contained in the sh_link field of the section header at index 0.
1198 // """
1199 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1200 Ehdr.e_shstrndx = SHN_XINDEX;
1201 else
1202 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001203 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001204 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001205 Ehdr.e_shoff = 0;
1206 Ehdr.e_shnum = 0;
1207 Ehdr.e_shstrndx = 0;
1208 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001209}
1210
Jake Ehrlich76e91102018-01-25 22:46:17 +00001211template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1212 for (auto &Seg : Obj.segments())
1213 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001214}
1215
Jake Ehrlich76e91102018-01-25 22:46:17 +00001216template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001217 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001218 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001219 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001220 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001221 Shdr.sh_name = 0;
1222 Shdr.sh_type = SHT_NULL;
1223 Shdr.sh_flags = 0;
1224 Shdr.sh_addr = 0;
1225 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001226 // See writeEhdr for why we do this.
1227 uint64_t Shnum = size(Obj.sections()) + 1;
1228 if (Shnum >= SHN_LORESERVE)
1229 Shdr.sh_size = Shnum;
1230 else
1231 Shdr.sh_size = 0;
1232 // See writeEhdr for why we do this.
1233 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1234 Shdr.sh_link = Obj.SectionNames->Index;
1235 else
1236 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001237 Shdr.sh_info = 0;
1238 Shdr.sh_addralign = 0;
1239 Shdr.sh_entsize = 0;
1240
Jake Ehrlich76e91102018-01-25 22:46:17 +00001241 for (auto &Sec : Obj.sections())
1242 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001243}
1244
Jake Ehrlich76e91102018-01-25 22:46:17 +00001245template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1246 for (auto &Sec : Obj.sections())
1247 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001248}
1249
Jake Ehrlich76e91102018-01-25 22:46:17 +00001250void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001251
1252 auto Iter = std::stable_partition(
1253 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1254 if (ToRemove(*Sec))
1255 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001256 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1257 if (auto ToRelSec = RelSec->getSection())
1258 return !ToRemove(*ToRelSec);
1259 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001260 return true;
1261 });
1262 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1263 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001264 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001265 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001266 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1267 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001268 // Now make sure there are no remaining references to the sections that will
1269 // be removed. Sometimes it is impossible to remove a reference so we emit
1270 // an error here instead.
1271 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1272 for (auto &Segment : Segments)
1273 Segment->removeSection(RemoveSec.get());
1274 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1275 KeepSec->removeSectionReferences(RemoveSec.get());
1276 }
1277 // Now finally get rid of them all togethor.
1278 Sections.erase(Iter, std::end(Sections));
1279}
1280
Paul Semel4246a462018-05-09 21:36:54 +00001281void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1282 if (!SymbolTable)
1283 return;
1284
1285 for (const SecPtr &Sec : Sections)
1286 Sec->removeSymbols(ToRemove);
1287}
1288
Jake Ehrlich76e91102018-01-25 22:46:17 +00001289void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001290 // Put all sections in offset order. Maintain the ordering as closely as
1291 // possible while meeting that demand however.
1292 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1293 return A->OriginalOffset < B->OriginalOffset;
1294 };
1295 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1296 CompareSections);
1297}
1298
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001299static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1300 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1301 if (Align == 0)
1302 Align = 1;
1303 auto Diff =
1304 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1305 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1306 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1307 if (Diff < 0)
1308 Diff += Align;
1309 return Offset + Diff;
1310}
1311
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001312// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001313static void orderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001314 std::stable_sort(std::begin(Segments), std::end(Segments),
1315 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001316}
1317
1318// This function finds a consistent layout for a list of segments starting from
1319// an Offset. It assumes that Segments have been sorted by OrderSegments and
1320// returns an Offset one past the end of the last segment.
1321static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1322 uint64_t Offset) {
1323 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001324 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001325 // The only way a segment should move is if a section was between two
1326 // segments and that section was removed. If that section isn't in a segment
1327 // then it's acceptable, but not ideal, to simply move it to after the
1328 // segments. So we can simply layout segments one after the other accounting
1329 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001330 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001331 // We assume that segments have been ordered by OriginalOffset and Index
1332 // such that a parent segment will always come before a child segment in
1333 // OrderedSegments. This means that the Offset of the ParentSegment should
1334 // already be set and we can set our offset relative to it.
1335 if (Segment->ParentSegment != nullptr) {
1336 auto Parent = Segment->ParentSegment;
1337 Segment->Offset =
1338 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1339 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001340 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001341 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001342 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001343 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001344 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001345 return Offset;
1346}
1347
1348// This function finds a consistent layout for a list of sections. It assumes
1349// that the ->ParentSegment of each section has already been laid out. The
1350// supplied starting Offset is used for the starting offset of any section that
1351// does not have a ParentSegment. It returns either the offset given if all
1352// sections had a ParentSegment or an offset one past the last section if there
1353// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001354template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001355static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001356 // Now the offset of every segment has been set we can assign the offsets
1357 // of each section. For sections that are covered by a segment we should use
1358 // the segment's original offset and the section's original offset to compute
1359 // the offset from the start of the segment. Using the offset from the start
1360 // of the segment we can assign a new offset to the section. For sections not
1361 // covered by segments we can just bump Offset to the next valid location.
1362 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001363 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001364 Section.Index = Index++;
1365 if (Section.ParentSegment != nullptr) {
1366 auto Segment = *Section.ParentSegment;
1367 Section.Offset =
1368 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001369 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001370 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1371 Section.Offset = Offset;
1372 if (Section.Type != SHT_NOBITS)
1373 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001374 }
1375 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001376 return Offset;
1377}
Petr Hosek3f383832017-08-26 01:32:20 +00001378
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001379template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1380 auto &ElfHdr = Obj.ElfHdrSegment;
1381 ElfHdr.Type = PT_PHDR;
1382 ElfHdr.Flags = 0;
1383 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1384 ElfHdr.VAddr = 0;
1385 ElfHdr.PAddr = 0;
1386 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1387 ElfHdr.Align = 0;
1388}
1389
Jake Ehrlich76e91102018-01-25 22:46:17 +00001390template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001391 // We need a temporary list of segments that has a special order to it
1392 // so that we know that anytime ->ParentSegment is set that segment has
1393 // already had its offset properly set.
1394 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001395 for (auto &Segment : Obj.segments())
1396 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001397 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1398 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001399 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001400 // Offset is used as the start offset of the first segment to be laid out.
1401 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1402 // we start at offset 0.
1403 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001404 Offset = LayoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001405 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001406 // If we need to write the section header table out then we need to align the
1407 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001408 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001409 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001410 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001411}
1412
Jake Ehrlich76e91102018-01-25 22:46:17 +00001413template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001414 // We already have the section header offset so we can calculate the total
1415 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001416 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1417 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001418 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001419}
1420
Jake Ehrlich76e91102018-01-25 22:46:17 +00001421template <class ELFT> void ELFWriter<ELFT>::write() {
1422 writeEhdr();
1423 writePhdrs();
1424 writeSectionData();
1425 if (WriteSectionHeaders)
1426 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001427 if (auto E = Buf.commit())
1428 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001429}
1430
1431template <class ELFT> void ELFWriter<ELFT>::finalize() {
1432 // It could happen that SectionNames has been removed and yet the user wants
1433 // a section header table output. We need to throw an error if a user tries
1434 // to do that.
1435 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1436 error("Cannot write section header table because section header string "
1437 "table was removed.");
1438
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001439 Obj.sortSections();
1440
1441 // We need to assign indexes before we perform layout because we need to know
1442 // if we need large indexes or not. We can assign indexes first and check as
1443 // we go to see if we will actully need large indexes.
1444 bool NeedsLargeIndexes = false;
1445 if (size(Obj.sections()) >= SHN_LORESERVE) {
1446 auto Sections = Obj.sections();
1447 NeedsLargeIndexes =
1448 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1449 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1450 // TODO: handle case where only one section needs the large index table but
1451 // only needs it because the large index table hasn't been removed yet.
1452 }
1453
1454 if (NeedsLargeIndexes) {
1455 // This means we definitely need to have a section index table but if we
1456 // already have one then we should use it instead of making a new one.
1457 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1458 // Addition of a section to the end does not invalidate the indexes of
1459 // other sections and assigns the correct index to the new section.
1460 auto &Shndx = Obj.addSection<SectionIndexSection>();
1461 Obj.SymbolTable->setShndxTable(&Shndx);
1462 Shndx.setSymTab(Obj.SymbolTable);
1463 }
1464 } else {
1465 // Since we don't need SectionIndexTable we should remove it and all
1466 // references to it.
1467 if (Obj.SectionIndexTable != nullptr) {
1468 Obj.removeSections([this](const SectionBase &Sec) {
1469 return &Sec == Obj.SectionIndexTable;
1470 });
1471 }
1472 }
1473
1474 // Make sure we add the names of all the sections. Importantly this must be
1475 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001476 if (Obj.SectionNames != nullptr)
1477 for (const auto &Section : Obj.sections()) {
1478 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001479 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001480
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001481 initEhdrSegment();
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001482 // Before we can prepare for layout the indexes need to be finalized.
1483 uint64_t Index = 0;
1484 for (auto &Sec : Obj.sections())
1485 Sec.Index = Index++;
1486
1487 // The symbol table does not update all other sections on update. For
1488 // instance, symbol names are not added as new symbols are added. This means
1489 // that some sections, like .strtab, don't yet have their final size.
1490 if (Obj.SymbolTable != nullptr)
1491 Obj.SymbolTable->prepareForLayout();
1492
Petr Hosekc4df10e2017-08-04 21:09:26 +00001493 assignOffsets();
1494
1495 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001496 if (Obj.SectionNames != nullptr)
1497 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001498 // Finally now that all offsets and indexes have been set we can finalize any
1499 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001500 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1501 for (auto &Section : Obj.sections()) {
1502 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001503 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001504 if (WriteSectionHeaders)
1505 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1506 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001507 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001508
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001509 Buf.allocate(totalSize());
1510 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001511}
1512
Jake Ehrlich76e91102018-01-25 22:46:17 +00001513void BinaryWriter::write() {
1514 for (auto &Section : Obj.sections()) {
1515 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001516 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001517 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001518 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001519 if (auto E = Buf.commit())
1520 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001521}
1522
Jake Ehrlich76e91102018-01-25 22:46:17 +00001523void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001524 // TODO: Create a filter range to construct OrderedSegments from so that this
1525 // code can be deduped with assignOffsets above. This should also solve the
1526 // todo below for LayoutSections.
1527 // We need a temporary list of segments that has a special order to it
1528 // so that we know that anytime ->ParentSegment is set that segment has
1529 // already had it's offset properly set. We only want to consider the segments
1530 // that will affect layout of allocated sections so we only add those.
1531 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001532 for (auto &Section : Obj.sections()) {
1533 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1534 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001535 }
1536 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001537
1538 // For binary output, we're going to use physical addresses instead of
1539 // virtual addresses, since a binary output is used for cases like ROM
1540 // loading and physical addresses are intended for ROM loading.
1541 // However, if no segment has a physical address, we'll fallback to using
1542 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001543 if (all_of(OrderedSegments,
1544 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1545 for (Segment *Seg : OrderedSegments)
1546 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001547
1548 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1549 compareSegmentsByPAddr);
1550
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001551 // Because we add a ParentSegment for each section we might have duplicate
1552 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1553 // would do very strange things.
1554 auto End =
1555 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1556 OrderedSegments.erase(End, std::end(OrderedSegments));
1557
Jake Ehrlich46814be2018-01-22 19:27:30 +00001558 uint64_t Offset = 0;
1559
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001560 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001561 // our layout algorithm to proceed as expected while not writing out the gap
1562 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001563 if (!OrderedSegments.empty()) {
1564 auto Seg = OrderedSegments[0];
1565 auto Sec = Seg->firstSection();
1566 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1567 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001568 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001569 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001570 // The PAddr needs to be increased to remove the gap before the first
1571 // section.
1572 Seg->PAddr += Diff;
1573 uint64_t LowestPAddr = Seg->PAddr;
1574 for (auto &Segment : OrderedSegments) {
1575 Segment->Offset = Segment->PAddr - LowestPAddr;
1576 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1577 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001578 }
1579
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001580 // TODO: generalize LayoutSections to take a range. Pass a special range
1581 // constructed from an iterator that skips values for which a predicate does
1582 // not hold. Then pass such a range to LayoutSections instead of constructing
1583 // AllocatedSections here.
1584 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001585 for (auto &Section : Obj.sections()) {
1586 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001587 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001588 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001589 }
Fangrui Song32a34e62018-11-01 16:02:12 +00001590 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001591
1592 // Now that every section has been laid out we just need to compute the total
1593 // file size. This might not be the same as the offset returned by
1594 // LayoutSections, because we want to truncate the last segment to the end of
1595 // its last section, to match GNU objcopy's behaviour.
1596 TotalSize = 0;
1597 for (const auto &Section : AllocatedSections) {
1598 if (Section->Type != SHT_NOBITS)
1599 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1600 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001601
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001602 Buf.allocate(TotalSize);
1603 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001604}
1605
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001606template class BinaryELFBuilder<ELF64LE>;
1607template class BinaryELFBuilder<ELF64BE>;
1608template class BinaryELFBuilder<ELF32LE>;
1609template class BinaryELFBuilder<ELF32BE>;
1610
Jake Ehrlich76e91102018-01-25 22:46:17 +00001611template class ELFBuilder<ELF64LE>;
1612template class ELFBuilder<ELF64BE>;
1613template class ELFBuilder<ELF32LE>;
1614template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001615
Jake Ehrlich76e91102018-01-25 22:46:17 +00001616template class ELFWriter<ELF64LE>;
1617template class ELFWriter<ELF64BE>;
1618template class ELFWriter<ELF32LE>;
1619template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001620
1621} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001622} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001623} // end namespace llvm