comparison tools/llvm-objcopy/Object.cpp @ 121:803732b1fca8

LLVM 5.0
author kono
date Fri, 27 Oct 2017 17:07:41 +0900
parents
children 3a76565eade5
comparison
equal deleted inserted replaced
120:1172e4bd9c6f 121:803732b1fca8
1 //===- Object.cpp -----------------------------------------------*- C++ -*-===//
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 #include "Object.h"
10 #include "llvm-objcopy.h"
11
12 using namespace llvm;
13 using namespace object;
14 using namespace ELF;
15
16 template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
17 typedef typename ELFT::Ehdr Elf_Ehdr;
18 typedef typename ELFT::Phdr Elf_Phdr;
19
20 uint8_t *Buf = Out.getBufferStart();
21 Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
22 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
23 Phdr.p_type = Type;
24 Phdr.p_flags = Flags;
25 Phdr.p_offset = Offset;
26 Phdr.p_vaddr = VAddr;
27 Phdr.p_paddr = PAddr;
28 Phdr.p_filesz = FileSize;
29 Phdr.p_memsz = MemSize;
30 Phdr.p_align = Align;
31 }
32
33 void Segment::writeSegment(FileOutputBuffer &Out) const {
34 uint8_t *Buf = Out.getBufferStart() + Offset;
35 // We want to maintain segments' interstitial data and contents exactly.
36 // This lets us just copy segments directly.
37 std::copy(std::begin(Contents), std::end(Contents), Buf);
38 }
39
40 void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
41 void SectionBase::initialize(SectionTableRef SecTable) {}
42 void SectionBase::finalize() {}
43
44 template <class ELFT>
45 void SectionBase::writeHeader(FileOutputBuffer &Out) const {
46 uint8_t *Buf = Out.getBufferStart();
47 Buf += HeaderOffset;
48 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
49 Shdr.sh_name = NameIndex;
50 Shdr.sh_type = Type;
51 Shdr.sh_flags = Flags;
52 Shdr.sh_addr = Addr;
53 Shdr.sh_offset = Offset;
54 Shdr.sh_size = Size;
55 Shdr.sh_link = Link;
56 Shdr.sh_info = Info;
57 Shdr.sh_addralign = Align;
58 Shdr.sh_entsize = EntrySize;
59 }
60
61 void Section::writeSection(FileOutputBuffer &Out) const {
62 if (Type == SHT_NOBITS)
63 return;
64 uint8_t *Buf = Out.getBufferStart() + Offset;
65 std::copy(std::begin(Contents), std::end(Contents), Buf);
66 }
67
68 void StringTableSection::addString(StringRef Name) {
69 StrTabBuilder.add(Name);
70 Size = StrTabBuilder.getSize();
71 }
72
73 uint32_t StringTableSection::findIndex(StringRef Name) const {
74 return StrTabBuilder.getOffset(Name);
75 }
76
77 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
78
79 void StringTableSection::writeSection(FileOutputBuffer &Out) const {
80 StrTabBuilder.write(Out.getBufferStart() + Offset);
81 }
82
83 static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
84 switch (Index) {
85 case SHN_ABS:
86 case SHN_COMMON:
87 return true;
88 }
89 if (Machine == EM_HEXAGON) {
90 switch (Index) {
91 case SHN_HEXAGON_SCOMMON:
92 case SHN_HEXAGON_SCOMMON_2:
93 case SHN_HEXAGON_SCOMMON_4:
94 case SHN_HEXAGON_SCOMMON_8:
95 return true;
96 }
97 }
98 return false;
99 }
100
101 uint16_t Symbol::getShndx() const {
102 if (DefinedIn != nullptr) {
103 return DefinedIn->Index;
104 }
105 switch (ShndxType) {
106 // This means that we don't have a defined section but we do need to
107 // output a legitimate section index.
108 case SYMBOL_SIMPLE_INDEX:
109 return SHN_UNDEF;
110 case SYMBOL_ABS:
111 case SYMBOL_COMMON:
112 case SYMBOL_HEXAGON_SCOMMON:
113 case SYMBOL_HEXAGON_SCOMMON_2:
114 case SYMBOL_HEXAGON_SCOMMON_4:
115 case SYMBOL_HEXAGON_SCOMMON_8:
116 return static_cast<uint16_t>(ShndxType);
117 }
118 llvm_unreachable("Symbol with invalid ShndxType encountered");
119 }
120
121 void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
122 SectionBase *DefinedIn, uint64_t Value,
123 uint16_t Shndx, uint64_t Sz) {
124 Symbol Sym;
125 Sym.Name = Name;
126 Sym.Binding = Bind;
127 Sym.Type = Type;
128 Sym.DefinedIn = DefinedIn;
129 if (DefinedIn == nullptr) {
130 if (Shndx >= SHN_LORESERVE)
131 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
132 else
133 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
134 }
135 Sym.Value = Value;
136 Sym.Size = Sz;
137 Sym.Index = Symbols.size();
138 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
139 Size += this->EntrySize;
140 }
141
142 void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
143 if (SymbolNames == Sec) {
144 error("String table " + SymbolNames->Name +
145 " cannot be removed because it is referenced by the symbol table " +
146 this->Name);
147 }
148 auto Iter =
149 std::remove_if(std::begin(Symbols), std::end(Symbols),
150 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
151 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
152 Symbols.erase(Iter, std::end(Symbols));
153 }
154
155 void SymbolTableSection::initialize(SectionTableRef SecTable) {
156 Size = 0;
157 setStrTab(SecTable.getSectionOfType<StringTableSection>(
158 Link,
159 "Symbol table has link index of " + Twine(Link) +
160 " which is not a valid index",
161 "Symbol table has link index of " + Twine(Link) +
162 " which is not a string table"));
163 }
164
165 void SymbolTableSection::finalize() {
166 // Make sure SymbolNames is finalized before getting name indexes.
167 SymbolNames->finalize();
168
169 uint32_t MaxLocalIndex = 0;
170 for (auto &Sym : Symbols) {
171 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
172 if (Sym->Binding == STB_LOCAL)
173 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
174 }
175 // Now we need to set the Link and Info fields.
176 Link = SymbolNames->Index;
177 Info = MaxLocalIndex + 1;
178 }
179
180 void SymbolTableSection::addSymbolNames() {
181 // Add all of our strings to SymbolNames so that SymbolNames has the right
182 // size before layout is decided.
183 for (auto &Sym : Symbols)
184 SymbolNames->addString(Sym->Name);
185 }
186
187 const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
188 if (Symbols.size() <= Index)
189 error("Invalid symbol index: " + Twine(Index));
190 return Symbols[Index].get();
191 }
192
193 template <class ELFT>
194 void SymbolTableSectionImpl<ELFT>::writeSection(
195 llvm::FileOutputBuffer &Out) const {
196 uint8_t *Buf = Out.getBufferStart();
197 Buf += Offset;
198 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
199 // Loop though symbols setting each entry of the symbol table.
200 for (auto &Symbol : Symbols) {
201 Sym->st_name = Symbol->NameIndex;
202 Sym->st_value = Symbol->Value;
203 Sym->st_size = Symbol->Size;
204 Sym->setBinding(Symbol->Binding);
205 Sym->setType(Symbol->Type);
206 Sym->st_shndx = Symbol->getShndx();
207 ++Sym;
208 }
209 }
210
211 template <class SymTabType>
212 void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
213 const SectionBase *Sec) {
214 if (Symbols == Sec) {
215 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
216 "referenced by the relocation "
217 "section " +
218 this->Name);
219 }
220 }
221
222 template <class SymTabType>
223 void RelocSectionWithSymtabBase<SymTabType>::initialize(
224 SectionTableRef SecTable) {
225 setSymTab(SecTable.getSectionOfType<SymTabType>(
226 Link,
227 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
228 "Link field value " + Twine(Link) + " in section " + Name +
229 " is not a symbol table"));
230
231 if (Info != SHN_UNDEF)
232 setSection(SecTable.getSection(Info,
233 "Info field value " + Twine(Info) +
234 " in section " + Name + " is invalid"));
235 else
236 setSection(nullptr);
237 }
238
239 template <class SymTabType>
240 void RelocSectionWithSymtabBase<SymTabType>::finalize() {
241 this->Link = Symbols->Index;
242 if (SecToApplyRel != nullptr)
243 this->Info = SecToApplyRel->Index;
244 }
245
246 template <class ELFT>
247 void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
248
249 template <class ELFT>
250 void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
251 Rela.r_addend = Addend;
252 }
253
254 template <class ELFT>
255 template <class T>
256 void RelocationSection<ELFT>::writeRel(T *Buf) const {
257 for (const auto &Reloc : Relocations) {
258 Buf->r_offset = Reloc.Offset;
259 setAddend(*Buf, Reloc.Addend);
260 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
261 ++Buf;
262 }
263 }
264
265 template <class ELFT>
266 void RelocationSection<ELFT>::writeSection(llvm::FileOutputBuffer &Out) const {
267 uint8_t *Buf = Out.getBufferStart() + Offset;
268 if (Type == SHT_REL)
269 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
270 else
271 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
272 }
273
274 void DynamicRelocationSection::writeSection(llvm::FileOutputBuffer &Out) const {
275 std::copy(std::begin(Contents), std::end(Contents),
276 Out.getBufferStart() + Offset);
277 }
278
279 void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
280 if (StrTab == Sec) {
281 error("String table " + StrTab->Name + " cannot be removed because it is "
282 "referenced by the section " +
283 this->Name);
284 }
285 }
286
287 bool SectionWithStrTab::classof(const SectionBase *S) {
288 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
289 }
290
291 void SectionWithStrTab::initialize(SectionTableRef SecTable) {
292 auto StrTab = SecTable.getSection(Link,
293 "Link field value " + Twine(Link) +
294 " in section " + Name + " is invalid");
295 if (StrTab->Type != SHT_STRTAB) {
296 error("Link field value " + Twine(Link) + " in section " + Name +
297 " is not a string table");
298 }
299 setStrTab(StrTab);
300 }
301
302 void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
303
304 // Returns true IFF a section is wholly inside the range of a segment
305 static bool sectionWithinSegment(const SectionBase &Section,
306 const Segment &Segment) {
307 // If a section is empty it should be treated like it has a size of 1. This is
308 // to clarify the case when an empty section lies on a boundary between two
309 // segments and ensures that the section "belongs" to the second segment and
310 // not the first.
311 uint64_t SecSize = Section.Size ? Section.Size : 1;
312 return Segment.Offset <= Section.OriginalOffset &&
313 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
314 }
315
316 // Returns true IFF a segment's original offset is inside of another segment's
317 // range.
318 static bool segmentOverlapsSegment(const Segment &Child,
319 const Segment &Parent) {
320
321 return Parent.OriginalOffset <= Child.OriginalOffset &&
322 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
323 }
324
325 template <class ELFT>
326 void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
327 uint32_t Index = 0;
328 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
329 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
330 (size_t)Phdr.p_filesz};
331 Segments.emplace_back(llvm::make_unique<Segment>(Data));
332 Segment &Seg = *Segments.back();
333 Seg.Type = Phdr.p_type;
334 Seg.Flags = Phdr.p_flags;
335 Seg.OriginalOffset = Phdr.p_offset;
336 Seg.Offset = Phdr.p_offset;
337 Seg.VAddr = Phdr.p_vaddr;
338 Seg.PAddr = Phdr.p_paddr;
339 Seg.FileSize = Phdr.p_filesz;
340 Seg.MemSize = Phdr.p_memsz;
341 Seg.Align = Phdr.p_align;
342 Seg.Index = Index++;
343 for (auto &Section : Sections) {
344 if (sectionWithinSegment(*Section, Seg)) {
345 Seg.addSection(&*Section);
346 if (!Section->ParentSegment ||
347 Section->ParentSegment->Offset > Seg.Offset) {
348 Section->ParentSegment = &Seg;
349 }
350 }
351 }
352 }
353 // Now we do an O(n^2) loop through the segments in order to match up
354 // segments.
355 for (auto &Child : Segments) {
356 for (auto &Parent : Segments) {
357 // Every segment will overlap with itself but we don't want a segment to
358 // be it's own parent so we avoid that situation.
359 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
360 // We want a canonical "most parental" segment but this requires
361 // inspecting the ParentSegment.
362 if (Child->ParentSegment != nullptr) {
363 if (Child->ParentSegment->OriginalOffset > Parent->OriginalOffset) {
364 Child->ParentSegment = Parent.get();
365 } else if (Child->ParentSegment->Index > Parent->Index) {
366 // They must have equal OriginalOffsets so we need to disambiguate.
367 // To decide which is the parent we'll choose the one with the
368 // higher index.
369 Child->ParentSegment = Parent.get();
370 }
371 } else {
372 Child->ParentSegment = Parent.get();
373 }
374 }
375 }
376 }
377 }
378
379 template <class ELFT>
380 void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
381 SymbolTableSection *SymTab,
382 SectionTableRef SecTable) {
383
384 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
385 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
386
387 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
388 SectionBase *DefSection = nullptr;
389 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
390
391 if (Sym.st_shndx >= SHN_LORESERVE) {
392 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
393 error(
394 "Symbol '" + Name +
395 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
396 Twine(Sym.st_shndx));
397 }
398 } else if (Sym.st_shndx != SHN_UNDEF) {
399 DefSection = SecTable.getSection(
400 Sym.st_shndx,
401 "Symbol '" + Name + "' is defined in invalid section with index " +
402 Twine(Sym.st_shndx));
403 }
404
405 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
406 Sym.getValue(), Sym.st_shndx, Sym.st_size);
407 }
408 }
409
410 template <class ELFT>
411 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
412
413 template <class ELFT>
414 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
415 ToSet = Rela.r_addend;
416 }
417
418 template <class ELFT, class T>
419 void initRelocations(RelocationSection<ELFT> *Relocs,
420 SymbolTableSection *SymbolTable, T RelRange) {
421 for (const auto &Rel : RelRange) {
422 Relocation ToAdd;
423 ToAdd.Offset = Rel.r_offset;
424 getAddend(ToAdd.Addend, Rel);
425 ToAdd.Type = Rel.getType(false);
426 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
427 Relocs->addRelocation(ToAdd);
428 }
429 }
430
431 SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
432 if (Index == SHN_UNDEF || Index > Sections.size())
433 error(ErrMsg);
434 return Sections[Index - 1].get();
435 }
436
437 template <class T>
438 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
439 Twine TypeErrMsg) {
440 if (T *Sec = llvm::dyn_cast<T>(getSection(Index, IndexErrMsg)))
441 return Sec;
442 error(TypeErrMsg);
443 }
444
445 template <class ELFT>
446 std::unique_ptr<SectionBase>
447 Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
448 const Elf_Shdr &Shdr) {
449 ArrayRef<uint8_t> Data;
450 switch (Shdr.sh_type) {
451 case SHT_REL:
452 case SHT_RELA:
453 if (Shdr.sh_flags & SHF_ALLOC) {
454 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
455 return llvm::make_unique<DynamicRelocationSection>(Data);
456 }
457 return llvm::make_unique<RelocationSection<ELFT>>();
458 case SHT_STRTAB:
459 // If a string table is allocated we don't want to mess with it. That would
460 // mean altering the memory image. There are no special link types or
461 // anything so we can just use a Section.
462 if (Shdr.sh_flags & SHF_ALLOC) {
463 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
464 return llvm::make_unique<Section>(Data);
465 }
466 return llvm::make_unique<StringTableSection>();
467 case SHT_HASH:
468 case SHT_GNU_HASH:
469 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
470 // Because of this we don't need to mess with the hash tables either.
471 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
472 return llvm::make_unique<Section>(Data);
473 case SHT_DYNSYM:
474 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
475 return llvm::make_unique<DynamicSymbolTableSection>(Data);
476 case SHT_DYNAMIC:
477 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
478 return llvm::make_unique<DynamicSection>(Data);
479 case SHT_SYMTAB: {
480 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
481 SymbolTable = SymTab.get();
482 return std::move(SymTab);
483 }
484 case SHT_NOBITS:
485 return llvm::make_unique<Section>(Data);
486 default:
487 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
488 return llvm::make_unique<Section>(Data);
489 }
490 }
491
492 template <class ELFT>
493 SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
494 uint32_t Index = 0;
495 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
496 if (Index == 0) {
497 ++Index;
498 continue;
499 }
500 SecPtr Sec = makeSection(ElfFile, Shdr);
501 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
502 Sec->Type = Shdr.sh_type;
503 Sec->Flags = Shdr.sh_flags;
504 Sec->Addr = Shdr.sh_addr;
505 Sec->Offset = Shdr.sh_offset;
506 Sec->OriginalOffset = Shdr.sh_offset;
507 Sec->Size = Shdr.sh_size;
508 Sec->Link = Shdr.sh_link;
509 Sec->Info = Shdr.sh_info;
510 Sec->Align = Shdr.sh_addralign;
511 Sec->EntrySize = Shdr.sh_entsize;
512 Sec->Index = Index++;
513 Sections.push_back(std::move(Sec));
514 }
515
516 SectionTableRef SecTable(Sections);
517
518 // Now that all of the sections have been added we can fill out some extra
519 // details about symbol tables. We need the symbol table filled out before
520 // any relocations.
521 if (SymbolTable) {
522 SymbolTable->initialize(SecTable);
523 initSymbolTable(ElfFile, SymbolTable, SecTable);
524 }
525
526 // Now that all sections and symbols have been added we can add
527 // relocations that reference symbols and set the link and info fields for
528 // relocation sections.
529 for (auto &Section : Sections) {
530 if (Section.get() == SymbolTable)
531 continue;
532 Section->initialize(SecTable);
533 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
534 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
535 if (RelSec->Type == SHT_REL)
536 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
537 else
538 initRelocations(RelSec, SymbolTable,
539 unwrapOrError(ElfFile.relas(Shdr)));
540 }
541 }
542
543 return SecTable;
544 }
545
546 template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
547 const auto &ElfFile = *Obj.getELFFile();
548 const auto &Ehdr = *ElfFile.getHeader();
549
550 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
551 Type = Ehdr.e_type;
552 Machine = Ehdr.e_machine;
553 Version = Ehdr.e_version;
554 Entry = Ehdr.e_entry;
555 Flags = Ehdr.e_flags;
556
557 SectionTableRef SecTable = readSectionHeaders(ElfFile);
558 readProgramHeaders(ElfFile);
559
560 SectionNames = SecTable.getSectionOfType<StringTableSection>(
561 Ehdr.e_shstrndx,
562 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
563 " is invalid",
564 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
565 " is not a string table");
566 }
567
568 template <class ELFT>
569 void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
570 uint8_t *Buf = Out.getBufferStart();
571 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
572 std::copy(Ident, Ident + 16, Ehdr.e_ident);
573 Ehdr.e_type = Type;
574 Ehdr.e_machine = Machine;
575 Ehdr.e_version = Version;
576 Ehdr.e_entry = Entry;
577 Ehdr.e_phoff = sizeof(Elf_Ehdr);
578 Ehdr.e_flags = Flags;
579 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
580 Ehdr.e_phentsize = sizeof(Elf_Phdr);
581 Ehdr.e_phnum = Segments.size();
582 Ehdr.e_shentsize = sizeof(Elf_Shdr);
583 if (WriteSectionHeaders) {
584 Ehdr.e_shoff = SHOffset;
585 Ehdr.e_shnum = Sections.size() + 1;
586 Ehdr.e_shstrndx = SectionNames->Index;
587 } else {
588 Ehdr.e_shoff = 0;
589 Ehdr.e_shnum = 0;
590 Ehdr.e_shstrndx = 0;
591 }
592 }
593
594 template <class ELFT>
595 void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
596 for (auto &Phdr : Segments)
597 Phdr->template writeHeader<ELFT>(Out);
598 }
599
600 template <class ELFT>
601 void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
602 uint8_t *Buf = Out.getBufferStart() + SHOffset;
603 // This reference serves to write the dummy section header at the begining
604 // of the file. It is not used for anything else
605 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
606 Shdr.sh_name = 0;
607 Shdr.sh_type = SHT_NULL;
608 Shdr.sh_flags = 0;
609 Shdr.sh_addr = 0;
610 Shdr.sh_offset = 0;
611 Shdr.sh_size = 0;
612 Shdr.sh_link = 0;
613 Shdr.sh_info = 0;
614 Shdr.sh_addralign = 0;
615 Shdr.sh_entsize = 0;
616
617 for (auto &Section : Sections)
618 Section->template writeHeader<ELFT>(Out);
619 }
620
621 template <class ELFT>
622 void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
623 for (auto &Section : Sections)
624 Section->writeSection(Out);
625 }
626
627 template <class ELFT>
628 void Object<ELFT>::removeSections(
629 std::function<bool(const SectionBase &)> ToRemove) {
630
631 auto Iter = std::stable_partition(
632 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
633 if (ToRemove(*Sec))
634 return false;
635 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
636 if (auto ToRelSec = RelSec->getSection())
637 return !ToRemove(*ToRelSec);
638 }
639 return true;
640 });
641 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
642 SymbolTable = nullptr;
643 if (ToRemove(*SectionNames)) {
644 if (WriteSectionHeaders)
645 error("Cannot remove " + SectionNames->Name +
646 " because it is the section header string table.");
647 SectionNames = nullptr;
648 }
649 // Now make sure there are no remaining references to the sections that will
650 // be removed. Sometimes it is impossible to remove a reference so we emit
651 // an error here instead.
652 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
653 for (auto &Segment : Segments)
654 Segment->removeSection(RemoveSec.get());
655 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
656 KeepSec->removeSectionReferences(RemoveSec.get());
657 }
658 // Now finally get rid of them all togethor.
659 Sections.erase(Iter, std::end(Sections));
660 }
661
662 template <class ELFT> void ELFObject<ELFT>::sortSections() {
663 // Put all sections in offset order. Maintain the ordering as closely as
664 // possible while meeting that demand however.
665 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
666 return A->OriginalOffset < B->OriginalOffset;
667 };
668 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
669 CompareSections);
670 }
671
672 template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
673 // We need a temporary list of segments that has a special order to it
674 // so that we know that anytime ->ParentSegment is set that segment has
675 // already had it's offset properly set.
676 std::vector<Segment *> OrderedSegments;
677 for (auto &Segment : this->Segments)
678 OrderedSegments.push_back(Segment.get());
679 auto CompareSegments = [](const Segment *A, const Segment *B) {
680 // Any segment without a parent segment should come before a segment
681 // that has a parent segment.
682 if (A->OriginalOffset < B->OriginalOffset)
683 return true;
684 if (A->OriginalOffset > B->OriginalOffset)
685 return false;
686 return A->Index < B->Index;
687 };
688 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
689 CompareSegments);
690 // The size of ELF + program headers will not change so it is ok to assume
691 // that the first offset of the first segment is a good place to start
692 // outputting sections. This covers both the standard case and the PT_PHDR
693 // case.
694 uint64_t Offset;
695 if (!OrderedSegments.empty()) {
696 Offset = OrderedSegments[0]->Offset;
697 } else {
698 Offset = sizeof(Elf_Ehdr);
699 }
700 // The only way a segment should move is if a section was between two
701 // segments and that section was removed. If that section isn't in a segment
702 // then it's acceptable, but not ideal, to simply move it to after the
703 // segments. So we can simply layout segments one after the other accounting
704 // for alignment.
705 for (auto &Segment : OrderedSegments) {
706 // We assume that segments have been ordered by OriginalOffset and Index
707 // such that a parent segment will always come before a child segment in
708 // OrderedSegments. This means that the Offset of the ParentSegment should
709 // already be set and we can set our offset relative to it.
710 if (Segment->ParentSegment != nullptr) {
711 auto Parent = Segment->ParentSegment;
712 Segment->Offset =
713 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
714 } else {
715 Offset = alignTo(Offset, Segment->Align == 0 ? 1 : Segment->Align);
716 Segment->Offset = Offset;
717 }
718 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
719 }
720 // Now the offset of every segment has been set we can assign the offsets
721 // of each section. For sections that are covered by a segment we should use
722 // the segment's original offset and the section's original offset to compute
723 // the offset from the start of the segment. Using the offset from the start
724 // of the segment we can assign a new offset to the section. For sections not
725 // covered by segments we can just bump Offset to the next valid location.
726 uint32_t Index = 1;
727 for (auto &Section : this->Sections) {
728 Section->Index = Index++;
729 if (Section->ParentSegment != nullptr) {
730 auto Segment = Section->ParentSegment;
731 Section->Offset =
732 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
733 } else {
734 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
735 Section->Offset = Offset;
736 if (Section->Type != SHT_NOBITS)
737 Offset += Section->Size;
738 }
739 }
740
741 if (this->WriteSectionHeaders) {
742 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
743 }
744 this->SHOffset = Offset;
745 }
746
747 template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
748 // We already have the section header offset so we can calculate the total
749 // size by just adding up the size of each section header.
750 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
751 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
752 NullSectionSize;
753 }
754
755 template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
756 this->writeHeader(Out);
757 this->writeProgramHeaders(Out);
758 this->writeSectionData(Out);
759 if (this->WriteSectionHeaders)
760 this->writeSectionHeaders(Out);
761 }
762
763 template <class ELFT> void ELFObject<ELFT>::finalize() {
764 // Make sure we add the names of all the sections.
765 if (this->SectionNames != nullptr)
766 for (const auto &Section : this->Sections) {
767 this->SectionNames->addString(Section->Name);
768 }
769 // Make sure we add the names of all the symbols.
770 if (this->SymbolTable != nullptr)
771 this->SymbolTable->addSymbolNames();
772
773 sortSections();
774 assignOffsets();
775
776 // Finalize SectionNames first so that we can assign name indexes.
777 if (this->SectionNames != nullptr)
778 this->SectionNames->finalize();
779 // Finally now that all offsets and indexes have been set we can finalize any
780 // remaining issues.
781 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
782 for (auto &Section : this->Sections) {
783 Section->HeaderOffset = Offset;
784 Offset += sizeof(Elf_Shdr);
785 if (this->WriteSectionHeaders)
786 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
787 Section->finalize();
788 }
789 }
790
791 template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
792 return TotalSize;
793 }
794
795 template <class ELFT>
796 void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
797 for (auto &Segment : this->Segments) {
798 // GNU objcopy does not output segments that do not cover a section. Such
799 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
800 if (Segment->Type == llvm::ELF::PT_LOAD &&
801 Segment->firstSection() != nullptr) {
802 Segment->writeSegment(Out);
803 }
804 }
805 }
806
807 template <class ELFT> void BinaryObject<ELFT>::finalize() {
808
809 // Put all segments in offset order.
810 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
811 return A->Offset < B->Offset;
812 };
813 std::sort(std::begin(this->Segments), std::end(this->Segments),
814 CompareSegments);
815
816 uint64_t Offset = 0;
817 for (auto &Segment : this->Segments) {
818 if (Segment->Type == llvm::ELF::PT_LOAD &&
819 Segment->firstSection() != nullptr) {
820 Offset = alignTo(Offset, Segment->Align);
821 Segment->Offset = Offset;
822 Offset += Segment->FileSize;
823 }
824 }
825 TotalSize = Offset;
826 }
827
828 template class Object<ELF64LE>;
829 template class Object<ELF64BE>;
830 template class Object<ELF32LE>;
831 template class Object<ELF32BE>;
832
833 template class ELFObject<ELF64LE>;
834 template class ELFObject<ELF64BE>;
835 template class ELFObject<ELF32LE>;
836 template class ELFObject<ELF32BE>;
837
838 template class BinaryObject<ELF64LE>;
839 template class BinaryObject<ELF64BE>;
840 template class BinaryObject<ELF32LE>;
841 template class BinaryObject<ELF32BE>;