Bug Summary

File:tools/llvm-objcopy/Object.cpp
Warning:line 363, column 3
Value stored to 'Size' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Object.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/llvm-objcopy -I /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objcopy -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/llvm-objcopy -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objcopy/Object.cpp -faddrsig
1//===- Object.cpp ---------------------------------------------------------===//
2//
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//===----------------------------------------------------------------------===//
9
10#include "Object.h"
11#include "llvm-objcopy.h"
12#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"
18#include "llvm/MC/MCTargetOptions.h"
19#include "llvm/Object/ELFObjectFile.h"
20#include "llvm/Support/Compression.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/FileOutputBuffer.h"
23#include "llvm/Support/Path.h"
24#include <algorithm>
25#include <cstddef>
26#include <cstdint>
27#include <iterator>
28#include <utility>
29#include <vector>
30
31namespace llvm {
32namespace objcopy {
33namespace elf {
34
35using namespace object;
36using namespace ELF;
37
38template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
39 uint8_t *B = Buf.getBufferStart();
40 B += Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
41 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
42 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;
50}
51
52void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
53void SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {}
54void SectionBase::initialize(SectionTableRef SecTable) {}
55void SectionBase::finalize() {}
56void SectionBase::markSymbols() {}
57
58template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
59 uint8_t *B = Buf.getBufferStart();
60 B += Sec.HeaderOffset;
61 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
62 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;
72}
73
74SectionVisitor::~SectionVisitor() {}
75
76void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
77 error("Cannot write symbol section index table '" + Sec.Name + "' ");
78}
79
80void 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) {
89 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");
94}
95
96void SectionWriter::visit(const Section &Sec) {
97 if (Sec.Type == SHT_NOBITS)
98 return;
99 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
100 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents), Buf);
101}
102
103void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
104
105void SectionWriter::visit(const OwnedDataSection &Sec) {
106 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
107 std::copy(std::begin(Sec.Data), std::end(Sec.Data), Buf);
108}
109
110static 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
167void OwnedDataSection::accept(SectionVisitor &Visitor) const {
168 Visitor.visit(*this);
169}
170
171void 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
237CompressedSection::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
245void CompressedSection::accept(SectionVisitor &Visitor) const {
246 Visitor.visit(*this);
247}
248
249void 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
260void 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);
266}
267
268template <class ELFT>
269void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
270 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
271 auto *IndexesBuffer = reinterpret_cast<Elf_Word *>(Buf);
272 std::copy(std::begin(Sec.Indexes), std::end(Sec.Indexes), IndexesBuffer);
273}
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
291static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
292 switch (Index) {
293 case SHN_ABS:
294 case SHN_COMMON:
295 return true;
296 }
297 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;
307}
308
309// 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.
312uint16_t Symbol::getShndx() const {
313 if (DefinedIn != nullptr) {
314 if (DefinedIn->Index >= SHN_LORESERVE)
315 return SHN_XINDEX;
316 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:
329 case SYMBOL_XINDEX:
330 return static_cast<uint16_t>(ShndxType);
331 }
332 llvm_unreachable("Symbol with invalid ShndxType encountered")::llvm::llvm_unreachable_internal("Symbol with invalid ShndxType encountered"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objcopy/Object.cpp"
, 332)
;
333}
334
335void SymbolTableSection::assignIndices() {
336 uint32_t Index = 0;
337 for (auto &Sym : Symbols)
338 Sym->Index = Index++;
339}
340
341void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
342 SectionBase *DefinedIn, uint64_t Value,
343 uint8_t Visibility, uint16_t Shndx,
344 uint64_t Size) {
345 Symbol Sym;
346 Sym.Name = Name.str();
347 Sym.Binding = Bind;
348 Sym.Type = Type;
349 Sym.DefinedIn = DefinedIn;
350 if (DefinedIn != nullptr)
351 DefinedIn->HasSymbol = true;
352 if (DefinedIn == nullptr) {
353 if (Shndx >= SHN_LORESERVE)
354 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
355 else
356 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
357 }
358 Sym.Value = Value;
359 Sym.Visibility = Visibility;
360 Sym.Size = Size;
361 Sym.Index = Symbols.size();
362 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
363 Size += this->EntrySize;
Value stored to 'Size' is never read
364}
365
366void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
367 if (SectionIndexTable == Sec)
368 SectionIndexTable = nullptr;
369 if (SymbolNames == Sec) {
370 error("String table " + SymbolNames->Name +
371 " cannot be removed because it is referenced by the symbol table " +
372 this->Name);
373 }
374 removeSymbols([Sec](const Symbol &Sym) { return Sym.DefinedIn == Sec; });
375}
376
377void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
378 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
379 [Callable](SymPtr &Sym) { Callable(*Sym); });
380 std::stable_partition(
381 std::begin(Symbols), std::end(Symbols),
382 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
383 assignIndices();
384}
385
386void SymbolTableSection::removeSymbols(
387 function_ref<bool(const Symbol &)> ToRemove) {
388 Symbols.erase(
389 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
390 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
391 std::end(Symbols));
392 Size = Symbols.size() * EntrySize;
393 assignIndices();
394}
395
396void SymbolTableSection::initialize(SectionTableRef SecTable) {
397 Size = 0;
398 setStrTab(SecTable.getSectionOfType<StringTableSection>(
399 Link,
400 "Symbol table has link index of " + Twine(Link) +
401 " which is not a valid index",
402 "Symbol table has link index of " + Twine(Link) +
403 " which is not a string table"));
404}
405
406void SymbolTableSection::finalize() {
407 // Make sure SymbolNames is finalized before getting name indexes.
408 SymbolNames->finalize();
409
410 uint32_t MaxLocalIndex = 0;
411 for (auto &Sym : Symbols) {
412 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
413 if (Sym->Binding == STB_LOCAL)
414 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
415 }
416 // Now we need to set the Link and Info fields.
417 Link = SymbolNames->Index;
418 Info = MaxLocalIndex + 1;
419}
420
421void SymbolTableSection::prepareForLayout() {
422 // Add all potential section indexes before file layout so that the section
423 // index section has the approprite size.
424 if (SectionIndexTable != nullptr) {
425 for (const auto &Sym : Symbols) {
426 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
427 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
428 else
429 SectionIndexTable->addIndex(SHN_UNDEF);
430 }
431 }
432 // Add all of our strings to SymbolNames so that SymbolNames has the right
433 // size before layout is decided.
434 for (auto &Sym : Symbols)
435 SymbolNames->addString(Sym->Name);
436}
437
438const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
439 if (Symbols.size() <= Index)
440 error("Invalid symbol index: " + Twine(Index));
441 return Symbols[Index].get();
442}
443
444Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
445 return const_cast<Symbol *>(
446 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
447}
448
449template <class ELFT>
450void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
451 uint8_t *Buf = Out.getBufferStart();
452 Buf += Sec.Offset;
453 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Buf);
454 // Loop though symbols setting each entry of the symbol table.
455 for (auto &Symbol : Sec.Symbols) {
456 Sym->st_name = Symbol->NameIndex;
457 Sym->st_value = Symbol->Value;
458 Sym->st_size = Symbol->Size;
459 Sym->st_other = Symbol->Visibility;
460 Sym->setBinding(Symbol->Binding);
461 Sym->setType(Symbol->Type);
462 Sym->st_shndx = Symbol->getShndx();
463 ++Sym;
464 }
465}
466
467void SymbolTableSection::accept(SectionVisitor &Visitor) const {
468 Visitor.visit(*this);
469}
470
471template <class SymTabType>
472void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
473 const SectionBase *Sec) {
474 if (Symbols == Sec) {
475 error("Symbol table " + Symbols->Name +
476 " cannot be removed because it is "
477 "referenced by the relocation "
478 "section " +
479 this->Name);
480 }
481}
482
483template <class SymTabType>
484void RelocSectionWithSymtabBase<SymTabType>::initialize(
485 SectionTableRef SecTable) {
486 if (Link != SHN_UNDEF)
487 setSymTab(SecTable.getSectionOfType<SymTabType>(
488 Link,
489 "Link field value " + Twine(Link) + " in section " + Name +
490 " is invalid",
491 "Link field value " + Twine(Link) + " in section " + Name +
492 " is not a symbol table"));
493
494 if (Info != SHN_UNDEF)
495 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
496 " in section " + Name +
497 " is invalid"));
498 else
499 setSection(nullptr);
500}
501
502template <class SymTabType>
503void RelocSectionWithSymtabBase<SymTabType>::finalize() {
504 this->Link = Symbols ? Symbols->Index : 0;
505
506 if (SecToApplyRel != nullptr)
507 this->Info = SecToApplyRel->Index;
508}
509
510template <class ELFT>
511static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
512
513template <class ELFT>
514static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
515 Rela.r_addend = Addend;
516}
517
518template <class RelRange, class T>
519static void writeRel(const RelRange &Relocations, T *Buf) {
520 for (const auto &Reloc : Relocations) {
521 Buf->r_offset = Reloc.Offset;
522 setAddend(*Buf, Reloc.Addend);
523 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
524 ++Buf;
525 }
526}
527
528template <class ELFT>
529void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
530 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
531 if (Sec.Type == SHT_REL)
532 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
533 else
534 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
535}
536
537void RelocationSection::accept(SectionVisitor &Visitor) const {
538 Visitor.visit(*this);
539}
540
541void RelocationSection::removeSymbols(
542 function_ref<bool(const Symbol &)> ToRemove) {
543 for (const Relocation &Reloc : Relocations)
544 if (ToRemove(*Reloc.RelocSymbol))
545 error("not stripping symbol '" + Reloc.RelocSymbol->Name +
546 "' because it is named in a relocation");
547}
548
549void RelocationSection::markSymbols() {
550 for (const Relocation &Reloc : Relocations)
551 Reloc.RelocSymbol->Referenced = true;
552}
553
554void SectionWriter::visit(const DynamicRelocationSection &Sec) {
555 std::copy(std::begin(Sec.Contents), std::end(Sec.Contents),
556 Out.getBufferStart() + Sec.Offset);
557}
558
559void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
560 Visitor.visit(*this);
561}
562
563void Section::removeSectionReferences(const SectionBase *Sec) {
564 if (LinkSection == Sec) {
565 error("Section " + LinkSection->Name +
566 " cannot be removed because it is "
567 "referenced by the section " +
568 this->Name);
569 }
570}
571
572void GroupSection::finalize() {
573 this->Info = Sym->Index;
574 this->Link = SymTab->Index;
575}
576
577void GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
578 if (ToRemove(*Sym)) {
579 error("Symbol " + Sym->Name +
580 " cannot be removed because it is "
581 "referenced by the section " +
582 this->Name + "[" + Twine(this->Index) + "]");
583 }
584}
585
586void GroupSection::markSymbols() {
587 if (Sym)
588 Sym->Referenced = true;
589}
590
591void Section::initialize(SectionTableRef SecTable) {
592 if (Link != ELF::SHN_UNDEF) {
593 LinkSection =
594 SecTable.getSection(Link, "Link field value " + Twine(Link) +
595 " in section " + Name + " is invalid");
596 if (LinkSection->Type == ELF::SHT_SYMTAB)
597 LinkSection = nullptr;
598 }
599}
600
601void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
602
603void GnuDebugLinkSection::init(StringRef File, StringRef Data) {
604 FileName = sys::path::filename(File);
605 // The format for the .gnu_debuglink starts with the file name and is
606 // followed by a null terminator and then the CRC32 of the file. The CRC32
607 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
608 // byte, and then finally push the size to alignment and add 4.
609 Size = alignTo(FileName.size() + 1, 4) + 4;
610 // The CRC32 will only be aligned if we align the whole section.
611 Align = 4;
612 Type = ELF::SHT_PROGBITS;
613 Name = ".gnu_debuglink";
614 // For sections not found in segments, OriginalOffset is only used to
615 // establish the order that sections should go in. By using the maximum
616 // possible offset we cause this section to wind up at the end.
617 OriginalOffset = std::numeric_limits<uint64_t>::max();
618 JamCRC crc;
619 crc.update(ArrayRef<char>(Data.data(), Data.size()));
620 // The CRC32 value needs to be complemented because the JamCRC dosn't
621 // finalize the CRC32 value. It also dosn't negate the initial CRC32 value
622 // but it starts by default at 0xFFFFFFFF which is the complement of zero.
623 CRC32 = ~crc.getCRC();
624}
625
626GnuDebugLinkSection::GnuDebugLinkSection(StringRef File) : FileName(File) {
627 // Read in the file to compute the CRC of it.
628 auto DebugOrErr = MemoryBuffer::getFile(File);
629 if (!DebugOrErr)
630 error("'" + File + "': " + DebugOrErr.getError().message());
631 auto Debug = std::move(*DebugOrErr);
632 init(File, Debug->getBuffer());
633}
634
635template <class ELFT>
636void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
637 auto Buf = Out.getBufferStart() + Sec.Offset;
638 char *File = reinterpret_cast<char *>(Buf);
639 Elf_Word *CRC =
640 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
641 *CRC = Sec.CRC32;
642 std::copy(std::begin(Sec.FileName), std::end(Sec.FileName), File);
643}
644
645void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
646 Visitor.visit(*this);
647}
648
649template <class ELFT>
650void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
651 ELF::Elf32_Word *Buf =
652 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
653 *Buf++ = Sec.FlagWord;
654 for (const auto *S : Sec.GroupMembers)
655 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
656}
657
658void GroupSection::accept(SectionVisitor &Visitor) const {
659 Visitor.visit(*this);
660}
661
662// Returns true IFF a section is wholly inside the range of a segment
663static bool sectionWithinSegment(const SectionBase &Section,
664 const Segment &Segment) {
665 // If a section is empty it should be treated like it has a size of 1. This is
666 // to clarify the case when an empty section lies on a boundary between two
667 // segments and ensures that the section "belongs" to the second segment and
668 // not the first.
669 uint64_t SecSize = Section.Size ? Section.Size : 1;
670 return Segment.Offset <= Section.OriginalOffset &&
671 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
672}
673
674// Returns true IFF a segment's original offset is inside of another segment's
675// range.
676static bool segmentOverlapsSegment(const Segment &Child,
677 const Segment &Parent) {
678
679 return Parent.OriginalOffset <= Child.OriginalOffset &&
680 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
681}
682
683static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
684 // Any segment without a parent segment should come before a segment
685 // that has a parent segment.
686 if (A->OriginalOffset < B->OriginalOffset)
687 return true;
688 if (A->OriginalOffset > B->OriginalOffset)
689 return false;
690 return A->Index < B->Index;
691}
692
693static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
694 if (A->PAddr < B->PAddr)
695 return true;
696 if (A->PAddr > B->PAddr)
697 return false;
698 return A->Index < B->Index;
699}
700
701template <class ELFT> void BinaryELFBuilder<ELFT>::initFileHeader() {
702 Obj->Flags = 0x0;
703 Obj->Type = ET_REL;
704 Obj->Entry = 0x0;
705 Obj->Machine = EMachine;
706 Obj->Version = 1;
707}
708
709template <class ELFT> void BinaryELFBuilder<ELFT>::initHeaderSegment() {
710 Obj->ElfHdrSegment.Index = 0;
711}
712
713template <class ELFT> StringTableSection *BinaryELFBuilder<ELFT>::addStrTab() {
714 auto &StrTab = Obj->addSection<StringTableSection>();
715 StrTab.Name = ".strtab";
716
717 Obj->SectionNames = &StrTab;
718 return &StrTab;
719}
720
721template <class ELFT>
722SymbolTableSection *
723BinaryELFBuilder<ELFT>::addSymTab(StringTableSection *StrTab) {
724 auto &SymTab = Obj->addSection<SymbolTableSection>();
725
726 SymTab.Name = ".symtab";
727 SymTab.Link = StrTab->Index;
728 // TODO: Factor out dependence on ElfType here.
729 SymTab.EntrySize = sizeof(Elf_Sym);
730
731 // The symbol table always needs a null symbol
732 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
733
734 Obj->SymbolTable = &SymTab;
735 return &SymTab;
736}
737
738template <class ELFT>
739void BinaryELFBuilder<ELFT>::addData(SymbolTableSection *SymTab) {
740 auto Data = ArrayRef<uint8_t>(
741 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
742 MemBuf->getBufferSize());
743 auto &DataSection = Obj->addSection<Section>(Data);
744 DataSection.Name = ".data";
745 DataSection.Type = ELF::SHT_PROGBITS;
746 DataSection.Size = Data.size();
747 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
748
749 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
750 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
751 [](char c) { return !isalnum(c); }, '_');
752 Twine Prefix = Twine("_binary_") + SanitizedFilename;
753
754 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
755 /*Value=*/0, STV_DEFAULT, 0, 0);
756 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
757 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
758 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
759 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
760}
761
762template <class ELFT> void BinaryELFBuilder<ELFT>::initSections() {
763 for (auto &Section : Obj->sections()) {
764 Section.initialize(Obj->sections());
765 }
766}
767
768template <class ELFT> std::unique_ptr<Object> BinaryELFBuilder<ELFT>::build() {
769 initFileHeader();
770 initHeaderSegment();
771 StringTableSection *StrTab = addStrTab();
772 SymbolTableSection *SymTab = addSymTab(StrTab);
773 initSections();
774 addData(SymTab);
775
776 return std::move(Obj);
777}
778
779template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
780 for (auto &Parent : Obj.segments()) {
781 // Every segment will overlap with itself but we don't want a segment to
782 // be it's own parent so we avoid that situation.
783 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
784 // We want a canonical "most parental" segment but this requires
785 // inspecting the ParentSegment.
786 if (compareSegmentsByOffset(&Parent, &Child))
787 if (Child.ParentSegment == nullptr ||
788 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
789 Child.ParentSegment = &Parent;
790 }
791 }
792 }
793}
794
795template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
796 uint32_t Index = 0;
797 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
798 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
799 (size_t)Phdr.p_filesz};
800 Segment &Seg = Obj.addSegment(Data);
801 Seg.Type = Phdr.p_type;
802 Seg.Flags = Phdr.p_flags;
803 Seg.OriginalOffset = Phdr.p_offset;
804 Seg.Offset = Phdr.p_offset;
805 Seg.VAddr = Phdr.p_vaddr;
806 Seg.PAddr = Phdr.p_paddr;
807 Seg.FileSize = Phdr.p_filesz;
808 Seg.MemSize = Phdr.p_memsz;
809 Seg.Align = Phdr.p_align;
810 Seg.Index = Index++;
811 for (auto &Section : Obj.sections()) {
812 if (sectionWithinSegment(Section, Seg)) {
813 Seg.addSection(&Section);
814 if (!Section.ParentSegment ||
815 Section.ParentSegment->Offset > Seg.Offset) {
816 Section.ParentSegment = &Seg;
817 }
818 }
819 }
820 }
821
822 auto &ElfHdr = Obj.ElfHdrSegment;
823 ElfHdr.Index = Index++;
824
825 const auto &Ehdr = *ElfFile.getHeader();
826 auto &PrHdr = Obj.ProgramHdrSegment;
827 PrHdr.Type = PT_PHDR;
828 PrHdr.Flags = 0;
829 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
830 // Whereas this works automatically for ElfHdr, here OriginalOffset is
831 // always non-zero and to ensure the equation we assign the same value to
832 // VAddr as well.
833 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
834 PrHdr.PAddr = 0;
835 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
836 // The spec requires us to naturally align all the fields.
837 PrHdr.Align = sizeof(Elf_Addr);
838 PrHdr.Index = Index++;
839
840 // Now we do an O(n^2) loop through the segments in order to match up
841 // segments.
842 for (auto &Child : Obj.segments())
843 setParentSegment(Child);
844 setParentSegment(ElfHdr);
845 setParentSegment(PrHdr);
846}
847
848template <class ELFT>
849void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
850 auto SecTable = Obj.sections();
851 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
852 GroupSec->Link,
853 "Link field value " + Twine(GroupSec->Link) + " in section " +
854 GroupSec->Name + " is invalid",
855 "Link field value " + Twine(GroupSec->Link) + " in section " +
856 GroupSec->Name + " is not a symbol table");
857 auto Sym = SymTab->getSymbolByIndex(GroupSec->Info);
858 if (!Sym)
859 error("Info field value " + Twine(GroupSec->Info) + " in section " +
860 GroupSec->Name + " is not a valid symbol index");
861 GroupSec->setSymTab(SymTab);
862 GroupSec->setSymbol(Sym);
863 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
864 GroupSec->Contents.empty())
865 error("The content of the section " + GroupSec->Name + " is malformed");
866 const ELF::Elf32_Word *Word =
867 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
868 const ELF::Elf32_Word *End =
869 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
870 GroupSec->setFlagWord(*Word++);
871 for (; Word != End; ++Word) {
872 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
873 GroupSec->addMember(SecTable.getSection(
874 Index, "Group member index " + Twine(Index) + " in section " +
875 GroupSec->Name + " is invalid"));
876 }
877}
878
879template <class ELFT>
880void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
881 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
882 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
883 ArrayRef<Elf_Word> ShndxData;
884
885 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
886 for (const auto &Sym : Symbols) {
887 SectionBase *DefSection = nullptr;
888 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
889
890 if (Sym.st_shndx == SHN_XINDEX) {
891 if (SymTab->getShndxTable() == nullptr)
892 error("Symbol '" + Name +
893 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists.");
894 if (ShndxData.data() == nullptr) {
895 const Elf_Shdr &ShndxSec =
896 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
897 ShndxData = unwrapOrError(
898 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
899 if (ShndxData.size() != Symbols.size())
900 error("Symbol section index table does not have the same number of "
901 "entries as the symbol table.");
902 }
903 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
904 DefSection = Obj.sections().getSection(
905 Index,
906 "Symbol '" + Name + "' has invalid section index " + Twine(Index));
907 } else if (Sym.st_shndx >= SHN_LORESERVE) {
908 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
909 error(
910 "Symbol '" + Name +
911 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
912 Twine(Sym.st_shndx));
913 }
914 } else if (Sym.st_shndx != SHN_UNDEF) {
915 DefSection = Obj.sections().getSection(
916 Sym.st_shndx, "Symbol '" + Name +
917 "' is defined has invalid section index " +
918 Twine(Sym.st_shndx));
919 }
920
921 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
922 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
923 }
924}
925
926template <class ELFT>
927static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
928
929template <class ELFT>
930static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
931 ToSet = Rela.r_addend;
932}
933
934template <class T>
935static void initRelocations(RelocationSection *Relocs,
936 SymbolTableSection *SymbolTable, T RelRange) {
937 for (const auto &Rel : RelRange) {
938 Relocation ToAdd;
939 ToAdd.Offset = Rel.r_offset;
940 getAddend(ToAdd.Addend, Rel);
941 ToAdd.Type = Rel.getType(false);
942 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
943 Relocs->addRelocation(ToAdd);
944 }
945}
946
947SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
948 if (Index == SHN_UNDEF || Index > Sections.size())
949 error(ErrMsg);
950 return Sections[Index - 1].get();
951}
952
953template <class T>
954T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
955 Twine TypeErrMsg) {
956 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
957 return Sec;
958 error(TypeErrMsg);
959}
960
961template <class ELFT>
962SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
963 ArrayRef<uint8_t> Data;
964 switch (Shdr.sh_type) {
965 case SHT_REL:
966 case SHT_RELA:
967 if (Shdr.sh_flags & SHF_ALLOC) {
968 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
969 return Obj.addSection<DynamicRelocationSection>(Data);
970 }
971 return Obj.addSection<RelocationSection>();
972 case SHT_STRTAB:
973 // If a string table is allocated we don't want to mess with it. That would
974 // mean altering the memory image. There are no special link types or
975 // anything so we can just use a Section.
976 if (Shdr.sh_flags & SHF_ALLOC) {
977 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
978 return Obj.addSection<Section>(Data);
979 }
980 return Obj.addSection<StringTableSection>();
981 case SHT_HASH:
982 case SHT_GNU_HASH:
983 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
984 // Because of this we don't need to mess with the hash tables either.
985 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
986 return Obj.addSection<Section>(Data);
987 case SHT_GROUP:
988 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
989 return Obj.addSection<GroupSection>(Data);
990 case SHT_DYNSYM:
991 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
992 return Obj.addSection<DynamicSymbolTableSection>(Data);
993 case SHT_DYNAMIC:
994 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
995 return Obj.addSection<DynamicSection>(Data);
996 case SHT_SYMTAB: {
997 auto &SymTab = Obj.addSection<SymbolTableSection>();
998 Obj.SymbolTable = &SymTab;
999 return SymTab;
1000 }
1001 case SHT_SYMTAB_SHNDX: {
1002 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1003 Obj.SectionIndexTable = &ShndxSection;
1004 return ShndxSection;
1005 }
1006 case SHT_NOBITS:
1007 return Obj.addSection<Section>(Data);
1008 default: {
1009 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1010
1011 if (isDataGnuCompressed(Data) || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
1012 uint64_t DecompressedSize, DecompressedAlign;
1013 std::tie(DecompressedSize, DecompressedAlign) =
1014 getDecompressedSizeAndAlignment<ELFT>(Data);
1015 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1016 DecompressedAlign);
1017 }
1018
1019 return Obj.addSection<Section>(Data);
1020 }
1021 }
1022}
1023
1024template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
1025 uint32_t Index = 0;
1026 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1027 if (Index == 0) {
1028 ++Index;
1029 continue;
1030 }
1031 auto &Sec = makeSection(Shdr);
1032 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1033 Sec.Type = Shdr.sh_type;
1034 Sec.Flags = Shdr.sh_flags;
1035 Sec.Addr = Shdr.sh_addr;
1036 Sec.Offset = Shdr.sh_offset;
1037 Sec.OriginalOffset = Shdr.sh_offset;
1038 Sec.Size = Shdr.sh_size;
1039 Sec.Link = Shdr.sh_link;
1040 Sec.Info = Shdr.sh_info;
1041 Sec.Align = Shdr.sh_addralign;
1042 Sec.EntrySize = Shdr.sh_entsize;
1043 Sec.Index = Index++;
1044 Sec.OriginalData =
1045 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1046 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
1047 }
1048
1049 // If a section index table exists we'll need to initialize it before we
1050 // initialize the symbol table because the symbol table might need to
1051 // reference it.
1052 if (Obj.SectionIndexTable)
1053 Obj.SectionIndexTable->initialize(Obj.sections());
1054
1055 // Now that all of the sections have been added we can fill out some extra
1056 // details about symbol tables. We need the symbol table filled out before
1057 // any relocations.
1058 if (Obj.SymbolTable) {
1059 Obj.SymbolTable->initialize(Obj.sections());
1060 initSymbolTable(Obj.SymbolTable);
1061 }
1062
1063 // Now that all sections and symbols have been added we can add
1064 // relocations that reference symbols and set the link and info fields for
1065 // relocation sections.
1066 for (auto &Section : Obj.sections()) {
1067 if (&Section == Obj.SymbolTable)
1068 continue;
1069 Section.initialize(Obj.sections());
1070 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
1071 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1072 if (RelSec->Type == SHT_REL)
1073 initRelocations(RelSec, Obj.SymbolTable,
1074 unwrapOrError(ElfFile.rels(Shdr)));
1075 else
1076 initRelocations(RelSec, Obj.SymbolTable,
1077 unwrapOrError(ElfFile.relas(Shdr)));
1078 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1079 initGroupSection(GroupSec);
1080 }
1081 }
1082}
1083
1084template <class ELFT> void ELFBuilder<ELFT>::build() {
1085 const auto &Ehdr = *ElfFile.getHeader();
1086
1087 Obj.Type = Ehdr.e_type;
1088 Obj.Machine = Ehdr.e_machine;
1089 Obj.Version = Ehdr.e_version;
1090 Obj.Entry = Ehdr.e_entry;
1091 Obj.Flags = Ehdr.e_flags;
1092
1093 readSectionHeaders();
1094 readProgramHeaders();
1095
1096 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1097 if (ShstrIndex == SHN_XINDEX)
1098 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1099
1100 Obj.SectionNames =
1101 Obj.sections().template getSectionOfType<StringTableSection>(
1102 ShstrIndex,
1103 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1104 " in elf header " + " is invalid",
1105 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1106 " in elf header " + " is not a string table");
1107}
1108
1109// A generic size function which computes sizes of any random access range.
1110template <class R> size_t size(R &&Range) {
1111 return static_cast<size_t>(std::end(Range) - std::begin(Range));
1112}
1113
1114Writer::~Writer() {}
1115
1116Reader::~Reader() {}
1117
1118std::unique_ptr<Object> BinaryReader::create() const {
1119 if (MInfo.Is64Bit)
1120 return MInfo.IsLittleEndian
1121 ? BinaryELFBuilder<ELF64LE>(MInfo.EMachine, MemBuf).build()
1122 : BinaryELFBuilder<ELF64BE>(MInfo.EMachine, MemBuf).build();
1123 else
1124 return MInfo.IsLittleEndian
1125 ? BinaryELFBuilder<ELF32LE>(MInfo.EMachine, MemBuf).build()
1126 : BinaryELFBuilder<ELF32BE>(MInfo.EMachine, MemBuf).build();
1127}
1128
1129std::unique_ptr<Object> ELFReader::create() const {
1130 auto Obj = llvm::make_unique<Object>();
1131 if (auto *o = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1132 ELFBuilder<ELF32LE> Builder(*o, *Obj);
1133 Builder.build();
1134 return Obj;
1135 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1136 ELFBuilder<ELF64LE> Builder(*o, *Obj);
1137 Builder.build();
1138 return Obj;
1139 } else if (auto *o = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1140 ELFBuilder<ELF32BE> Builder(*o, *Obj);
1141 Builder.build();
1142 return Obj;
1143 } else if (auto *o = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1144 ELFBuilder<ELF64BE> Builder(*o, *Obj);
1145 Builder.build();
1146 return Obj;
1147 }
1148 error("Invalid file type");
1149}
1150
1151template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
1152 uint8_t *B = Buf.getBufferStart();
1153 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(B);
1154 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1155 Ehdr.e_ident[EI_MAG0] = 0x7f;
1156 Ehdr.e_ident[EI_MAG1] = 'E';
1157 Ehdr.e_ident[EI_MAG2] = 'L';
1158 Ehdr.e_ident[EI_MAG3] = 'F';
1159 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1160 Ehdr.e_ident[EI_DATA] =
1161 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1162 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1163 Ehdr.e_ident[EI_OSABI] = ELFOSABI_NONE;
1164 Ehdr.e_ident[EI_ABIVERSION] = 0;
1165
1166 Ehdr.e_type = Obj.Type;
1167 Ehdr.e_machine = Obj.Machine;
1168 Ehdr.e_version = Obj.Version;
1169 Ehdr.e_entry = Obj.Entry;
1170 // We have to use the fully-qualified name llvm::size
1171 // since some compilers complain on ambiguous resolution.
1172 Ehdr.e_phnum = llvm::size(Obj.segments());
1173 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1174 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
1175 Ehdr.e_flags = Obj.Flags;
1176 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
1177 if (WriteSectionHeaders && size(Obj.sections()) != 0) {
1178 Ehdr.e_shentsize = sizeof(Elf_Shdr);
1179 Ehdr.e_shoff = Obj.SHOffset;
1180 // """
1181 // If the number of sections is greater than or equal to
1182 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1183 // number of section header table entries is contained in the sh_size field
1184 // of the section header at index 0.
1185 // """
1186 auto Shnum = size(Obj.sections()) + 1;
1187 if (Shnum >= SHN_LORESERVE)
1188 Ehdr.e_shnum = 0;
1189 else
1190 Ehdr.e_shnum = Shnum;
1191 // """
1192 // If the section name string table section index is greater than or equal
1193 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1194 // and the actual index of the section name string table section is
1195 // contained in the sh_link field of the section header at index 0.
1196 // """
1197 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1198 Ehdr.e_shstrndx = SHN_XINDEX;
1199 else
1200 Ehdr.e_shstrndx = Obj.SectionNames->Index;
1201 } else {
1202 Ehdr.e_shentsize = 0;
1203 Ehdr.e_shoff = 0;
1204 Ehdr.e_shnum = 0;
1205 Ehdr.e_shstrndx = 0;
1206 }
1207}
1208
1209template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1210 for (auto &Seg : Obj.segments())
1211 writePhdr(Seg);
1212}
1213
1214template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
1215 uint8_t *B = Buf.getBufferStart() + Obj.SHOffset;
1216 // This reference serves to write the dummy section header at the begining
1217 // of the file. It is not used for anything else
1218 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
1219 Shdr.sh_name = 0;
1220 Shdr.sh_type = SHT_NULL;
1221 Shdr.sh_flags = 0;
1222 Shdr.sh_addr = 0;
1223 Shdr.sh_offset = 0;
1224 // See writeEhdr for why we do this.
1225 uint64_t Shnum = size(Obj.sections()) + 1;
1226 if (Shnum >= SHN_LORESERVE)
1227 Shdr.sh_size = Shnum;
1228 else
1229 Shdr.sh_size = 0;
1230 // See writeEhdr for why we do this.
1231 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1232 Shdr.sh_link = Obj.SectionNames->Index;
1233 else
1234 Shdr.sh_link = 0;
1235 Shdr.sh_info = 0;
1236 Shdr.sh_addralign = 0;
1237 Shdr.sh_entsize = 0;
1238
1239 for (auto &Sec : Obj.sections())
1240 writeShdr(Sec);
1241}
1242
1243template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
1244 for (auto &Sec : Obj.sections())
1245 Sec.accept(*SecWriter);
1246}
1247
1248void Object::removeSections(std::function<bool(const SectionBase &)> ToRemove) {
1249
1250 auto Iter = std::stable_partition(
1251 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1252 if (ToRemove(*Sec))
1253 return false;
1254 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1255 if (auto ToRelSec = RelSec->getSection())
1256 return !ToRemove(*ToRelSec);
1257 }
1258 return true;
1259 });
1260 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1261 SymbolTable = nullptr;
1262 if (SectionNames != nullptr && ToRemove(*SectionNames))
1263 SectionNames = nullptr;
1264 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1265 SectionIndexTable = nullptr;
1266 // Now make sure there are no remaining references to the sections that will
1267 // be removed. Sometimes it is impossible to remove a reference so we emit
1268 // an error here instead.
1269 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1270 for (auto &Segment : Segments)
1271 Segment->removeSection(RemoveSec.get());
1272 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
1273 KeepSec->removeSectionReferences(RemoveSec.get());
1274 }
1275 // Now finally get rid of them all togethor.
1276 Sections.erase(Iter, std::end(Sections));
1277}
1278
1279void Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1280 if (!SymbolTable)
1281 return;
1282
1283 for (const SecPtr &Sec : Sections)
1284 Sec->removeSymbols(ToRemove);
1285}
1286
1287void Object::sortSections() {
1288 // Put all sections in offset order. Maintain the ordering as closely as
1289 // possible while meeting that demand however.
1290 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
1291 return A->OriginalOffset < B->OriginalOffset;
1292 };
1293 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
1294 CompareSections);
1295}
1296
1297static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1298 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1299 if (Align == 0)
1300 Align = 1;
1301 auto Diff =
1302 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1303 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1304 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1305 if (Diff < 0)
1306 Diff += Align;
1307 return Offset + Diff;
1308}
1309
1310// Orders segments such that if x = y->ParentSegment then y comes before x.
1311static void OrderSegments(std::vector<Segment *> &Segments) {
1312 std::stable_sort(std::begin(Segments), std::end(Segments),
1313 compareSegmentsByOffset);
1314}
1315
1316// This function finds a consistent layout for a list of segments starting from
1317// an Offset. It assumes that Segments have been sorted by OrderSegments and
1318// returns an Offset one past the end of the last segment.
1319static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
1320 uint64_t Offset) {
1321 assert(std::is_sorted(std::begin(Segments), std::end(Segments),((std::is_sorted(std::begin(Segments), std::end(Segments), compareSegmentsByOffset
)) ? static_cast<void> (0) : __assert_fail ("std::is_sorted(std::begin(Segments), std::end(Segments), compareSegmentsByOffset)"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objcopy/Object.cpp"
, 1322, __PRETTY_FUNCTION__))
1322 compareSegmentsByOffset))((std::is_sorted(std::begin(Segments), std::end(Segments), compareSegmentsByOffset
)) ? static_cast<void> (0) : __assert_fail ("std::is_sorted(std::begin(Segments), std::end(Segments), compareSegmentsByOffset)"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objcopy/Object.cpp"
, 1322, __PRETTY_FUNCTION__))
;
1323 // The only way a segment should move is if a section was between two
1324 // segments and that section was removed. If that section isn't in a segment
1325 // then it's acceptable, but not ideal, to simply move it to after the
1326 // segments. So we can simply layout segments one after the other accounting
1327 // for alignment.
1328 for (auto &Segment : Segments) {
1329 // We assume that segments have been ordered by OriginalOffset and Index
1330 // such that a parent segment will always come before a child segment in
1331 // OrderedSegments. This means that the Offset of the ParentSegment should
1332 // already be set and we can set our offset relative to it.
1333 if (Segment->ParentSegment != nullptr) {
1334 auto Parent = Segment->ParentSegment;
1335 Segment->Offset =
1336 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
1337 } else {
1338 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
1339 Segment->Offset = Offset;
1340 }
1341 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1342 }
1343 return Offset;
1344}
1345
1346// This function finds a consistent layout for a list of sections. It assumes
1347// that the ->ParentSegment of each section has already been laid out. The
1348// supplied starting Offset is used for the starting offset of any section that
1349// does not have a ParentSegment. It returns either the offset given if all
1350// sections had a ParentSegment or an offset one past the last section if there
1351// was a section that didn't have a ParentSegment.
1352template <class Range>
1353static uint64_t LayoutSections(Range Sections, uint64_t Offset) {
1354 // Now the offset of every segment has been set we can assign the offsets
1355 // of each section. For sections that are covered by a segment we should use
1356 // the segment's original offset and the section's original offset to compute
1357 // the offset from the start of the segment. Using the offset from the start
1358 // of the segment we can assign a new offset to the section. For sections not
1359 // covered by segments we can just bump Offset to the next valid location.
1360 uint32_t Index = 1;
1361 for (auto &Section : Sections) {
1362 Section.Index = Index++;
1363 if (Section.ParentSegment != nullptr) {
1364 auto Segment = *Section.ParentSegment;
1365 Section.Offset =
1366 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
1367 } else {
1368 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1369 Section.Offset = Offset;
1370 if (Section.Type != SHT_NOBITS)
1371 Offset += Section.Size;
1372 }
1373 }
1374 return Offset;
1375}
1376
1377template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
1378 auto &ElfHdr = Obj.ElfHdrSegment;
1379 ElfHdr.Type = PT_PHDR;
1380 ElfHdr.Flags = 0;
1381 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1382 ElfHdr.VAddr = 0;
1383 ElfHdr.PAddr = 0;
1384 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1385 ElfHdr.Align = 0;
1386}
1387
1388template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
1389 // We need a temporary list of segments that has a special order to it
1390 // so that we know that anytime ->ParentSegment is set that segment has
1391 // already had its offset properly set.
1392 std::vector<Segment *> OrderedSegments;
1393 for (auto &Segment : Obj.segments())
1394 OrderedSegments.push_back(&Segment);
1395 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1396 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
1397 OrderSegments(OrderedSegments);
1398 // Offset is used as the start offset of the first segment to be laid out.
1399 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1400 // we start at offset 0.
1401 uint64_t Offset = 0;
1402 Offset = LayoutSegments(OrderedSegments, Offset);
1403 Offset = LayoutSections(Obj.sections(), Offset);
1404 // If we need to write the section header table out then we need to align the
1405 // Offset so that SHOffset is valid.
1406 if (WriteSectionHeaders)
1407 Offset = alignTo(Offset, sizeof(Elf_Addr));
1408 Obj.SHOffset = Offset;
1409}
1410
1411template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
1412 // We already have the section header offset so we can calculate the total
1413 // size by just adding up the size of each section header.
1414 auto NullSectionSize = WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
1415 return Obj.SHOffset + size(Obj.sections()) * sizeof(Elf_Shdr) +
1416 NullSectionSize;
1417}
1418
1419template <class ELFT> void ELFWriter<ELFT>::write() {
1420 writeEhdr();
1421 writePhdrs();
1422 writeSectionData();
1423 if (WriteSectionHeaders)
1424 writeShdrs();
1425 if (auto E = Buf.commit())
1426 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
1427}
1428
1429template <class ELFT> void ELFWriter<ELFT>::finalize() {
1430 // It could happen that SectionNames has been removed and yet the user wants
1431 // a section header table output. We need to throw an error if a user tries
1432 // to do that.
1433 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
1434 error("Cannot write section header table because section header string "
1435 "table was removed.");
1436
1437 Obj.sortSections();
1438
1439 // We need to assign indexes before we perform layout because we need to know
1440 // if we need large indexes or not. We can assign indexes first and check as
1441 // we go to see if we will actully need large indexes.
1442 bool NeedsLargeIndexes = false;
1443 if (size(Obj.sections()) >= SHN_LORESERVE) {
1444 auto Sections = Obj.sections();
1445 NeedsLargeIndexes =
1446 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1447 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1448 // TODO: handle case where only one section needs the large index table but
1449 // only needs it because the large index table hasn't been removed yet.
1450 }
1451
1452 if (NeedsLargeIndexes) {
1453 // This means we definitely need to have a section index table but if we
1454 // already have one then we should use it instead of making a new one.
1455 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1456 // Addition of a section to the end does not invalidate the indexes of
1457 // other sections and assigns the correct index to the new section.
1458 auto &Shndx = Obj.addSection<SectionIndexSection>();
1459 Obj.SymbolTable->setShndxTable(&Shndx);
1460 Shndx.setSymTab(Obj.SymbolTable);
1461 }
1462 } else {
1463 // Since we don't need SectionIndexTable we should remove it and all
1464 // references to it.
1465 if (Obj.SectionIndexTable != nullptr) {
1466 Obj.removeSections([this](const SectionBase &Sec) {
1467 return &Sec == Obj.SectionIndexTable;
1468 });
1469 }
1470 }
1471
1472 // Make sure we add the names of all the sections. Importantly this must be
1473 // done after we decide to add or remove SectionIndexes.
1474 if (Obj.SectionNames != nullptr)
1475 for (const auto &Section : Obj.sections()) {
1476 Obj.SectionNames->addString(Section.Name);
1477 }
1478
1479 initEhdrSegment();
1480 // Before we can prepare for layout the indexes need to be finalized.
1481 uint64_t Index = 0;
1482 for (auto &Sec : Obj.sections())
1483 Sec.Index = Index++;
1484
1485 // The symbol table does not update all other sections on update. For
1486 // instance, symbol names are not added as new symbols are added. This means
1487 // that some sections, like .strtab, don't yet have their final size.
1488 if (Obj.SymbolTable != nullptr)
1489 Obj.SymbolTable->prepareForLayout();
1490
1491 assignOffsets();
1492
1493 // Finalize SectionNames first so that we can assign name indexes.
1494 if (Obj.SectionNames != nullptr)
1495 Obj.SectionNames->finalize();
1496 // Finally now that all offsets and indexes have been set we can finalize any
1497 // remaining issues.
1498 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
1499 for (auto &Section : Obj.sections()) {
1500 Section.HeaderOffset = Offset;
1501 Offset += sizeof(Elf_Shdr);
1502 if (WriteSectionHeaders)
1503 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1504 Section.finalize();
1505 }
1506
1507 Buf.allocate(totalSize());
1508 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
1509}
1510
1511void BinaryWriter::write() {
1512 for (auto &Section : Obj.sections()) {
1513 if ((Section.Flags & SHF_ALLOC) == 0)
1514 continue;
1515 Section.accept(*SecWriter);
1516 }
1517 if (auto E = Buf.commit())
1518 reportError(Buf.getName(), errorToErrorCode(std::move(E)));
1519}
1520
1521void BinaryWriter::finalize() {
1522 // TODO: Create a filter range to construct OrderedSegments from so that this
1523 // code can be deduped with assignOffsets above. This should also solve the
1524 // todo below for LayoutSections.
1525 // We need a temporary list of segments that has a special order to it
1526 // so that we know that anytime ->ParentSegment is set that segment has
1527 // already had it's offset properly set. We only want to consider the segments
1528 // that will affect layout of allocated sections so we only add those.
1529 std::vector<Segment *> OrderedSegments;
1530 for (auto &Section : Obj.sections()) {
1531 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr) {
1532 OrderedSegments.push_back(Section.ParentSegment);
1533 }
1534 }
1535
1536 // For binary output, we're going to use physical addresses instead of
1537 // virtual addresses, since a binary output is used for cases like ROM
1538 // loading and physical addresses are intended for ROM loading.
1539 // However, if no segment has a physical address, we'll fallback to using
1540 // virtual addresses for all.
1541 if (std::all_of(std::begin(OrderedSegments), std::end(OrderedSegments),
1542 [](const Segment *Segment) { return Segment->PAddr == 0; }))
1543 for (const auto &Segment : OrderedSegments)
1544 Segment->PAddr = Segment->VAddr;
1545
1546 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
1547 compareSegmentsByPAddr);
1548
1549 // Because we add a ParentSegment for each section we might have duplicate
1550 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1551 // would do very strange things.
1552 auto End =
1553 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1554 OrderedSegments.erase(End, std::end(OrderedSegments));
1555
1556 uint64_t Offset = 0;
1557
1558 // Modify the first segment so that there is no gap at the start. This allows
1559 // our layout algorithm to proceed as expected while not out writing out the
1560 // gap at the start.
1561 if (!OrderedSegments.empty()) {
1562 auto Seg = OrderedSegments[0];
1563 auto Sec = Seg->firstSection();
1564 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1565 Seg->OriginalOffset += Diff;
1566 // The size needs to be shrunk as well.
1567 Seg->FileSize -= Diff;
1568 // The PAddr needs to be increased to remove the gap before the first
1569 // section.
1570 Seg->PAddr += Diff;
1571 uint64_t LowestPAddr = Seg->PAddr;
1572 for (auto &Segment : OrderedSegments) {
1573 Segment->Offset = Segment->PAddr - LowestPAddr;
1574 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1575 }
1576 }
1577
1578 // TODO: generalize LayoutSections to take a range. Pass a special range
1579 // constructed from an iterator that skips values for which a predicate does
1580 // not hold. Then pass such a range to LayoutSections instead of constructing
1581 // AllocatedSections here.
1582 std::vector<SectionBase *> AllocatedSections;
1583 for (auto &Section : Obj.sections()) {
1584 if ((Section.Flags & SHF_ALLOC) == 0)
1585 continue;
1586 AllocatedSections.push_back(&Section);
1587 }
1588 LayoutSections(make_pointee_range(AllocatedSections), Offset);
1589
1590 // Now that every section has been laid out we just need to compute the total
1591 // file size. This might not be the same as the offset returned by
1592 // LayoutSections, because we want to truncate the last segment to the end of
1593 // its last section, to match GNU objcopy's behaviour.
1594 TotalSize = 0;
1595 for (const auto &Section : AllocatedSections) {
1596 if (Section->Type != SHT_NOBITS)
1597 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
1598 }
1599
1600 Buf.allocate(TotalSize);
1601 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
1602}
1603
1604template class BinaryELFBuilder<ELF64LE>;
1605template class BinaryELFBuilder<ELF64BE>;
1606template class BinaryELFBuilder<ELF32LE>;
1607template class BinaryELFBuilder<ELF32BE>;
1608
1609template class ELFBuilder<ELF64LE>;
1610template class ELFBuilder<ELF64BE>;
1611template class ELFBuilder<ELF32LE>;
1612template class ELFBuilder<ELF32BE>;
1613
1614template class ELFWriter<ELF64LE>;
1615template class ELFWriter<ELF64BE>;
1616template class ELFWriter<ELF32LE>;
1617template class ELFWriter<ELF32BE>;
1618
1619} // end namespace elf
1620} // end namespace objcopy
1621} // end namespace llvm