blob: 3e6606f70950c256ac863152ddeaa0d30161a48d [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
Petr Hosekc4df10e2017-08-04 21:09:26 +000033void 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
Jake Ehrlichf5a43772017-09-25 20:37:28 +000040void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000041void SectionBase::finalize() {}
42
43template <class ELFT>
44void SectionBase::writeHeader(FileOutputBuffer &Out) const {
45 uint8_t *Buf = Out.getBufferStart();
46 Buf += HeaderOffset;
47 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
48 Shdr.sh_name = NameIndex;
49 Shdr.sh_type = Type;
50 Shdr.sh_flags = Flags;
51 Shdr.sh_addr = Addr;
52 Shdr.sh_offset = Offset;
53 Shdr.sh_size = Size;
54 Shdr.sh_link = Link;
55 Shdr.sh_info = Info;
56 Shdr.sh_addralign = Align;
57 Shdr.sh_entsize = EntrySize;
58}
59
60void Section::writeSection(FileOutputBuffer &Out) const {
61 if (Type == SHT_NOBITS)
62 return;
63 uint8_t *Buf = Out.getBufferStart() + Offset;
64 std::copy(std::begin(Contents), std::end(Contents), Buf);
65}
66
67void StringTableSection::addString(StringRef Name) {
68 StrTabBuilder.add(Name);
69 Size = StrTabBuilder.getSize();
70}
71
72uint32_t StringTableSection::findIndex(StringRef Name) const {
73 return StrTabBuilder.getOffset(Name);
74}
75
76void StringTableSection::finalize() { StrTabBuilder.finalize(); }
77
78void StringTableSection::writeSection(FileOutputBuffer &Out) const {
79 StrTabBuilder.write(Out.getBufferStart() + Offset);
80}
81
Petr Hosekc1135772017-09-13 03:04:50 +000082static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +000083 switch (Index) {
84 case SHN_ABS:
85 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +000086 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +000087 }
Petr Hosekc1135772017-09-13 03:04:50 +000088 if (Machine == EM_HEXAGON) {
89 switch (Index) {
90 case SHN_HEXAGON_SCOMMON:
91 case SHN_HEXAGON_SCOMMON_2:
92 case SHN_HEXAGON_SCOMMON_4:
93 case SHN_HEXAGON_SCOMMON_8:
94 return true;
95 }
96 }
97 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +000098}
99
100uint16_t Symbol::getShndx() const {
101 if (DefinedIn != nullptr) {
102 return DefinedIn->Index;
103 }
104 switch (ShndxType) {
105 // This means that we don't have a defined section but we do need to
106 // output a legitimate section index.
107 case SYMBOL_SIMPLE_INDEX:
108 return SHN_UNDEF;
109 case SYMBOL_ABS:
110 case SYMBOL_COMMON:
111 case SYMBOL_HEXAGON_SCOMMON:
112 case SYMBOL_HEXAGON_SCOMMON_2:
113 case SYMBOL_HEXAGON_SCOMMON_4:
114 case SYMBOL_HEXAGON_SCOMMON_8:
115 return static_cast<uint16_t>(ShndxType);
116 }
117 llvm_unreachable("Symbol with invalid ShndxType encountered");
118}
119
Petr Hosek79cee9e2017-08-29 02:12:03 +0000120void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
121 SectionBase *DefinedIn, uint64_t Value,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000122 uint16_t Shndx, uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000123 Symbol Sym;
124 Sym.Name = Name;
125 Sym.Binding = Bind;
126 Sym.Type = Type;
127 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000128 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000129 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000130 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
131 else
132 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
133 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000134 Sym.Value = Value;
135 Sym.Size = Sz;
136 Sym.Index = Symbols.size();
137 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
138 Size += this->EntrySize;
139}
140
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000141void SymbolTableSection::initialize(SectionTableRef SecTable) {
142 Size = 0;
143 setStrTab(SecTable.getSectionOfType<StringTableSection>(
144 Link,
145 "Symbol table has link index of " + Twine(Link) +
146 " which is not a valid index",
147 "Symbol table has link index of " + Twine(Link) +
148 " which is not a string table"));
149}
150
Petr Hosek79cee9e2017-08-29 02:12:03 +0000151void SymbolTableSection::finalize() {
152 // Make sure SymbolNames is finalized before getting name indexes.
153 SymbolNames->finalize();
154
155 uint32_t MaxLocalIndex = 0;
156 for (auto &Sym : Symbols) {
157 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
158 if (Sym->Binding == STB_LOCAL)
159 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
160 }
161 // Now we need to set the Link and Info fields.
162 Link = SymbolNames->Index;
163 Info = MaxLocalIndex + 1;
164}
165
166void SymbolTableSection::addSymbolNames() {
167 // Add all of our strings to SymbolNames so that SymbolNames has the right
168 // size before layout is decided.
169 for (auto &Sym : Symbols)
170 SymbolNames->addString(Sym->Name);
171}
172
173const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
174 if (Symbols.size() <= Index)
175 error("Invalid symbol index: " + Twine(Index));
176 return Symbols[Index].get();
177}
178
179template <class ELFT>
180void SymbolTableSectionImpl<ELFT>::writeSection(
181 llvm::FileOutputBuffer &Out) const {
182 uint8_t *Buf = Out.getBufferStart();
183 Buf += Offset;
184 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
185 // Loop though symbols setting each entry of the symbol table.
186 for (auto &Symbol : Symbols) {
187 Sym->st_name = Symbol->NameIndex;
188 Sym->st_value = Symbol->Value;
189 Sym->st_size = Symbol->Size;
190 Sym->setBinding(Symbol->Binding);
191 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000192 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000193 ++Sym;
194 }
195}
196
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000197template <class SymTabType>
198void RelocationSectionBase<SymTabType>::initialize(SectionTableRef SecTable) {
199 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000200 Link,
201 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
202 "Link field value " + Twine(Link) + " in section " + Name +
203 " is not a symbol table"));
204
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000205 if (Info != SHN_UNDEF)
206 setSection(SecTable.getSection(Info,
207 "Info field value " + Twine(Info) +
208 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000209 else
210 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000211}
212
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000213template <class SymTabType> void RelocationSectionBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000214 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000215 if (SecToApplyRel != nullptr)
216 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000217}
218
219template <class ELFT>
220void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
221
222template <class ELFT>
223void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
224 Rela.r_addend = Addend;
225}
226
227template <class ELFT>
228template <class T>
229void RelocationSection<ELFT>::writeRel(T *Buf) const {
230 for (const auto &Reloc : Relocations) {
231 Buf->r_offset = Reloc.Offset;
232 setAddend(*Buf, Reloc.Addend);
233 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
234 ++Buf;
235 }
236}
237
238template <class ELFT>
239void RelocationSection<ELFT>::writeSection(llvm::FileOutputBuffer &Out) const {
240 uint8_t *Buf = Out.getBufferStart() + Offset;
241 if (Type == SHT_REL)
242 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
243 else
244 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
245}
246
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000247void DynamicRelocationSection::writeSection(llvm::FileOutputBuffer &Out) const {
248 std::copy(std::begin(Contents), std::end(Contents),
249 Out.getBufferStart() + Offset);
250}
251
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000252bool SectionWithStrTab::classof(const SectionBase *S) {
253 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
254}
255
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000256void SectionWithStrTab::initialize(SectionTableRef SecTable) {
257 setStrTab(SecTable.getSectionOfType<StringTableSection>(
258 Link,
259 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
260 "Link field value " + Twine(Link) + " in section " + Name +
261 " is not a string table"));
262}
263
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000264void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
265
Petr Hosek05a04cb2017-08-01 00:33:58 +0000266// Returns true IFF a section is wholly inside the range of a segment
267static bool sectionWithinSegment(const SectionBase &Section,
268 const Segment &Segment) {
269 // If a section is empty it should be treated like it has a size of 1. This is
270 // to clarify the case when an empty section lies on a boundary between two
271 // segments and ensures that the section "belongs" to the second segment and
272 // not the first.
273 uint64_t SecSize = Section.Size ? Section.Size : 1;
274 return Segment.Offset <= Section.OriginalOffset &&
275 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
276}
277
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000278// Returns true IFF a segment's original offset is inside of another segment's
279// range.
280static bool segmentOverlapsSegment(const Segment &Child,
281 const Segment &Parent) {
282
283 return Parent.OriginalOffset <= Child.OriginalOffset &&
284 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
285}
286
Petr Hosek05a04cb2017-08-01 00:33:58 +0000287template <class ELFT>
288void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
289 uint32_t Index = 0;
290 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000291 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
292 (size_t)Phdr.p_filesz};
293 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000294 Segment &Seg = *Segments.back();
295 Seg.Type = Phdr.p_type;
296 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000297 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000298 Seg.Offset = Phdr.p_offset;
299 Seg.VAddr = Phdr.p_vaddr;
300 Seg.PAddr = Phdr.p_paddr;
301 Seg.FileSize = Phdr.p_filesz;
302 Seg.MemSize = Phdr.p_memsz;
303 Seg.Align = Phdr.p_align;
304 Seg.Index = Index++;
305 for (auto &Section : Sections) {
306 if (sectionWithinSegment(*Section, Seg)) {
307 Seg.addSection(&*Section);
308 if (!Section->ParentSegment ||
309 Section->ParentSegment->Offset > Seg.Offset) {
310 Section->ParentSegment = &Seg;
311 }
312 }
313 }
314 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000315 // Now we do an O(n^2) loop through the segments in order to match up
316 // segments.
317 for (auto &Child : Segments) {
318 for (auto &Parent : Segments) {
319 // Every segment will overlap with itself but we don't want a segment to
320 // be it's own parent so we avoid that situation.
321 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
322 // We want a canonical "most parental" segment but this requires
323 // inspecting the ParentSegment.
324 if (Child->ParentSegment != nullptr) {
325 if (Child->ParentSegment->OriginalOffset > Parent->OriginalOffset) {
326 Child->ParentSegment = Parent.get();
327 } else if (Child->ParentSegment->Index > Parent->Index) {
328 // They must have equal OriginalOffsets so we need to disambiguate.
329 // To decide which is the parent we'll choose the one with the
330 // higher index.
331 Child->ParentSegment = Parent.get();
332 }
333 } else {
334 Child->ParentSegment = Parent.get();
335 }
336 }
337 }
338 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000339}
340
341template <class ELFT>
Petr Hosek79cee9e2017-08-29 02:12:03 +0000342void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000343 SymbolTableSection *SymTab,
344 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000345
346 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
347 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
348
349 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
350 SectionBase *DefSection = nullptr;
351 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000352
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000353 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000354 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000355 error(
356 "Symbol '" + Name +
357 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
358 Twine(Sym.st_shndx));
359 }
360 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000361 DefSection = SecTable.getSection(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000362 Sym.st_shndx,
363 "Symbol '" + Name + "' is defined in invalid section with index " +
Petr Hosek79cee9e2017-08-29 02:12:03 +0000364 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000365 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000366
Petr Hosek79cee9e2017-08-29 02:12:03 +0000367 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000368 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000369 }
370}
371
372template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000373static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
374
375template <class ELFT>
376static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
377 ToSet = Rela.r_addend;
378}
379
380template <class ELFT, class T>
381void initRelocations(RelocationSection<ELFT> *Relocs,
382 SymbolTableSection *SymbolTable, T RelRange) {
383 for (const auto &Rel : RelRange) {
384 Relocation ToAdd;
385 ToAdd.Offset = Rel.r_offset;
386 getAddend(ToAdd.Addend, Rel);
387 ToAdd.Type = Rel.getType(false);
388 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
389 Relocs->addRelocation(ToAdd);
390 }
391}
392
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000393SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
394 if (Index == SHN_UNDEF || Index > Sections.size())
395 error(ErrMsg);
396 return Sections[Index - 1].get();
397}
398
399template <class T>
400T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000401 Twine TypeErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000402 if (T *Sec = llvm::dyn_cast<T>(getSection(Index, IndexErrMsg)))
403 return Sec;
404 error(TypeErrMsg);
405}
406
Petr Hosekd7df9b22017-09-06 23:41:02 +0000407template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000408std::unique_ptr<SectionBase>
409Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
410 const Elf_Shdr &Shdr) {
411 ArrayRef<uint8_t> Data;
412 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000413 case SHT_REL:
414 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000415 if (Shdr.sh_flags & SHF_ALLOC) {
416 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
417 return llvm::make_unique<DynamicRelocationSection>(Data);
418 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000419 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000420 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000421 // If a string table is allocated we don't want to mess with it. That would
422 // mean altering the memory image. There are no special link types or
423 // anything so we can just use a Section.
424 if (Shdr.sh_flags & SHF_ALLOC) {
425 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
426 return llvm::make_unique<Section>(Data);
427 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000428 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000429 case SHT_HASH:
430 case SHT_GNU_HASH:
431 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
432 // Because of this we don't need to mess with the hash tables either.
433 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
434 return llvm::make_unique<Section>(Data);
435 case SHT_DYNSYM:
436 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
437 return llvm::make_unique<DynamicSymbolTableSection>(Data);
438 case SHT_DYNAMIC:
439 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
440 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000441 case SHT_SYMTAB: {
442 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
443 SymbolTable = SymTab.get();
444 return std::move(SymTab);
445 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000446 case SHT_NOBITS:
447 return llvm::make_unique<Section>(Data);
448 default:
449 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
450 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000451 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000452}
453
454template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000455SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000456 uint32_t Index = 0;
457 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
458 if (Index == 0) {
459 ++Index;
460 continue;
461 }
462 SecPtr Sec = makeSection(ElfFile, Shdr);
463 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
464 Sec->Type = Shdr.sh_type;
465 Sec->Flags = Shdr.sh_flags;
466 Sec->Addr = Shdr.sh_addr;
467 Sec->Offset = Shdr.sh_offset;
468 Sec->OriginalOffset = Shdr.sh_offset;
469 Sec->Size = Shdr.sh_size;
470 Sec->Link = Shdr.sh_link;
471 Sec->Info = Shdr.sh_info;
472 Sec->Align = Shdr.sh_addralign;
473 Sec->EntrySize = Shdr.sh_entsize;
474 Sec->Index = Index++;
475 Sections.push_back(std::move(Sec));
476 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000477
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000478 SectionTableRef SecTable(Sections);
479
Petr Hosek79cee9e2017-08-29 02:12:03 +0000480 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000481 // details about symbol tables. We need the symbol table filled out before
482 // any relocations.
483 if (SymbolTable) {
484 SymbolTable->initialize(SecTable);
485 initSymbolTable(ElfFile, SymbolTable, SecTable);
486 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000487
488 // Now that all sections and symbols have been added we can add
489 // relocations that reference symbols and set the link and info fields for
490 // relocation sections.
491 for (auto &Section : Sections) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000492 if (Section.get() == SymbolTable)
493 continue;
494 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000495 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000496 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
497 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000498 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000499 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000500 initRelocations(RelSec, SymbolTable,
501 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000502 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000503
504 if (auto Sec = dyn_cast<SectionWithStrTab>(Section.get())) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000505 Sec->setStrTab(SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000506 Sec->Link,
507 "Link field value " + Twine(Sec->Link) + " in section " + Sec->Name +
508 " is invalid",
509 "Link field value " + Twine(Sec->Link) + " in section " + Sec->Name +
510 " is not a string table"));
511 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000512 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000513
514 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000515}
516
Petr Hosek05a04cb2017-08-01 00:33:58 +0000517template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
518 const auto &ElfFile = *Obj.getELFFile();
519 const auto &Ehdr = *ElfFile.getHeader();
520
521 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
522 Type = Ehdr.e_type;
523 Machine = Ehdr.e_machine;
524 Version = Ehdr.e_version;
525 Entry = Ehdr.e_entry;
526 Flags = Ehdr.e_flags;
527
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000528 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000529 readProgramHeaders(ElfFile);
530
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000531 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000532 Ehdr.e_shstrndx,
533 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
534 " is invalid",
535 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
536 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000537}
538
Petr Hosek05a04cb2017-08-01 00:33:58 +0000539template <class ELFT>
540void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
541 uint8_t *Buf = Out.getBufferStart();
542 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
543 std::copy(Ident, Ident + 16, Ehdr.e_ident);
544 Ehdr.e_type = Type;
545 Ehdr.e_machine = Machine;
546 Ehdr.e_version = Version;
547 Ehdr.e_entry = Entry;
548 Ehdr.e_phoff = sizeof(Elf_Ehdr);
549 Ehdr.e_shoff = SHOffset;
550 Ehdr.e_flags = Flags;
551 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
552 Ehdr.e_phentsize = sizeof(Elf_Phdr);
553 Ehdr.e_phnum = Segments.size();
554 Ehdr.e_shentsize = sizeof(Elf_Shdr);
555 Ehdr.e_shnum = Sections.size() + 1;
556 Ehdr.e_shstrndx = SectionNames->Index;
557}
558
559template <class ELFT>
560void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
561 for (auto &Phdr : Segments)
562 Phdr->template writeHeader<ELFT>(Out);
563}
564
565template <class ELFT>
566void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
567 uint8_t *Buf = Out.getBufferStart() + SHOffset;
568 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000569 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000570 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
571 Shdr.sh_name = 0;
572 Shdr.sh_type = SHT_NULL;
573 Shdr.sh_flags = 0;
574 Shdr.sh_addr = 0;
575 Shdr.sh_offset = 0;
576 Shdr.sh_size = 0;
577 Shdr.sh_link = 0;
578 Shdr.sh_info = 0;
579 Shdr.sh_addralign = 0;
580 Shdr.sh_entsize = 0;
581
582 for (auto &Section : Sections)
583 Section->template writeHeader<ELFT>(Out);
584}
585
586template <class ELFT>
587void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
588 for (auto &Section : Sections)
589 Section->writeSection(Out);
590}
591
Petr Hosekc4df10e2017-08-04 21:09:26 +0000592template <class ELFT> void ELFObject<ELFT>::sortSections() {
593 // Put all sections in offset order. Maintain the ordering as closely as
594 // possible while meeting that demand however.
595 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
596 return A->OriginalOffset < B->OriginalOffset;
597 };
598 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
599 CompareSections);
600}
601
602template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000603 // We need a temporary list of segments that has a special order to it
604 // so that we know that anytime ->ParentSegment is set that segment has
605 // already had it's offset properly set.
606 std::vector<Segment *> OrderedSegments;
607 for (auto &Segment : this->Segments)
608 OrderedSegments.push_back(Segment.get());
609 auto CompareSegments = [](const Segment *A, const Segment *B) {
610 // Any segment without a parent segment should come before a segment
611 // that has a parent segment.
612 if (A->OriginalOffset < B->OriginalOffset)
613 return true;
614 if (A->OriginalOffset > B->OriginalOffset)
615 return false;
616 return A->Index < B->Index;
617 };
618 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
619 CompareSegments);
Petr Hosek3f383832017-08-26 01:32:20 +0000620 // The size of ELF + program headers will not change so it is ok to assume
621 // that the first offset of the first segment is a good place to start
622 // outputting sections. This covers both the standard case and the PT_PHDR
623 // case.
624 uint64_t Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000625 if (!OrderedSegments.empty()) {
626 Offset = OrderedSegments[0]->Offset;
Petr Hosek3f383832017-08-26 01:32:20 +0000627 } else {
628 Offset = sizeof(Elf_Ehdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000629 }
Petr Hosek3f383832017-08-26 01:32:20 +0000630 // The only way a segment should move is if a section was between two
631 // segments and that section was removed. If that section isn't in a segment
632 // then it's acceptable, but not ideal, to simply move it to after the
633 // segments. So we can simply layout segments one after the other accounting
634 // for alignment.
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000635 for (auto &Segment : OrderedSegments) {
636 // We assume that segments have been ordered by OriginalOffset and Index
637 // such that a parent segment will always come before a child segment in
638 // OrderedSegments. This means that the Offset of the ParentSegment should
639 // already be set and we can set our offset relative to it.
640 if (Segment->ParentSegment != nullptr) {
641 auto Parent = Segment->ParentSegment;
642 Segment->Offset =
643 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
644 } else {
645 Offset = alignTo(Offset, Segment->Align == 0 ? 1 : Segment->Align);
646 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000647 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000648 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000649 }
650 // Now the offset of every segment has been set we can assign the offsets
651 // of each section. For sections that are covered by a segment we should use
652 // the segment's original offset and the section's original offset to compute
653 // the offset from the start of the segment. Using the offset from the start
654 // of the segment we can assign a new offset to the section. For sections not
655 // covered by segments we can just bump Offset to the next valid location.
656 uint32_t Index = 1;
657 for (auto &Section : this->Sections) {
658 Section->Index = Index++;
659 if (Section->ParentSegment != nullptr) {
660 auto Segment = Section->ParentSegment;
661 Section->Offset =
662 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
663 } else {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000664 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000665 Section->Offset = Offset;
666 if (Section->Type != SHT_NOBITS)
667 Offset += Section->Size;
668 }
669 }
670
Petr Hosekc4df10e2017-08-04 21:09:26 +0000671 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
672 this->SHOffset = Offset;
673}
674
675template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
676 // We already have the section header offset so we can calculate the total
677 // size by just adding up the size of each section header.
678 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
679 sizeof(Elf_Shdr);
680}
681
682template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
683 this->writeHeader(Out);
684 this->writeProgramHeaders(Out);
685 this->writeSectionData(Out);
686 this->writeSectionHeaders(Out);
687}
688
689template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000690 // Make sure we add the names of all the sections.
Petr Hosekc4df10e2017-08-04 21:09:26 +0000691 for (const auto &Section : this->Sections) {
692 this->SectionNames->addString(Section->Name);
693 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000694 // Make sure we add the names of all the symbols.
695 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000696
697 sortSections();
698 assignOffsets();
699
700 // Finalize SectionNames first so that we can assign name indexes.
701 this->SectionNames->finalize();
702 // Finally now that all offsets and indexes have been set we can finalize any
703 // remaining issues.
704 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
705 for (auto &Section : this->Sections) {
706 Section->HeaderOffset = Offset;
707 Offset += sizeof(Elf_Shdr);
708 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
709 Section->finalize();
710 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000711}
712
713template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
714 return TotalSize;
715}
716
717template <class ELFT>
718void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
719 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000720 // GNU objcopy does not output segments that do not cover a section. Such
721 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
722 if (Segment->Type == llvm::ELF::PT_LOAD &&
723 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000724 Segment->writeSegment(Out);
725 }
726 }
727}
728
729template <class ELFT> void BinaryObject<ELFT>::finalize() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000730
731 // Put all segments in offset order.
732 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
733 return A->Offset < B->Offset;
734 };
735 std::sort(std::begin(this->Segments), std::end(this->Segments),
736 CompareSegments);
737
738 uint64_t Offset = 0;
739 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000740 if (Segment->Type == llvm::ELF::PT_LOAD &&
741 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000742 Offset = alignTo(Offset, Segment->Align);
743 Segment->Offset = Offset;
744 Offset += Segment->FileSize;
745 }
746 }
747 TotalSize = Offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000748}
749
Petr Hosek35fdbd52017-08-01 05:31:50 +0000750template class Object<ELF64LE>;
751template class Object<ELF64BE>;
752template class Object<ELF32LE>;
753template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000754
755template class ELFObject<ELF64LE>;
756template class ELFObject<ELF64BE>;
757template class ELFObject<ELF32LE>;
758template class ELFObject<ELF32BE>;
759
760template class BinaryObject<ELF64LE>;
761template class BinaryObject<ELF64BE>;
762template class BinaryObject<ELF32LE>;
763template class BinaryObject<ELF32BE>;