1 //===- Object.cpp -----------------------------------------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
10 #include "llvm-objcopy.h"
13 using namespace object;
16 template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
17 typedef typename ELFT::Ehdr Elf_Ehdr;
18 typedef typename ELFT::Phdr Elf_Phdr;
20 uint8_t *Buf = Out.getBufferStart();
21 Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
22 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
25 Phdr.p_offset = Offset;
28 Phdr.p_filesz = FileSize;
29 Phdr.p_memsz = MemSize;
33 void Segment::finalize() {
34 auto FirstSec = firstSection();
36 // It is possible for a gap to be at the begining of a segment. Because of
37 // this we need to compute the new offset based on how large this gap was
38 // in the source file. Section layout should have already ensured that this
39 // space is not used for something else.
40 uint64_t OriginalOffset = Offset;
41 Offset = FirstSec->Offset - (FirstSec->OriginalOffset - OriginalOffset);
45 void Segment::writeSegment(FileOutputBuffer &Out) const {
46 uint8_t *Buf = Out.getBufferStart() + Offset;
47 // We want to maintain segments' interstitial data and contents exactly.
48 // This lets us just copy segments directly.
49 std::copy(std::begin(Contents), std::end(Contents), Buf);
52 void SectionBase::finalize() {}
55 void SectionBase::writeHeader(FileOutputBuffer &Out) const {
56 uint8_t *Buf = Out.getBufferStart();
58 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
59 Shdr.sh_name = NameIndex;
61 Shdr.sh_flags = Flags;
63 Shdr.sh_offset = Offset;
67 Shdr.sh_addralign = Align;
68 Shdr.sh_entsize = EntrySize;
71 void Section::writeSection(FileOutputBuffer &Out) const {
72 if (Type == SHT_NOBITS)
74 uint8_t *Buf = Out.getBufferStart() + Offset;
75 std::copy(std::begin(Contents), std::end(Contents), Buf);
78 void StringTableSection::addString(StringRef Name) {
79 StrTabBuilder.add(Name);
80 Size = StrTabBuilder.getSize();
83 uint32_t StringTableSection::findIndex(StringRef Name) const {
84 return StrTabBuilder.getOffset(Name);
87 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
89 void StringTableSection::writeSection(FileOutputBuffer &Out) const {
90 StrTabBuilder.write(Out.getBufferStart() + Offset);
93 static bool isValidReservedSectionIndex(uint16_t Index) {
97 case SHN_HEXAGON_SCOMMON:
98 case SHN_HEXAGON_SCOMMON_2:
99 case SHN_HEXAGON_SCOMMON_4:
100 case SHN_HEXAGON_SCOMMON_8:
107 uint16_t Symbol::getShndx() const {
108 if (DefinedIn != nullptr) {
109 return DefinedIn->Index;
112 // This means that we don't have a defined section but we do need to
113 // output a legitimate section index.
114 case SYMBOL_SIMPLE_INDEX:
118 case SYMBOL_HEXAGON_SCOMMON:
119 case SYMBOL_HEXAGON_SCOMMON_2:
120 case SYMBOL_HEXAGON_SCOMMON_4:
121 case SYMBOL_HEXAGON_SCOMMON_8:
122 return static_cast<uint16_t>(ShndxType);
124 llvm_unreachable("Symbol with invalid ShndxType encountered");
127 void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
128 SectionBase *DefinedIn, uint64_t Value,
129 uint16_t Shndx, uint64_t Sz) {
134 Sym.DefinedIn = DefinedIn;
135 if (DefinedIn == nullptr) {
136 if (isValidReservedSectionIndex(Shndx))
137 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
139 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
143 Sym.Index = Symbols.size();
144 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
145 Size += this->EntrySize;
148 void SymbolTableSection::finalize() {
149 // Make sure SymbolNames is finalized before getting name indexes.
150 SymbolNames->finalize();
152 uint32_t MaxLocalIndex = 0;
153 for (auto &Sym : Symbols) {
154 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
155 if (Sym->Binding == STB_LOCAL)
156 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
158 // Now we need to set the Link and Info fields.
159 Link = SymbolNames->Index;
160 Info = MaxLocalIndex + 1;
163 void SymbolTableSection::addSymbolNames() {
164 // Add all of our strings to SymbolNames so that SymbolNames has the right
165 // size before layout is decided.
166 for (auto &Sym : Symbols)
167 SymbolNames->addString(Sym->Name);
170 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
171 if (Symbols.size() <= Index)
172 error("Invalid symbol index: " + Twine(Index));
173 return Symbols[Index].get();
176 template <class ELFT>
177 void SymbolTableSectionImpl<ELFT>::writeSection(
178 llvm::FileOutputBuffer &Out) const {
179 uint8_t *Buf = Out.getBufferStart();
181 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
182 // Loop though symbols setting each entry of the symbol table.
183 for (auto &Symbol : Symbols) {
184 Sym->st_name = Symbol->NameIndex;
185 Sym->st_value = Symbol->Value;
186 Sym->st_size = Symbol->Size;
187 Sym->setBinding(Symbol->Binding);
188 Sym->setType(Symbol->Type);
189 Sym->st_shndx = Symbol->getShndx();
194 template <class ELFT> void RelocationSection<ELFT>::finalize() {
195 this->Link = Symbols->Index;
196 this->Info = SecToApplyRel->Index;
199 template <class ELFT>
200 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
202 template <class ELFT>
203 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
204 Rela.r_addend = Addend;
207 template <class ELFT>
209 void RelocationSection<ELFT>::writeRel(T *Buf) const {
210 for (const auto &Reloc : Relocations) {
211 Buf->r_offset = Reloc.Offset;
212 setAddend(*Buf, Reloc.Addend);
213 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
218 template <class ELFT>
219 void RelocationSection<ELFT>::writeSection(llvm::FileOutputBuffer &Out) const {
220 uint8_t *Buf = Out.getBufferStart() + Offset;
222 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
224 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
227 // Returns true IFF a section is wholly inside the range of a segment
228 static bool sectionWithinSegment(const SectionBase &Section,
229 const Segment &Segment) {
230 // If a section is empty it should be treated like it has a size of 1. This is
231 // to clarify the case when an empty section lies on a boundary between two
232 // segments and ensures that the section "belongs" to the second segment and
234 uint64_t SecSize = Section.Size ? Section.Size : 1;
235 return Segment.Offset <= Section.OriginalOffset &&
236 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
239 template <class ELFT>
240 void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
242 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
243 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
244 (size_t)Phdr.p_filesz};
245 Segments.emplace_back(llvm::make_unique<Segment>(Data));
246 Segment &Seg = *Segments.back();
247 Seg.Type = Phdr.p_type;
248 Seg.Flags = Phdr.p_flags;
249 Seg.OriginalOffset = Phdr.p_offset;
250 Seg.Offset = Phdr.p_offset;
251 Seg.VAddr = Phdr.p_vaddr;
252 Seg.PAddr = Phdr.p_paddr;
253 Seg.FileSize = Phdr.p_filesz;
254 Seg.MemSize = Phdr.p_memsz;
255 Seg.Align = Phdr.p_align;
257 for (auto &Section : Sections) {
258 if (sectionWithinSegment(*Section, Seg)) {
259 Seg.addSection(&*Section);
260 if (!Section->ParentSegment ||
261 Section->ParentSegment->Offset > Seg.Offset) {
262 Section->ParentSegment = &Seg;
269 template <class ELFT>
270 void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
271 SymbolTableSection *SymTab) {
274 if (SymbolTable->Link - 1 >= Sections.size())
275 error("Symbol table has link index of " + Twine(SymbolTable->Link) +
276 " which is not a valid index");
279 dyn_cast<StringTableSection>(Sections[SymbolTable->Link - 1].get()))
280 SymTab->setStrTab(StrTab);
282 error("Symbol table has link index of " + Twine(SymbolTable->Link) +
283 "which is not a string table");
285 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
286 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
288 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
289 SectionBase *DefSection = nullptr;
290 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
291 if (Sym.st_shndx >= SHN_LORESERVE) {
292 if (!isValidReservedSectionIndex(Sym.st_shndx)) {
295 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
296 Twine(Sym.st_shndx));
298 } else if (Sym.st_shndx != SHN_UNDEF) {
299 if (Sym.st_shndx >= Sections.size())
300 error("Symbol '" + Name +
301 "' is defined in invalid section with index " +
302 Twine(Sym.st_shndx));
303 DefSection = Sections[Sym.st_shndx - 1].get();
305 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
306 Sym.getValue(), Sym.st_shndx, Sym.st_size);
310 template <class ELFT>
311 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
313 template <class ELFT>
314 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
315 ToSet = Rela.r_addend;
318 template <class ELFT, class T>
319 void initRelocations(RelocationSection<ELFT> *Relocs,
320 SymbolTableSection *SymbolTable, T RelRange) {
321 for (const auto &Rel : RelRange) {
323 ToAdd.Offset = Rel.r_offset;
324 getAddend(ToAdd.Addend, Rel);
325 ToAdd.Type = Rel.getType(false);
326 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
327 Relocs->addRelocation(ToAdd);
331 template <class ELFT>
332 std::unique_ptr<SectionBase>
333 Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
334 const Elf_Shdr &Shdr) {
335 ArrayRef<uint8_t> Data;
336 switch (Shdr.sh_type) {
339 return llvm::make_unique<RelocationSection<ELFT>>();
341 return llvm::make_unique<StringTableSection>();
343 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
344 SymbolTable = SymTab.get();
345 return std::move(SymTab);
348 return llvm::make_unique<Section>(Data);
350 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
351 return llvm::make_unique<Section>(Data);
355 template <class ELFT>
356 void Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
358 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
363 SecPtr Sec = makeSection(ElfFile, Shdr);
364 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
365 Sec->Type = Shdr.sh_type;
366 Sec->Flags = Shdr.sh_flags;
367 Sec->Addr = Shdr.sh_addr;
368 Sec->Offset = Shdr.sh_offset;
369 Sec->OriginalOffset = Shdr.sh_offset;
370 Sec->Size = Shdr.sh_size;
371 Sec->Link = Shdr.sh_link;
372 Sec->Info = Shdr.sh_info;
373 Sec->Align = Shdr.sh_addralign;
374 Sec->EntrySize = Shdr.sh_entsize;
375 Sec->Index = Index++;
376 Sections.push_back(std::move(Sec));
379 // Now that all of the sections have been added we can fill out some extra
380 // details about symbol tables.
382 initSymbolTable(ElfFile, SymbolTable);
384 // Now that all sections and symbols have been added we can add
385 // relocations that reference symbols and set the link and info fields for
386 // relocation sections.
387 for (auto &Section : Sections) {
388 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
389 if (RelSec->Link - 1 >= Sections.size() || RelSec->Link == 0) {
390 error("Link field value " + Twine(RelSec->Link) + " in section " +
391 RelSec->Name + " is invalid");
393 if (RelSec->Info - 1 >= Sections.size() || RelSec->Info == 0) {
394 error("Info field value " + Twine(RelSec->Link) + " in section " +
395 RelSec->Name + " is invalid");
398 dyn_cast<SymbolTableSection>(Sections[RelSec->Link - 1].get());
399 if (SymTab == nullptr) {
400 error("Link field of relocation section " + RelSec->Name +
401 " is not a symbol table");
403 RelSec->setSymTab(SymTab);
404 RelSec->setSection(Sections[RelSec->Info - 1].get());
405 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
406 if (RelSec->Type == SHT_REL)
407 initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.rels(Shdr)));
409 initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.relas(Shdr)));
414 template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
415 const auto &ElfFile = *Obj.getELFFile();
416 const auto &Ehdr = *ElfFile.getHeader();
418 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
420 Machine = Ehdr.e_machine;
421 Version = Ehdr.e_version;
422 Entry = Ehdr.e_entry;
423 Flags = Ehdr.e_flags;
425 readSectionHeaders(ElfFile);
426 readProgramHeaders(ElfFile);
429 dyn_cast<StringTableSection>(Sections[Ehdr.e_shstrndx - 1].get());
432 template <class ELFT>
433 void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
434 uint8_t *Buf = Out.getBufferStart();
435 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
436 std::copy(Ident, Ident + 16, Ehdr.e_ident);
438 Ehdr.e_machine = Machine;
439 Ehdr.e_version = Version;
440 Ehdr.e_entry = Entry;
441 Ehdr.e_phoff = sizeof(Elf_Ehdr);
442 Ehdr.e_shoff = SHOffset;
443 Ehdr.e_flags = Flags;
444 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
445 Ehdr.e_phentsize = sizeof(Elf_Phdr);
446 Ehdr.e_phnum = Segments.size();
447 Ehdr.e_shentsize = sizeof(Elf_Shdr);
448 Ehdr.e_shnum = Sections.size() + 1;
449 Ehdr.e_shstrndx = SectionNames->Index;
452 template <class ELFT>
453 void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
454 for (auto &Phdr : Segments)
455 Phdr->template writeHeader<ELFT>(Out);
458 template <class ELFT>
459 void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
460 uint8_t *Buf = Out.getBufferStart() + SHOffset;
461 // This reference serves to write the dummy section header at the begining
463 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
465 Shdr.sh_type = SHT_NULL;
472 Shdr.sh_addralign = 0;
475 for (auto &Section : Sections)
476 Section->template writeHeader<ELFT>(Out);
479 template <class ELFT>
480 void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
481 for (auto &Section : Sections)
482 Section->writeSection(Out);
485 template <class ELFT> void ELFObject<ELFT>::sortSections() {
486 // Put all sections in offset order. Maintain the ordering as closely as
487 // possible while meeting that demand however.
488 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
489 return A->OriginalOffset < B->OriginalOffset;
491 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
495 template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
496 // The size of ELF + program headers will not change so it is ok to assume
497 // that the first offset of the first segment is a good place to start
498 // outputting sections. This covers both the standard case and the PT_PHDR
501 if (!this->Segments.empty()) {
502 Offset = this->Segments[0]->Offset;
504 Offset = sizeof(Elf_Ehdr);
506 // The only way a segment should move is if a section was between two
507 // segments and that section was removed. If that section isn't in a segment
508 // then it's acceptable, but not ideal, to simply move it to after the
509 // segments. So we can simply layout segments one after the other accounting
511 for (auto &Segment : this->Segments) {
512 Offset = alignTo(Offset, Segment->Align);
513 Segment->Offset = Offset;
514 Offset += Segment->FileSize;
516 // Now the offset of every segment has been set we can assign the offsets
517 // of each section. For sections that are covered by a segment we should use
518 // the segment's original offset and the section's original offset to compute
519 // the offset from the start of the segment. Using the offset from the start
520 // of the segment we can assign a new offset to the section. For sections not
521 // covered by segments we can just bump Offset to the next valid location.
523 for (auto &Section : this->Sections) {
524 Section->Index = Index++;
525 if (Section->ParentSegment != nullptr) {
526 auto Segment = Section->ParentSegment;
528 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
530 Offset = alignTo(Offset, Section->Offset);
531 Section->Offset = Offset;
532 if (Section->Type != SHT_NOBITS)
533 Offset += Section->Size;
537 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
538 this->SHOffset = Offset;
541 template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
542 // We already have the section header offset so we can calculate the total
543 // size by just adding up the size of each section header.
544 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
548 template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
549 this->writeHeader(Out);
550 this->writeProgramHeaders(Out);
551 this->writeSectionData(Out);
552 this->writeSectionHeaders(Out);
555 template <class ELFT> void ELFObject<ELFT>::finalize() {
556 // Make sure we add the names of all the sections.
557 for (const auto &Section : this->Sections) {
558 this->SectionNames->addString(Section->Name);
560 // Make sure we add the names of all the symbols.
561 this->SymbolTable->addSymbolNames();
566 // Finalize SectionNames first so that we can assign name indexes.
567 this->SectionNames->finalize();
568 // Finally now that all offsets and indexes have been set we can finalize any
570 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
571 for (auto &Section : this->Sections) {
572 Section->HeaderOffset = Offset;
573 Offset += sizeof(Elf_Shdr);
574 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
578 for (auto &Segment : this->Segments)
582 template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
586 template <class ELFT>
587 void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
588 for (auto &Segment : this->Segments) {
589 // GNU objcopy does not output segments that do not cover a section. Such
590 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
591 if (Segment->Type == llvm::ELF::PT_LOAD &&
592 Segment->firstSection() != nullptr) {
593 Segment->writeSegment(Out);
598 template <class ELFT> void BinaryObject<ELFT>::finalize() {
599 for (auto &Segment : this->Segments)
602 // Put all segments in offset order.
603 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
604 return A->Offset < B->Offset;
606 std::sort(std::begin(this->Segments), std::end(this->Segments),
610 for (auto &Segment : this->Segments) {
611 if (Segment->Type == llvm::ELF::PT_LOAD &&
612 Segment->firstSection() != nullptr) {
613 Offset = alignTo(Offset, Segment->Align);
614 Segment->Offset = Offset;
615 Offset += Segment->FileSize;
621 template class Object<ELF64LE>;
622 template class Object<ELF64BE>;
623 template class Object<ELF32LE>;
624 template class Object<ELF32BE>;
626 template class ELFObject<ELF64LE>;
627 template class ELFObject<ELF64BE>;
628 template class ELFObject<ELF32LE>;
629 template class ELFObject<ELF32BE>;
631 template class BinaryObject<ELF64LE>;
632 template class BinaryObject<ELF64BE>;
633 template class BinaryObject<ELF32LE>;
634 template class BinaryObject<ELF32BE>;