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 uint16_t Shndx, uint64_t Sz) {
149 Sym.DefinedIn = DefinedIn;
150 if (DefinedIn == nullptr) {
151 if (Shndx >= SHN_LORESERVE)
152 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
154 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
158 Sym.Index = Symbols.size();
159 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
160 Size += this->EntrySize;
163 void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
164 if (SymbolNames == Sec) {
165 error("String table " + SymbolNames->Name +
166 " cannot be removed because it is referenced by the symbol table " +
170 std::remove_if(std::begin(Symbols), std::end(Symbols),
171 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
172 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
173 Symbols.erase(Iter, std::end(Symbols));
176 void SymbolTableSection::initialize(SectionTableRef SecTable) {
178 setStrTab(SecTable.getSectionOfType<StringTableSection>(
180 "Symbol table has link index of " + Twine(Link) +
181 " which is not a valid index",
182 "Symbol table has link index of " + Twine(Link) +
183 " which is not a string table"));
186 void SymbolTableSection::finalize() {
187 // Make sure SymbolNames is finalized before getting name indexes.
188 SymbolNames->finalize();
190 uint32_t MaxLocalIndex = 0;
191 for (auto &Sym : Symbols) {
192 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
193 if (Sym->Binding == STB_LOCAL)
194 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
196 // Now we need to set the Link and Info fields.
197 Link = SymbolNames->Index;
198 Info = MaxLocalIndex + 1;
201 void SymbolTableSection::addSymbolNames() {
202 // Add all of our strings to SymbolNames so that SymbolNames has the right
203 // size before layout is decided.
204 for (auto &Sym : Symbols)
205 SymbolNames->addString(Sym->Name);
208 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
209 if (Symbols.size() <= Index)
210 error("Invalid symbol index: " + Twine(Index));
211 return Symbols[Index].get();
214 template <class ELFT>
215 void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
216 uint8_t *Buf = Out.getBufferStart();
218 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
219 // Loop though symbols setting each entry of the symbol table.
220 for (auto &Symbol : Symbols) {
221 Sym->st_name = Symbol->NameIndex;
222 Sym->st_value = Symbol->Value;
223 Sym->st_size = Symbol->Size;
224 Sym->setBinding(Symbol->Binding);
225 Sym->setType(Symbol->Type);
226 Sym->st_shndx = Symbol->getShndx();
231 template <class SymTabType>
232 void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
233 const SectionBase *Sec) {
234 if (Symbols == Sec) {
235 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
236 "referenced by the relocation "
242 template <class SymTabType>
243 void RelocSectionWithSymtabBase<SymTabType>::initialize(
244 SectionTableRef SecTable) {
245 setSymTab(SecTable.getSectionOfType<SymTabType>(
247 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
248 "Link field value " + Twine(Link) + " in section " + Name +
249 " is not a symbol table"));
251 if (Info != SHN_UNDEF)
252 setSection(SecTable.getSection(Info,
253 "Info field value " + Twine(Info) +
254 " in section " + Name + " is invalid"));
259 template <class SymTabType>
260 void RelocSectionWithSymtabBase<SymTabType>::finalize() {
261 this->Link = Symbols->Index;
262 if (SecToApplyRel != nullptr)
263 this->Info = SecToApplyRel->Index;
266 template <class ELFT>
267 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
269 template <class ELFT>
270 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
271 Rela.r_addend = Addend;
274 template <class ELFT>
276 void RelocationSection<ELFT>::writeRel(T *Buf) const {
277 for (const auto &Reloc : Relocations) {
278 Buf->r_offset = Reloc.Offset;
279 setAddend(*Buf, Reloc.Addend);
280 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
285 template <class ELFT>
286 void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
287 uint8_t *Buf = Out.getBufferStart() + Offset;
289 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
291 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
294 void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
295 std::copy(std::begin(Contents), std::end(Contents),
296 Out.getBufferStart() + Offset);
299 void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
301 error("String table " + StrTab->Name + " cannot be removed because it is "
302 "referenced by the section " +
307 bool SectionWithStrTab::classof(const SectionBase *S) {
308 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
311 void SectionWithStrTab::initialize(SectionTableRef SecTable) {
312 auto StrTab = SecTable.getSection(Link,
313 "Link field value " + Twine(Link) +
314 " in section " + Name + " is invalid");
315 if (StrTab->Type != SHT_STRTAB) {
316 error("Link field value " + Twine(Link) + " in section " + Name +
317 " is not a string table");
322 void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
324 // Returns true IFF a section is wholly inside the range of a segment
325 static bool sectionWithinSegment(const SectionBase &Section,
326 const Segment &Segment) {
327 // If a section is empty it should be treated like it has a size of 1. This is
328 // to clarify the case when an empty section lies on a boundary between two
329 // segments and ensures that the section "belongs" to the second segment and
331 uint64_t SecSize = Section.Size ? Section.Size : 1;
332 return Segment.Offset <= Section.OriginalOffset &&
333 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
336 // Returns true IFF a segment's original offset is inside of another segment's
338 static bool segmentOverlapsSegment(const Segment &Child,
339 const Segment &Parent) {
341 return Parent.OriginalOffset <= Child.OriginalOffset &&
342 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
345 static bool compareSegments(const Segment *A, const Segment *B) {
346 // Any segment without a parent segment should come before a segment
347 // that has a parent segment.
348 if (A->OriginalOffset < B->OriginalOffset)
350 if (A->OriginalOffset > B->OriginalOffset)
352 return A->Index < B->Index;
355 template <class ELFT>
356 void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
358 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
359 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
360 (size_t)Phdr.p_filesz};
361 Segments.emplace_back(llvm::make_unique<Segment>(Data));
362 Segment &Seg = *Segments.back();
363 Seg.Type = Phdr.p_type;
364 Seg.Flags = Phdr.p_flags;
365 Seg.OriginalOffset = Phdr.p_offset;
366 Seg.Offset = Phdr.p_offset;
367 Seg.VAddr = Phdr.p_vaddr;
368 Seg.PAddr = Phdr.p_paddr;
369 Seg.FileSize = Phdr.p_filesz;
370 Seg.MemSize = Phdr.p_memsz;
371 Seg.Align = Phdr.p_align;
373 for (auto &Section : Sections) {
374 if (sectionWithinSegment(*Section, Seg)) {
375 Seg.addSection(&*Section);
376 if (!Section->ParentSegment ||
377 Section->ParentSegment->Offset > Seg.Offset) {
378 Section->ParentSegment = &Seg;
383 // Now we do an O(n^2) loop through the segments in order to match up
385 for (auto &Child : Segments) {
386 for (auto &Parent : Segments) {
387 // Every segment will overlap with itself but we don't want a segment to
388 // be it's own parent so we avoid that situation.
389 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
390 // We want a canonical "most parental" segment but this requires
391 // inspecting the ParentSegment.
392 if (compareSegments(Parent.get(), Child.get()))
393 if (Child->ParentSegment == nullptr ||
394 compareSegments(Parent.get(), Child->ParentSegment)) {
395 Child->ParentSegment = Parent.get();
402 template <class ELFT>
403 void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
404 SymbolTableSection *SymTab,
405 SectionTableRef SecTable) {
406 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
407 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
409 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
410 SectionBase *DefSection = nullptr;
411 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
413 if (Sym.st_shndx >= SHN_LORESERVE) {
414 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
417 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
418 Twine(Sym.st_shndx));
420 } else if (Sym.st_shndx != SHN_UNDEF) {
421 DefSection = SecTable.getSection(
423 "Symbol '" + Name + "' is defined in invalid section with index " +
424 Twine(Sym.st_shndx));
427 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
428 Sym.getValue(), Sym.st_shndx, Sym.st_size);
432 template <class ELFT>
433 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
435 template <class ELFT>
436 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
437 ToSet = Rela.r_addend;
440 template <class ELFT, class T>
441 void initRelocations(RelocationSection<ELFT> *Relocs,
442 SymbolTableSection *SymbolTable, T RelRange) {
443 for (const auto &Rel : RelRange) {
445 ToAdd.Offset = Rel.r_offset;
446 getAddend(ToAdd.Addend, Rel);
447 ToAdd.Type = Rel.getType(false);
448 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
449 Relocs->addRelocation(ToAdd);
453 SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
454 if (Index == SHN_UNDEF || Index > Sections.size())
456 return Sections[Index - 1].get();
460 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
462 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
467 template <class ELFT>
468 std::unique_ptr<SectionBase>
469 Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
470 const Elf_Shdr &Shdr) {
471 ArrayRef<uint8_t> Data;
472 switch (Shdr.sh_type) {
475 if (Shdr.sh_flags & SHF_ALLOC) {
476 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
477 return llvm::make_unique<DynamicRelocationSection>(Data);
479 return llvm::make_unique<RelocationSection<ELFT>>();
481 // If a string table is allocated we don't want to mess with it. That would
482 // mean altering the memory image. There are no special link types or
483 // anything so we can just use a Section.
484 if (Shdr.sh_flags & SHF_ALLOC) {
485 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
486 return llvm::make_unique<Section>(Data);
488 return llvm::make_unique<StringTableSection>();
491 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
492 // Because of this we don't need to mess with the hash tables either.
493 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
494 return llvm::make_unique<Section>(Data);
496 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
497 return llvm::make_unique<DynamicSymbolTableSection>(Data);
499 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
500 return llvm::make_unique<DynamicSection>(Data);
502 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
503 SymbolTable = SymTab.get();
504 return std::move(SymTab);
507 return llvm::make_unique<Section>(Data);
509 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
510 return llvm::make_unique<Section>(Data);
514 template <class ELFT>
515 SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
517 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
522 SecPtr Sec = makeSection(ElfFile, Shdr);
523 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
524 Sec->Type = Shdr.sh_type;
525 Sec->Flags = Shdr.sh_flags;
526 Sec->Addr = Shdr.sh_addr;
527 Sec->Offset = Shdr.sh_offset;
528 Sec->OriginalOffset = Shdr.sh_offset;
529 Sec->Size = Shdr.sh_size;
530 Sec->Link = Shdr.sh_link;
531 Sec->Info = Shdr.sh_info;
532 Sec->Align = Shdr.sh_addralign;
533 Sec->EntrySize = Shdr.sh_entsize;
534 Sec->Index = Index++;
535 Sections.push_back(std::move(Sec));
538 SectionTableRef SecTable(Sections);
540 // Now that all of the sections have been added we can fill out some extra
541 // details about symbol tables. We need the symbol table filled out before
544 SymbolTable->initialize(SecTable);
545 initSymbolTable(ElfFile, SymbolTable, SecTable);
548 // Now that all sections and symbols have been added we can add
549 // relocations that reference symbols and set the link and info fields for
550 // relocation sections.
551 for (auto &Section : Sections) {
552 if (Section.get() == SymbolTable)
554 Section->initialize(SecTable);
555 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
556 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
557 if (RelSec->Type == SHT_REL)
558 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
560 initRelocations(RelSec, SymbolTable,
561 unwrapOrError(ElfFile.relas(Shdr)));
568 template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
569 const auto &ElfFile = *Obj.getELFFile();
570 const auto &Ehdr = *ElfFile.getHeader();
572 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
574 Machine = Ehdr.e_machine;
575 Version = Ehdr.e_version;
576 Entry = Ehdr.e_entry;
577 Flags = Ehdr.e_flags;
579 SectionTableRef SecTable = readSectionHeaders(ElfFile);
580 readProgramHeaders(ElfFile);
582 SectionNames = SecTable.getSectionOfType<StringTableSection>(
584 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
586 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
587 " is not a string table");
590 template <class ELFT>
591 void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
592 uint8_t *Buf = Out.getBufferStart();
593 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
594 std::copy(Ident, Ident + 16, Ehdr.e_ident);
596 Ehdr.e_machine = Machine;
597 Ehdr.e_version = Version;
598 Ehdr.e_entry = Entry;
599 Ehdr.e_phoff = sizeof(Elf_Ehdr);
600 Ehdr.e_flags = Flags;
601 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
602 Ehdr.e_phentsize = sizeof(Elf_Phdr);
603 Ehdr.e_phnum = Segments.size();
604 Ehdr.e_shentsize = sizeof(Elf_Shdr);
605 if (WriteSectionHeaders) {
606 Ehdr.e_shoff = SHOffset;
607 Ehdr.e_shnum = Sections.size() + 1;
608 Ehdr.e_shstrndx = SectionNames->Index;
616 template <class ELFT>
617 void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
618 for (auto &Phdr : Segments)
619 Phdr->template writeHeader<ELFT>(Out);
622 template <class ELFT>
623 void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
624 uint8_t *Buf = Out.getBufferStart() + SHOffset;
625 // This reference serves to write the dummy section header at the begining
626 // of the file. It is not used for anything else
627 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
629 Shdr.sh_type = SHT_NULL;
636 Shdr.sh_addralign = 0;
639 for (auto &Section : Sections)
640 Section->template writeHeader<ELFT>(Out);
643 template <class ELFT>
644 void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
645 for (auto &Section : Sections)
646 Section->writeSection(Out);
649 template <class ELFT>
650 void Object<ELFT>::removeSections(
651 std::function<bool(const SectionBase &)> ToRemove) {
653 auto Iter = std::stable_partition(
654 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
657 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
658 if (auto ToRelSec = RelSec->getSection())
659 return !ToRemove(*ToRelSec);
663 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
664 SymbolTable = nullptr;
665 if (ToRemove(*SectionNames)) {
666 if (WriteSectionHeaders)
667 error("Cannot remove " + SectionNames->Name +
668 " because it is the section header string table.");
669 SectionNames = nullptr;
671 // Now make sure there are no remaining references to the sections that will
672 // be removed. Sometimes it is impossible to remove a reference so we emit
673 // an error here instead.
674 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
675 for (auto &Segment : Segments)
676 Segment->removeSection(RemoveSec.get());
677 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
678 KeepSec->removeSectionReferences(RemoveSec.get());
680 // Now finally get rid of them all togethor.
681 Sections.erase(Iter, std::end(Sections));
684 template <class ELFT>
685 void Object<ELFT>::addSection(StringRef SecName, ArrayRef<uint8_t> Data) {
686 auto Sec = llvm::make_unique<OwnedDataSection>(SecName, Data);
687 Sec->OriginalOffset = ~0ULL;
688 Sections.push_back(std::move(Sec));
691 template <class ELFT> void ELFObject<ELFT>::sortSections() {
692 // Put all sections in offset order. Maintain the ordering as closely as
693 // possible while meeting that demand however.
694 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
695 return A->OriginalOffset < B->OriginalOffset;
697 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
701 static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
702 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
706 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
707 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
708 // (Offset + Diff) & -Align == Addr & -Align will still hold.
711 return Offset + Diff;
714 // Orders segments such that if x = y->ParentSegment then y comes before x.
715 static void OrderSegments(std::vector<Segment *> &Segments) {
716 std::stable_sort(std::begin(Segments), std::end(Segments), compareSegments);
719 // This function finds a consistent layout for a list of segments starting from
720 // an Offset. It assumes that Segments have been sorted by OrderSegments and
721 // returns an Offset one past the end of the last segment.
722 static uint64_t LayoutSegments(std::vector<Segment *> &Segments,
724 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
726 // The only way a segment should move is if a section was between two
727 // segments and that section was removed. If that section isn't in a segment
728 // then it's acceptable, but not ideal, to simply move it to after the
729 // segments. So we can simply layout segments one after the other accounting
731 for (auto &Segment : Segments) {
732 // We assume that segments have been ordered by OriginalOffset and Index
733 // such that a parent segment will always come before a child segment in
734 // OrderedSegments. This means that the Offset of the ParentSegment should
735 // already be set and we can set our offset relative to it.
736 if (Segment->ParentSegment != nullptr) {
737 auto Parent = Segment->ParentSegment;
739 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
741 Offset = alignToAddr(Offset, Segment->VAddr, Segment->Align);
742 Segment->Offset = Offset;
744 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
749 // This function finds a consistent layout for a list of sections. It assumes
750 // that the ->ParentSegment of each section has already been laid out. The
751 // supplied starting Offset is used for the starting offset of any section that
752 // does not have a ParentSegment. It returns either the offset given if all
753 // sections had a ParentSegment or an offset one past the last section if there
754 // was a section that didn't have a ParentSegment.
755 template <class SecPtr>
756 static uint64_t LayoutSections(std::vector<SecPtr> &Sections, uint64_t Offset) {
757 // Now the offset of every segment has been set we can assign the offsets
758 // of each section. For sections that are covered by a segment we should use
759 // the segment's original offset and the section's original offset to compute
760 // the offset from the start of the segment. Using the offset from the start
761 // of the segment we can assign a new offset to the section. For sections not
762 // covered by segments we can just bump Offset to the next valid location.
764 for (auto &Section : Sections) {
765 Section->Index = Index++;
766 if (Section->ParentSegment != nullptr) {
767 auto Segment = Section->ParentSegment;
769 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
771 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
772 Section->Offset = Offset;
773 if (Section->Type != SHT_NOBITS)
774 Offset += Section->Size;
780 template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
781 // We need a temporary list of segments that has a special order to it
782 // so that we know that anytime ->ParentSegment is set that segment has
783 // already had its offset properly set.
784 std::vector<Segment *> OrderedSegments;
785 for (auto &Segment : this->Segments)
786 OrderedSegments.push_back(Segment.get());
787 OrderSegments(OrderedSegments);
788 // The size of ELF + program headers will not change so it is ok to assume
789 // that the first offset of the first segment is a good place to start
790 // outputting sections. This covers both the standard case and the PT_PHDR
793 if (!OrderedSegments.empty()) {
794 Offset = OrderedSegments[0]->Offset;
796 Offset = sizeof(Elf_Ehdr);
798 Offset = LayoutSegments(OrderedSegments, Offset);
799 Offset = LayoutSections(this->Sections, Offset);
800 // If we need to write the section header table out then we need to align the
801 // Offset so that SHOffset is valid.
802 if (this->WriteSectionHeaders)
803 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
804 this->SHOffset = Offset;
807 template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
808 // We already have the section header offset so we can calculate the total
809 // size by just adding up the size of each section header.
810 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
811 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
815 template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
816 this->writeHeader(Out);
817 this->writeProgramHeaders(Out);
818 this->writeSectionData(Out);
819 if (this->WriteSectionHeaders)
820 this->writeSectionHeaders(Out);
823 template <class ELFT> void ELFObject<ELFT>::finalize() {
824 // Make sure we add the names of all the sections.
825 if (this->SectionNames != nullptr)
826 for (const auto &Section : this->Sections) {
827 this->SectionNames->addString(Section->Name);
829 // Make sure we add the names of all the symbols.
830 if (this->SymbolTable != nullptr)
831 this->SymbolTable->addSymbolNames();
836 // Finalize SectionNames first so that we can assign name indexes.
837 if (this->SectionNames != nullptr)
838 this->SectionNames->finalize();
839 // Finally now that all offsets and indexes have been set we can finalize any
841 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
842 for (auto &Section : this->Sections) {
843 Section->HeaderOffset = Offset;
844 Offset += sizeof(Elf_Shdr);
845 if (this->WriteSectionHeaders)
846 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
851 template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
855 template <class ELFT>
856 void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
857 for (auto &Section : this->Sections) {
858 if ((Section->Flags & SHF_ALLOC) == 0)
860 Section->writeSection(Out);
864 template <class ELFT> void BinaryObject<ELFT>::finalize() {
865 // TODO: Create a filter range to construct OrderedSegments from so that this
866 // code can be deduped with assignOffsets above. This should also solve the
867 // todo below for LayoutSections.
868 // We need a temporary list of segments that has a special order to it
869 // so that we know that anytime ->ParentSegment is set that segment has
870 // already had it's offset properly set. We only want to consider the segments
871 // that will affect layout of allocated sections so we only add those.
872 std::vector<Segment *> OrderedSegments;
873 for (auto &Section : this->Sections) {
874 if ((Section->Flags & SHF_ALLOC) != 0 &&
875 Section->ParentSegment != nullptr) {
876 OrderedSegments.push_back(Section->ParentSegment);
879 OrderSegments(OrderedSegments);
880 // Because we add a ParentSegment for each section we might have duplicate
881 // segments in OrderedSegments. If there were duplicates then LayoutSegments
882 // would do very strange things.
884 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
885 OrderedSegments.erase(End, std::end(OrderedSegments));
887 // Modify the first segment so that there is no gap at the start. This allows
888 // our layout algorithm to proceed as expected while not out writing out the
890 if (!OrderedSegments.empty()) {
891 auto Seg = OrderedSegments[0];
892 auto Sec = Seg->firstSection();
893 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
894 Seg->OriginalOffset += Diff;
895 // The size needs to be shrunk as well
896 Seg->FileSize -= Diff;
897 Seg->MemSize -= Diff;
898 // The VAddr needs to be adjusted so that the alignment is correct as well
900 Seg->PAddr = Seg->VAddr;
901 // We don't want this to be shifted by alignment so we need to set the
902 // alignment to zero.
906 uint64_t Offset = LayoutSegments(OrderedSegments, 0);
908 // TODO: generalize LayoutSections to take a range. Pass a special range
909 // constructed from an iterator that skips values for which a predicate does
910 // not hold. Then pass such a range to LayoutSections instead of constructing
911 // AllocatedSections here.
912 std::vector<SectionBase *> AllocatedSections;
913 for (auto &Section : this->Sections) {
914 if ((Section->Flags & SHF_ALLOC) == 0)
916 AllocatedSections.push_back(Section.get());
918 LayoutSections(AllocatedSections, Offset);
920 // Now that every section has been laid out we just need to compute the total
921 // file size. This might not be the same as the offset returned by
922 // LayoutSections, because we want to truncate the last segment to the end of
923 // its last section, to match GNU objcopy's behaviour.
925 for (const auto &Section : AllocatedSections) {
926 if (Section->Type != SHT_NOBITS)
927 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
933 template class Object<ELF64LE>;
934 template class Object<ELF64BE>;
935 template class Object<ELF32LE>;
936 template class Object<ELF32BE>;
938 template class ELFObject<ELF64LE>;
939 template class ELFObject<ELF64BE>;
940 template class ELFObject<ELF32LE>;
941 template class ELFObject<ELF32BE>;
943 template class BinaryObject<ELF64LE>;
944 template class BinaryObject<ELF64BE>;
945 template class BinaryObject<ELF32LE>;
946 template class BinaryObject<ELF32BE>;
948 } // end namespace llvm