blob: 22ae47f1cace7a1929d7b24544209e0588965b82 [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00009
Petr Hosek05a04cb2017-08-01 00:33:58 +000010#include "Object.h"
11#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000012#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/BinaryFormat/ELF.h"
18#include "llvm/Object/ELFObjectFile.h"
19#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Support/FileOutputBuffer.h"
21#include <algorithm>
22#include <cstddef>
23#include <cstdint>
24#include <iterator>
25#include <utility>
26#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000027
28using namespace llvm;
29using namespace object;
30using namespace ELF;
31
32template <class ELFT> void Segment::writeHeader(FileOutputBuffer &Out) const {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000033 using Elf_Ehdr = typename ELFT::Ehdr;
34 using Elf_Phdr = typename ELFT::Phdr;
Petr Hosek05a04cb2017-08-01 00:33:58 +000035
36 uint8_t *Buf = Out.getBufferStart();
37 Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
38 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(Buf);
39 Phdr.p_type = Type;
40 Phdr.p_flags = Flags;
41 Phdr.p_offset = Offset;
42 Phdr.p_vaddr = VAddr;
43 Phdr.p_paddr = PAddr;
44 Phdr.p_filesz = FileSize;
45 Phdr.p_memsz = MemSize;
46 Phdr.p_align = Align;
47}
48
Petr Hosekc4df10e2017-08-04 21:09:26 +000049void Segment::writeSegment(FileOutputBuffer &Out) const {
50 uint8_t *Buf = Out.getBufferStart() + Offset;
51 // We want to maintain segments' interstitial data and contents exactly.
52 // This lets us just copy segments directly.
53 std::copy(std::begin(Contents), std::end(Contents), Buf);
54}
55
Jake Ehrlich36a2eb32017-10-10 18:47:09 +000056void SectionBase::removeSectionReferences(const SectionBase *Sec) {}
Jake Ehrlichf5a43772017-09-25 20:37:28 +000057void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000058void SectionBase::finalize() {}
59
60template <class ELFT>
61void SectionBase::writeHeader(FileOutputBuffer &Out) const {
62 uint8_t *Buf = Out.getBufferStart();
63 Buf += HeaderOffset;
64 typename ELFT::Shdr &Shdr = *reinterpret_cast<typename ELFT::Shdr *>(Buf);
65 Shdr.sh_name = NameIndex;
66 Shdr.sh_type = Type;
67 Shdr.sh_flags = Flags;
68 Shdr.sh_addr = Addr;
69 Shdr.sh_offset = Offset;
70 Shdr.sh_size = Size;
71 Shdr.sh_link = Link;
72 Shdr.sh_info = Info;
73 Shdr.sh_addralign = Align;
74 Shdr.sh_entsize = EntrySize;
75}
76
77void Section::writeSection(FileOutputBuffer &Out) const {
78 if (Type == SHT_NOBITS)
79 return;
80 uint8_t *Buf = Out.getBufferStart() + Offset;
81 std::copy(std::begin(Contents), std::end(Contents), Buf);
82}
83
84void StringTableSection::addString(StringRef Name) {
85 StrTabBuilder.add(Name);
86 Size = StrTabBuilder.getSize();
87}
88
89uint32_t StringTableSection::findIndex(StringRef Name) const {
90 return StrTabBuilder.getOffset(Name);
91}
92
93void StringTableSection::finalize() { StrTabBuilder.finalize(); }
94
95void StringTableSection::writeSection(FileOutputBuffer &Out) const {
96 StrTabBuilder.write(Out.getBufferStart() + Offset);
97}
98
Petr Hosekc1135772017-09-13 03:04:50 +000099static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000100 switch (Index) {
101 case SHN_ABS:
102 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000103 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000104 }
Petr Hosekc1135772017-09-13 03:04:50 +0000105 if (Machine == EM_HEXAGON) {
106 switch (Index) {
107 case SHN_HEXAGON_SCOMMON:
108 case SHN_HEXAGON_SCOMMON_2:
109 case SHN_HEXAGON_SCOMMON_4:
110 case SHN_HEXAGON_SCOMMON_8:
111 return true;
112 }
113 }
114 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000115}
116
117uint16_t Symbol::getShndx() const {
118 if (DefinedIn != nullptr) {
119 return DefinedIn->Index;
120 }
121 switch (ShndxType) {
122 // This means that we don't have a defined section but we do need to
123 // output a legitimate section index.
124 case SYMBOL_SIMPLE_INDEX:
125 return SHN_UNDEF;
126 case SYMBOL_ABS:
127 case SYMBOL_COMMON:
128 case SYMBOL_HEXAGON_SCOMMON:
129 case SYMBOL_HEXAGON_SCOMMON_2:
130 case SYMBOL_HEXAGON_SCOMMON_4:
131 case SYMBOL_HEXAGON_SCOMMON_8:
132 return static_cast<uint16_t>(ShndxType);
133 }
134 llvm_unreachable("Symbol with invalid ShndxType encountered");
135}
136
Petr Hosek79cee9e2017-08-29 02:12:03 +0000137void SymbolTableSection::addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
138 SectionBase *DefinedIn, uint64_t Value,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000139 uint16_t Shndx, uint64_t Sz) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000140 Symbol Sym;
141 Sym.Name = Name;
142 Sym.Binding = Bind;
143 Sym.Type = Type;
144 Sym.DefinedIn = DefinedIn;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000145 if (DefinedIn == nullptr) {
Petr Hosekc1135772017-09-13 03:04:50 +0000146 if (Shndx >= SHN_LORESERVE)
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000147 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
148 else
149 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
150 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000151 Sym.Value = Value;
152 Sym.Size = Sz;
153 Sym.Index = Symbols.size();
154 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
155 Size += this->EntrySize;
156}
157
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000158void SymbolTableSection::removeSectionReferences(const SectionBase *Sec) {
159 if (SymbolNames == Sec) {
160 error("String table " + SymbolNames->Name +
161 " cannot be removed because it is referenced by the symbol table " +
162 this->Name);
163 }
164 auto Iter =
165 std::remove_if(std::begin(Symbols), std::end(Symbols),
166 [=](const SymPtr &Sym) { return Sym->DefinedIn == Sec; });
167 Size -= (std::end(Symbols) - Iter) * this->EntrySize;
168 Symbols.erase(Iter, std::end(Symbols));
169}
170
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000171void SymbolTableSection::initialize(SectionTableRef SecTable) {
172 Size = 0;
173 setStrTab(SecTable.getSectionOfType<StringTableSection>(
174 Link,
175 "Symbol table has link index of " + Twine(Link) +
176 " which is not a valid index",
177 "Symbol table has link index of " + Twine(Link) +
178 " which is not a string table"));
179}
180
Petr Hosek79cee9e2017-08-29 02:12:03 +0000181void SymbolTableSection::finalize() {
182 // Make sure SymbolNames is finalized before getting name indexes.
183 SymbolNames->finalize();
184
185 uint32_t MaxLocalIndex = 0;
186 for (auto &Sym : Symbols) {
187 Sym->NameIndex = SymbolNames->findIndex(Sym->Name);
188 if (Sym->Binding == STB_LOCAL)
189 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
190 }
191 // Now we need to set the Link and Info fields.
192 Link = SymbolNames->Index;
193 Info = MaxLocalIndex + 1;
194}
195
196void SymbolTableSection::addSymbolNames() {
197 // Add all of our strings to SymbolNames so that SymbolNames has the right
198 // size before layout is decided.
199 for (auto &Sym : Symbols)
200 SymbolNames->addString(Sym->Name);
201}
202
203const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
204 if (Symbols.size() <= Index)
205 error("Invalid symbol index: " + Twine(Index));
206 return Symbols[Index].get();
207}
208
209template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000210void SymbolTableSectionImpl<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000211 uint8_t *Buf = Out.getBufferStart();
212 Buf += Offset;
213 typename ELFT::Sym *Sym = reinterpret_cast<typename ELFT::Sym *>(Buf);
214 // Loop though symbols setting each entry of the symbol table.
215 for (auto &Symbol : Symbols) {
216 Sym->st_name = Symbol->NameIndex;
217 Sym->st_value = Symbol->Value;
218 Sym->st_size = Symbol->Size;
219 Sym->setBinding(Symbol->Binding);
220 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000221 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000222 ++Sym;
223 }
224}
225
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000226template <class SymTabType>
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000227void RelocSectionWithSymtabBase<SymTabType>::removeSectionReferences(
228 const SectionBase *Sec) {
229 if (Symbols == Sec) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000230 error("Symbol table " + Symbols->Name +
231 " cannot be removed because it is "
232 "referenced by the relocation "
233 "section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000234 this->Name);
235 }
236}
237
238template <class SymTabType>
239void RelocSectionWithSymtabBase<SymTabType>::initialize(
240 SectionTableRef SecTable) {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000241 setSymTab(SecTable.getSectionOfType<SymTabType>(
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000242 Link,
243 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
244 "Link field value " + Twine(Link) + " in section " + Name +
245 " is not a symbol table"));
246
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000247 if (Info != SHN_UNDEF)
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000248 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
249 " in section " + Name +
250 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000251 else
252 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000253}
254
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000255template <class SymTabType>
256void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000257 this->Link = Symbols->Index;
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000258 if (SecToApplyRel != nullptr)
259 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000260}
261
262template <class ELFT>
263void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
264
265template <class ELFT>
266void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
267 Rela.r_addend = Addend;
268}
269
270template <class ELFT>
271template <class T>
272void RelocationSection<ELFT>::writeRel(T *Buf) const {
273 for (const auto &Reloc : Relocations) {
274 Buf->r_offset = Reloc.Offset;
275 setAddend(*Buf, Reloc.Addend);
276 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
277 ++Buf;
278 }
279}
280
281template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000282void RelocationSection<ELFT>::writeSection(FileOutputBuffer &Out) const {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000283 uint8_t *Buf = Out.getBufferStart() + Offset;
284 if (Type == SHT_REL)
285 writeRel(reinterpret_cast<Elf_Rel *>(Buf));
286 else
287 writeRel(reinterpret_cast<Elf_Rela *>(Buf));
288}
289
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000290void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000291 std::copy(std::begin(Contents), std::end(Contents),
292 Out.getBufferStart() + Offset);
293}
294
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000295void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
296 if (StrTab == Sec) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000297 error("String table " + StrTab->Name +
298 " cannot be removed because it is "
299 "referenced by the section " +
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000300 this->Name);
301 }
302}
303
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000304bool SectionWithStrTab::classof(const SectionBase *S) {
305 return isa<DynamicSymbolTableSection>(S) || isa<DynamicSection>(S);
306}
307
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000308void SectionWithStrTab::initialize(SectionTableRef SecTable) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000309 auto StrTab =
310 SecTable.getSection(Link, "Link field value " + Twine(Link) +
311 " in section " + Name + " is invalid");
Jake Ehrlich70bd75f2017-10-10 21:28:22 +0000312 if (StrTab->Type != SHT_STRTAB) {
313 error("Link field value " + Twine(Link) + " in section " + Name +
314 " is not a string table");
315 }
316 setStrTab(StrTab);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000317}
318
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000319void SectionWithStrTab::finalize() { this->Link = StrTab->Index; }
320
Petr Hosek05a04cb2017-08-01 00:33:58 +0000321// Returns true IFF a section is wholly inside the range of a segment
322static bool sectionWithinSegment(const SectionBase &Section,
323 const Segment &Segment) {
324 // If a section is empty it should be treated like it has a size of 1. This is
325 // to clarify the case when an empty section lies on a boundary between two
326 // segments and ensures that the section "belongs" to the second segment and
327 // not the first.
328 uint64_t SecSize = Section.Size ? Section.Size : 1;
329 return Segment.Offset <= Section.OriginalOffset &&
330 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
331}
332
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000333// Returns true IFF a segment's original offset is inside of another segment's
334// range.
335static bool segmentOverlapsSegment(const Segment &Child,
336 const Segment &Parent) {
337
338 return Parent.OriginalOffset <= Child.OriginalOffset &&
339 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
340}
341
Petr Hosek05a04cb2017-08-01 00:33:58 +0000342template <class ELFT>
343void Object<ELFT>::readProgramHeaders(const ELFFile<ELFT> &ElfFile) {
344 uint32_t Index = 0;
345 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000346 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
347 (size_t)Phdr.p_filesz};
348 Segments.emplace_back(llvm::make_unique<Segment>(Data));
Petr Hosek05a04cb2017-08-01 00:33:58 +0000349 Segment &Seg = *Segments.back();
350 Seg.Type = Phdr.p_type;
351 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +0000352 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000353 Seg.Offset = Phdr.p_offset;
354 Seg.VAddr = Phdr.p_vaddr;
355 Seg.PAddr = Phdr.p_paddr;
356 Seg.FileSize = Phdr.p_filesz;
357 Seg.MemSize = Phdr.p_memsz;
358 Seg.Align = Phdr.p_align;
359 Seg.Index = Index++;
360 for (auto &Section : Sections) {
361 if (sectionWithinSegment(*Section, Seg)) {
362 Seg.addSection(&*Section);
363 if (!Section->ParentSegment ||
364 Section->ParentSegment->Offset > Seg.Offset) {
365 Section->ParentSegment = &Seg;
366 }
367 }
368 }
369 }
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000370 // Now we do an O(n^2) loop through the segments in order to match up
371 // segments.
372 for (auto &Child : Segments) {
373 for (auto &Parent : Segments) {
374 // Every segment will overlap with itself but we don't want a segment to
375 // be it's own parent so we avoid that situation.
376 if (&Child != &Parent && segmentOverlapsSegment(*Child, *Parent)) {
377 // We want a canonical "most parental" segment but this requires
378 // inspecting the ParentSegment.
379 if (Child->ParentSegment != nullptr) {
380 if (Child->ParentSegment->OriginalOffset > Parent->OriginalOffset) {
381 Child->ParentSegment = Parent.get();
382 } else if (Child->ParentSegment->Index > Parent->Index) {
383 // They must have equal OriginalOffsets so we need to disambiguate.
384 // To decide which is the parent we'll choose the one with the
385 // higher index.
386 Child->ParentSegment = Parent.get();
387 }
388 } else {
389 Child->ParentSegment = Parent.get();
390 }
391 }
392 }
393 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000394}
395
396template <class ELFT>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000397void Object<ELFT>::initSymbolTable(const object::ELFFile<ELFT> &ElfFile,
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000398 SymbolTableSection *SymTab,
399 SectionTableRef SecTable) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000400 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
401 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
402
403 for (const auto &Sym : unwrapOrError(ElfFile.symbols(&Shdr))) {
404 SectionBase *DefSection = nullptr;
405 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000406
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000407 if (Sym.st_shndx >= SHN_LORESERVE) {
Petr Hosekc1135772017-09-13 03:04:50 +0000408 if (!isValidReservedSectionIndex(Sym.st_shndx, Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000409 error(
410 "Symbol '" + Name +
411 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
412 Twine(Sym.st_shndx));
413 }
414 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000415 DefSection = SecTable.getSection(
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000416 Sym.st_shndx, "Symbol '" + Name +
417 "' is defined in invalid section with index " +
418 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000419 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000420
Petr Hosek79cee9e2017-08-29 02:12:03 +0000421 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000422 Sym.getValue(), Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000423 }
424}
425
426template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +0000427static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
428
429template <class ELFT>
430static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
431 ToSet = Rela.r_addend;
432}
433
434template <class ELFT, class T>
435void initRelocations(RelocationSection<ELFT> *Relocs,
436 SymbolTableSection *SymbolTable, T RelRange) {
437 for (const auto &Rel : RelRange) {
438 Relocation ToAdd;
439 ToAdd.Offset = Rel.r_offset;
440 getAddend(ToAdd.Addend, Rel);
441 ToAdd.Type = Rel.getType(false);
442 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
443 Relocs->addRelocation(ToAdd);
444 }
445}
446
Zachary Turner41a9ee92017-10-11 23:54:34 +0000447SectionBase *SectionTableRef::getSection(uint16_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000448 if (Index == SHN_UNDEF || Index > Sections.size())
449 error(ErrMsg);
450 return Sections[Index - 1].get();
451}
452
453template <class T>
Zachary Turner41a9ee92017-10-11 23:54:34 +0000454T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
455 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000456 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000457 return Sec;
458 error(TypeErrMsg);
459}
460
Petr Hosekd7df9b22017-09-06 23:41:02 +0000461template <class ELFT>
Petr Hosek05a04cb2017-08-01 00:33:58 +0000462std::unique_ptr<SectionBase>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000463Object<ELFT>::makeSection(const object::ELFFile<ELFT> &ElfFile,
Petr Hosek05a04cb2017-08-01 00:33:58 +0000464 const Elf_Shdr &Shdr) {
465 ArrayRef<uint8_t> Data;
466 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000467 case SHT_REL:
468 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000469 if (Shdr.sh_flags & SHF_ALLOC) {
470 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
471 return llvm::make_unique<DynamicRelocationSection>(Data);
472 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000473 return llvm::make_unique<RelocationSection<ELFT>>();
Petr Hosek05a04cb2017-08-01 00:33:58 +0000474 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000475 // If a string table is allocated we don't want to mess with it. That would
476 // mean altering the memory image. There are no special link types or
477 // anything so we can just use a Section.
478 if (Shdr.sh_flags & SHF_ALLOC) {
479 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
480 return llvm::make_unique<Section>(Data);
481 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000482 return llvm::make_unique<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000483 case SHT_HASH:
484 case SHT_GNU_HASH:
485 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
486 // Because of this we don't need to mess with the hash tables either.
487 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
488 return llvm::make_unique<Section>(Data);
489 case SHT_DYNSYM:
490 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
491 return llvm::make_unique<DynamicSymbolTableSection>(Data);
492 case SHT_DYNAMIC:
493 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
494 return llvm::make_unique<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000495 case SHT_SYMTAB: {
496 auto SymTab = llvm::make_unique<SymbolTableSectionImpl<ELFT>>();
497 SymbolTable = SymTab.get();
498 return std::move(SymTab);
499 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000500 case SHT_NOBITS:
501 return llvm::make_unique<Section>(Data);
502 default:
503 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
504 return llvm::make_unique<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000505 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000506}
507
508template <class ELFT>
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000509SectionTableRef Object<ELFT>::readSectionHeaders(const ELFFile<ELFT> &ElfFile) {
Petr Hosek05a04cb2017-08-01 00:33:58 +0000510 uint32_t Index = 0;
511 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
512 if (Index == 0) {
513 ++Index;
514 continue;
515 }
516 SecPtr Sec = makeSection(ElfFile, Shdr);
517 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
518 Sec->Type = Shdr.sh_type;
519 Sec->Flags = Shdr.sh_flags;
520 Sec->Addr = Shdr.sh_addr;
521 Sec->Offset = Shdr.sh_offset;
522 Sec->OriginalOffset = Shdr.sh_offset;
523 Sec->Size = Shdr.sh_size;
524 Sec->Link = Shdr.sh_link;
525 Sec->Info = Shdr.sh_info;
526 Sec->Align = Shdr.sh_addralign;
527 Sec->EntrySize = Shdr.sh_entsize;
528 Sec->Index = Index++;
529 Sections.push_back(std::move(Sec));
530 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000531
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000532 SectionTableRef SecTable(Sections);
533
Petr Hosek79cee9e2017-08-29 02:12:03 +0000534 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000535 // details about symbol tables. We need the symbol table filled out before
536 // any relocations.
537 if (SymbolTable) {
538 SymbolTable->initialize(SecTable);
539 initSymbolTable(ElfFile, SymbolTable, SecTable);
540 }
Petr Hosekd7df9b22017-09-06 23:41:02 +0000541
542 // Now that all sections and symbols have been added we can add
543 // relocations that reference symbols and set the link and info fields for
544 // relocation sections.
545 for (auto &Section : Sections) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000546 if (Section.get() == SymbolTable)
547 continue;
548 Section->initialize(SecTable);
Petr Hosekd7df9b22017-09-06 23:41:02 +0000549 if (auto RelSec = dyn_cast<RelocationSection<ELFT>>(Section.get())) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000550 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
551 if (RelSec->Type == SHT_REL)
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000552 initRelocations(RelSec, SymbolTable, unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000553 else
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000554 initRelocations(RelSec, SymbolTable,
555 unwrapOrError(ElfFile.relas(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000556 }
557 }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000558
559 return SecTable;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000560}
561
Petr Hosek05a04cb2017-08-01 00:33:58 +0000562template <class ELFT> Object<ELFT>::Object(const ELFObjectFile<ELFT> &Obj) {
563 const auto &ElfFile = *Obj.getELFFile();
564 const auto &Ehdr = *ElfFile.getHeader();
565
566 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
567 Type = Ehdr.e_type;
568 Machine = Ehdr.e_machine;
569 Version = Ehdr.e_version;
570 Entry = Ehdr.e_entry;
571 Flags = Ehdr.e_flags;
572
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000573 SectionTableRef SecTable = readSectionHeaders(ElfFile);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000574 readProgramHeaders(ElfFile);
575
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000576 SectionNames = SecTable.getSectionOfType<StringTableSection>(
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000577 Ehdr.e_shstrndx,
578 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
579 " is invalid",
580 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) + " in elf header " +
581 " is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +0000582}
583
Petr Hosek05a04cb2017-08-01 00:33:58 +0000584template <class ELFT>
585void Object<ELFT>::writeHeader(FileOutputBuffer &Out) const {
586 uint8_t *Buf = Out.getBufferStart();
587 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf);
588 std::copy(Ident, Ident + 16, Ehdr.e_ident);
589 Ehdr.e_type = Type;
590 Ehdr.e_machine = Machine;
591 Ehdr.e_version = Version;
592 Ehdr.e_entry = Entry;
593 Ehdr.e_phoff = sizeof(Elf_Ehdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000594 Ehdr.e_flags = Flags;
595 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
596 Ehdr.e_phentsize = sizeof(Elf_Phdr);
597 Ehdr.e_phnum = Segments.size();
598 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000599 if (WriteSectionHeaders) {
600 Ehdr.e_shoff = SHOffset;
601 Ehdr.e_shnum = Sections.size() + 1;
602 Ehdr.e_shstrndx = SectionNames->Index;
603 } else {
604 Ehdr.e_shoff = 0;
605 Ehdr.e_shnum = 0;
606 Ehdr.e_shstrndx = 0;
607 }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000608}
609
610template <class ELFT>
611void Object<ELFT>::writeProgramHeaders(FileOutputBuffer &Out) const {
612 for (auto &Phdr : Segments)
613 Phdr->template writeHeader<ELFT>(Out);
614}
615
616template <class ELFT>
617void Object<ELFT>::writeSectionHeaders(FileOutputBuffer &Out) const {
618 uint8_t *Buf = Out.getBufferStart() + SHOffset;
619 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +0000620 // of the file. It is not used for anything else
Petr Hosek05a04cb2017-08-01 00:33:58 +0000621 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(Buf);
622 Shdr.sh_name = 0;
623 Shdr.sh_type = SHT_NULL;
624 Shdr.sh_flags = 0;
625 Shdr.sh_addr = 0;
626 Shdr.sh_offset = 0;
627 Shdr.sh_size = 0;
628 Shdr.sh_link = 0;
629 Shdr.sh_info = 0;
630 Shdr.sh_addralign = 0;
631 Shdr.sh_entsize = 0;
632
633 for (auto &Section : Sections)
634 Section->template writeHeader<ELFT>(Out);
635}
636
637template <class ELFT>
638void Object<ELFT>::writeSectionData(FileOutputBuffer &Out) const {
639 for (auto &Section : Sections)
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000640 Section->writeSection(Out);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000641}
642
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000643template <class ELFT>
644void Object<ELFT>::removeSections(
645 std::function<bool(const SectionBase &)> ToRemove) {
646
647 auto Iter = std::stable_partition(
648 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
649 if (ToRemove(*Sec))
650 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000651 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
652 if (auto ToRelSec = RelSec->getSection())
653 return !ToRemove(*ToRelSec);
654 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000655 return true;
656 });
657 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
658 SymbolTable = nullptr;
659 if (ToRemove(*SectionNames)) {
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000660 if (WriteSectionHeaders)
661 error("Cannot remove " + SectionNames->Name +
662 " because it is the section header string table.");
663 SectionNames = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000664 }
665 // Now make sure there are no remaining references to the sections that will
666 // be removed. Sometimes it is impossible to remove a reference so we emit
667 // an error here instead.
668 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
669 for (auto &Segment : Segments)
670 Segment->removeSection(RemoveSec.get());
671 for (auto &KeepSec : make_range(std::begin(Sections), Iter))
672 KeepSec->removeSectionReferences(RemoveSec.get());
673 }
674 // Now finally get rid of them all togethor.
675 Sections.erase(Iter, std::end(Sections));
676}
677
Petr Hosekc4df10e2017-08-04 21:09:26 +0000678template <class ELFT> void ELFObject<ELFT>::sortSections() {
679 // Put all sections in offset order. Maintain the ordering as closely as
680 // possible while meeting that demand however.
681 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
682 return A->OriginalOffset < B->OriginalOffset;
683 };
684 std::stable_sort(std::begin(this->Sections), std::end(this->Sections),
685 CompareSections);
686}
687
688template <class ELFT> void ELFObject<ELFT>::assignOffsets() {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000689 // We need a temporary list of segments that has a special order to it
690 // so that we know that anytime ->ParentSegment is set that segment has
691 // already had it's offset properly set.
692 std::vector<Segment *> OrderedSegments;
693 for (auto &Segment : this->Segments)
694 OrderedSegments.push_back(Segment.get());
695 auto CompareSegments = [](const Segment *A, const Segment *B) {
696 // Any segment without a parent segment should come before a segment
697 // that has a parent segment.
698 if (A->OriginalOffset < B->OriginalOffset)
699 return true;
700 if (A->OriginalOffset > B->OriginalOffset)
701 return false;
702 return A->Index < B->Index;
703 };
704 std::stable_sort(std::begin(OrderedSegments), std::end(OrderedSegments),
705 CompareSegments);
Petr Hosek3f383832017-08-26 01:32:20 +0000706 // The size of ELF + program headers will not change so it is ok to assume
707 // that the first offset of the first segment is a good place to start
708 // outputting sections. This covers both the standard case and the PT_PHDR
709 // case.
710 uint64_t Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000711 if (!OrderedSegments.empty()) {
712 Offset = OrderedSegments[0]->Offset;
Petr Hosek3f383832017-08-26 01:32:20 +0000713 } else {
714 Offset = sizeof(Elf_Ehdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000715 }
Petr Hosek3f383832017-08-26 01:32:20 +0000716 // The only way a segment should move is if a section was between two
717 // segments and that section was removed. If that section isn't in a segment
718 // then it's acceptable, but not ideal, to simply move it to after the
719 // segments. So we can simply layout segments one after the other accounting
720 // for alignment.
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000721 for (auto &Segment : OrderedSegments) {
722 // We assume that segments have been ordered by OriginalOffset and Index
723 // such that a parent segment will always come before a child segment in
724 // OrderedSegments. This means that the Offset of the ParentSegment should
725 // already be set and we can set our offset relative to it.
726 if (Segment->ParentSegment != nullptr) {
727 auto Parent = Segment->ParentSegment;
728 Segment->Offset =
729 Parent->Offset + Segment->OriginalOffset - Parent->OriginalOffset;
730 } else {
731 Offset = alignTo(Offset, Segment->Align == 0 ? 1 : Segment->Align);
732 Segment->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000733 }
Jake Ehrlich084400b2017-10-04 17:44:42 +0000734 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +0000735 }
736 // Now the offset of every segment has been set we can assign the offsets
737 // of each section. For sections that are covered by a segment we should use
738 // the segment's original offset and the section's original offset to compute
739 // the offset from the start of the segment. Using the offset from the start
740 // of the segment we can assign a new offset to the section. For sections not
741 // covered by segments we can just bump Offset to the next valid location.
742 uint32_t Index = 1;
743 for (auto &Section : this->Sections) {
744 Section->Index = Index++;
745 if (Section->ParentSegment != nullptr) {
746 auto Segment = Section->ParentSegment;
747 Section->Offset =
748 Segment->Offset + (Section->OriginalOffset - Segment->OriginalOffset);
749 } else {
Jake Ehrlich084400b2017-10-04 17:44:42 +0000750 Offset = alignTo(Offset, Section->Align == 0 ? 1 : Section->Align);
Petr Hosek3f383832017-08-26 01:32:20 +0000751 Section->Offset = Offset;
752 if (Section->Type != SHT_NOBITS)
753 Offset += Section->Size;
754 }
755 }
756
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000757 if (this->WriteSectionHeaders) {
758 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
759 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000760 this->SHOffset = Offset;
761}
762
763template <class ELFT> size_t ELFObject<ELFT>::totalSize() const {
764 // We already have the section header offset so we can calculate the total
765 // size by just adding up the size of each section header.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000766 auto NullSectionSize = this->WriteSectionHeaders ? sizeof(Elf_Shdr) : 0;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000767 return this->SHOffset + this->Sections.size() * sizeof(Elf_Shdr) +
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000768 NullSectionSize;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000769}
770
771template <class ELFT> void ELFObject<ELFT>::write(FileOutputBuffer &Out) const {
772 this->writeHeader(Out);
773 this->writeProgramHeaders(Out);
774 this->writeSectionData(Out);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000775 if (this->WriteSectionHeaders)
776 this->writeSectionHeaders(Out);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000777}
778
779template <class ELFT> void ELFObject<ELFT>::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000780 // Make sure we add the names of all the sections.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000781 if (this->SectionNames != nullptr)
782 for (const auto &Section : this->Sections) {
783 this->SectionNames->addString(Section->Name);
784 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000785 // Make sure we add the names of all the symbols.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000786 if (this->SymbolTable != nullptr)
787 this->SymbolTable->addSymbolNames();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000788
789 sortSections();
790 assignOffsets();
791
792 // Finalize SectionNames first so that we can assign name indexes.
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000793 if (this->SectionNames != nullptr)
794 this->SectionNames->finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +0000795 // Finally now that all offsets and indexes have been set we can finalize any
796 // remaining issues.
797 uint64_t Offset = this->SHOffset + sizeof(Elf_Shdr);
798 for (auto &Section : this->Sections) {
799 Section->HeaderOffset = Offset;
800 Offset += sizeof(Elf_Shdr);
Jake Ehrlichf03384d2017-10-11 18:09:18 +0000801 if (this->WriteSectionHeaders)
802 Section->NameIndex = this->SectionNames->findIndex(Section->Name);
Petr Hosekc4df10e2017-08-04 21:09:26 +0000803 Section->finalize();
804 }
Petr Hosekc4df10e2017-08-04 21:09:26 +0000805}
806
807template <class ELFT> size_t BinaryObject<ELFT>::totalSize() const {
808 return TotalSize;
809}
810
811template <class ELFT>
812void BinaryObject<ELFT>::write(FileOutputBuffer &Out) const {
813 for (auto &Segment : this->Segments) {
Petr Hosekd53951d2017-08-04 23:18:18 +0000814 // GNU objcopy does not output segments that do not cover a section. Such
815 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000816 if (Segment->Type == PT_LOAD && Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000817 Segment->writeSegment(Out);
818 }
819 }
820}
821
822template <class ELFT> void BinaryObject<ELFT>::finalize() {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000823 // Put all segments in offset order.
824 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
825 return A->Offset < B->Offset;
826 };
827 std::sort(std::begin(this->Segments), std::end(this->Segments),
828 CompareSegments);
829
830 uint64_t Offset = 0;
831 for (auto &Segment : this->Segments) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000832 if (Segment->Type == PT_LOAD && Segment->firstSection() != nullptr) {
Petr Hosekc4df10e2017-08-04 21:09:26 +0000833 Offset = alignTo(Offset, Segment->Align);
834 Segment->Offset = Offset;
835 Offset += Segment->FileSize;
836 }
837 }
838 TotalSize = Offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +0000839}
840
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000841namespace llvm {
842
Petr Hosek35fdbd52017-08-01 05:31:50 +0000843template class Object<ELF64LE>;
844template class Object<ELF64BE>;
845template class Object<ELF32LE>;
846template class Object<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +0000847
848template class ELFObject<ELF64LE>;
849template class ELFObject<ELF64BE>;
850template class ELFObject<ELF32LE>;
851template class ELFObject<ELF32BE>;
852
853template class BinaryObject<ELF64LE>;
854template class BinaryObject<ELF64BE>;
855template class BinaryObject<ELF32LE>;
856template class BinaryObject<ELF32BE>;
Eugene Zelenko0ad18f82017-11-01 21:16:06 +0000857
858} // end namespace llvm