blob: 0d16e69923dd04bcd11e1360fe0cc3fb72e3e435 [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
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000231bool SectionWithStrTab::classof(const SectionBase *S) {
232 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
233}
234
235void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
236
Petr Hosek05a04cb2017-08-01 00:33:58 +0000237// Returns true IFF a section is wholly inside the range of a segment
238static bool sectionWithinSegment(const SectionBase &Section,
239 const Segment &Segment) {
240 // If a section is empty it should be treated like it has a size of 1. This is
241 // to clarify the case when an empty section lies on a boundary between two
242 // segments and ensures that the section "belongs" to the second segment and
243 // not the first.
244 uint64_t SecSize = Section.Size ? Section.Size : 1;
245 return Segment.Offset <= Section.OriginalOffset &&
246 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
247}
248
249template <class ELFT>
250void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
251 uint32_t Index = 0;
252 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000253 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
254 (size_t)Phdr.p_filesz};
255 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000256 Segment &Seg = *Segments.back();
257 Seg.Type = Phdr.p_type;
258 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000259 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000260 Seg.Offset = Phdr.p_offset;
261 Seg.VAddr = Phdr.p_vaddr;
262 Seg.PAddr = Phdr.p_paddr;
263 Seg.FileSize = Phdr.p_filesz;
264 Seg.MemSize = Phdr.p_memsz;
265 Seg.Align = Phdr.p_align;
266 Seg.Index = Index++;
267 for (auto &Section : Sections) {
268 if (sectionWithinSegment(*Section, Seg)) {
269 Seg.addSection(&*Section);
270 if (!Section->ParentSegment ||
271 Section->ParentSegment->Offset > Seg.Offset) {
272 Section->ParentSegment = &Seg;
273 }
274 }
275 }
276 }
277}
278
279template <class ELFT>
Petr Hosek79cee9e2017-08-29 02:12:03 +0000280void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
281 SymbolTableSection *SymTab) {
282
283 SymTab->Size = 0;
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000284 SymTab->setStrTab(getSectionOfType<StringTableSection>(
285 SymbolTable->Link,
286 "Symbol table has link index of " + Twine(SymTab->Link) +
287 " which is not a valid index",
288 "Symbol table has link index of " + Twine(SymTab->Link) +
289 " which is not a string table"));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000290
291 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
292 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
293
294 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
295 SectionBase *DefSection = nullptr;
296 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000297
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000298 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000299 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000300 error(
301 "Symbol '" + Name +
302 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
303 Twine(Sym.st_shndx));
304 }
305 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000306 DefSection = getSection(
307 Sym.st_shndx,
308 "Symbol '" + Name + "' is defined in invalid section with index " +
Petr Hosek79cee9e2017-08-29 02:12:03 +0000309 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000310 }
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000311
Petr Hosek79cee9e2017-08-29 02:12:03 +0000312 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000313 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000314 }
315}
316
317template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000318static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
319
320template <class ELFT>
321static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
322 ToSet = Rela.r_addend;
323}
324
325template <class ELFT, class T>
326void initRelocations(RelocationSection<ELFT> *Relocs,
327 SymbolTableSection *SymbolTable, T RelRange) {
328 for (const auto &Rel : RelRange) {
329 Relocation ToAdd;
330 ToAdd.Offset = Rel.r_offset;
331 getAddend(ToAdd.Addend, Rel);
332 ToAdd.Type = Rel.getType(false);
333 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
334 Relocs->addRelocation(ToAdd);
335 }
336}
337
338template <class ELFT>
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000339SectionBase *Object<ELFT>::getSection(uint16_t Index, Twine ErrMsg) {
340 if (Index == SHN_UNDEF || Index > Sections.size())
341 error(ErrMsg);
342 return Sections[Index - 1].get();
343}
344
345template <class ELFT>
346template <class T>
347T *Object<ELFT>::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
348 Twine TypeErrMsg) {
349 if (T *TSec = llvm::dyn_cast<T>(getSection(Index, IndexErrMsg)))
350 return TSec;
351 error(TypeErrMsg);
352}
353
354template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000355std::unique_ptr<SectionBase>
356Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
357 const Elf_Shdr &Shdr) {
358 ArrayRef<uint8_t> Data;
359 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000360 case SHT_REL:
361 case SHT_RELA:
362 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000363 case SHT_STRTAB:
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000364 // If a string table is allocated we don't want to mess with it. That would
365 // mean altering the memory image. There are no special link types or
366 // anything so we can just use a Section.
367 if (Shdr.sh_flags & SHF_ALLOC) {
368 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
369 return llvm::make_unique<Section>(Data);
370 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000371 return llvm::make_unique<StringTableSection>();
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000372 case SHT_HASH:
373 case SHT_GNU_HASH:
374 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
375 // Because of this we don't need to mess with the hash tables either.
376 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
377 return llvm::make_unique<Section>(Data);
378 case SHT_DYNSYM:
379 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
380 return llvm::make_unique<DynamicSymbolTableSection>(Data);
381 case SHT_DYNAMIC:
382 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
383 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000384 case SHT_SYMTAB: {
385 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
386 SymbolTable = SymTab.get();
387 return std::move(SymTab);
388 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000389 case SHT_NOBITS:
390 return llvm::make_unique<Section>(Data);
391 default:
392 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
393 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000394 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000395}
396
397template <class ELFT>
398void Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
399 uint32_t Index = 0;
400 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
401 if (Index == 0) {
402 ++Index;
403 continue;
404 }
405 SecPtr Sec = makeSection(ElfFile, Shdr);
406 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
407 Sec->Type = Shdr.sh_type;
408 Sec->Flags = Shdr.sh_flags;
409 Sec->Addr = Shdr.sh_addr;
410 Sec->Offset = Shdr.sh_offset;
411 Sec->OriginalOffset = Shdr.sh_offset;
412 Sec->Size = Shdr.sh_size;
413 Sec->Link = Shdr.sh_link;
414 Sec->Info = Shdr.sh_info;
415 Sec->Align = Shdr.sh_addralign;
416 Sec->EntrySize = Shdr.sh_entsize;
417 Sec->Index = Index++;
418 Sections.push_back(std::move(Sec));
419 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000420
421 // Now that all of the sections have been added we can fill out some extra
422 // details about symbol tables.
423 if (SymbolTable)
424 initSymbolTable(ElfFile, SymbolTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000425
426 // Now that all sections and symbols have been added we can add
427 // relocations that reference symbols and set the link and info fields for
428 // relocation sections.
429 for (auto &Section : Sections) {
430 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000431
432 auto SymTab = getSectionOfType<SymbolTableSection>(
433 RelSec->Link,
434 "Link field value " + Twine(RelSec->Link) + " in section " +
435 RelSec->Name + " is invalid",
436 "Link field value " + Twine(RelSec->Link) + " in section " +
437 RelSec->Name + " is not a symbol table");
Petr Hosekd7df9b22017-09-06 23:41:02 +0000438 RelSec->setSymTab(SymTab);
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000439
440 RelSec->setSection(getSection(RelSec->Info,
441 "Info field value " + Twine(RelSec->Link) +
442 " in section " + RelSec->Name +
443 " is invalid"));
444
Petr Hosekd7df9b22017-09-06 23:41:02 +0000445 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
446 if (RelSec->Type == SHT_REL)
447 initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.rels(Shdr)));
448 else
449 initRelocations(RelSec, SymTab, unwrapOrError(ElfFile.relas(Shdr)));
450 }
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000451
452 if (auto Sec = dyn_cast<SectionWithStrTab>(Section.get())) {
453 Sec->setStrTab(getSectionOfType<StringTableSection>(
454 Sec->Link,
455 "Link field value " + Twine(Sec->Link) + " in section " + Sec->Name +
456 " is invalid",
457 "Link field value " + Twine(Sec->Link) + " in section " + Sec->Name +
458 " is not a string table"));
459 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000460 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000461}
462
Petr Hosek05a04cb2017-08-01 00:33:58 +0000463template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
464 const auto &ElfFile = *Obj.getELFFile();
465 const auto &Ehdr = *ElfFile.getHeader();
466
467 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
468 Type = Ehdr.e_type;
469 Machine = Ehdr.e_machine;
470 Version = Ehdr.e_version;
471 Entry = Ehdr.e_entry;
472 Flags = Ehdr.e_flags;
473
474 readSectionHeaders(ElfFile);
475 readProgramHeaders(ElfFile);
476
Jake Ehrlichf20c3f42017-09-19 19:21:09 +0000477 SectionNames = getSectionOfType<StringTableSection>(
478 Ehdr.e_shstrndx,
479 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
480 " is invalid",
481 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
482 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000483}
484
Petr Hosek05a04cb2017-08-01 00:33:58 +0000485template <class ELFT>
486void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
487 uint8_t *Buf = Out.getBufferStart();
488 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
489 std::copy(Ident, Ident + 16, Ehdr.e_ident);
490 Ehdr.e_type = Type;
491 Ehdr.e_machine = Machine;
492 Ehdr.e_version = Version;
493 Ehdr.e_entry = Entry;
494 Ehdr.e_phoff = sizeof(Elf_Ehdr);
495 Ehdr.e_shoff = SHOffset;
496 Ehdr.e_flags = Flags;
497 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
498 Ehdr.e_phentsize = sizeof(Elf_Phdr);
499 Ehdr.e_phnum = Segments.size();
500 Ehdr.e_shentsize = sizeof(Elf_Shdr);
501 Ehdr.e_shnum = Sections.size() + 1;
502 Ehdr.e_shstrndx = SectionNames->Index;
503}
504
505template <class ELFT>
506void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
507 for (auto &Phdr : Segments)
508 Phdr->template writeHeader<ELFT>(Out);
509}
510
511template <class ELFT>
512void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
513 uint8_t *Buf = Out.getBufferStart() + SHOffset;
514 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000515 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000516 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
517 Shdr.sh_name = 0;
518 Shdr.sh_type = SHT_NULL;
519 Shdr.sh_flags = 0;
520 Shdr.sh_addr = 0;
521 Shdr.sh_offset = 0;
522 Shdr.sh_size = 0;
523 Shdr.sh_link = 0;
524 Shdr.sh_info = 0;
525 Shdr.sh_addralign = 0;
526 Shdr.sh_entsize = 0;
527
528 for (auto &Section : Sections)
529 Section->template writeHeader<ELFT>(Out);
530}
531
532template <class ELFT>
533void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
534 for (auto &Section : Sections)
535 Section->writeSection(Out);
536}
537
Petr Hosekc4df10e2017-08-04 21:09:26 +0000538template <class ELFT> void ELFObject<ELFT>::sortSections() {
539 // Put all sections in offset order. Maintain the ordering as closely as
540 // possible while meeting that demand however.
541 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
542 return A->OriginalOffset < B->OriginalOffset;
543 };
544 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
545 CompareSections);
546}
547
548template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
Petr Hosek3f383832017-08-26 01:32:20 +0000549 // The size of ELF + program headers will not change so it is ok to assume
550 // that the first offset of the first segment is a good place to start
551 // outputting sections. This covers both the standard case and the PT_PHDR
552 // case.
553 uint64_t Offset;
Jake Ehrlich8f108242017-09-19 19:52:09 +0000554 if (!this->Segments.empty()) {
555 Offset = this->Segments[0]->Offset;
Petr Hosek3f383832017-08-26 01:32:20 +0000556 } else {
557 Offset = sizeof(Elf_Ehdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000558 }
Petr Hosek3f383832017-08-26 01:32:20 +0000559 // The only way a segment should move is if a section was between two
560 // segments and that section was removed. If that section isn't in a segment
561 // then it's acceptable, but not ideal, to simply move it to after the
562 // segments. So we can simply layout segments one after the other accounting
563 // for alignment.
Jake Ehrlich8f108242017-09-19 19:52:09 +0000564 for (auto &Segment : this->Segments) {
565 Offset = alignTo(Offset, Segment->Align);
566 Segment->Offset = Offset;
567 Offset += Segment->FileSize;
Petr Hosek3f383832017-08-26 01:32:20 +0000568 }
569 // Now the offset of every segment has been set we can assign the offsets
570 // of each section. For sections that are covered by a segment we should use
571 // the segment's original offset and the section's original offset to compute
572 // the offset from the start of the segment. Using the offset from the start
573 // of the segment we can assign a new offset to the section. For sections not
574 // covered by segments we can just bump Offset to the next valid location.
575 uint32_t Index = 1;
576 for (auto &Section : this->Sections) {
577 Section->Index = Index++;
578 if (Section->ParentSegment != nullptr) {
579 auto Segment = Section->ParentSegment;
580 Section->Offset =
581 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
582 } else {
583 Offset = alignTo(Offset, Section->Offset);
584 Section->Offset = Offset;
585 if (Section->Type != SHT_NOBITS)
586 Offset += Section->Size;
587 }
588 }
589
Petr Hosekc4df10e2017-08-04 21:09:26 +0000590 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
591 this->SHOffset = Offset;
592}
593
594template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
595 // We already have the section header offset so we can calculate the total
596 // size by just adding up the size of each section header.
597 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
598 sizeof(Elf_Shdr);
599}
600
601template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
602 this->writeHeader(Out);
603 this->writeProgramHeaders(Out);
604 this->writeSectionData(Out);
605 this->writeSectionHeaders(Out);
606}
607
608template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000609 // Make sure we add the names of all the sections.
Petr Hosekc4df10e2017-08-04 21:09:26 +0000610 for (const auto &Section : this->Sections) {
611 this->SectionNames->addString(Section->Name);
612 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000613 // Make sure we add the names of all the symbols.
614 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000615
616 sortSections();
617 assignOffsets();
618
619 // Finalize SectionNames first so that we can assign name indexes.
620 this->SectionNames->finalize();
621 // Finally now that all offsets and indexes have been set we can finalize any
622 // remaining issues.
623 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
624 for (auto &Section : this->Sections) {
625 Section->HeaderOffset = Offset;
626 Offset += sizeof(Elf_Shdr);
627 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
628 Section->finalize();
629 }
630
631 for (auto &Segment : this->Segments)
632 Segment->finalize();
633}
634
635template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
636 return TotalSize;
637}
638
639template <class ELFT>
640void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
641 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000642 // GNU objcopy does not output segments that do not cover a section. Such
643 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
644 if (Segment->Type == llvm::ELF::PT_LOAD &&
645 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000646 Segment->writeSegment(Out);
647 }
648 }
649}
650
651template <class ELFT> void BinaryObject<ELFT>::finalize() {
652 for (auto &Segment : this->Segments)
653 Segment->finalize();
654
655 // Put all segments in offset order.
656 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
657 return A->Offset < B->Offset;
658 };
659 std::sort(std::begin(this->Segments), std::end(this->Segments),
660 CompareSegments);
661
662 uint64_t Offset = 0;
663 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000664 if (Segment->Type == llvm::ELF::PT_LOAD &&
665 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000666 Offset = alignTo(Offset, Segment->Align);
667 Segment->Offset = Offset;
668 Offset += Segment->FileSize;
669 }
670 }
671 TotalSize = Offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000672}
673
Petr Hosek35fdbd52017-08-01 05:31:50 +0000674template class Object<ELF64LE>;
675template class Object<ELF64BE>;
676template class Object<ELF32LE>;
677template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000678
679template class ELFObject<ELF64LE>;
680template class ELFObject<ELF64BE>;
681template class ELFObject<ELF32LE>;
682template class ELFObject<ELF32BE>;
683
684template class BinaryObject<ELF64LE>;
685template class BinaryObject<ELF64BE>;
686template class BinaryObject<ELF32LE>;
687template class BinaryObject<ELF32BE>;