blob: ddf811a769bde35b98a051092e139cb503c49626 [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
31using namespace llvm;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +000032using namespace llvm::objcopy;
Petr Hosek05a04cb2017-08-01 00:33:58 +000033using namespace object;
34using namespace ELF;
35
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000036Buffer::~Buffer() {}
37
38void FileBuffer::allocate(size_t Size) {
39 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
40 FileOutputBuffer::create(getName(), Size, FileOutputBuffer::F_executable);
41 handleAllErrors(BufferOrErr.takeError(), [this](const ErrorInfoBase &E) {
42 error("failed to open " + getName() + ": " + E.message());
43 });
44 Buf = std::move(*BufferOrErr);
45}
46
47Error FileBuffer::commit() { return Buf->commit(); }
48
49uint8_t *FileBuffer::getBufferStart() {
50 return reinterpret_cast<uint8_t *>(Buf->getBufferStart());
51}
52
53void MemBuffer::allocate(size_t Size) {
54 Buf = WritableMemoryBuffer::getNewMemBuffer(Size, getName());
55}
56
57Error MemBuffer::commit() { return Error::success(); }
58
59uint8_t *MemBuffer::getBufferStart() {
60 return reinterpret_cast<uint8_t *>(Buf->getBufferStart());
61}
62
63std::unique_ptr<WritableMemoryBuffer> MemBuffer::releaseMemoryBuffer() {
64 return std::move(Buf);
65}
66
Jake Ehrlich76e91102018-01-25 22:46:17 +000067template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000068 uint8_t *B = Buf.getBufferStart();
69 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
70 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000071 Phdr.p_type = Seg.Type;
72 Phdr.p_flags = Seg.Flags;
73 Phdr.p_offset = Seg.Offset;
74 Phdr.p_vaddr = Seg.VAddr;
75 Phdr.p_paddr = Seg.PAddr;
76 Phdr.p_filesz = Seg.FileSize;
77 Phdr.p_memsz = Seg.MemSize;
78 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000079}
80
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000081void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Paul Semel4246a462018-05-09 21:36:54 +000082void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000083void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000084void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000085void SectionBase::markSymbols() {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000086
Jake Ehrlich76e91102018-01-25 22:46:17 +000087template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000088 uint8_t *B = Buf.getBufferStart();
89 B += Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000090 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000091 Shdr.sh_name = Sec.NameIndex;
92 Shdr.sh_type = Sec.Type;
93 Shdr.sh_flags = Sec.Flags;
94 Shdr.sh_addr = Sec.Addr;
95 Shdr.sh_offset = Sec.Offset;
96 Shdr.sh_size = Sec.Size;
97 Shdr.sh_link = Sec.Link;
98 Shdr.sh_info = Sec.Info;
99 Shdr.sh_addralign = Sec.Align;
100 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000101}
102
Jake Ehrlich76e91102018-01-25 22:46:17 +0000103SectionVisitor::~SectionVisitor() {}
104
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000105void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
106 error("Cannot write symbol section index table '" + Sec.Name + "' ");
107}
108
Jake Ehrlich76e91102018-01-25 22:46:17 +0000109void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
110 error("Cannot write symbol table '" + Sec.Name + "' out to binary");
111}
112
113void BinarySectionWriter::visit(const RelocationSection &Sec) {
114 error("Cannot write relocation section '" + Sec.Name + "' out to binary");
115}
116
117void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000118 error("Cannot write '" + Sec.Name + "' out to binary");
119}
120
121void BinarySectionWriter::visit(const GroupSection &Sec) {
122 error("Cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000123}
124
125void SectionWriter::visit(const Section &Sec) {
126 if (Sec.Type == SHT_NOBITS)
Petr Hosek05a04cb2017-08-01 00:33:58 +0000127 return;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000128 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
129 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000130}
131
Jake Ehrlich76e91102018-01-25 22:46:17 +0000132void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
133
134void SectionWriter::visit(const OwnedDataSection &Sec) {
135 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
136 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
137}
138
Puyan Lotfiaf048642018-10-01 10:29:41 +0000139static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
140
141static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
142 return Data.size() > ZlibGnuMagic.size() &&
143 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
144}
145
146template <class ELFT>
147static std::tuple<uint64_t, uint64_t>
148getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
149 const bool IsGnuDebug = isDataGnuCompressed(Data);
150 const uint64_t DecompressedSize =
151 IsGnuDebug
152 ? support::endian::read64be(reinterpret_cast<const uint64_t *>(
153 Data.data() + ZlibGnuMagic.size()))
154 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
155 const uint64_t DecompressedAlign =
156 IsGnuDebug ? 1
157 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
158 ->ch_addralign;
159
160 return std::make_tuple(DecompressedSize, DecompressedAlign);
161}
162
163template <class ELFT>
164void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
165 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
166
167 if (!zlib::isAvailable()) {
168 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
169 return;
170 }
171
172 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
173 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
174 : sizeof(Elf_Chdr_Impl<ELFT>);
175
176 StringRef CompressedContent(
177 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
178 Sec.OriginalData.size() - DataOffset);
179
180 SmallVector<char, 128> DecompressedContent;
181 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
182 static_cast<size_t>(Sec.Size)))
183 reportError(Sec.Name, std::move(E));
184
185 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
186}
187
188void BinarySectionWriter::visit(const DecompressedSection &Sec) {
189 error("Cannot write compressed section '" + Sec.Name + "' ");
190}
191
192void DecompressedSection::accept(SectionVisitor &Visitor) const {
193 Visitor.visit(*this);
194}
195
Jake Ehrlich76e91102018-01-25 22:46:17 +0000196void OwnedDataSection::accept(SectionVisitor &Visitor) const {
197 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000198}
199
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000200void BinarySectionWriter::visit(const CompressedSection &Sec) {
201 error("Cannot write compressed section '" + Sec.Name + "' ");
202}
203
204template <class ELFT>
205void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
206 uint8_t *Buf = Out.getBufferStart();
207 Buf += Sec.Offset;
208
209 if (Sec.CompressionType == DebugCompressionType::None) {
210 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
211 return;
212 }
213
214 if (Sec.CompressionType == DebugCompressionType::GNU) {
215 const char *Magic = "ZLIB";
216 memcpy(Buf, Magic, strlen(Magic));
217 Buf += strlen(Magic);
218 const uint64_t DecompressedSize =
219 support::endian::read64be(&Sec.DecompressedSize);
220 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
221 Buf += sizeof(DecompressedSize);
222 } else {
223 Elf_Chdr_Impl<ELFT> Chdr;
224 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
225 Chdr.ch_size = Sec.DecompressedSize;
226 Chdr.ch_addralign = Sec.DecompressedAlign;
227 memcpy(Buf, &Chdr, sizeof(Chdr));
228 Buf += sizeof(Chdr);
229 }
230
231 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
232}
233
234CompressedSection::CompressedSection(const SectionBase &Sec,
235 DebugCompressionType CompressionType)
236 : SectionBase(Sec), CompressionType(CompressionType),
237 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
238
239 if (!zlib::isAvailable()) {
240 CompressionType = DebugCompressionType::None;
241 return;
242 }
243
244 if (Error E = zlib::compress(
245 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
246 OriginalData.size()),
247 CompressedData))
248 reportError(Name, std::move(E));
249
250 size_t ChdrSize;
251 if (CompressionType == DebugCompressionType::GNU) {
252 Name = ".z" + Sec.Name.substr(1);
253 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
254 } else {
255 Flags |= ELF::SHF_COMPRESSED;
256 ChdrSize =
257 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
258 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
259 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
260 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
261 }
262 Size = ChdrSize + CompressedData.size();
263 Align = 8;
264}
265
Puyan Lotfiaf048642018-10-01 10:29:41 +0000266CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
267 uint64_t DecompressedSize,
268 uint64_t DecompressedAlign)
269 : CompressionType(DebugCompressionType::None),
270 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
271 OriginalData = CompressedData;
272}
273
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000274void CompressedSection::accept(SectionVisitor &Visitor) const {
275 Visitor.visit(*this);
276}
277
Petr Hosek05a04cb2017-08-01 00:33:58 +0000278void StringTableSection::addString(StringRef Name) {
279 StrTabBuilder.add(Name);
280 Size = StrTabBuilder.getSize();
281}
282
283uint32_t StringTableSection::findIndex(StringRef Name) const {
284 return StrTabBuilder.getOffset(Name);
285}
286
287void StringTableSection::finalize() { StrTabBuilder.finalize(); }
288
Jake Ehrlich76e91102018-01-25 22:46:17 +0000289void SectionWriter::visit(const StringTableSection &Sec) {
290 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
291}
292
293void StringTableSection::accept(SectionVisitor &Visitor) const {
294 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000295}
296
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000297template <class ELFT>
298void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
299 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000300 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000301 std::copy(std::begin(Sec.Indexes), std::end(Sec.Indexes), IndexesBuffer);
302}
303
304void SectionIndexSection::initialize(SectionTableRef SecTable) {
305 Size = 0;
306 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
307 Link,
308 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
309 "Link field value " + Twine(Link) + " in section " + Name +
310 " is not a symbol table"));
311 Symbols->setShndxTable(this);
312}
313
314void SectionIndexSection::finalize() { Link = Symbols->Index; }
315
316void SectionIndexSection::accept(SectionVisitor &Visitor) const {
317 Visitor.visit(*this);
318}
319
Petr Hosekc1135772017-09-13 03:04:50 +0000320static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000321 switch (Index) {
322 case SHN_ABS:
323 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000324 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000325 }
Petr Hosekc1135772017-09-13 03:04:50 +0000326 if (Machine == EM_HEXAGON) {
327 switch (Index) {
328 case SHN_HEXAGON_SCOMMON:
329 case SHN_HEXAGON_SCOMMON_2:
330 case SHN_HEXAGON_SCOMMON_4:
331 case SHN_HEXAGON_SCOMMON_8:
332 return true;
333 }
334 }
335 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000336}
337
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000338// Large indexes force us to clarify exactly what this function should do. This
339// function should return the value that will appear in st_shndx when written
340// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000341uint16_t Symbol::getShndx() const {
342 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000343 if (DefinedIn->Index >= SHN_LORESERVE)
344 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000345 return DefinedIn->Index;
346 }
347 switch (ShndxType) {
348 // This means that we don't have a defined section but we do need to
349 // output a legitimate section index.
350 case SYMBOL_SIMPLE_INDEX:
351 return SHN_UNDEF;
352 case SYMBOL_ABS:
353 case SYMBOL_COMMON:
354 case SYMBOL_HEXAGON_SCOMMON:
355 case SYMBOL_HEXAGON_SCOMMON_2:
356 case SYMBOL_HEXAGON_SCOMMON_4:
357 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000358 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000359 return static_cast<uint16_t>(ShndxType);
360 }
361 llvm_unreachable("Symbol with invalid ShndxType encountered");
362}
363
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000364void SymbolTableSection::assignIndices() {
365 uint32_t Index = 0;
366 for (auto &Sym : Symbols)
367 Sym->Index = Index++;
368}
369
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000370void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000371 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000372 uint8_t Visibility, uint16_t Shndx,
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000373 uint64_t Size) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000374 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000375 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000376 Sym.Binding = Bind;
377 Sym.Type = Type;
378 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000379 if (DefinedIn != nullptr)
380 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000381 if (DefinedIn == nullptr) {
382 if (Shndx >= SHN_LORESERVE)
383 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
384 else
385 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
386 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000387 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000388 Sym.Visibility = Visibility;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000389 Sym.Size = Size;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000390 Sym.Index = Symbols.size();
391 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
392 Size += this->EntrySize;
393}
394
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000395void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000396 if (SectionIndexTable == Sec)
397 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000398 if (SymbolNames == Sec) {
399 error("String table " + SymbolNames->Name +
400 " cannot be removed because it is referenced by the symbol table " +
401 this->Name);
402 }
Paul Semel41695f82018-05-02 20:19:22 +0000403 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000404}
405
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000406void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000407 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
408 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000409 std::stable_partition(
410 std::begin(Symbols), std::end(Symbols),
411 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000412 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000413}
414
Paul Semel4246a462018-05-09 21:36:54 +0000415void SymbolTableSection::removeSymbols(
416 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000417 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000418 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000419 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
420 std::end(Symbols));
421 Size = Symbols.size() * EntrySize;
422 assignIndices();
423}
424
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000425void SymbolTableSection::initialize(SectionTableRef SecTable) {
426 Size = 0;
427 setStrTab(SecTable.getSectionOfType<StringTableSection>(
428 Link,
429 "Symbol table has link index of " + Twine(Link) +
430 " which is not a valid index",
431 "Symbol table has link index of " + Twine(Link) +
432 " which is not a string table"));
433}
434
Petr Hosek79cee9e2017-08-29 02:12:03 +0000435void SymbolTableSection::finalize() {
436 // Make sure SymbolNames is finalized before getting name indexes.
437 SymbolNames->finalize();
438
439 uint32_t MaxLocalIndex = 0;
440 for (auto &Sym : Symbols) {
441 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
442 if (Sym->Binding == STB_LOCAL)
443 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
444 }
445 // Now we need to set the Link and Info fields.
446 Link = SymbolNames->Index;
447 Info = MaxLocalIndex + 1;
448}
449
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000450void SymbolTableSection::prepareForLayout() {
451 // Add all potential section indexes before file layout so that the section
452 // index section has the approprite size.
453 if (SectionIndexTable != nullptr) {
454 for (const auto &Sym : Symbols) {
455 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
456 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
457 else
458 SectionIndexTable->addIndex(SHN_UNDEF);
459 }
460 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000461 // Add all of our strings to SymbolNames so that SymbolNames has the right
462 // size before layout is decided.
463 for (auto &Sym : Symbols)
464 SymbolNames->addString(Sym->Name);
465}
466
467const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
468 if (Symbols.size() <= Index)
469 error("Invalid symbol index: " + Twine(Index));
470 return Symbols[Index].get();
471}
472
Paul Semel99dda0b2018-05-25 11:01:25 +0000473Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
474 return const_cast<Symbol *>(
475 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
476}
477
Petr Hosek79cee9e2017-08-29 02:12:03 +0000478template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000479void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000480 uint8_t *Buf = Out.getBufferStart();
Jake Ehrlich76e91102018-01-25 22:46:17 +0000481 Buf += Sec.Offset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +0000482 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000483 // Loop though symbols setting each entry of the symbol table.
Jake Ehrlich76e91102018-01-25 22:46:17 +0000484 for (auto &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000485 Sym->st_name = Symbol->NameIndex;
486 Sym->st_value = Symbol->Value;
487 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000488 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000489 Sym->setBinding(Symbol->Binding);
490 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000491 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000492 ++Sym;
493 }
494}
495
Jake Ehrlich76e91102018-01-25 22:46:17 +0000496void SymbolTableSection::accept(SectionVisitor &Visitor) const {
497 Visitor.visit(*this);
498}
499
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000500template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000501void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
502 const SectionBase *Sec) {
503 if (Symbols == Sec) {
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000504 error("Symbol table " + Symbols->Name +
505 " cannot be removed because it is "
506 "referenced by the relocation "
507 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000508 this->Name);
509 }
510}
511
512template <class SymTabType>
513void RelocSectionWithSymtabBase<SymTabType>::initialize(
514 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000515 if (Link != SHN_UNDEF)
516 setSymTab(SecTable.getSectionOfType<SymTabType>(
517 Link,
518 "Link field value " + Twine(Link) + " in section " + Name +
519 " is invalid",
520 "Link field value " + Twine(Link) + " in section " + Name +
521 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000522
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000523 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000524 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
525 " in section " + Name +
526 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000527 else
528 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000529}
530
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000531template <class SymTabType>
532void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000533 this->Link = Symbols ? Symbols->Index : 0;
534
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000535 if (SecToApplyRel != nullptr)
536 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000537}
538
539template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000540static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000541
542template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000543static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000544 Rela.r_addend = Addend;
545}
546
Jake Ehrlich76e91102018-01-25 22:46:17 +0000547template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000548static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000549 for (const auto &Reloc : Relocations) {
550 Buf->r_offset = Reloc.Offset;
551 setAddend(*Buf, Reloc.Addend);
552 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
553 ++Buf;
554 }
555}
556
557template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000558void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
559 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
560 if (Sec.Type == SHT_REL)
561 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000562 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000563 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000564}
565
Jake Ehrlich76e91102018-01-25 22:46:17 +0000566void RelocationSection::accept(SectionVisitor &Visitor) const {
567 Visitor.visit(*this);
568}
569
Paul Semel4246a462018-05-09 21:36:54 +0000570void RelocationSection::removeSymbols(
571 function_ref<bool(const Symbol &)> ToRemove) {
572 for (const Relocation &Reloc : Relocations)
573 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht88ed5e52018-08-09 22:52:03 +0000574 error("not stripping symbol '" + Reloc.RelocSymbol->Name +
Paul Semel4246a462018-05-09 21:36:54 +0000575 "' because it is named in a relocation");
576}
577
Paul Semel99dda0b2018-05-25 11:01:25 +0000578void RelocationSection::markSymbols() {
579 for (const Relocation &Reloc : Relocations)
580 Reloc.RelocSymbol->Referenced = true;
581}
582
Jake Ehrlich76e91102018-01-25 22:46:17 +0000583void SectionWriter::visit(const DynamicRelocationSection &Sec) {
584 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
585 Out.getBufferStart() + Sec.Offset);
586}
587
588void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
589 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000590}
591
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000592void Section::removeSectionReferences(const SectionBase *Sec) {
593 if (LinkSection == Sec) {
594 error("Section " + LinkSection->Name +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000595 " cannot be removed because it is "
596 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000597 this->Name);
598 }
599}
600
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000601void GroupSection::finalize() {
602 this->Info = Sym->Index;
603 this->Link = SymTab->Index;
604}
605
Paul Semel4246a462018-05-09 21:36:54 +0000606void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
607 if (ToRemove(*Sym)) {
608 error("Symbol " + Sym->Name +
609 " cannot be removed because it is "
610 "referenced by the section " +
611 this->Name + "[" + Twine(this->Index) + "]");
612 }
613}
614
Paul Semel99dda0b2018-05-25 11:01:25 +0000615void GroupSection::markSymbols() {
616 if (Sym)
617 Sym->Referenced = true;
618}
619
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000620void Section::initialize(SectionTableRef SecTable) {
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000621 if (Link != ELF::SHN_UNDEF) {
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000622 LinkSection =
623 SecTable.getSection(Link, "Link field value " + Twine(Link) +
624 " in section " + Name + " is invalid");
Peter Collingbourne1651ac12018-05-30 19:30:39 +0000625 if (LinkSection->Type == ELF::SHT_SYMTAB)
626 LinkSection = nullptr;
627 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000628}
629
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000630void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000631
Jake Ehrlich76e91102018-01-25 22:46:17 +0000632void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000633 FileName = sys::path::filename(File);
634 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000635 // followed by a null terminator and then the CRC32 of the file. The CRC32
636 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
637 // byte, and then finally push the size to alignment and add 4.
638 Size = alignTo(FileName.size() + 1, 4) + 4;
639 // The CRC32 will only be aligned if we align the whole section.
640 Align = 4;
641 Type = ELF::SHT_PROGBITS;
642 Name = ".gnu_debuglink";
643 // For sections not found in segments, OriginalOffset is only used to
644 // establish the order that sections should go in. By using the maximum
645 // possible offset we cause this section to wind up at the end.
646 OriginalOffset = std::numeric_limits<uint64_t>::max();
647 JamCRC crc;
648 crc.update(ArrayRef<char>(Data.data(), Data.size()));
649 // The CRC32 value needs to be complemented because the JamCRC dosn't
650 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
651 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
652 CRC32 = ~crc.getCRC();
653}
654
Jake Ehrlich76e91102018-01-25 22:46:17 +0000655GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000656 // Read in the file to compute the CRC of it.
657 auto DebugOrErr = MemoryBuffer::getFile(File);
658 if (!DebugOrErr)
659 error("'" + File + "': " + DebugOrErr.getError().message());
660 auto Debug = std::move(*DebugOrErr);
661 init(File, Debug->getBuffer());
662}
663
664template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000665void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
666 auto Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000667 char *File = reinterpret_cast<char *>(Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000668 Elf_Word *CRC =
669 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
670 *CRC = Sec.CRC32;
671 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
672}
673
674void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
675 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000676}
677
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000678template <class ELFT>
679void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
680 ELF::Elf32_Word *Buf =
681 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
682 *Buf++ = Sec.FlagWord;
683 for (const auto *S : Sec.GroupMembers)
684 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
685}
686
687void GroupSection::accept(SectionVisitor &Visitor) const {
688 Visitor.visit(*this);
689}
690
Petr Hosek05a04cb2017-08-01 00:33:58 +0000691// Returns true IFF a section is wholly inside the range of a segment
692static bool sectionWithinSegment(const SectionBase &Section,
693 const Segment &Segment) {
694 // If a section is empty it should be treated like it has a size of 1. This is
695 // to clarify the case when an empty section lies on a boundary between two
696 // segments and ensures that the section "belongs" to the second segment and
697 // not the first.
698 uint64_t SecSize = Section.Size ? Section.Size : 1;
699 return Segment.Offset <= Section.OriginalOffset &&
700 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
701}
702
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000703// Returns true IFF a segment's original offset is inside of another segment's
704// range.
705static bool segmentOverlapsSegment(const Segment &Child,
706 const Segment &Parent) {
707
708 return Parent.OriginalOffset <= Child.OriginalOffset &&
709 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
710}
711
Jake Ehrlich46814be2018-01-22 19:27:30 +0000712static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000713 // Any segment without a parent segment should come before a segment
714 // that has a parent segment.
715 if (A->OriginalOffset < B->OriginalOffset)
716 return true;
717 if (A->OriginalOffset > B->OriginalOffset)
718 return false;
719 return A->Index < B->Index;
720}
721
Jake Ehrlich46814be2018-01-22 19:27:30 +0000722static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
723 if (A->PAddr < B->PAddr)
724 return true;
725 if (A->PAddr > B->PAddr)
726 return false;
727 return A->Index < B->Index;
728}
729
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000730template <class ELFT> void BinaryELFBuilder<ELFT>::initFileHeader() {
731 Obj->Flags = 0x0;
732 Obj->Type = ET_REL;
733 Obj->Entry = 0x0;
734 Obj->Machine = EMachine;
735 Obj->Version = 1;
736}
737
738template <class ELFT> void BinaryELFBuilder<ELFT>::initHeaderSegment() {
739 Obj->ElfHdrSegment.Index = 0;
740}
741
742template <class ELFT> StringTableSection *BinaryELFBuilder<ELFT>::addStrTab() {
743 auto &StrTab = Obj->addSection<StringTableSection>();
744 StrTab.Name = ".strtab";
745
746 Obj->SectionNames = &StrTab;
747 return &StrTab;
748}
749
750template <class ELFT>
751SymbolTableSection *
752BinaryELFBuilder<ELFT>::addSymTab(StringTableSection *StrTab) {
753 auto &SymTab = Obj->addSection<SymbolTableSection>();
754
755 SymTab.Name = ".symtab";
756 SymTab.Link = StrTab->Index;
757 // TODO: Factor out dependence on ElfType here.
758 SymTab.EntrySize = sizeof(Elf_Sym);
759
760 // The symbol table always needs a null symbol
761 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
762
763 Obj->SymbolTable = &SymTab;
764 return &SymTab;
765}
766
767template <class ELFT>
768void BinaryELFBuilder<ELFT>::addData(SymbolTableSection *SymTab) {
769 auto Data = ArrayRef<uint8_t>(
770 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
771 MemBuf->getBufferSize());
772 auto &DataSection = Obj->addSection<Section>(Data);
773 DataSection.Name = ".data";
774 DataSection.Type = ELF::SHT_PROGBITS;
775 DataSection.Size = Data.size();
776 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
777
778 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
779 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
780 [](char c) { return !isalnum(c); }, '_');
781 Twine Prefix = Twine("_binary_") + SanitizedFilename;
782
783 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
784 /*Value=*/0, STV_DEFAULT, 0, 0);
785 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
786 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
787 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
788 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
789}
790
791template <class ELFT> void BinaryELFBuilder<ELFT>::initSections() {
792 for (auto &Section : Obj->sections()) {
793 Section.initialize(Obj->sections());
794 }
795}
796
797template <class ELFT> std::unique_ptr<Object> BinaryELFBuilder<ELFT>::build() {
798 initFileHeader();
799 initHeaderSegment();
800 StringTableSection *StrTab = addStrTab();
801 SymbolTableSection *SymTab = addSymTab(StrTab);
802 initSections();
803 addData(SymTab);
804
805 return std::move(Obj);
806}
807
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000808template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
Jake Ehrlich6452b112018-02-14 23:31:33 +0000809 for (auto &Parent : Obj.segments()) {
810 // Every segment will overlap with itself but we don't want a segment to
811 // be it's own parent so we avoid that situation.
812 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
813 // We want a canonical "most parental" segment but this requires
814 // inspecting the ParentSegment.
815 if (compareSegmentsByOffset(&Parent, &Child))
816 if (Child.ParentSegment == nullptr ||
817 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
818 Child.ParentSegment = &Parent;
819 }
820 }
821 }
822}
823
Jake Ehrlich76e91102018-01-25 22:46:17 +0000824template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000825 uint32_t Index = 0;
826 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000827 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
828 (size_t)Phdr.p_filesz};
Jake Ehrlich76e91102018-01-25 22:46:17 +0000829 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000830 Seg.Type = Phdr.p_type;
831 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000832 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000833 Seg.Offset = Phdr.p_offset;
834 Seg.VAddr = Phdr.p_vaddr;
835 Seg.PAddr = Phdr.p_paddr;
836 Seg.FileSize = Phdr.p_filesz;
837 Seg.MemSize = Phdr.p_memsz;
838 Seg.Align = Phdr.p_align;
839 Seg.Index = Index++;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000840 for (auto &Section : Obj.sections()) {
841 if (sectionWithinSegment(Section, Seg)) {
842 Seg.addSection(&Section);
843 if (!Section.ParentSegment ||
844 Section.ParentSegment->Offset > Seg.Offset) {
845 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000846 }
847 }
848 }
849 }
Jake Ehrlich6452b112018-02-14 23:31:33 +0000850
851 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +0000852 ElfHdr.Index = Index++;
853
854 const auto &Ehdr = *ElfFile.getHeader();
855 auto &PrHdr = Obj.ProgramHdrSegment;
856 PrHdr.Type = PT_PHDR;
857 PrHdr.Flags = 0;
858 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
859 // Whereas this works automatically for ElfHdr, here OriginalOffset is
860 // always non-zero and to ensure the equation we assign the same value to
861 // VAddr as well.
862 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
863 PrHdr.PAddr = 0;
864 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000865 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000866 PrHdr.Align = sizeof(Elf_Addr);
867 PrHdr.Index = Index++;
868
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000869 // Now we do an O(n^2) loop through the segments in order to match up
870 // segments.
Jake Ehrlich6452b112018-02-14 23:31:33 +0000871 for (auto &Child : Obj.segments())
872 setParentSegment(Child);
873 setParentSegment(ElfHdr);
874 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000875}
876
877template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000878void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
879 auto SecTable = Obj.sections();
880 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
881 GroupSec->Link,
882 "Link field value " + Twine(GroupSec->Link) + " in section " +
883 GroupSec->Name + " is invalid",
884 "Link field value " + Twine(GroupSec->Link) + " in section " +
885 GroupSec->Name + " is not a symbol table");
886 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
887 if (!Sym)
888 error("Info field value " + Twine(GroupSec->Info) + " in section " +
889 GroupSec->Name + " is not a valid symbol index");
890 GroupSec->setSymTab(SymTab);
891 GroupSec->setSymbol(Sym);
892 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
893 GroupSec->Contents.empty())
894 error("The content of the section " + GroupSec->Name + " is malformed");
895 const ELF::Elf32_Word *Word =
896 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
897 const ELF::Elf32_Word *End =
898 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
899 GroupSec->setFlagWord(*Word++);
900 for (; Word != End; ++Word) {
901 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
902 GroupSec->addMember(SecTable.getSection(
903 Index, "Group member index " + Twine(Index) + " in section " +
904 GroupSec->Name + " is invalid"));
905 }
906}
907
908template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000909void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000910 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
911 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000912 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000913
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000914 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
915 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000916 SectionBase *DefSection = nullptr;
917 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000918
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000919 if (Sym.st_shndx == SHN_XINDEX) {
920 if (SymTab->getShndxTable() == nullptr)
921 error("Symbol '" + Name +
922 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
923 if (ShndxData.data() == nullptr) {
924 const Elf_Shdr &ShndxSec =
925 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
926 ShndxData = unwrapOrError(
927 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
928 if (ShndxData.size() != Symbols.size())
929 error("Symbol section index table does not have the same number of "
930 "entries as the symbol table.");
931 }
932 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
933 DefSection = Obj.sections().getSection(
934 Index,
Puyan Lotfi97604b42018-08-02 18:16:52 +0000935 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000936 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000937 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000938 error(
939 "Symbol '" + Name +
940 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
941 Twine(Sym.st_shndx));
942 }
943 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +0000944 DefSection = Obj.sections().getSection(
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000945 Sym.st_shndx, "Symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000946 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000947 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000948 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000949
Petr Hosek79cee9e2017-08-29 02:12:03 +0000950 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000951 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000952 }
953}
954
955template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000956static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
957
958template <class ELFT>
959static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
960 ToSet = Rela.r_addend;
961}
962
Jake Ehrlich76e91102018-01-25 22:46:17 +0000963template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000964static void initRelocations(RelocationSection *Relocs,
965 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000966 for (const auto &Rel : RelRange) {
967 Relocation ToAdd;
968 ToAdd.Offset = Rel.r_offset;
969 getAddend(ToAdd.Addend, Rel);
970 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +0000971 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000972 Relocs->addRelocation(ToAdd);
973 }
974}
975
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000976SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000977 if (Index == SHN_UNDEF || Index > Sections.size())
978 error(ErrMsg);
979 return Sections[Index - 1].get();
980}
981
982template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000983T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +0000984 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000985 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000986 return Sec;
987 error(TypeErrMsg);
988}
989
Petr Hosekd7df9b22017-09-06 23:41:02 +0000990template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000991SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000992 ArrayRef<uint8_t> Data;
993 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000994 case SHT_REL:
995 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000996 if (Shdr.sh_flags & SHF_ALLOC) {
997 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +0000998 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000999 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001000 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001001 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001002 // If a string table is allocated we don't want to mess with it. That would
1003 // mean altering the memory image. There are no special link types or
1004 // anything so we can just use a Section.
1005 if (Shdr.sh_flags & SHF_ALLOC) {
1006 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001007 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001008 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001009 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001010 case SHT_HASH:
1011 case SHT_GNU_HASH:
1012 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1013 // Because of this we don't need to mess with the hash tables either.
1014 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001015 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001016 case SHT_GROUP:
1017 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1018 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001019 case SHT_DYNSYM:
1020 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001021 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001022 case SHT_DYNAMIC:
1023 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001024 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001025 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001026 auto &SymTab = Obj.addSection<SymbolTableSection>();
1027 Obj.SymbolTable = &SymTab;
1028 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001029 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001030 case SHT_SYMTAB_SHNDX: {
1031 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1032 Obj.SectionIndexTable = &ShndxSection;
1033 return ShndxSection;
1034 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001035 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001036 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001037 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001038 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001039
1040 if (isDataGnuCompressed(Data) || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
1041 uint64_t DecompressedSize, DecompressedAlign;
1042 std::tie(DecompressedSize, DecompressedAlign) =
1043 getDecompressedSizeAndAlignment<ELFT>(Data);
1044 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1045 DecompressedAlign);
1046 }
1047
Jake Ehrlich76e91102018-01-25 22:46:17 +00001048 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001049 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001050 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001051}
1052
Jake Ehrlich76e91102018-01-25 22:46:17 +00001053template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001054 uint32_t Index = 0;
1055 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1056 if (Index == 0) {
1057 ++Index;
1058 continue;
1059 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001060 auto &Sec = makeSection(Shdr);
1061 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1062 Sec.Type = Shdr.sh_type;
1063 Sec.Flags = Shdr.sh_flags;
1064 Sec.Addr = Shdr.sh_addr;
1065 Sec.Offset = Shdr.sh_offset;
1066 Sec.OriginalOffset = Shdr.sh_offset;
1067 Sec.Size = Shdr.sh_size;
1068 Sec.Link = Shdr.sh_link;
1069 Sec.Info = Shdr.sh_info;
1070 Sec.Align = Shdr.sh_addralign;
1071 Sec.EntrySize = Shdr.sh_entsize;
1072 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001073 Sec.OriginalData =
1074 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1075 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001076 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001077
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001078 // If a section index table exists we'll need to initialize it before we
1079 // initialize the symbol table because the symbol table might need to
1080 // reference it.
1081 if (Obj.SectionIndexTable)
1082 Obj.SectionIndexTable->initialize(Obj.sections());
1083
Petr Hosek79cee9e2017-08-29 02:12:03 +00001084 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001085 // details about symbol tables. We need the symbol table filled out before
1086 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001087 if (Obj.SymbolTable) {
1088 Obj.SymbolTable->initialize(Obj.sections());
1089 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001090 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001091
1092 // Now that all sections and symbols have been added we can add
1093 // relocations that reference symbols and set the link and info fields for
1094 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001095 for (auto &Section : Obj.sections()) {
1096 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001097 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001098 Section.initialize(Obj.sections());
1099 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001100 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1101 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001102 initRelocations(RelSec, Obj.SymbolTable,
1103 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001104 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001105 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001106 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001107 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1108 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001109 }
1110 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001111}
1112
Jake Ehrlich76e91102018-01-25 22:46:17 +00001113template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001114 const auto &Ehdr = *ElfFile.getHeader();
1115
Jake Ehrlich76e91102018-01-25 22:46:17 +00001116 Obj.Type = Ehdr.e_type;
1117 Obj.Machine = Ehdr.e_machine;
1118 Obj.Version = Ehdr.e_version;
1119 Obj.Entry = Ehdr.e_entry;
1120 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001121
Jake Ehrlich76e91102018-01-25 22:46:17 +00001122 readSectionHeaders();
1123 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001124
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001125 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1126 if (ShstrIndex == SHN_XINDEX)
1127 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1128
Jake Ehrlich76e91102018-01-25 22:46:17 +00001129 Obj.SectionNames =
1130 Obj.sections().template getSectionOfType<StringTableSection>(
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001131 ShstrIndex,
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001132 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001133 " in elf header " + " is invalid",
Jake Ehrlich8b831c12018-03-07 20:33:02 +00001134 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
Jake Ehrlich76e91102018-01-25 22:46:17 +00001135 " in elf header " + " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001136}
1137
Jake Ehrlich76e91102018-01-25 22:46:17 +00001138// A generic size function which computes sizes of any random access range.
1139template <class R> size_t size(R &&Range) {
1140 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1141}
1142
1143Writer::~Writer() {}
1144
1145Reader::~Reader() {}
1146
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001147std::unique_ptr<Object> BinaryReader::create() const {
1148 if (MInfo.Is64Bit)
1149 return MInfo.IsLittleEndian
1150 ? BinaryELFBuilder<ELF64LE>(MInfo.EMachine, MemBuf).build()
1151 : BinaryELFBuilder<ELF64BE>(MInfo.EMachine, MemBuf).build();
1152 else
1153 return MInfo.IsLittleEndian
1154 ? BinaryELFBuilder<ELF32LE>(MInfo.EMachine, MemBuf).build()
1155 : BinaryELFBuilder<ELF32BE>(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001156}
1157
1158std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001159 auto Obj = llvm::make_unique<Object>();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001160 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001161 ELFBuilder<ELF32LE> Builder(*o, *Obj);
1162 Builder.build();
1163 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001164 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001165 ELFBuilder<ELF64LE> Builder(*o, *Obj);
1166 Builder.build();
1167 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001168 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001169 ELFBuilder<ELF32BE> Builder(*o, *Obj);
1170 Builder.build();
1171 return Obj;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001172 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001173 ELFBuilder<ELF64BE> Builder(*o, *Obj);
1174 Builder.build();
1175 return Obj;
1176 }
1177 error("Invalid file type");
1178}
1179
1180template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001181 uint8_t *B = Buf.getBufferStart();
1182 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001183 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1184 Ehdr.e_ident[EI_MAG0] = 0x7f;
1185 Ehdr.e_ident[EI_MAG1] = 'E';
1186 Ehdr.e_ident[EI_MAG2] = 'L';
1187 Ehdr.e_ident[EI_MAG3] = 'F';
1188 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1189 Ehdr.e_ident[EI_DATA] =
1190 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1191 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1192 Ehdr.e_ident[EI_OSABI] = ELFOSABI_NONE;
1193 Ehdr.e_ident[EI_ABIVERSION] = 0;
1194
Jake Ehrlich76e91102018-01-25 22:46:17 +00001195 Ehdr.e_type = Obj.Type;
1196 Ehdr.e_machine = Obj.Machine;
1197 Ehdr.e_version = Obj.Version;
1198 Ehdr.e_entry = Obj.Entry;
Julie Hockett468722e2018-09-12 17:56:31 +00001199 Ehdr.e_phnum = size(Obj.segments());
1200 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1201 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001202 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001203 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Julie Hockett468722e2018-09-12 17:56:31 +00001204 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1205 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001206 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001207 // """
1208 // If the number of sections is greater than or equal to
1209 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1210 // number of section header table entries is contained in the sh_size field
1211 // of the section header at index 0.
1212 // """
1213 auto Shnum = size(Obj.sections()) + 1;
1214 if (Shnum >= SHN_LORESERVE)
1215 Ehdr.e_shnum = 0;
1216 else
1217 Ehdr.e_shnum = Shnum;
1218 // """
1219 // If the section name string table section index is greater than or equal
1220 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1221 // and the actual index of the section name string table section is
1222 // contained in the sh_link field of the section header at index 0.
1223 // """
1224 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1225 Ehdr.e_shstrndx = SHN_XINDEX;
1226 else
1227 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001228 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001229 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001230 Ehdr.e_shoff = 0;
1231 Ehdr.e_shnum = 0;
1232 Ehdr.e_shstrndx = 0;
1233 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001234}
1235
Jake Ehrlich76e91102018-01-25 22:46:17 +00001236template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1237 for (auto &Seg : Obj.segments())
1238 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001239}
1240
Jake Ehrlich76e91102018-01-25 22:46:17 +00001241template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001242 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001243 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001244 // of the file. It is not used for anything else
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001245 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001246 Shdr.sh_name = 0;
1247 Shdr.sh_type = SHT_NULL;
1248 Shdr.sh_flags = 0;
1249 Shdr.sh_addr = 0;
1250 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001251 // See writeEhdr for why we do this.
1252 uint64_t Shnum = size(Obj.sections()) + 1;
1253 if (Shnum >= SHN_LORESERVE)
1254 Shdr.sh_size = Shnum;
1255 else
1256 Shdr.sh_size = 0;
1257 // See writeEhdr for why we do this.
1258 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1259 Shdr.sh_link = Obj.SectionNames->Index;
1260 else
1261 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001262 Shdr.sh_info = 0;
1263 Shdr.sh_addralign = 0;
1264 Shdr.sh_entsize = 0;
1265
Jake Ehrlich76e91102018-01-25 22:46:17 +00001266 for (auto &Sec : Obj.sections())
1267 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001268}
1269
Jake Ehrlich76e91102018-01-25 22:46:17 +00001270template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1271 for (auto &Sec : Obj.sections())
1272 Sec.accept(*SecWriter);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001273}
1274
Jake Ehrlich76e91102018-01-25 22:46:17 +00001275void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001276
1277 auto Iter = std::stable_partition(
1278 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1279 if (ToRemove(*Sec))
1280 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001281 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1282 if (auto ToRelSec = RelSec->getSection())
1283 return !ToRemove(*ToRelSec);
1284 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001285 return true;
1286 });
1287 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1288 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001289 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001290 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001291 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1292 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001293 // Now make sure there are no remaining references to the sections that will
1294 // be removed. Sometimes it is impossible to remove a reference so we emit
1295 // an error here instead.
1296 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1297 for (auto &Segment : Segments)
1298 Segment->removeSection(RemoveSec.get());
1299 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1300 KeepSec->removeSectionReferences(RemoveSec.get());
1301 }
1302 // Now finally get rid of them all togethor.
1303 Sections.erase(Iter, std::end(Sections));
1304}
1305
Paul Semel4246a462018-05-09 21:36:54 +00001306void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1307 if (!SymbolTable)
1308 return;
1309
1310 for (const SecPtr &Sec : Sections)
1311 Sec->removeSymbols(ToRemove);
1312}
1313
Jake Ehrlich76e91102018-01-25 22:46:17 +00001314void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001315 // Put all sections in offset order. Maintain the ordering as closely as
1316 // possible while meeting that demand however.
1317 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1318 return A->OriginalOffset < B->OriginalOffset;
1319 };
1320 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1321 CompareSections);
1322}
1323
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001324static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1325 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1326 if (Align == 0)
1327 Align = 1;
1328 auto Diff =
1329 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1330 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1331 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1332 if (Diff < 0)
1333 Diff += Align;
1334 return Offset + Diff;
1335}
1336
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001337// Orders segments such that if x = y->ParentSegment then y comes before x.
1338static void OrderSegments(std::vector<Segment *> &Segments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001339 std::stable_sort(std::begin(Segments), std::end(Segments),
1340 compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001341}
1342
1343// This function finds a consistent layout for a list of segments starting from
1344// an Offset. It assumes that Segments have been sorted by OrderSegments and
1345// returns an Offset one past the end of the last segment.
1346static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1347 uint64_t Offset) {
1348 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001349 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001350 // The only way a segment should move is if a section was between two
1351 // segments and that section was removed. If that section isn't in a segment
1352 // then it's acceptable, but not ideal, to simply move it to after the
1353 // segments. So we can simply layout segments one after the other accounting
1354 // for alignment.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001355 for (auto &Segment : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001356 // We assume that segments have been ordered by OriginalOffset and Index
1357 // such that a parent segment will always come before a child segment in
1358 // OrderedSegments. This means that the Offset of the ParentSegment should
1359 // already be set and we can set our offset relative to it.
1360 if (Segment->ParentSegment != nullptr) {
1361 auto Parent = Segment->ParentSegment;
1362 Segment->Offset =
1363 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1364 } else {
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001365 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001366 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001367 }
Jake Ehrlich084400b2017-10-04 17:44:42 +00001368 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001369 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001370 return Offset;
1371}
1372
1373// This function finds a consistent layout for a list of sections. It assumes
1374// that the ->ParentSegment of each section has already been laid out. The
1375// supplied starting Offset is used for the starting offset of any section that
1376// does not have a ParentSegment. It returns either the offset given if all
1377// sections had a ParentSegment or an offset one past the last section if there
1378// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001379template <class Range>
1380static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001381 // Now the offset of every segment has been set we can assign the offsets
1382 // of each section. For sections that are covered by a segment we should use
1383 // the segment's original offset and the section's original offset to compute
1384 // the offset from the start of the segment. Using the offset from the start
1385 // of the segment we can assign a new offset to the section. For sections not
1386 // covered by segments we can just bump Offset to the next valid location.
1387 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001388 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001389 Section.Index = Index++;
1390 if (Section.ParentSegment != nullptr) {
1391 auto Segment = *Section.ParentSegment;
1392 Section.Offset =
1393 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001394 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001395 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1396 Section.Offset = Offset;
1397 if (Section.Type != SHT_NOBITS)
1398 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001399 }
1400 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001401 return Offset;
1402}
Petr Hosek3f383832017-08-26 01:32:20 +00001403
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001404template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1405 auto &ElfHdr = Obj.ElfHdrSegment;
1406 ElfHdr.Type = PT_PHDR;
1407 ElfHdr.Flags = 0;
1408 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1409 ElfHdr.VAddr = 0;
1410 ElfHdr.PAddr = 0;
1411 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1412 ElfHdr.Align = 0;
1413}
1414
Jake Ehrlich76e91102018-01-25 22:46:17 +00001415template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001416 // We need a temporary list of segments that has a special order to it
1417 // so that we know that anytime ->ParentSegment is set that segment has
1418 // already had its offset properly set.
1419 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001420 for (auto &Segment : Obj.segments())
1421 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001422 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1423 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001424 OrderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001425 // Offset is used as the start offset of the first segment to be laid out.
1426 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1427 // we start at offset 0.
1428 uint64_t Offset = 0;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001429 Offset = LayoutSegments(OrderedSegments, Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001430 Offset = LayoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001431 // If we need to write the section header table out then we need to align the
1432 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001433 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001434 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001435 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001436}
1437
Jake Ehrlich76e91102018-01-25 22:46:17 +00001438template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001439 // We already have the section header offset so we can calculate the total
1440 // size by just adding up the size of each section header.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001441 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1442 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001443 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001444}
1445
Jake Ehrlich76e91102018-01-25 22:46:17 +00001446template <class ELFT> void ELFWriter<ELFT>::write() {
1447 writeEhdr();
1448 writePhdrs();
1449 writeSectionData();
1450 if (WriteSectionHeaders)
1451 writeShdrs();
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001452 if (auto E = Buf.commit())
1453 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001454}
1455
1456template <class ELFT> void ELFWriter<ELFT>::finalize() {
1457 // It could happen that SectionNames has been removed and yet the user wants
1458 // a section header table output. We need to throw an error if a user tries
1459 // to do that.
1460 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1461 error("Cannot write section header table because section header string "
1462 "table was removed.");
1463
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001464 Obj.sortSections();
1465
1466 // We need to assign indexes before we perform layout because we need to know
1467 // if we need large indexes or not. We can assign indexes first and check as
1468 // we go to see if we will actully need large indexes.
1469 bool NeedsLargeIndexes = false;
1470 if (size(Obj.sections()) >= SHN_LORESERVE) {
1471 auto Sections = Obj.sections();
1472 NeedsLargeIndexes =
1473 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1474 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1475 // TODO: handle case where only one section needs the large index table but
1476 // only needs it because the large index table hasn't been removed yet.
1477 }
1478
1479 if (NeedsLargeIndexes) {
1480 // This means we definitely need to have a section index table but if we
1481 // already have one then we should use it instead of making a new one.
1482 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1483 // Addition of a section to the end does not invalidate the indexes of
1484 // other sections and assigns the correct index to the new section.
1485 auto &Shndx = Obj.addSection<SectionIndexSection>();
1486 Obj.SymbolTable->setShndxTable(&Shndx);
1487 Shndx.setSymTab(Obj.SymbolTable);
1488 }
1489 } else {
1490 // Since we don't need SectionIndexTable we should remove it and all
1491 // references to it.
1492 if (Obj.SectionIndexTable != nullptr) {
1493 Obj.removeSections([this](const SectionBase &Sec) {
1494 return &Sec == Obj.SectionIndexTable;
1495 });
1496 }
1497 }
1498
1499 // Make sure we add the names of all the sections. Importantly this must be
1500 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001501 if (Obj.SectionNames != nullptr)
1502 for (const auto &Section : Obj.sections()) {
1503 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001504 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001505
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001506 initEhdrSegment();
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001507 // Before we can prepare for layout the indexes need to be finalized.
1508 uint64_t Index = 0;
1509 for (auto &Sec : Obj.sections())
1510 Sec.Index = Index++;
1511
1512 // The symbol table does not update all other sections on update. For
1513 // instance, symbol names are not added as new symbols are added. This means
1514 // that some sections, like .strtab, don't yet have their final size.
1515 if (Obj.SymbolTable != nullptr)
1516 Obj.SymbolTable->prepareForLayout();
1517
Petr Hosekc4df10e2017-08-04 21:09:26 +00001518 assignOffsets();
1519
1520 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001521 if (Obj.SectionNames != nullptr)
1522 Obj.SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001523 // Finally now that all offsets and indexes have been set we can finalize any
1524 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001525 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1526 for (auto &Section : Obj.sections()) {
1527 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001528 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001529 if (WriteSectionHeaders)
1530 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1531 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001532 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001533
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001534 Buf.allocate(totalSize());
1535 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001536}
1537
Jake Ehrlich76e91102018-01-25 22:46:17 +00001538void BinaryWriter::write() {
1539 for (auto &Section : Obj.sections()) {
1540 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001541 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001542 Section.accept(*SecWriter);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001543 }
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001544 if (auto E = Buf.commit())
1545 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
Petr Hosekc4df10e2017-08-04 21:09:26 +00001546}
1547
Jake Ehrlich76e91102018-01-25 22:46:17 +00001548void BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001549 // TODO: Create a filter range to construct OrderedSegments from so that this
1550 // code can be deduped with assignOffsets above. This should also solve the
1551 // todo below for LayoutSections.
1552 // We need a temporary list of segments that has a special order to it
1553 // so that we know that anytime ->ParentSegment is set that segment has
1554 // already had it's offset properly set. We only want to consider the segments
1555 // that will affect layout of allocated sections so we only add those.
1556 std::vector<Segment *> OrderedSegments;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001557 for (auto &Section : Obj.sections()) {
1558 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1559 OrderedSegments.push_back(Section.ParentSegment);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001560 }
1561 }
Jake Ehrlich46814be2018-01-22 19:27:30 +00001562
1563 // For binary output, we're going to use physical addresses instead of
1564 // virtual addresses, since a binary output is used for cases like ROM
1565 // loading and physical addresses are intended for ROM loading.
1566 // However, if no segment has a physical address, we'll fallback to using
1567 // virtual addresses for all.
1568 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1569 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1570 for (const auto &Segment : OrderedSegments)
1571 Segment->PAddr = Segment->VAddr;
1572
1573 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1574 compareSegmentsByPAddr);
1575
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001576 // Because we add a ParentSegment for each section we might have duplicate
1577 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1578 // would do very strange things.
1579 auto End =
1580 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1581 OrderedSegments.erase(End, std::end(OrderedSegments));
1582
Jake Ehrlich46814be2018-01-22 19:27:30 +00001583 uint64_t Offset = 0;
1584
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001585 // Modify the first segment so that there is no gap at the start. This allows
1586 // our layout algorithm to proceed as expected while not out writing out the
1587 // gap at the start.
1588 if (!OrderedSegments.empty()) {
1589 auto Seg = OrderedSegments[0];
1590 auto Sec = Seg->firstSection();
1591 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1592 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001593 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001594 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001595 // The PAddr needs to be increased to remove the gap before the first
1596 // section.
1597 Seg->PAddr += Diff;
1598 uint64_t LowestPAddr = Seg->PAddr;
1599 for (auto &Segment : OrderedSegments) {
1600 Segment->Offset = Segment->PAddr - LowestPAddr;
1601 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1602 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001603 }
1604
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001605 // TODO: generalize LayoutSections to take a range. Pass a special range
1606 // constructed from an iterator that skips values for which a predicate does
1607 // not hold. Then pass such a range to LayoutSections instead of constructing
1608 // AllocatedSections here.
1609 std::vector<SectionBase *> AllocatedSections;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001610 for (auto &Section : Obj.sections()) {
1611 if ((Section.Flags & SHF_ALLOC) == 0)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001612 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001613 AllocatedSections.push_back(&Section);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001614 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001615 LayoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001616
1617 // Now that every section has been laid out we just need to compute the total
1618 // file size. This might not be the same as the offset returned by
1619 // LayoutSections, because we want to truncate the last segment to the end of
1620 // its last section, to match GNU objcopy's behaviour.
1621 TotalSize = 0;
1622 for (const auto &Section : AllocatedSections) {
1623 if (Section->Type != SHT_NOBITS)
1624 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1625 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001626
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001627 Buf.allocate(TotalSize);
1628 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001629}
1630
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001631namespace llvm {
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001632namespace objcopy {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001633
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001634template class BinaryELFBuilder<ELF64LE>;
1635template class BinaryELFBuilder<ELF64BE>;
1636template class BinaryELFBuilder<ELF32LE>;
1637template class BinaryELFBuilder<ELF32BE>;
1638
Jake Ehrlich76e91102018-01-25 22:46:17 +00001639template class ELFBuilder<ELF64LE>;
1640template class ELFBuilder<ELF64BE>;
1641template class ELFBuilder<ELF32LE>;
1642template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001643
Jake Ehrlich76e91102018-01-25 22:46:17 +00001644template class ELFWriter<ELF64LE>;
1645template class ELFWriter<ELF64BE>;
1646template class ELFWriter<ELF32LE>;
1647template class ELFWriter<ELF32BE>;
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00001648} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001649} // end namespace llvm