blob: 16bfdfd140c6243925a9e3b4356977b9b290076c [file] [log] [blame]
Petr Hosek05a04cb2017-08-01 00:33:58 +00001//===- 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
12using namespace llvm;
13using namespace object;
14using namespace ELF;
15
16template <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
33void Segment::finalize() {
34 auto FirstSec = firstSection();
35 if (FirstSec) {
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);
42 }
43}
44
Petr Hosekc4df10e2017-08-04 21:09:26 +000045void 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);
50}
51
Petr Hosek05a04cb2017-08-01 00:33:58 +000052void SectionBase::finalize() {}
53
54template <class ELFT>
55void SectionBase::writeHeader(FileOutputBuffer &Out) const {
56 uint8_t *Buf = Out.getBufferStart();
57 Buf += HeaderOffset;
58 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
59 Shdr.sh_name = NameIndex;
60 Shdr.sh_type = Type;
61 Shdr.sh_flags = Flags;
62 Shdr.sh_addr = Addr;
63 Shdr.sh_offset = Offset;
64 Shdr.sh_size = Size;
65 Shdr.sh_link = Link;
66 Shdr.sh_info = Info;
67 Shdr.sh_addralign = Align;
68 Shdr.sh_entsize = EntrySize;
69}
70
71void Section::writeSection(FileOutputBuffer &Out) const {
72 if (Type == SHT_NOBITS)
73 return;
74 uint8_t *Buf = Out.getBufferStart() + Offset;
75 std::copy(std::begin(Contents), std::end(Contents), Buf);
76}
77
78void StringTableSection::addString(StringRef Name) {
79 StrTabBuilder.add(Name);
80 Size = StrTabBuilder.getSize();
81}
82
83uint32_t StringTableSection::findIndex(StringRef Name) const {
84 return StrTabBuilder.getOffset(Name);
85}
86
87void StringTableSection::finalize() { StrTabBuilder.finalize(); }
88
89void StringTableSection::writeSection(FileOutputBuffer &Out) const {
90 StrTabBuilder.write(Out.getBufferStart() + Offset);
91}
92
Petr Hosekc1135772017-09-13 03:04:50 +000093static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +000094 switch (Index) {
95 case SHN_ABS:
96 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +000097 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +000098 }
Petr Hosekc1135772017-09-13 03:04:50 +000099 if (Machine == EM_HEXAGON) {
100 switch (Index) {
101 case SHN_HEXAGON_SCOMMON:
102 case SHN_HEXAGON_SCOMMON_2:
103 case SHN_HEXAGON_SCOMMON_4:
104 case SHN_HEXAGON_SCOMMON_8:
105 return true;
106 }
107 }
108 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000109}
110
111uint16_t Symbol::getShndx() const {
112 if (DefinedIn != nullptr) {
113 return DefinedIn->Index;
114 }
115 switch (ShndxType) {
116 // This means that we don't have a defined section but we do need to
117 // output a legitimate section index.
118 case SYMBOL_SIMPLE_INDEX:
119 return SHN_UNDEF;
120 case SYMBOL_ABS:
121 case SYMBOL_COMMON:
122 case SYMBOL_HEXAGON_SCOMMON:
123 case SYMBOL_HEXAGON_SCOMMON_2:
124 case SYMBOL_HEXAGON_SCOMMON_4:
125 case SYMBOL_HEXAGON_SCOMMON_8:
126 return static_cast<uint16_t>(ShndxType);
127 }
128 llvm_unreachable("Symbol with invalid ShndxType encountered");
129}
130
Petr Hosek79cee9e2017-08-29 02:12:03 +0000131void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
132 SectionBase *DefinedIn, uint64_t Value,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000133 uint16_t Shndx, uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000134 Symbol Sym;
135 Sym.Name = Name;
136 Sym.Binding = Bind;
137 Sym.Type = Type;
138 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000139 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000140 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000141 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
142 else
143 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
144 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000145 Sym.Value = Value;
146 Sym.Size = Sz;
147 Sym.Index = Symbols.size();
148 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
149 Size += this->EntrySize;
150}
151
152void SymbolTableSection::finalize() {
153 // Make sure SymbolNames is finalized before getting name indexes.
154 SymbolNames->finalize();
155
156 uint32_t MaxLocalIndex = 0;
157 for (auto &Sym : Symbols) {
158 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
159 if (Sym->Binding == STB_LOCAL)
160 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
161 }
162 // Now we need to set the Link and Info fields.
163 Link = SymbolNames->Index;
164 Info = MaxLocalIndex + 1;
165}
166
167void SymbolTableSection::addSymbolNames() {
168 // Add all of our strings to SymbolNames so that SymbolNames has the right
169 // size before layout is decided.
170 for (auto &Sym : Symbols)
171 SymbolNames->addString(Sym->Name);
172}
173
174const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
175 if (Symbols.size() <= Index)
176 error("Invalid symbol index: " + Twine(Index));
177 return Symbols[Index].get();
178}
179
180template <class ELFT>
181void SymbolTableSectionImpl<ELFT>::writeSection(
182 llvm::FileOutputBuffer &Out) const {
183 uint8_t *Buf = Out.getBufferStart();
184 Buf += Offset;
185 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
186 // Loop though symbols setting each entry of the symbol table.
187 for (auto &Symbol : Symbols) {
188 Sym->st_name = Symbol->NameIndex;
189 Sym->st_value = Symbol->Value;
190 Sym->st_size = Symbol->Size;
191 Sym->setBinding(Symbol->Binding);
192 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000193 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000194 ++Sym;
195 }
196}
197
Petr Hosekd7df9b22017-09-06 23:41:02 +0000198template <class ELFT> void RelocationSection<ELFT>::finalize() {
199 this->Link = Symbols->Index;
200 this->Info = SecToApplyRel->Index;
201}
202
203template <class ELFT>
204void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
205
206template <class ELFT>
207void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
208 Rela.r_addend = Addend;
209}
210
211template <class ELFT>
212template <class T>
213void RelocationSection<ELFT>::writeRel(T *Buf) const {
214 for (const auto &Reloc : Relocations) {
215 Buf->r_offset = Reloc.Offset;
216 setAddend(*Buf, Reloc.Addend);
217 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
218 ++Buf;
219 }
220}
221
222template <class ELFT>
223void RelocationSection<ELFT>::writeSection(llvm::FileOutputBuffer &Out) const {
224 uint8_t *Buf = Out.getBufferStart() + Offset;
225 if (Type == SHT_REL)
226 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
227 else
228 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
229}
230
Petr Hosek05a04cb2017-08-01 00:33:58 +0000231// Returns true IFF a section is wholly inside the range of a segment
232static bool sectionWithinSegment(const SectionBase &Section,
233 const Segment &Segment) {
234 // If a section is empty it should be treated like it has a size of 1. This is
235 // to clarify the case when an empty section lies on a boundary between two
236 // segments and ensures that the section "belongs" to the second segment and
237 // not the first.
238 uint64_t SecSize = Section.Size ? Section.Size : 1;
239 return Segment.Offset <= Section.OriginalOffset &&
240 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
241}
242
Jake Ehrlich0a84b1a2017-09-19 18:14:03 +0000243// Returns true IFF a segment's original offset is inside of another segment's
244// range.
245static bool segmentOverlapsSegment(const Segment &Child,
246 const Segment &Parent) {
247
248 return Parent.OriginalOffset <= Child.OriginalOffset &&
249 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
250}
251
Petr Hosek05a04cb2017-08-01 00:33:58 +0000252template <class ELFT>
253void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
254 uint32_t Index = 0;
255 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000256 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
257 (size_t)Phdr.p_filesz};
258 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000259 Segment &Seg = *Segments.back();
260 Seg.Type = Phdr.p_type;
261 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000262 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000263 Seg.Offset = Phdr.p_offset;
264 Seg.VAddr = Phdr.p_vaddr;
265 Seg.PAddr = Phdr.p_paddr;
266 Seg.FileSize = Phdr.p_filesz;
267 Seg.MemSize = Phdr.p_memsz;
268 Seg.Align = Phdr.p_align;
269 Seg.Index = Index++;
270 for (auto &Section : Sections) {
271 if (sectionWithinSegment(*Section, Seg)) {
272 Seg.addSection(&*Section);
273 if (!Section->ParentSegment ||
274 Section->ParentSegment->Offset > Seg.Offset) {
275 Section->ParentSegment = &Seg;
276 }
277 }
278 }
279 }
Jake Ehrlich0a84b1a2017-09-19 18:14:03 +0000280 // Now we do an O(n^2) loop through the segments in order to match up
281 // segments.
282 for (auto &Child : Segments) {
283 for (auto &Parent : Segments) {
284 // Every segment will overlap with itself but we don't want a segment to
285 // be it's own parent so we avoid that situation.
286 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
287 // We want a canonical "most parental" segment but this requires
288 // inspecting the ParentSegment.
289 if (Child->ParentSegment != nullptr) {
290 if (Child->ParentSegment->OriginalOffset > Parent->OriginalOffset) {
291 Child->ParentSegment = Parent.get();
292 } else if (Child->ParentSegment->Index > Parent->Index) {
293 // They must have equal OriginalOffsets so we need to disambiguate.
294 // To decide which is the parent we'll choose the one with the
295 // higher index.
296 Child->ParentSegment = Parent.get();
297 }
298 } else {
299 Child->ParentSegment = Parent.get();
300 }
301 }
302 }
303 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000304}
305
306template <class ELFT>
Petr Hosek79cee9e2017-08-29 02:12:03 +0000307void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
308 SymbolTableSection *SymTab) {
309
310 SymTab->Size = 0;
311 if (SymbolTable->Link - 1 >= Sections.size())
312 error("Symbol table has link index of " + Twine(SymbolTable->Link) +
313 " which is not a valid index");
314
315 if (auto StrTab =
316 dyn_cast<StringTableSection>(Sections[SymbolTable->Link - 1].get()))
317 SymTab->setStrTab(StrTab);
318 else
319 error("Symbol table has link index of " + Twine(SymbolTable->Link) +
320 "which is not a string table");
321
322 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
323 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
324
325 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
326 SectionBase *DefSection = nullptr;
327 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000328 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000329 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000330 error(
331 "Symbol '" + Name +
332 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
333 Twine(Sym.st_shndx));
334 }
335 } else if (Sym.st_shndx != SHN_UNDEF) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000336 if (Sym.st_shndx >= Sections.size())
337 error("Symbol '" + Name +
338 "' is defined in invalid section with index " +
339 Twine(Sym.st_shndx));
340 DefSection = Sections[Sym.st_shndx - 1].get();
341 }
342 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000343 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000344 }
345}
346
347template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000348static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
349
350template <class ELFT>
351static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
352 ToSet = Rela.r_addend;
353}
354
355template <class ELFT, class T>
356void initRelocations(RelocationSection<ELFT> *Relocs,
357 SymbolTableSection *SymbolTable, T RelRange) {
358 for (const auto &Rel : RelRange) {
359 Relocation ToAdd;
360 ToAdd.Offset = Rel.r_offset;
361 getAddend(ToAdd.Addend, Rel);
362 ToAdd.Type = Rel.getType(false);
363 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
364 Relocs->addRelocation(ToAdd);
365 }
366}
367
368template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000369std::unique_ptr<SectionBase>
370Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
371 const Elf_Shdr &Shdr) {
372 ArrayRef<uint8_t> Data;
373 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000374 case SHT_REL:
375 case SHT_RELA:
376 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000377 case SHT_STRTAB:
378 return llvm::make_unique<StringTableSection>();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000379 case SHT_SYMTAB: {
380 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
381 SymbolTable = SymTab.get();
382 return std::move(SymTab);
383 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000384 case SHT_NOBITS:
385 return llvm::make_unique<Section>(Data);
386 default:
387 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
388 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000389 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000390}
391
392template <class ELFT>
393void Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
394 uint32_t Index = 0;
395 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
396 if (Index == 0) {
397 ++Index;
398 continue;
399 }
400 SecPtr Sec = makeSection(ElfFile, Shdr);
401 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
402 Sec->Type = Shdr.sh_type;
403 Sec->Flags = Shdr.sh_flags;
404 Sec->Addr = Shdr.sh_addr;
405 Sec->Offset = Shdr.sh_offset;
406 Sec->OriginalOffset = Shdr.sh_offset;
407 Sec->Size = Shdr.sh_size;
408 Sec->Link = Shdr.sh_link;
409 Sec->Info = Shdr.sh_info;
410 Sec->Align = Shdr.sh_addralign;
411 Sec->EntrySize = Shdr.sh_entsize;
412 Sec->Index = Index++;
413 Sections.push_back(std::move(Sec));
414 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000415
416 // Now that all of the sections have been added we can fill out some extra
417 // details about symbol tables.
418 if (SymbolTable)
419 initSymbolTable(ElfFile, SymbolTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000420
421 // Now that all sections and symbols have been added we can add
422 // relocations that reference symbols and set the link and info fields for
423 // relocation sections.
424 for (auto &Section : Sections) {
425 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
426 if (RelSec->Link - 1 >= Sections.size() || RelSec->Link == 0) {
427 error("Link field value " + Twine(RelSec->Link) + " in section " +
428 RelSec->Name + " is invalid");
429 }
430 if (RelSec->Info - 1 >= Sections.size() || RelSec->Info == 0) {
431 error("Info field value " + Twine(RelSec->Link) + " in section " +
432 RelSec->Name + " is invalid");
433 }
434 auto SymTab =
435 dyn_cast<SymbolTableSection>(Sections[RelSec->Link - 1].get());
436 if (SymTab == nullptr) {
437 error("Link field of relocation section " + RelSec->Name +
438 " is not a symbol table");
439 }
440 RelSec->setSymTab(SymTab);
441 RelSec->setSection(Sections[RelSec->Info - 1].get());
442 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
443 if (RelSec->Type == SHT_REL)
444 initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.rels(Shdr)));
445 else
446 initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.relas(Shdr)));
447 }
448 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000449}
450
Petr Hosek05a04cb2017-08-01 00:33:58 +0000451template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
452 const auto &ElfFile = *Obj.getELFFile();
453 const auto &Ehdr = *ElfFile.getHeader();
454
455 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
456 Type = Ehdr.e_type;
457 Machine = Ehdr.e_machine;
458 Version = Ehdr.e_version;
459 Entry = Ehdr.e_entry;
460 Flags = Ehdr.e_flags;
461
462 readSectionHeaders(ElfFile);
463 readProgramHeaders(ElfFile);
464
465 SectionNames =
466 dyn_cast<StringTableSection>(Sections[Ehdr.e_shstrndx - 1].get());
467}
468
Petr Hosek05a04cb2017-08-01 00:33:58 +0000469template <class ELFT>
470void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
471 uint8_t *Buf = Out.getBufferStart();
472 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
473 std::copy(Ident, Ident + 16, Ehdr.e_ident);
474 Ehdr.e_type = Type;
475 Ehdr.e_machine = Machine;
476 Ehdr.e_version = Version;
477 Ehdr.e_entry = Entry;
478 Ehdr.e_phoff = sizeof(Elf_Ehdr);
479 Ehdr.e_shoff = SHOffset;
480 Ehdr.e_flags = Flags;
481 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
482 Ehdr.e_phentsize = sizeof(Elf_Phdr);
483 Ehdr.e_phnum = Segments.size();
484 Ehdr.e_shentsize = sizeof(Elf_Shdr);
485 Ehdr.e_shnum = Sections.size() + 1;
486 Ehdr.e_shstrndx = SectionNames->Index;
487}
488
489template <class ELFT>
490void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
491 for (auto &Phdr : Segments)
492 Phdr->template writeHeader<ELFT>(Out);
493}
494
495template <class ELFT>
496void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
497 uint8_t *Buf = Out.getBufferStart() + SHOffset;
498 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000499 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000500 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
501 Shdr.sh_name = 0;
502 Shdr.sh_type = SHT_NULL;
503 Shdr.sh_flags = 0;
504 Shdr.sh_addr = 0;
505 Shdr.sh_offset = 0;
506 Shdr.sh_size = 0;
507 Shdr.sh_link = 0;
508 Shdr.sh_info = 0;
509 Shdr.sh_addralign = 0;
510 Shdr.sh_entsize = 0;
511
512 for (auto &Section : Sections)
513 Section->template writeHeader<ELFT>(Out);
514}
515
516template <class ELFT>
517void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
518 for (auto &Section : Sections)
519 Section->writeSection(Out);
520}
521
Petr Hosekc4df10e2017-08-04 21:09:26 +0000522template <class ELFT> void ELFObject<ELFT>::sortSections() {
523 // Put all sections in offset order. Maintain the ordering as closely as
524 // possible while meeting that demand however.
525 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
526 return A->OriginalOffset < B->OriginalOffset;
527 };
528 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
529 CompareSections);
530}
531
532template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
Jake Ehrlich0a84b1a2017-09-19 18:14:03 +0000533 // We need a temporary list of segments that has a special order to it
534 // so that we know that anytime ->ParentSegment is set that segment has
535 // already had it's offset properly set.
536 std::vector<Segment *> OrderedSegments;
537 for (auto &Segment : this->Segments)
538 OrderedSegments.push_back(Segment.get());
539 auto CompareSegments = [](const Segment *A, const Segment *B) {
540 // Any segment without a parent segment should come before a segment
541 // that has a parent segment.
542 if (A->OriginalOffset < B->OriginalOffset)
543 return true;
544 if (A->OriginalOffset > B->OriginalOffset)
545 return false;
546 return A->Index < B->Index;
547 };
548 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
549 CompareSegments);
Petr Hosek3f383832017-08-26 01:32:20 +0000550 // The size of ELF + program headers will not change so it is ok to assume
551 // that the first offset of the first segment is a good place to start
552 // outputting sections. This covers both the standard case and the PT_PHDR
553 // case.
554 uint64_t Offset;
Jake Ehrlich0a84b1a2017-09-19 18:14:03 +0000555 if (!OrderedSegments.empty()) {
556 Offset = OrderedSegments[0]->Offset;
Petr Hosek3f383832017-08-26 01:32:20 +0000557 } else {
558 Offset = sizeof(Elf_Ehdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000559 }
Petr Hosek3f383832017-08-26 01:32:20 +0000560 // The only way a segment should move is if a section was between two
561 // segments and that section was removed. If that section isn't in a segment
562 // then it's acceptable, but not ideal, to simply move it to after the
563 // segments. So we can simply layout segments one after the other accounting
564 // for alignment.
Jake Ehrlich0a84b1a2017-09-19 18:14:03 +0000565 for (auto &Segment : OrderedSegments) {
566 // We assume that segments have been ordered by OriginalOffset and Index
567 // such that a parent segment will always come before a child segment in
568 // OrderedSegments. This means that the Offset of the ParentSegment should
569 // already be set and we can set our offset relative to it.
570 if (Segment->ParentSegment != nullptr) {
571 auto Parent = Segment->ParentSegment;
572 Segment->Offset =
573 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
574 } else {
575 Offset = alignTo(Offset, Segment->Align == 0 ? 1 : Segment->Align);
576 Segment->Offset = Offset;
577 Offset += Segment->FileSize;
578 }
Petr Hosek3f383832017-08-26 01:32:20 +0000579 }
580 // Now the offset of every segment has been set we can assign the offsets
581 // of each section. For sections that are covered by a segment we should use
582 // the segment's original offset and the section's original offset to compute
583 // the offset from the start of the segment. Using the offset from the start
584 // of the segment we can assign a new offset to the section. For sections not
585 // covered by segments we can just bump Offset to the next valid location.
586 uint32_t Index = 1;
587 for (auto &Section : this->Sections) {
588 Section->Index = Index++;
589 if (Section->ParentSegment != nullptr) {
590 auto Segment = Section->ParentSegment;
591 Section->Offset =
592 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
593 } else {
594 Offset = alignTo(Offset, Section->Offset);
595 Section->Offset = Offset;
596 if (Section->Type != SHT_NOBITS)
597 Offset += Section->Size;
598 }
599 }
600
Petr Hosekc4df10e2017-08-04 21:09:26 +0000601 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
602 this->SHOffset = Offset;
603}
604
605template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
606 // We already have the section header offset so we can calculate the total
607 // size by just adding up the size of each section header.
608 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
609 sizeof(Elf_Shdr);
610}
611
612template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
613 this->writeHeader(Out);
614 this->writeProgramHeaders(Out);
615 this->writeSectionData(Out);
616 this->writeSectionHeaders(Out);
617}
618
619template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000620 // Make sure we add the names of all the sections.
Petr Hosekc4df10e2017-08-04 21:09:26 +0000621 for (const auto &Section : this->Sections) {
622 this->SectionNames->addString(Section->Name);
623 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000624 // Make sure we add the names of all the symbols.
625 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000626
627 sortSections();
628 assignOffsets();
629
630 // Finalize SectionNames first so that we can assign name indexes.
631 this->SectionNames->finalize();
632 // Finally now that all offsets and indexes have been set we can finalize any
633 // remaining issues.
634 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
635 for (auto &Section : this->Sections) {
636 Section->HeaderOffset = Offset;
637 Offset += sizeof(Elf_Shdr);
638 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
639 Section->finalize();
640 }
641
642 for (auto &Segment : this->Segments)
643 Segment->finalize();
644}
645
646template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
647 return TotalSize;
648}
649
650template <class ELFT>
651void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
652 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000653 // GNU objcopy does not output segments that do not cover a section. Such
654 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
655 if (Segment->Type == llvm::ELF::PT_LOAD &&
656 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000657 Segment->writeSegment(Out);
658 }
659 }
660}
661
662template <class ELFT> void BinaryObject<ELFT>::finalize() {
663 for (auto &Segment : this->Segments)
664 Segment->finalize();
665
666 // Put all segments in offset order.
667 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
668 return A->Offset < B->Offset;
669 };
670 std::sort(std::begin(this->Segments), std::end(this->Segments),
671 CompareSegments);
672
673 uint64_t Offset = 0;
674 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000675 if (Segment->Type == llvm::ELF::PT_LOAD &&
676 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000677 Offset = alignTo(Offset, Segment->Align);
678 Segment->Offset = Offset;
679 Offset += Segment->FileSize;
680 }
681 }
682 TotalSize = Offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000683}
684
Petr Hosek35fdbd52017-08-01 05:31:50 +0000685template class Object<ELF64LE>;
686template class Object<ELF64BE>;
687template class Object<ELF32LE>;
688template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000689
690template class ELFObject<ELF64LE>;
691template class ELFObject<ELF64BE>;
692template class ELFObject<ELF32LE>;
693template class ELFObject<ELF32BE>;
694
695template class BinaryObject<ELF64LE>;
696template class BinaryObject<ELF64BE>;
697template class BinaryObject<ELF32LE>;
698template class BinaryObject<ELF32BE>;