1 //===- Object.cpp ---------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/Object/ELFObjectFile.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/FileOutputBuffer.h"
29 using namespace object;
32 template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
33 using Elf_Ehdr = typename ELFT::Ehdr;
34 using Elf_Phdr = typename ELFT::Phdr;
36 uint8_t *Buf = Out.getBufferStart();
37 Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
38 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
41 Phdr.p_offset = Offset;
44 Phdr.p_filesz = FileSize;
45 Phdr.p_memsz = MemSize;
49 void Segment::writeSegment(FileOutputBuffer &Out) const {
50 uint8_t *Buf = Out.getBufferStart() + Offset;
51 // We want to maintain segments' interstitial data and contents exactly.
52 // This lets us just copy segments directly.
53 std::copy(std::begin(Contents), std::end(Contents), Buf);
56 void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
57 void SectionBase::initialize(SectionTableRef SecTable) {}
58 void SectionBase::finalize() {}
61 void SectionBase::writeHeader(FileOutputBuffer &Out) const {
62 uint8_t *Buf = Out.getBufferStart();
64 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
65 Shdr.sh_name = NameIndex;
67 Shdr.sh_flags = Flags;
69 Shdr.sh_offset = Offset;
73 Shdr.sh_addralign = Align;
74 Shdr.sh_entsize = EntrySize;
77 void Section::writeSection(FileOutputBuffer &Out) const {
78 if (Type == SHT_NOBITS)
80 uint8_t *Buf = Out.getBufferStart() + Offset;
81 std::copy(std::begin(Contents), std::end(Contents), Buf);
84 void OwnedDataSection::writeSection(FileOutputBuffer &Out) const {
85 uint8_t *Buf = Out.getBufferStart() + Offset;
86 std::copy(std::begin(Data), std::end(Data), Buf);
89 void StringTableSection::addString(StringRef Name) {
90 StrTabBuilder.add(Name);
91 Size = StrTabBuilder.getSize();
94 uint32_t StringTableSection::findIndex(StringRef Name) const {
95 return StrTabBuilder.getOffset(Name);
98 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
100 void StringTableSection::writeSection(FileOutputBuffer &Out) const {
101 StrTabBuilder.write(Out.getBufferStart() + Offset);
104 static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
110 if (Machine == EM_HEXAGON) {
112 case SHN_HEXAGON_SCOMMON:
113 case SHN_HEXAGON_SCOMMON_2:
114 case SHN_HEXAGON_SCOMMON_4:
115 case SHN_HEXAGON_SCOMMON_8:
122 uint16_t Symbol::getShndx() const {
123 if (DefinedIn != nullptr) {
124 return DefinedIn->Index;
127 // This means that we don't have a defined section but we do need to
128 // output a legitimate section index.
129 case SYMBOL_SIMPLE_INDEX:
133 case SYMBOL_HEXAGON_SCOMMON:
134 case SYMBOL_HEXAGON_SCOMMON_2:
135 case SYMBOL_HEXAGON_SCOMMON_4:
136 case SYMBOL_HEXAGON_SCOMMON_8:
137 return static_cast<uint16_t>(ShndxType);
139 llvm_unreachable("Symbol with invalid ShndxType encountered");
142 void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
143 SectionBase *DefinedIn, uint64_t Value,
144 uint8_t Visibility, uint16_t Shndx,
150 Sym.DefinedIn = DefinedIn;
151 if (DefinedIn == nullptr) {
152 if (Shndx >= SHN_LORESERVE)
153 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
155 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
158 Sym.Visibility = Visibility;
160 Sym.Index = Symbols.size();
161 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
162 Size += this->EntrySize;
165 void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
166 if (SymbolNames == Sec) {
167 error("String table " + SymbolNames->Name +
168 " cannot be removed because it is referenced by the symbol table " +
172 std::remove_if(std::begin(Symbols), std::end(Symbols),
173 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
174 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
175 Symbols.erase(Iter, std::end(Symbols));
178 void SymbolTableSection::initialize(SectionTableRef SecTable) {
180 setStrTab(SecTable.getSectionOfType<StringTableSection>(
182 "Symbol table has link index of " + Twine(Link) +
183 " which is not a valid index",
184 "Symbol table has link index of " + Twine(Link) +
185 " which is not a string table"));
188 void SymbolTableSection::finalize() {
189 // Make sure SymbolNames is finalized before getting name indexes.
190 SymbolNames->finalize();
192 uint32_t MaxLocalIndex = 0;
193 for (auto &Sym : Symbols) {
194 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
195 if (Sym->Binding == STB_LOCAL)
196 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
198 // Now we need to set the Link and Info fields.
199 Link = SymbolNames->Index;
200 Info = MaxLocalIndex + 1;
203 void SymbolTableSection::addSymbolNames() {
204 // Add all of our strings to SymbolNames so that SymbolNames has the right
205 // size before layout is decided.
206 for (auto &Sym : Symbols)
207 SymbolNames->addString(Sym->Name);
210 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
211 if (Symbols.size() <= Index)
212 error("Invalid symbol index: " + Twine(Index));
213 return Symbols[Index].get();
216 template <class ELFT>
217 void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
218 uint8_t *Buf = Out.getBufferStart();
220 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
221 // Loop though symbols setting each entry of the symbol table.
222 for (auto &Symbol : Symbols) {
223 Sym->st_name = Symbol->NameIndex;
224 Sym->st_value = Symbol->Value;
225 Sym->st_size = Symbol->Size;
226 Sym->st_other = Symbol->Visibility;
227 Sym->setBinding(Symbol->Binding);
228 Sym->setType(Symbol->Type);
229 Sym->st_shndx = Symbol->getShndx();
234 template <class SymTabType>
235 void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
236 const SectionBase *Sec) {
237 if (Symbols == Sec) {
238 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
239 "referenced by the relocation "
245 template <class SymTabType>
246 void RelocSectionWithSymtabBase<SymTabType>::initialize(
247 SectionTableRef SecTable) {
248 setSymTab(SecTable.getSectionOfType<SymTabType>(
250 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
251 "Link field value " + Twine(Link) + " in section " + Name +
252 " is not a symbol table"));
254 if (Info != SHN_UNDEF)
255 setSection(SecTable.getSection(Info,
256 "Info field value " + Twine(Info) +
257 " in section " + Name + " is invalid"));
262 template <class SymTabType>
263 void RelocSectionWithSymtabBase<SymTabType>::finalize() {
264 this->Link = Symbols->Index;
265 if (SecToApplyRel != nullptr)
266 this->Info = SecToApplyRel->Index;
269 template <class ELFT>
270 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
272 template <class ELFT>
273 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
274 Rela.r_addend = Addend;
277 template <class ELFT>
279 void RelocationSection<ELFT>::writeRel(T *Buf) const {
280 for (const auto &Reloc : Relocations) {
281 Buf->r_offset = Reloc.Offset;
282 setAddend(*Buf, Reloc.Addend);
283 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
288 template <class ELFT>
289 void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
290 uint8_t *Buf = Out.getBufferStart() + Offset;
292 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
294 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
297 void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
298 std::copy(std::begin(Contents), std::end(Contents),
299 Out.getBufferStart() + Offset);
302 void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
304 error("String table " + StrTab->Name + " cannot be removed because it is "
305 "referenced by the section " +
310 bool SectionWithStrTab::classof(const SectionBase *S) {
311 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
314 void SectionWithStrTab::initialize(SectionTableRef SecTable) {
315 auto StrTab = SecTable.getSection(Link,
316 "Link field value " + Twine(Link) +
317 " in section " + Name + " is invalid");
318 if (StrTab->Type != SHT_STRTAB) {
319 error("Link field value " + Twine(Link) + " in section " + Name +
320 " is not a string table");
325 void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
327 // Returns true IFF a section is wholly inside the range of a segment
328 static bool sectionWithinSegment(const SectionBase &Section,
329 const Segment &Segment) {
330 // If a section is empty it should be treated like it has a size of 1. This is
331 // to clarify the case when an empty section lies on a boundary between two
332 // segments and ensures that the section "belongs" to the second segment and
334 uint64_t SecSize = Section.Size ? Section.Size : 1;
335 return Segment.Offset <= Section.OriginalOffset &&
336 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
339 // Returns true IFF a segment's original offset is inside of another segment's
341 static bool segmentOverlapsSegment(const Segment &Child,
342 const Segment &Parent) {
344 return Parent.OriginalOffset <= Child.OriginalOffset &&
345 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
348 static bool compareSegments(const Segment *A, const Segment *B) {
349 // Any segment without a parent segment should come before a segment
350 // that has a parent segment.
351 if (A->OriginalOffset < B->OriginalOffset)
353 if (A->OriginalOffset > B->OriginalOffset)
355 return A->Index < B->Index;
358 template <class ELFT>
359 void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
361 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
362 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
363 (size_t)Phdr.p_filesz};
364 Segments.emplace_back(llvm::make_unique<Segment>(Data));
365 Segment &Seg = *Segments.back();
366 Seg.Type = Phdr.p_type;
367 Seg.Flags = Phdr.p_flags;
368 Seg.OriginalOffset = Phdr.p_offset;
369 Seg.Offset = Phdr.p_offset;
370 Seg.VAddr = Phdr.p_vaddr;
371 Seg.PAddr = Phdr.p_paddr;
372 Seg.FileSize = Phdr.p_filesz;
373 Seg.MemSize = Phdr.p_memsz;
374 Seg.Align = Phdr.p_align;
376 for (auto &Section : Sections) {
377 if (sectionWithinSegment(*Section, Seg)) {
378 Seg.addSection(&*Section);
379 if (!Section->ParentSegment ||
380 Section->ParentSegment->Offset > Seg.Offset) {
381 Section->ParentSegment = &Seg;
386 // Now we do an O(n^2) loop through the segments in order to match up
388 for (auto &Child : Segments) {
389 for (auto &Parent : Segments) {
390 // Every segment will overlap with itself but we don't want a segment to
391 // be it's own parent so we avoid that situation.
392 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
393 // We want a canonical "most parental" segment but this requires
394 // inspecting the ParentSegment.
395 if (compareSegments(Parent.get(), Child.get()))
396 if (Child->ParentSegment == nullptr ||
397 compareSegments(Parent.get(), Child->ParentSegment)) {
398 Child->ParentSegment = Parent.get();
405 template <class ELFT>
406 void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
407 SymbolTableSection *SymTab,
408 SectionTableRef SecTable) {
409 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
410 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
412 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
413 SectionBase *DefSection = nullptr;
414 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
416 if (Sym.st_shndx >= SHN_LORESERVE) {
417 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
420 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
421 Twine(Sym.st_shndx));
423 } else if (Sym.st_shndx != SHN_UNDEF) {
424 DefSection = SecTable.getSection(
426 "Symbol '" + Name + "' is defined in invalid section with index " +
427 Twine(Sym.st_shndx));
430 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
431 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
435 template <class ELFT>
436 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
438 template <class ELFT>
439 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
440 ToSet = Rela.r_addend;
443 template <class ELFT, class T>
444 void initRelocations(RelocationSection<ELFT> *Relocs,
445 SymbolTableSection *SymbolTable, T RelRange) {
446 for (const auto &Rel : RelRange) {
448 ToAdd.Offset = Rel.r_offset;
449 getAddend(ToAdd.Addend, Rel);
450 ToAdd.Type = Rel.getType(false);
451 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
452 Relocs->addRelocation(ToAdd);
456 SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
457 if (Index == SHN_UNDEF || Index > Sections.size())
459 return Sections[Index - 1].get();
463 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
465 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
470 template <class ELFT>
471 std::unique_ptr<SectionBase>
472 Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
473 const Elf_Shdr &Shdr) {
474 ArrayRef<uint8_t> Data;
475 switch (Shdr.sh_type) {
478 if (Shdr.sh_flags & SHF_ALLOC) {
479 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
480 return llvm::make_unique<DynamicRelocationSection>(Data);
482 return llvm::make_unique<RelocationSection<ELFT>>();
484 // If a string table is allocated we don't want to mess with it. That would
485 // mean altering the memory image. There are no special link types or
486 // anything so we can just use a Section.
487 if (Shdr.sh_flags & SHF_ALLOC) {
488 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
489 return llvm::make_unique<Section>(Data);
491 return llvm::make_unique<StringTableSection>();
494 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
495 // Because of this we don't need to mess with the hash tables either.
496 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
497 return llvm::make_unique<Section>(Data);
499 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
500 return llvm::make_unique<DynamicSymbolTableSection>(Data);
502 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
503 return llvm::make_unique<DynamicSection>(Data);
505 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
506 SymbolTable = SymTab.get();
507 return std::move(SymTab);
510 return llvm::make_unique<Section>(Data);
512 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
513 return llvm::make_unique<Section>(Data);
517 template <class ELFT>
518 SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
520 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
525 SecPtr Sec = makeSection(ElfFile, Shdr);
526 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
527 Sec->Type = Shdr.sh_type;
528 Sec->Flags = Shdr.sh_flags;
529 Sec->Addr = Shdr.sh_addr;
530 Sec->Offset = Shdr.sh_offset;
531 Sec->OriginalOffset = Shdr.sh_offset;
532 Sec->Size = Shdr.sh_size;
533 Sec->Link = Shdr.sh_link;
534 Sec->Info = Shdr.sh_info;
535 Sec->Align = Shdr.sh_addralign;
536 Sec->EntrySize = Shdr.sh_entsize;
537 Sec->Index = Index++;
538 Sections.push_back(std::move(Sec));
541 SectionTableRef SecTable(Sections);
543 // Now that all of the sections have been added we can fill out some extra
544 // details about symbol tables. We need the symbol table filled out before
547 SymbolTable->initialize(SecTable);
548 initSymbolTable(ElfFile, SymbolTable, SecTable);
551 // Now that all sections and symbols have been added we can add
552 // relocations that reference symbols and set the link and info fields for
553 // relocation sections.
554 for (auto &Section : Sections) {
555 if (Section.get() == SymbolTable)
557 Section->initialize(SecTable);
558 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
559 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
560 if (RelSec->Type == SHT_REL)
561 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
563 initRelocations(RelSec, SymbolTable,
564 unwrapOrError(ElfFile.relas(Shdr)));
571 template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
572 const auto &ElfFile = *Obj.getELFFile();
573 const auto &Ehdr = *ElfFile.getHeader();
575 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
577 Machine = Ehdr.e_machine;
578 Version = Ehdr.e_version;
579 Entry = Ehdr.e_entry;
580 Flags = Ehdr.e_flags;
582 SectionTableRef SecTable = readSectionHeaders(ElfFile);
583 readProgramHeaders(ElfFile);
585 SectionNames = SecTable.getSectionOfType<StringTableSection>(
587 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
589 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
590 " is not a string table");
593 template <class ELFT>
594 void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
595 uint8_t *Buf = Out.getBufferStart();
596 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
597 std::copy(Ident, Ident + 16, Ehdr.e_ident);
599 Ehdr.e_machine = Machine;
600 Ehdr.e_version = Version;
601 Ehdr.e_entry = Entry;
602 Ehdr.e_phoff = sizeof(Elf_Ehdr);
603 Ehdr.e_flags = Flags;
604 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
605 Ehdr.e_phentsize = sizeof(Elf_Phdr);
606 Ehdr.e_phnum = Segments.size();
607 Ehdr.e_shentsize = sizeof(Elf_Shdr);
608 if (WriteSectionHeaders) {
609 Ehdr.e_shoff = SHOffset;
610 Ehdr.e_shnum = Sections.size() + 1;
611 Ehdr.e_shstrndx = SectionNames->Index;
619 template <class ELFT>
620 void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
621 for (auto &Phdr : Segments)
622 Phdr->template writeHeader<ELFT>(Out);
625 template <class ELFT>
626 void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
627 uint8_t *Buf = Out.getBufferStart() + SHOffset;
628 // This reference serves to write the dummy section header at the begining
629 // of the file. It is not used for anything else
630 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
632 Shdr.sh_type = SHT_NULL;
639 Shdr.sh_addralign = 0;
642 for (auto &Section : Sections)
643 Section->template writeHeader<ELFT>(Out);
646 template <class ELFT>
647 void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
648 for (auto &Section : Sections)
649 Section->writeSection(Out);
652 template <class ELFT>
653 void Object<ELFT>::removeSections(
654 std::function<bool(const SectionBase &)> ToRemove) {
656 auto Iter = std::stable_partition(
657 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
660 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
661 if (auto ToRelSec = RelSec->getSection())
662 return !ToRemove(*ToRelSec);
666 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
667 SymbolTable = nullptr;
668 if (ToRemove(*SectionNames)) {
669 if (WriteSectionHeaders)
670 error("Cannot remove " + SectionNames->Name +
671 " because it is the section header string table.");
672 SectionNames = nullptr;
674 // Now make sure there are no remaining references to the sections that will
675 // be removed. Sometimes it is impossible to remove a reference so we emit
676 // an error here instead.
677 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
678 for (auto &Segment : Segments)
679 Segment->removeSection(RemoveSec.get());
680 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
681 KeepSec->removeSectionReferences(RemoveSec.get());
683 // Now finally get rid of them all togethor.
684 Sections.erase(Iter, std::end(Sections));
687 template <class ELFT>
688 void Object<ELFT>::addSection(StringRef SecName, ArrayRef<uint8_t> Data) {
689 auto Sec = llvm::make_unique<OwnedDataSection>(SecName, Data);
690 Sec->OriginalOffset = ~0ULL;
691 Sections.push_back(std::move(Sec));
694 template <class ELFT> void ELFObject<ELFT>::sortSections() {
695 // Put all sections in offset order. Maintain the ordering as closely as
696 // possible while meeting that demand however.
697 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
698 return A->OriginalOffset < B->OriginalOffset;
700 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
704 static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
705 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
709 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
710 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
711 // (Offset + Diff) & -Align == Addr & -Align will still hold.
714 return Offset + Diff;
717 // Orders segments such that if x = y->ParentSegment then y comes before x.
718 static void OrderSegments(std::vector<Segment *> &Segments) {
719 std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
722 // This function finds a consistent layout for a list of segments starting from
723 // an Offset. It assumes that Segments have been sorted by OrderSegments and
724 // returns an Offset one past the end of the last segment.
725 static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
727 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
729 // The only way a segment should move is if a section was between two
730 // segments and that section was removed. If that section isn't in a segment
731 // then it's acceptable, but not ideal, to simply move it to after the
732 // segments. So we can simply layout segments one after the other accounting
734 for (auto &Segment : Segments) {
735 // We assume that segments have been ordered by OriginalOffset and Index
736 // such that a parent segment will always come before a child segment in
737 // OrderedSegments. This means that the Offset of the ParentSegment should
738 // already be set and we can set our offset relative to it.
739 if (Segment->ParentSegment != nullptr) {
740 auto Parent = Segment->ParentSegment;
742 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
744 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
745 Segment->Offset = Offset;
747 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
752 // This function finds a consistent layout for a list of sections. It assumes
753 // that the ->ParentSegment of each section has already been laid out. The
754 // supplied starting Offset is used for the starting offset of any section that
755 // does not have a ParentSegment. It returns either the offset given if all
756 // sections had a ParentSegment or an offset one past the last section if there
757 // was a section that didn't have a ParentSegment.
758 template <class SecPtr>
759 static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
760 // Now the offset of every segment has been set we can assign the offsets
761 // of each section. For sections that are covered by a segment we should use
762 // the segment's original offset and the section's original offset to compute
763 // the offset from the start of the segment. Using the offset from the start
764 // of the segment we can assign a new offset to the section. For sections not
765 // covered by segments we can just bump Offset to the next valid location.
767 for (auto &Section : Sections) {
768 Section->Index = Index++;
769 if (Section->ParentSegment != nullptr) {
770 auto Segment = Section->ParentSegment;
772 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
774 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
775 Section->Offset = Offset;
776 if (Section->Type != SHT_NOBITS)
777 Offset += Section->Size;
783 template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
784 // We need a temporary list of segments that has a special order to it
785 // so that we know that anytime ->ParentSegment is set that segment has
786 // already had its offset properly set.
787 std::vector<Segment *> OrderedSegments;
788 for (auto &Segment : this->Segments)
789 OrderedSegments.push_back(Segment.get());
790 OrderSegments(OrderedSegments);
791 // The size of ELF + program headers will not change so it is ok to assume
792 // that the first offset of the first segment is a good place to start
793 // outputting sections. This covers both the standard case and the PT_PHDR
796 if (!OrderedSegments.empty()) {
797 Offset = OrderedSegments[0]->Offset;
799 Offset = sizeof(Elf_Ehdr);
801 Offset = LayoutSegments(OrderedSegments, Offset);
802 Offset = LayoutSections(this->Sections, Offset);
803 // If we need to write the section header table out then we need to align the
804 // Offset so that SHOffset is valid.
805 if (this->WriteSectionHeaders)
806 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
807 this->SHOffset = Offset;
810 template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
811 // We already have the section header offset so we can calculate the total
812 // size by just adding up the size of each section header.
813 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
814 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
818 template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
819 this->writeHeader(Out);
820 this->writeProgramHeaders(Out);
821 this->writeSectionData(Out);
822 if (this->WriteSectionHeaders)
823 this->writeSectionHeaders(Out);
826 template <class ELFT> void ELFObject<ELFT>::finalize() {
827 // Make sure we add the names of all the sections.
828 if (this->SectionNames != nullptr)
829 for (const auto &Section : this->Sections) {
830 this->SectionNames->addString(Section->Name);
832 // Make sure we add the names of all the symbols.
833 if (this->SymbolTable != nullptr)
834 this->SymbolTable->addSymbolNames();
839 // Finalize SectionNames first so that we can assign name indexes.
840 if (this->SectionNames != nullptr)
841 this->SectionNames->finalize();
842 // Finally now that all offsets and indexes have been set we can finalize any
844 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
845 for (auto &Section : this->Sections) {
846 Section->HeaderOffset = Offset;
847 Offset += sizeof(Elf_Shdr);
848 if (this->WriteSectionHeaders)
849 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
854 template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
858 template <class ELFT>
859 void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
860 for (auto &Section : this->Sections) {
861 if ((Section->Flags & SHF_ALLOC) == 0)
863 Section->writeSection(Out);
867 template <class ELFT> void BinaryObject<ELFT>::finalize() {
868 // TODO: Create a filter range to construct OrderedSegments from so that this
869 // code can be deduped with assignOffsets above. This should also solve the
870 // todo below for LayoutSections.
871 // We need a temporary list of segments that has a special order to it
872 // so that we know that anytime ->ParentSegment is set that segment has
873 // already had it's offset properly set. We only want to consider the segments
874 // that will affect layout of allocated sections so we only add those.
875 std::vector<Segment *> OrderedSegments;
876 for (auto &Section : this->Sections) {
877 if ((Section->Flags & SHF_ALLOC) != 0 &&
878 Section->ParentSegment != nullptr) {
879 OrderedSegments.push_back(Section->ParentSegment);
882 OrderSegments(OrderedSegments);
883 // Because we add a ParentSegment for each section we might have duplicate
884 // segments in OrderedSegments. If there were duplicates then LayoutSegments
885 // would do very strange things.
887 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
888 OrderedSegments.erase(End, std::end(OrderedSegments));
890 // Modify the first segment so that there is no gap at the start. This allows
891 // our layout algorithm to proceed as expected while not out writing out the
893 if (!OrderedSegments.empty()) {
894 auto Seg = OrderedSegments[0];
895 auto Sec = Seg->firstSection();
896 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
897 Seg->OriginalOffset += Diff;
898 // The size needs to be shrunk as well
899 Seg->FileSize -= Diff;
900 Seg->MemSize -= Diff;
901 // The VAddr needs to be adjusted so that the alignment is correct as well
903 Seg->PAddr = Seg->VAddr;
904 // We don't want this to be shifted by alignment so we need to set the
905 // alignment to zero.
909 uint64_t Offset = LayoutSegments(OrderedSegments, 0);
911 // TODO: generalize LayoutSections to take a range. Pass a special range
912 // constructed from an iterator that skips values for which a predicate does
913 // not hold. Then pass such a range to LayoutSections instead of constructing
914 // AllocatedSections here.
915 std::vector<SectionBase *> AllocatedSections;
916 for (auto &Section : this->Sections) {
917 if ((Section->Flags & SHF_ALLOC) == 0)
919 AllocatedSections.push_back(Section.get());
921 LayoutSections(AllocatedSections, Offset);
923 // Now that every section has been laid out we just need to compute the total
924 // file size. This might not be the same as the offset returned by
925 // LayoutSections, because we want to truncate the last segment to the end of
926 // its last section, to match GNU objcopy's behaviour.
928 for (const auto &Section : AllocatedSections) {
929 if (Section->Type != SHT_NOBITS)
930 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
936 template class Object<ELF64LE>;
937 template class Object<ELF64BE>;
938 template class Object<ELF32LE>;
939 template class Object<ELF32BE>;
941 template class ELFObject<ELF64LE>;
942 template class ELFObject<ELF64BE>;
943 template class ELFObject<ELF32LE>;
944 template class ELFObject<ELF32BE>;
946 template class BinaryObject<ELF64LE>;
947 template class BinaryObject<ELF64BE>;
948 template class BinaryObject<ELF32LE>;
949 template class BinaryObject<ELF32BE>;
951 } // end namespace llvm