blob: f9acf001ae93be08812c5e360080337c84ced675 [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 Ehrlich36a2eb32017-10-10 18:47:09 +000040void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000041void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000042void SectionBase::finalize() {}
43
44template <class ELFT>
45void 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
61void 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
68void StringTableSection::addString(StringRef Name) {
69 StrTabBuilder.add(Name);
70 Size = StrTabBuilder.getSize();
71}
72
73uint32_t StringTableSection::findIndex(StringRef Name) const {
74 return StrTabBuilder.getOffset(Name);
75}
76
77void StringTableSection::finalize() { StrTabBuilder.finalize(); }
78
79void StringTableSection::writeSection(FileOutputBuffer &Out) const {
80 StrTabBuilder.write(Out.getBufferStart() + Offset);
81}
82
Petr Hosekc1135772017-09-13 03:04:50 +000083static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +000084 switch (Index) {
85 case SHN_ABS:
86 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +000087 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +000088 }
Petr Hosekc1135772017-09-13 03:04:50 +000089 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;
Petr Hosekec2b3fc2017-09-07 23:02:50 +000099}
100
101uint16_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
Petr Hosek79cee9e2017-08-29 02:12:03 +0000121void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
122 SectionBase *DefinedIn, uint64_t Value,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000123 uint16_t Shndx, uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000124 Symbol Sym;
125 Sym.Name = Name;
126 Sym.Binding = Bind;
127 Sym.Type = Type;
128 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000129 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000130 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000131 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
132 else
133 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
134 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000135 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
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000142void 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
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000155void 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
Petr Hosek79cee9e2017-08-29 02:12:03 +0000165void 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
180void 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
187const 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
193template <class ELFT>
194void 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);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000206 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000207 ++Sym;
208 }
209}
210
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000211template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000212void 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
222template <class SymTabType>
223void RelocSectionWithSymtabBase<SymTabType>::initialize(
224 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000225 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000226 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
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000231 if (Info != SHN_UNDEF)
232 setSection(SecTable.getSection(Info,
233 "Info field value " + Twine(Info) +
234 " in section " + Name + " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000235 else
236 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000237}
238
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000239template <class SymTabType>
240void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000241 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000242 if (SecToApplyRel != nullptr)
243 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000244}
245
246template <class ELFT>
247void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
248
249template <class ELFT>
250void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
251 Rela.r_addend = Addend;
252}
253
254template <class ELFT>
255template <class T>
256void 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
265template <class ELFT>
266void 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
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000274void DynamicRelocationSection::writeSection(llvm::FileOutputBuffer &Out) const {
275 std::copy(std::begin(Contents), std::end(Contents),
276 Out.getBufferStart() + Offset);
277}
278
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000279void 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
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000287bool SectionWithStrTab::classof(const SectionBase *S) {
288 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
289}
290
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000291void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000292 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);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000300}
301
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000302void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
303
Petr Hosek05a04cb2017-08-01 00:33:58 +0000304// Returns true IFF a section is wholly inside the range of a segment
305static 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
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000316// Returns true IFF a segment's original offset is inside of another segment's
317// range.
318static 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
Petr Hosek05a04cb2017-08-01 00:33:58 +0000325template <class ELFT>
326void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
327 uint32_t Index = 0;
328 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000329 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
330 (size_t)Phdr.p_filesz};
331 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000332 Segment &Seg = *Segments.back();
333 Seg.Type = Phdr.p_type;
334 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000335 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000336 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 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000353 // 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 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000377}
378
379template <class ELFT>
Petr Hosek79cee9e2017-08-29 02:12:03 +0000380void Object<ELFT>::initSymbolTable(const llvm::object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000381 SymbolTableSection *SymTab,
382 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000383
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));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000390
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000391 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000392 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000393 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) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000399 DefSection = SecTable.getSection(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000400 Sym.st_shndx,
401 "Symbol '" + Name + "' is defined in invalid section with index " +
Petr Hosek79cee9e2017-08-29 02:12:03 +0000402 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000403 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000404
Petr Hosek79cee9e2017-08-29 02:12:03 +0000405 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000406 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000407 }
408}
409
410template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000411static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
412
413template <class ELFT>
414static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
415 ToSet = Rela.r_addend;
416}
417
418template <class ELFT, class T>
419void 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
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000431SectionBase *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
437template <class T>
438T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000439 Twine TypeErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000440 if (T *Sec = llvm::dyn_cast<T>(getSection(Index, IndexErrMsg)))
441 return Sec;
442 error(TypeErrMsg);
443}
444
Petr Hosekd7df9b22017-09-06 23:41:02 +0000445template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000446std::unique_ptr<SectionBase>
447Object<ELFT>::makeSection(const llvm::object::ELFFile<ELFT> &ElfFile,
448 const Elf_Shdr &Shdr) {
449 ArrayRef<uint8_t> Data;
450 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000451 case SHT_REL:
452 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000453 if (Shdr.sh_flags & SHF_ALLOC) {
454 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
455 return llvm::make_unique<DynamicRelocationSection>(Data);
456 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000457 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000458 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000459 // 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 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000466 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000467 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);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000479 case SHT_SYMTAB: {
480 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
481 SymbolTable = SymTab.get();
482 return std::move(SymTab);
483 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000484 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);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000489 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000490}
491
492template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000493SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000494 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 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000515
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000516 SectionTableRef SecTable(Sections);
517
Petr Hosek79cee9e2017-08-29 02:12:03 +0000518 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000519 // 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 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000525
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) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000530 if (Section.get() == SymbolTable)
531 continue;
532 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000533 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000534 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
535 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000536 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000537 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000538 initRelocations(RelSec, SymbolTable,
539 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000540 }
541 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000542
543 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000544}
545
Petr Hosek05a04cb2017-08-01 00:33:58 +0000546template <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
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000557 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000558 readProgramHeaders(ElfFile);
559
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000560 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000561 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");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000566}
567
Petr Hosek05a04cb2017-08-01 00:33:58 +0000568template <class ELFT>
569void 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);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000578 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);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000583 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 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000592}
593
594template <class ELFT>
595void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
596 for (auto &Phdr : Segments)
597 Phdr->template writeHeader<ELFT>(Out);
598}
599
600template <class ELFT>
601void 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
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000604 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000605 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
621template <class ELFT>
622void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
623 for (auto &Section : Sections)
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000624 Section->writeSection(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000625}
626
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000627template <class ELFT>
628void 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;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000635 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
636 if (auto ToRelSec = RelSec->getSection())
637 return !ToRemove(*ToRelSec);
638 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000639 return true;
640 });
641 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
642 SymbolTable = nullptr;
643 if (ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000644 if (WriteSectionHeaders)
645 error("Cannot remove " + SectionNames->Name +
646 " because it is the section header string table.");
647 SectionNames = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000648 }
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
Petr Hosekc4df10e2017-08-04 21:09:26 +0000662template <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
672template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000673 // 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);
Petr Hosek3f383832017-08-26 01:32:20 +0000690 // 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;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000695 if (!OrderedSegments.empty()) {
696 Offset = OrderedSegments[0]->Offset;
Petr Hosek3f383832017-08-26 01:32:20 +0000697 } else {
698 Offset = sizeof(Elf_Ehdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000699 }
Petr Hosek3f383832017-08-26 01:32:20 +0000700 // 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.
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000705 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;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000717 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000718 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000719 }
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 {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000734 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000735 Section->Offset = Offset;
736 if (Section->Type != SHT_NOBITS)
737 Offset += Section->Size;
738 }
739 }
740
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000741 if (this->WriteSectionHeaders) {
742 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
743 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000744 this->SHOffset = Offset;
745}
746
747template <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.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000750 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000751 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000752 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000753}
754
755template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
756 this->writeHeader(Out);
757 this->writeProgramHeaders(Out);
758 this->writeSectionData(Out);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000759 if (this->WriteSectionHeaders)
760 this->writeSectionHeaders(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000761}
762
763template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000764 // Make sure we add the names of all the sections.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000765 if (this->SectionNames != nullptr)
766 for (const auto &Section : this->Sections) {
767 this->SectionNames->addString(Section->Name);
768 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000769 // Make sure we add the names of all the symbols.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000770 if (this->SymbolTable != nullptr)
771 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000772
773 sortSections();
774 assignOffsets();
775
776 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000777 if (this->SectionNames != nullptr)
778 this->SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000779 // 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);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000785 if (this->WriteSectionHeaders)
786 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000787 Section->finalize();
788 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000789}
790
791template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
792 return TotalSize;
793}
794
795template <class ELFT>
796void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
797 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000798 // 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) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000802 Segment->writeSegment(Out);
803 }
804 }
805}
806
807template <class ELFT> void BinaryObject<ELFT>::finalize() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000808
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) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000818 if (Segment->Type == llvm::ELF::PT_LOAD &&
819 Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000820 Offset = alignTo(Offset, Segment->Align);
821 Segment->Offset = Offset;
822 Offset += Segment->FileSize;
823 }
824 }
825 TotalSize = Offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000826}
827
Petr Hosek35fdbd52017-08-01 05:31:50 +0000828template class Object<ELF64LE>;
829template class Object<ELF64BE>;
830template class Object<ELF32LE>;
831template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000832
833template class ELFObject<ELF64LE>;
834template class ELFObject<ELF64BE>;
835template class ELFObject<ELF32LE>;
836template class ELFObject<ELF32BE>;
837
838template class BinaryObject<ELF64LE>;
839template class BinaryObject<ELF64BE>;
840template class BinaryObject<ELF32LE>;
841template class BinaryObject<ELF32BE>;