blob: 472eda96d8a6ab46168710f53c1bc120a2718bc1 [file] [log] [blame]
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001//===- OutputSections.cpp -------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "OutputSections.h"
11#include "Config.h"
George Rimare2ee72b2016-02-26 14:48:31 +000012#include "LinkerScript.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000013#include "SymbolTable.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000014#include "Target.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000015#include "llvm/Support/Dwarf.h"
Igor Kudrin1b0d7062015-10-22 08:21:35 +000016#include "llvm/Support/MathExtras.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000017#include <map>
Rafael Espindola5805c4f2015-09-21 21:38:08 +000018
Rafael Espindola5805c4f2015-09-21 21:38:08 +000019using namespace llvm;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +000020using namespace llvm::dwarf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000021using namespace llvm::object;
Rafael Espindolaa6627382015-10-06 23:56:53 +000022using namespace llvm::support::endian;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000023using namespace llvm::ELF;
24
25using namespace lld;
26using namespace lld::elf2;
27
George Rimar12737b72016-02-25 08:40:26 +000028static bool isAlpha(char C) {
29 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
30}
31
32static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
33
34// Returns true if S is valid as a C language identifier.
35bool elf2::isValidCIdentifier(StringRef S) {
36 if (S.empty() || !isAlpha(S[0]))
37 return false;
38 return std::all_of(S.begin() + 1, S.end(), isAlnum);
39}
40
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000041template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +000042OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type,
43 uintX_t Flags)
Rafael Espindola5805c4f2015-09-21 21:38:08 +000044 : Name(Name) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000045 memset(&Header, 0, sizeof(Elf_Shdr));
Rui Ueyamad97e5c42016-01-07 18:33:11 +000046 Header.sh_type = Type;
47 Header.sh_flags = Flags;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000048}
49
Rafael Espindola35c6af32015-09-25 17:19:10 +000050template <class ELFT>
George Rimar648a2c32015-10-20 08:54:27 +000051GotPltSection<ELFT>::GotPltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000052 : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
George Rimar648a2c32015-10-20 08:54:27 +000053 this->Header.sh_addralign = sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000054}
55
56template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody *Sym) {
Rui Ueyama724d6252016-01-29 01:49:32 +000057 Sym->GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
George Rimar648a2c32015-10-20 08:54:27 +000058 Entries.push_back(Sym);
59}
60
61template <class ELFT> bool GotPltSection<ELFT>::empty() const {
Igor Kudrin351b41d2015-11-16 17:44:08 +000062 return Entries.empty();
George Rimar648a2c32015-10-20 08:54:27 +000063}
64
George Rimar648a2c32015-10-20 08:54:27 +000065template <class ELFT> void GotPltSection<ELFT>::finalize() {
Igor Kudrin351b41d2015-11-16 17:44:08 +000066 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +000067 (Target->GotPltHeaderEntriesNum + Entries.size()) * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000068}
69
70template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +000071 Target->writeGotPltHeader(Buf);
Rui Ueyama724d6252016-01-29 01:49:32 +000072 Buf += Target->GotPltHeaderEntriesNum * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000073 for (const SymbolBody *B : Entries) {
Rui Ueyamab5a69702016-02-01 21:00:35 +000074 Target->writeGotPlt(Buf, B->getPltVA<ELFT>());
George Rimar648a2c32015-10-20 08:54:27 +000075 Buf += sizeof(uintX_t);
76 }
77}
78
79template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +000080GotSection<ELFT>::GotSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000081 : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
Igor Kudrin15cd9ff2015-11-06 07:43:03 +000082 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +000083 this->Header.sh_flags |= SHF_MIPS_GPREL;
Rui Ueyama5f551ae2015-10-14 14:02:06 +000084 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +000085}
86
Rafael Espindola5805c4f2015-09-21 21:38:08 +000087template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody *Sym) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +000088 Sym->GotIndex = Entries.size();
Rafael Espindola5805c4f2015-09-21 21:38:08 +000089 Entries.push_back(Sym);
George Rimar687138c2015-11-13 16:28:53 +000090}
91
Simon Atanasyan56ab5f02016-01-21 05:33:23 +000092template <class ELFT> void GotSection<ELFT>::addMipsLocalEntry() {
93 ++MipsLocalEntries;
94}
95
George Rimar90cd0a82015-12-01 19:20:26 +000096template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody *Sym) {
97 if (Sym->hasGlobalDynIndex())
98 return false;
Rui Ueyama724d6252016-01-29 01:49:32 +000099 Sym->GlobalDynIndex = Target->GotHeaderEntriesNum + Entries.size();
Michael J. Spencer627ae702015-11-13 00:28:34 +0000100 // Global Dynamic TLS entries take two GOT slots.
George Rimar687138c2015-11-13 16:28:53 +0000101 Entries.push_back(Sym);
102 Entries.push_back(nullptr);
George Rimar90cd0a82015-12-01 19:20:26 +0000103 return true;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000104}
105
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000106// Reserves TLS entries for a TLS module ID and a TLS block offset.
107// In total it takes two GOT slots.
108template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
109 if (TlsIndexOff != uint32_t(-1))
George Rimarb17f7392015-12-01 18:24:07 +0000110 return false;
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000111 TlsIndexOff = Entries.size() * sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000112 Entries.push_back(nullptr);
113 Entries.push_back(nullptr);
George Rimarb17f7392015-12-01 18:24:07 +0000114 return true;
Michael J. Spencer1e225612015-11-11 01:00:24 +0000115}
116
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000117template <class ELFT>
118typename GotSection<ELFT>::uintX_t
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000119GotSection<ELFT>::getMipsLocalFullAddr(const SymbolBody &B) {
Rui Ueyamab5a69702016-02-01 21:00:35 +0000120 return getMipsLocalEntryAddr(B.getVA<ELFT>());
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000121}
122
123template <class ELFT>
124typename GotSection<ELFT>::uintX_t
125GotSection<ELFT>::getMipsLocalPageAddr(uintX_t EntryValue) {
126 // Initialize the entry by the %hi(EntryValue) expression
127 // but without right-shifting.
128 return getMipsLocalEntryAddr((EntryValue + 0x8000) & ~0xffff);
129}
130
131template <class ELFT>
132typename GotSection<ELFT>::uintX_t
133GotSection<ELFT>::getMipsLocalEntryAddr(uintX_t EntryValue) {
Rui Ueyama724d6252016-01-29 01:49:32 +0000134 size_t NewIndex = Target->GotHeaderEntriesNum + MipsLocalGotPos.size();
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000135 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
136 assert(!P.second || MipsLocalGotPos.size() <= MipsLocalEntries);
137 return this->getVA() + P.first->second * sizeof(uintX_t);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000138}
139
Igor Kudrin304860a2015-11-12 04:39:49 +0000140template <class ELFT>
George Rimar90cd0a82015-12-01 19:20:26 +0000141typename GotSection<ELFT>::uintX_t
142GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
143 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
144}
145
146template <class ELFT>
Igor Kudrin304860a2015-11-12 04:39:49 +0000147const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
148 return Entries.empty() ? nullptr : Entries.front();
149}
150
151template <class ELFT>
152unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
Rui Ueyama724d6252016-01-29 01:49:32 +0000153 return Target->GotHeaderEntriesNum + MipsLocalEntries;
Igor Kudrin304860a2015-11-12 04:39:49 +0000154}
155
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000156template <class ELFT> void GotSection<ELFT>::finalize() {
157 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +0000158 (Target->GotHeaderEntriesNum + MipsLocalEntries + Entries.size()) *
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000159 sizeof(uintX_t);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000160}
161
Rafael Espindolaa6627382015-10-06 23:56:53 +0000162template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +0000163 Target->writeGotHeader(Buf);
Rui Ueyama5cbf5d22016-02-02 02:29:03 +0000164 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000165 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
166 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
167 }
Rui Ueyama724d6252016-01-29 01:49:32 +0000168 Buf += Target->GotHeaderEntriesNum * sizeof(uintX_t);
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000169 Buf += MipsLocalEntries * sizeof(uintX_t);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000170 for (const SymbolBody *B : Entries) {
Rafael Espindolae782f672015-10-07 03:56:05 +0000171 uint8_t *Entry = Buf;
172 Buf += sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000173 if (!B)
174 continue;
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000175 // MIPS has special rules to fill up GOT entries.
176 // See "Global Offset Table" in Chapter 5 in the following document
177 // for detailed description:
178 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
179 // As the first approach, we can just store addresses for all symbols.
Rafael Espindola993f0272016-02-26 14:27:47 +0000180 if (Config->EMachine != EM_MIPS && canBePreempted(B))
Rafael Espindolaa6627382015-10-06 23:56:53 +0000181 continue; // The dynamic linker will take care of it.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000182 uintX_t VA = B->getVA<ELFT>();
Rafael Espindolae782f672015-10-07 03:56:05 +0000183 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000184 }
185}
186
Rafael Espindola35c6af32015-09-25 17:19:10 +0000187template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000188PltSection<ELFT>::PltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000189 : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000190 this->Header.sh_addralign = 16;
191}
192
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000193template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama242ddf42015-10-12 18:56:36 +0000194 size_t Off = 0;
Rui Ueyama9398f862016-01-29 04:15:02 +0000195 if (Target->UseLazyBinding) {
Rui Ueyama74937fc2016-02-02 02:53:58 +0000196 // At beginning of PLT, we have code to call the dynamic linker
197 // to resolve dynsyms at runtime. Write such code.
Rui Ueyama900e2d22016-01-29 03:51:49 +0000198 Target->writePltZero(Buf);
Rui Ueyama62515452016-01-29 03:00:32 +0000199 Off += Target->PltZeroSize;
George Rimar648a2c32015-10-20 08:54:27 +0000200 }
George Rimarfb5d7f22015-11-26 19:58:51 +0000201 for (auto &I : Entries) {
Rui Ueyama9398f862016-01-29 04:15:02 +0000202 const SymbolBody *B = I.first;
George Rimar77b77792015-11-25 22:15:01 +0000203 unsigned RelOff = I.second;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000204 uint64_t Got =
205 Target->UseLazyBinding ? B->getGotPltVA<ELFT>() : B->getGotVA<ELFT>();
Rui Ueyama242ddf42015-10-12 18:56:36 +0000206 uint64_t Plt = this->getVA() + Off;
Rui Ueyama9398f862016-01-29 04:15:02 +0000207 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
Rui Ueyama724d6252016-01-29 01:49:32 +0000208 Off += Target->PltEntrySize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000209 }
210}
211
212template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody *Sym) {
Rui Ueyama49c68a72015-10-09 00:42:06 +0000213 Sym->PltIndex = Entries.size();
Rui Ueyama724d6252016-01-29 01:49:32 +0000214 unsigned RelOff = Target->UseLazyBinding
George Rimar77b77792015-11-25 22:15:01 +0000215 ? Out<ELFT>::RelaPlt->getRelocOffset()
216 : Out<ELFT>::RelaDyn->getRelocOffset();
217 Entries.push_back(std::make_pair(Sym, RelOff));
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000218}
219
George Rimar648a2c32015-10-20 08:54:27 +0000220template <class ELFT> void PltSection<ELFT>::finalize() {
Rui Ueyama724d6252016-01-29 01:49:32 +0000221 this->Header.sh_size =
Rui Ueyama62515452016-01-29 03:00:32 +0000222 Target->PltZeroSize + Entries.size() * Target->PltEntrySize;
Hal Finkel6c2a3b82015-10-08 21:51:31 +0000223}
224
225template <class ELFT>
George Rimar648a2c32015-10-20 08:54:27 +0000226RelocationSection<ELFT>::RelocationSection(StringRef Name, bool IsRela)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000227 : OutputSectionBase<ELFT>(Name, IsRela ? SHT_RELA : SHT_REL, SHF_ALLOC),
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000228 IsRela(IsRela) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000229 this->Header.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000230 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000231}
232
George Rimar5828c232015-11-30 17:49:19 +0000233template <class ELFT>
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000234void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
235 SymbolBody *Sym = Reloc.Sym;
236 if (!Reloc.UseSymVA && Sym)
Rafael Espindolaabebed92016-02-05 15:27:15 +0000237 Sym->MustBeInDynSym = true;
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000238 Relocs.push_back(Reloc);
239}
240
241template <class ELFT>
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000242typename ELFFile<ELFT>::uintX_t DynamicReloc<ELFT>::getOffset() const {
243 switch (OKind) {
244 case Off_GTlsIndex:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000245 return Out<ELFT>::Got->getGlobalDynAddr(*Sym);
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000246 case Off_GTlsOffset:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000247 return Out<ELFT>::Got->getGlobalDynAddr(*Sym) + sizeof(uintX_t);
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000248 case Off_LTlsIndex:
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000249 return Out<ELFT>::Got->getTlsIndexVA();
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000250 case Off_Sec:
251 return OffsetSec->getOffset(OffsetInSec) + OffsetSec->OutSec->getVA();
252 case Off_Bss:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000253 return cast<SharedSymbol<ELFT>>(Sym)->OffsetInBss + Out<ELFT>::Bss->getVA();
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000254 case Off_Got:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000255 return Sym->getGotVA<ELFT>();
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000256 case Off_GotPlt:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000257 return Sym->getGotPltVA<ELFT>();
George Rimar5828c232015-11-30 17:49:19 +0000258 }
Rafael Espindolade9857e2016-02-04 21:33:05 +0000259 llvm_unreachable("Invalid offset kind");
George Rimar5828c232015-11-30 17:49:19 +0000260}
261
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000262template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000263 for (const DynamicReloc<ELFT> &Rel : Relocs) {
Rafael Espindola50534c22015-09-22 17:49:38 +0000264 auto *P = reinterpret_cast<Elf_Rel *>(Buf);
Rui Ueyamac7b073a2016-01-05 16:35:48 +0000265 Buf += IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rafael Espindolade9857e2016-02-04 21:33:05 +0000266 SymbolBody *Sym = Rel.Sym;
Rui Ueyamab0210e832016-01-26 00:24:57 +0000267
Rafael Espindola9e3f84b2016-02-03 21:02:48 +0000268 if (IsRela) {
Rafael Espindolade9857e2016-02-04 21:33:05 +0000269 uintX_t VA = 0;
Rafael Espindola435c00f2016-02-23 20:19:44 +0000270 if (Rel.UseSymVA)
Rafael Espindolade9857e2016-02-04 21:33:05 +0000271 VA = Sym->getVA<ELFT>();
Rafael Espindola435c00f2016-02-23 20:19:44 +0000272 else if (Rel.TargetSec)
Rafael Espindolade9857e2016-02-04 21:33:05 +0000273 VA = Rel.TargetSec->getOffset(Rel.OffsetInTargetSec) +
274 Rel.TargetSec->OutSec->getVA();
275 reinterpret_cast<Elf_Rela *>(P)->r_addend = Rel.Addend + VA;
Rafael Espindola9e3f84b2016-02-03 21:02:48 +0000276 }
277
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000278 P->r_offset = Rel.getOffset();
Rafael Espindolade9857e2016-02-04 21:33:05 +0000279 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0;
280 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000281 }
282}
283
George Rimar77b77792015-11-25 22:15:01 +0000284template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
Rui Ueyama5a0b2f72016-02-05 19:13:18 +0000285 return this->Header.sh_entsize * Relocs.size();
George Rimar77b77792015-11-25 22:15:01 +0000286}
287
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000288template <class ELFT> void RelocationSection<ELFT>::finalize() {
George Rimara07ff662015-12-21 10:12:06 +0000289 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
290 : Out<ELFT>::DynSymTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000291 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
292}
293
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000294template <class ELFT>
295InterpSection<ELFT>::InterpSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000296 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000297 this->Header.sh_size = Config->DynamicLinker.size() + 1;
298 this->Header.sh_addralign = 1;
299}
300
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000301template <class ELFT>
302void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *SHdr) {
303 *SHdr = Header;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000304}
305
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000306template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000307 memcpy(Buf, Config->DynamicLinker.data(), Config->DynamicLinker.size());
308}
309
Rafael Espindola35c6af32015-09-25 17:19:10 +0000310template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000311HashTableSection<ELFT>::HashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000312 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000313 this->Header.sh_entsize = sizeof(Elf_Word);
314 this->Header.sh_addralign = sizeof(Elf_Word);
315}
316
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000317static uint32_t hashSysv(StringRef Name) {
Rui Ueyama5f1eee1a2015-10-15 21:27:17 +0000318 uint32_t H = 0;
319 for (char C : Name) {
320 H = (H << 4) + C;
321 uint32_t G = H & 0xf0000000;
322 if (G)
323 H ^= G >> 24;
324 H &= ~G;
325 }
326 return H;
327}
328
Rui Ueyama0db335f2015-10-07 16:58:54 +0000329template <class ELFT> void HashTableSection<ELFT>::finalize() {
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000330 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000331
George Rimare9e1d322016-02-18 15:17:01 +0000332 unsigned NumEntries = 2; // nbucket and nchain.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000333 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
Rui Ueyama0db335f2015-10-07 16:58:54 +0000334
335 // Create as many buckets as there are symbols.
336 // FIXME: This is simplistic. We can try to optimize it, but implementing
337 // support for SHT_GNU_HASH is probably even more profitable.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000338 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000339 this->Header.sh_size = NumEntries * sizeof(Elf_Word);
340}
341
342template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000343 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000344 auto *P = reinterpret_cast<Elf_Word *>(Buf);
345 *P++ = NumSymbols; // nbucket
346 *P++ = NumSymbols; // nchain
347
348 Elf_Word *Buckets = P;
349 Elf_Word *Chains = P + NumSymbols;
350
Rafael Espindolae2c24612016-01-29 01:24:25 +0000351 for (const std::pair<SymbolBody *, unsigned> &P :
352 Out<ELFT>::DynSymTab->getSymbols()) {
353 SymbolBody *Body = P.first;
Igor Kudrinab665fc2015-10-20 21:47:58 +0000354 StringRef Name = Body->getName();
Rui Ueyama572a6f72016-01-29 01:49:33 +0000355 unsigned I = Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000356 uint32_t Hash = hashSysv(Name) % NumSymbols;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000357 Chains[I] = Buckets[Hash];
358 Buckets[Hash] = I;
359 }
360}
361
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000362static uint32_t hashGnu(StringRef Name) {
363 uint32_t H = 5381;
364 for (uint8_t C : Name)
365 H = (H << 5) + H + C;
366 return H;
367}
368
369template <class ELFT>
370GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000371 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000372 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000373 this->Header.sh_addralign = sizeof(uintX_t);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000374}
375
376template <class ELFT>
377unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
378 if (!NumHashed)
379 return 0;
380
381 // These values are prime numbers which are not greater than 2^(N-1) + 1.
382 // In result, for any particular NumHashed we return a prime number
383 // which is not greater than NumHashed.
384 static const unsigned Primes[] = {
385 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
386 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
387
388 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
389 array_lengthof(Primes) - 1)];
390}
391
392// Bloom filter estimation: at least 8 bits for each hashed symbol.
393// GNU Hash table requirement: it should be a power of 2,
394// the minimum value is 1, even for an empty table.
395// Expected results for a 32-bit target:
396// calcMaskWords(0..4) = 1
397// calcMaskWords(5..8) = 2
398// calcMaskWords(9..16) = 4
399// For a 64-bit target:
400// calcMaskWords(0..8) = 1
401// calcMaskWords(9..16) = 2
402// calcMaskWords(17..32) = 4
403template <class ELFT>
404unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
405 if (!NumHashed)
406 return 1;
407 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
408}
409
410template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000411 unsigned NumHashed = Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000412 NBuckets = calcNBuckets(NumHashed);
413 MaskWords = calcMaskWords(NumHashed);
414 // Second hash shift estimation: just predefined values.
415 Shift2 = ELFT::Is64Bits ? 6 : 5;
416
417 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
418 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header
419 + sizeof(Elf_Off) * MaskWords // Bloom Filter
420 + sizeof(Elf_Word) * NBuckets // Hash Buckets
421 + sizeof(Elf_Word) * NumHashed; // Hash Values
422}
423
424template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
425 writeHeader(Buf);
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000426 if (Symbols.empty())
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000427 return;
428 writeBloomFilter(Buf);
429 writeHashTable(Buf);
430}
431
432template <class ELFT>
433void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
434 auto *P = reinterpret_cast<Elf_Word *>(Buf);
435 *P++ = NBuckets;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000436 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000437 *P++ = MaskWords;
438 *P++ = Shift2;
439 Buf = reinterpret_cast<uint8_t *>(P);
440}
441
442template <class ELFT>
443void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
444 unsigned C = sizeof(Elf_Off) * 8;
445
446 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
Rui Ueyama861c7312016-02-17 05:40:03 +0000447 for (const SymbolData &Sym : Symbols) {
448 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
449 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
450 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000451 Masks[Pos] |= V;
452 }
453 Buf += sizeof(Elf_Off) * MaskWords;
454}
455
456template <class ELFT>
457void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
458 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
459 Elf_Word *Values = Buckets + NBuckets;
460
461 int PrevBucket = -1;
462 int I = 0;
Rui Ueyama861c7312016-02-17 05:40:03 +0000463 for (const SymbolData &Sym : Symbols) {
464 int Bucket = Sym.Hash % NBuckets;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000465 assert(PrevBucket <= Bucket);
466 if (Bucket != PrevBucket) {
Rui Ueyama861c7312016-02-17 05:40:03 +0000467 Buckets[Bucket] = Sym.Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000468 PrevBucket = Bucket;
469 if (I > 0)
470 Values[I - 1] |= 1;
471 }
Rui Ueyama861c7312016-02-17 05:40:03 +0000472 Values[I] = Sym.Hash & ~1;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000473 ++I;
474 }
475 if (I > 0)
476 Values[I - 1] |= 1;
477}
478
Rafael Espindola31f88882015-11-02 14:33:11 +0000479static bool includeInGnuHashTable(SymbolBody *B) {
Rui Ueyamac112c1b2016-01-29 02:17:01 +0000480 // Assume that includeInDynsym() is already checked.
Rafael Espindola31f88882015-11-02 14:33:11 +0000481 return !B->isUndefined();
482}
483
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000484// Add symbols to this symbol hash table. Note that this function
485// destructively sort a given vector -- which is needed because
486// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000487template <class ELFT>
Rafael Espindolae2c24612016-01-29 01:24:25 +0000488void GnuHashTableSection<ELFT>::addSymbols(
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000489 std::vector<std::pair<SymbolBody *, size_t>> &V) {
490 auto Mid = std::stable_partition(V.begin(), V.end(),
491 [](std::pair<SymbolBody *, size_t> &P) {
492 return !includeInGnuHashTable(P.first);
493 });
494 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000495 return;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000496 for (auto I = Mid, E = V.end(); I != E; ++I) {
497 SymbolBody *B = I->first;
498 size_t StrOff = I->second;
499 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
500 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000501
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000502 unsigned NBuckets = calcNBuckets(Symbols.size());
503 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000504 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000505 return L.Hash % NBuckets < R.Hash % NBuckets;
506 });
507
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000508 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000509 for (const SymbolData &Sym : Symbols)
510 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000511}
512
513template <class ELFT>
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000514DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000515 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE),
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000516 SymTab(SymTab) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000517 Elf_Shdr &Header = this->Header;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000518 Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000519 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000520
521 // .dynamic section is not writable on MIPS.
522 // See "Special Section" in Chapter 4 in the following document:
523 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
524 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000525 Header.sh_flags = SHF_ALLOC;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000526}
527
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000528template <class ELFT> void DynamicSection<ELFT>::finalize() {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000529 if (this->Header.sh_size)
530 return; // Already finalized.
531
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000532 Elf_Shdr &Header = this->Header;
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000533 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000534
Rafael Espindolae2c24612016-01-29 01:24:25 +0000535 auto Add = [=](Entry E) { Entries.push_back(E); };
536
537 // Add strings. We know that these are the last strings to be added to
Rafael Espindolade069362016-01-25 21:32:04 +0000538 // DynStrTab and doing this here allows this function to set DT_STRSZ.
539 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000540 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
541 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rafael Espindolade069362016-01-25 21:32:04 +0000542 for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
543 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000544 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
545 if (!Config->SoName.empty())
546 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
547
Rafael Espindolade069362016-01-25 21:32:04 +0000548 Out<ELFT>::DynStrTab->finalize();
549
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000550 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rafael Espindolade069362016-01-25 21:32:04 +0000551 bool IsRela = Out<ELFT>::RelaDyn->isRela();
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000552 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
553 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
554 Add({IsRela ? DT_RELAENT : DT_RELENT,
555 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000556 }
George Rimar648a2c32015-10-20 08:54:27 +0000557 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000558 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
559 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
560 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
561 Out<ELFT>::GotPlt});
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000562 Add({DT_PLTREL, uint64_t(Out<ELFT>::RelaPlt->isRela() ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000563 }
564
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000565 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
566 Add({DT_SYMENT, sizeof(Elf_Sym)});
567 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
568 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000569 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000570 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000571 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000572 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000573
Rafael Espindolade069362016-01-25 21:32:04 +0000574 if (PreInitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000575 Add({DT_PREINIT_ARRAY, PreInitArraySec});
576 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000577 }
578 if (InitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000579 Add({DT_INIT_ARRAY, InitArraySec});
580 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000581 }
582 if (FiniArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000583 Add({DT_FINI_ARRAY, FiniArraySec});
584 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000585 }
586
Rui Ueyama304d1352016-01-25 21:47:25 +0000587 if (SymbolBody *B = SymTab.find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000588 Add({DT_INIT, B});
Rui Ueyama304d1352016-01-25 21:47:25 +0000589 if (SymbolBody *B = SymTab.find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000590 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000591
Rafael Espindolade069362016-01-25 21:32:04 +0000592 uint32_t DtFlags = 0;
593 uint32_t DtFlags1 = 0;
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000594 if (Config->Bsymbolic)
595 DtFlags |= DF_SYMBOLIC;
596 if (Config->ZNodelete)
597 DtFlags1 |= DF_1_NODELETE;
598 if (Config->ZNow) {
599 DtFlags |= DF_BIND_NOW;
600 DtFlags1 |= DF_1_NOW;
601 }
602 if (Config->ZOrigin) {
603 DtFlags |= DF_ORIGIN;
604 DtFlags1 |= DF_1_ORIGIN;
605 }
606
607 if (DtFlags)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000608 Add({DT_FLAGS, DtFlags});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000609 if (DtFlags1)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000610 Add({DT_FLAGS_1, DtFlags1});
Igor Kudrin304860a2015-11-12 04:39:49 +0000611
Ed Mastef5d3cf62016-01-06 15:52:27 +0000612 if (!Config->Entry.empty())
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000613 Add({DT_DEBUG, (uint64_t)0});
Ed Mastef5d3cf62016-01-06 15:52:27 +0000614
Igor Kudrin304860a2015-11-12 04:39:49 +0000615 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000616 Add({DT_MIPS_RLD_VERSION, 1});
617 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
618 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
619 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
620 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000621 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000622 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000623 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000624 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
625 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000626 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000627 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000628 }
629
Rafael Espindolade069362016-01-25 21:32:04 +0000630 // +1 for DT_NULL
631 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000632}
633
634template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000635 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
636
Rafael Espindolade069362016-01-25 21:32:04 +0000637 for (const Entry &E : Entries) {
638 P->d_tag = E.Tag;
639 switch (E.Kind) {
640 case Entry::SecAddr:
641 P->d_un.d_ptr = E.OutSec->getVA();
642 break;
643 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000644 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000645 break;
646 case Entry::PlainInt:
647 P->d_un.d_val = E.Val;
648 break;
649 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000650 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000651 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000652}
653
654template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000655EhFrameHeader<ELFT>::EhFrameHeader()
656 : OutputSectionBase<ELFT>(".eh_frame_hdr", llvm::ELF::SHT_PROGBITS,
657 SHF_ALLOC) {
658 // It's a 4 bytes of header + pointer to the contents of the .eh_frame section
659 // + the number of FDE pointers in the table.
660 this->Header.sh_size = 12;
661}
662
663// We have to get PC values of FDEs. They depend on relocations
664// which are target specific, so we run this code after performing
665// all relocations. We read the values from ouput buffer according to the
666// encoding given for FDEs. Return value is an offset to the initial PC value
667// for the FDE.
668template <class ELFT>
669typename EhFrameHeader<ELFT>::uintX_t
670EhFrameHeader<ELFT>::getFdePc(uintX_t EhVA, const FdeData &F) {
671 const endianness E = ELFT::TargetEndianness;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000672 assert((F.Enc & 0xF0) != DW_EH_PE_datarel);
George Rimarf6bc65a2016-01-15 13:34:52 +0000673
674 uintX_t FdeOff = EhVA + F.Off + 8;
675 switch (F.Enc & 0xF) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000676 case DW_EH_PE_udata2:
677 case DW_EH_PE_sdata2:
George Rimarf6bc65a2016-01-15 13:34:52 +0000678 return FdeOff + read16<E>(F.PCRel);
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000679 case DW_EH_PE_udata4:
680 case DW_EH_PE_sdata4:
George Rimarf6bc65a2016-01-15 13:34:52 +0000681 return FdeOff + read32<E>(F.PCRel);
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000682 case DW_EH_PE_udata8:
683 case DW_EH_PE_sdata8:
George Rimarf6bc65a2016-01-15 13:34:52 +0000684 return FdeOff + read64<E>(F.PCRel);
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000685 case DW_EH_PE_absptr:
George Rimarf6bc65a2016-01-15 13:34:52 +0000686 if (sizeof(uintX_t) == 8)
687 return FdeOff + read64<E>(F.PCRel);
688 return FdeOff + read32<E>(F.PCRel);
689 }
Rui Ueyama64cfffd2016-01-28 18:40:06 +0000690 fatal("unknown FDE size encoding");
George Rimarf6bc65a2016-01-15 13:34:52 +0000691}
692
693template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
694 const endianness E = ELFT::TargetEndianness;
695
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000696 const uint8_t Header[] = {1, DW_EH_PE_pcrel | DW_EH_PE_sdata4,
697 DW_EH_PE_udata4,
698 DW_EH_PE_datarel | DW_EH_PE_sdata4};
George Rimarf6bc65a2016-01-15 13:34:52 +0000699 memcpy(Buf, Header, sizeof(Header));
700
701 uintX_t EhVA = Sec->getVA();
702 uintX_t VA = this->getVA();
703 uintX_t EhOff = EhVA - VA - 4;
704 write32<E>(Buf + 4, EhOff);
705 write32<E>(Buf + 8, this->FdeList.size());
706 Buf += 12;
707
708 // InitialPC -> Offset in .eh_frame, sorted by InitialPC.
709 std::map<uintX_t, size_t> PcToOffset;
710 for (const FdeData &F : FdeList)
711 PcToOffset[getFdePc(EhVA, F)] = F.Off;
712
713 for (auto &I : PcToOffset) {
714 // The first four bytes are an offset to the initial PC value for the FDE.
715 write32<E>(Buf, I.first - VA);
716 // The last four bytes are an offset to the FDE data itself.
717 write32<E>(Buf + 4, EhVA + I.second - VA);
718 Buf += 8;
719 }
720}
721
722template <class ELFT>
723void EhFrameHeader<ELFT>::assignEhFrame(EHOutputSection<ELFT> *Sec) {
George Rimar45ca88d2016-01-25 19:27:50 +0000724 assert((!this->Sec || this->Sec == Sec) &&
725 "multiple .eh_frame sections not supported for .eh_frame_hdr");
George Rimarf6bc65a2016-01-15 13:34:52 +0000726 Live = Config->EhFrameHdr;
727 this->Sec = Sec;
728}
729
730template <class ELFT>
731void EhFrameHeader<ELFT>::addFde(uint8_t Enc, size_t Off, uint8_t *PCRel) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000732 if (Live && (Enc & 0xF0) == DW_EH_PE_datarel)
Rui Ueyama64cfffd2016-01-28 18:40:06 +0000733 fatal("DW_EH_PE_datarel encoding unsupported for FDEs by .eh_frame_hdr");
George Rimarf6bc65a2016-01-15 13:34:52 +0000734 FdeList.push_back(FdeData{Enc, Off, PCRel});
735}
736
737template <class ELFT> void EhFrameHeader<ELFT>::reserveFde() {
738 // Each FDE entry is 8 bytes long:
739 // The first four bytes are an offset to the initial PC value for the FDE. The
740 // last four byte are an offset to the FDE data itself.
741 this->Header.sh_size += 8;
742}
743
744template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000745OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
746 : OutputSectionBase<ELFT>(Name, Type, Flags) {
747 if (Type == SHT_RELA)
748 this->Header.sh_entsize = sizeof(Elf_Rela);
749 else if (Type == SHT_REL)
750 this->Header.sh_entsize = sizeof(Elf_Rel);
751}
752
753template <class ELFT> void OutputSection<ELFT>::finalize() {
754 uint32_t Type = this->Header.sh_type;
755 if (Type != SHT_RELA && Type != SHT_REL)
756 return;
757 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
758 // sh_info for SHT_REL[A] sections should contain the section header index of
759 // the section to which the relocation applies.
760 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
761 this->Header.sh_info = S->OutSec->SectionIndex;
762}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000763
764template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +0000765void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000766 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000767 auto *S = cast<InputSection<ELFT>>(C);
768 Sections.push_back(S);
769 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000770 this->updateAlign(S->Align);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000771
772 uintX_t Off = this->Header.sh_size;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000773 Off = alignTo(Off, S->Align);
Rui Ueyama40845e62015-12-26 05:51:07 +0000774 S->OutSecOff = Off;
775 Off += S->getSize();
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000776 this->Header.sh_size = Off;
777}
778
Rui Ueyamac4185702016-02-10 23:20:42 +0000779// If an input string is in the form of "foo.N" where N is a number,
780// return N. Otherwise, returns 65536, which is one greater than the
781// lowest priority.
782static int getPriority(StringRef S) {
783 size_t Pos = S.rfind('.');
784 if (Pos == StringRef::npos)
785 return 65536;
786 int V;
787 if (S.substr(Pos + 1).getAsInteger(10, V))
788 return 65536;
789 return V;
790}
791
Rui Ueyama5af83682016-02-11 23:41:38 +0000792// This function is called after we sort input sections
793// to update their offsets.
794template <class ELFT> void OutputSection<ELFT>::reassignOffsets() {
795 uintX_t Off = 0;
796 for (InputSection<ELFT> *S : Sections) {
Rui Ueyama5ac58912016-02-24 00:38:18 +0000797 Off = alignTo(Off, S->Align);
Rui Ueyama5af83682016-02-11 23:41:38 +0000798 S->OutSecOff = Off;
799 Off += S->getSize();
800 }
801 this->Header.sh_size = Off;
802}
803
Rui Ueyamac4185702016-02-10 23:20:42 +0000804// Sorts input sections by section name suffixes, so that .foo.N comes
805// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000806// We want to keep the original order if the priorities are the same
807// because the compiler keeps the original initialization order in a
808// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000809// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000810template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000811 // Sort sections by priority.
812 typedef std::pair<int, InputSection<ELFT> *> Pair;
Rui Ueyama704da022016-02-10 23:43:16 +0000813 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
814
Rui Ueyamac4185702016-02-10 23:20:42 +0000815 std::vector<Pair> V;
816 for (InputSection<ELFT> *S : Sections)
817 V.push_back({getPriority(S->getSectionName()), S});
Rui Ueyama704da022016-02-10 23:43:16 +0000818 std::stable_sort(V.begin(), V.end(), Comp);
Rui Ueyamac4185702016-02-10 23:20:42 +0000819 Sections.clear();
820 for (Pair &P : V)
821 Sections.push_back(P.second);
Rui Ueyama5af83682016-02-11 23:41:38 +0000822 reassignOffsets();
823}
Rui Ueyamac4185702016-02-10 23:20:42 +0000824
Rui Ueyama5af83682016-02-11 23:41:38 +0000825// Returns true if S matches /Filename.?\.o$/.
826static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
827 if (!S.endswith(".o"))
828 return false;
829 S = S.drop_back(2);
830 if (S.endswith(Filename))
831 return true;
832 return !S.empty() && S.drop_back().endswith(Filename);
833}
834
835static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
836static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
837
838// .ctors and .dtors are sorted by this priority from highest to lowest.
839//
840// 1. The section was contained in crtbegin (crtbegin contains
841// some sentinel value in its .ctors and .dtors so that the runtime
842// can find the beginning of the sections.)
843//
844// 2. The section has an optional priority value in the form of ".ctors.N"
845// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
846// they are compared as string rather than number.
847//
848// 3. The section is just ".ctors" or ".dtors".
849//
850// 4. The section was contained in crtend, which contains an end marker.
851//
852// In an ideal world, we don't need this function because .init_array and
853// .ctors are duplicate features (and .init_array is newer.) However, there
854// are too many real-world use cases of .ctors, so we had no choice to
855// support that with this rather ad-hoc semantics.
856template <class ELFT>
857static bool compCtors(const InputSection<ELFT> *A,
858 const InputSection<ELFT> *B) {
859 bool BeginA = isCrtbegin(A->getFile()->getName());
860 bool BeginB = isCrtbegin(B->getFile()->getName());
861 if (BeginA != BeginB)
862 return BeginA;
863 bool EndA = isCrtend(A->getFile()->getName());
864 bool EndB = isCrtend(B->getFile()->getName());
865 if (EndA != EndB)
866 return EndB;
867 StringRef X = A->getSectionName();
868 StringRef Y = B->getSectionName();
869 assert(X.startswith(".ctors") || X.startswith(".dtors"));
870 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
871 X = X.substr(6);
872 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +0000873 if (X.empty() && Y.empty())
874 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +0000875 return X < Y;
876}
877
878// Sorts input sections by the special rules for .ctors and .dtors.
879// Unfortunately, the rules are different from the one for .{init,fini}_array.
880// Read the comment above.
881template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
882 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
883 reassignOffsets();
Rui Ueyamac4185702016-02-10 23:20:42 +0000884}
885
Rui Ueyama34f29242015-10-13 19:51:57 +0000886// Returns a VA which a relocatin RI refers to. Used only for local symbols.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000887// For non-local symbols, use SymbolBody::getVA instead.
Rafael Espindola932efcf2015-10-19 20:24:44 +0000888template <class ELFT, bool IsRela>
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000889typename ELFFile<ELFT>::uintX_t
Rui Ueyama83cd6e02016-01-06 20:11:55 +0000890elf2::getLocalRelTarget(const ObjectFile<ELFT> &File,
891 const Elf_Rel_Impl<ELFT, IsRela> &RI,
892 typename ELFFile<ELFT>::uintX_t Addend) {
Rafael Espindola932efcf2015-10-19 20:24:44 +0000893 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
Rafael Espindola435c00f2016-02-23 20:19:44 +0000894 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
Rafael Espindola932efcf2015-10-19 20:24:44 +0000895
Hal Finkel6f97c2b2015-10-16 21:55:40 +0000896 // PPC64 has a special relocation representing the TOC base pointer
897 // that does not have a corresponding symbol.
Hal Finkel230c5c52015-10-16 22:37:32 +0000898 if (Config->EMachine == EM_PPC64 && RI.getType(false) == R_PPC64_TOC)
Rafael Espindola932efcf2015-10-19 20:24:44 +0000899 return getPPC64TocBase() + Addend;
Hal Finkel6f97c2b2015-10-16 21:55:40 +0000900
Rui Ueyama126d08f2015-10-12 20:28:22 +0000901 const Elf_Sym *Sym =
902 File.getObj().getRelocationSymbol(&RI, File.getSymbolTable());
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000903
Rui Ueyama126d08f2015-10-12 20:28:22 +0000904 if (!Sym)
Rui Ueyama64cfffd2016-01-28 18:40:06 +0000905 fatal("Unsupported relocation without symbol");
Rui Ueyama126d08f2015-10-12 20:28:22 +0000906
Rafael Espindola435c00f2016-02-23 20:19:44 +0000907 InputSectionBase<ELFT> *Section = File.getSection(*Sym);
Michael J. Spencerdc9c5df2015-11-11 01:28:23 +0000908
Rafael Espindola435c00f2016-02-23 20:19:44 +0000909 if (Sym->getType() == STT_TLS)
910 return (Section->OutSec->getVA() + Section->getOffset(*Sym) + Addend) -
George Rimarcc06a6f2015-11-29 14:14:20 +0000911 Out<ELFT>::TlsPhdr->p_vaddr;
Michael J. Spencerdc9c5df2015-11-11 01:28:23 +0000912
Rafael Espindola444576d2015-10-09 19:25:07 +0000913 // According to the ELF spec reference to a local symbol from outside
914 // the group are not allowed. Unfortunately .eh_frame breaks that rule
915 // and must be treated specially. For now we just replace the symbol with
916 // 0.
Rui Ueyama733153d2016-02-24 18:33:35 +0000917 if (Section == InputSection<ELFT>::Discarded || !Section->Live)
Rafael Espindola932efcf2015-10-19 20:24:44 +0000918 return Addend;
Rafael Espindola444576d2015-10-09 19:25:07 +0000919
Rafael Espindola435c00f2016-02-23 20:19:44 +0000920 uintX_t Offset = Sym->st_value;
921 if (Sym->getType() == STT_SECTION) {
Rafael Espindolac159c962015-10-19 21:00:02 +0000922 Offset += Addend;
Rafael Espindolaf5af8352015-10-20 22:08:49 +0000923 Addend = 0;
Rafael Espindolac159c962015-10-19 21:00:02 +0000924 }
Rafael Espindola38a36c42016-02-03 16:53:39 +0000925 return Section->OutSec->getVA() + Section->getOffset(Offset) + Addend;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000926}
927
Rui Ueyama34f29242015-10-13 19:51:57 +0000928// Returns true if a symbol can be replaced at load-time by a symbol
929// with the same name defined in other ELF executable or DSO.
Rafael Espindola993f0272016-02-26 14:27:47 +0000930bool elf2::canBePreempted(const SymbolBody *Body) {
Rafael Espindolaa6627382015-10-06 23:56:53 +0000931 if (!Body)
Rui Ueyama34f29242015-10-13 19:51:57 +0000932 return false; // Body is a local symbol.
Rafael Espindolacea0b3b2015-10-07 04:22:55 +0000933 if (Body->isShared())
934 return true;
Rafael Espindolacc6ebb82015-10-14 18:42:16 +0000935
936 if (Body->isUndefined()) {
937 if (!Body->isWeak())
938 return true;
939
Rafael Espindola993f0272016-02-26 14:27:47 +0000940 // Ideally the static linker should see a definition for every symbol, but
941 // shared object are normally allowed to have undefined references that the
942 // static linker never sees a definition for.
943 if (Config->Shared)
944 return true;
945
946 // Otherwise, just resolve to 0.
947 return false;
Rafael Espindolacc6ebb82015-10-14 18:42:16 +0000948 }
Rafael Espindolaa6627382015-10-06 23:56:53 +0000949 if (!Config->Shared)
950 return false;
George Rimar5c36e592016-02-02 09:28:53 +0000951 if (Body->getVisibility() != STV_DEFAULT)
952 return false;
953 if (Config->Bsymbolic || (Config->BsymbolicFunctions && Body->isFunc()))
954 return false;
955 return true;
Rafael Espindolaa6627382015-10-06 23:56:53 +0000956}
957
George Rimare2ee72b2016-02-26 14:48:31 +0000958static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
959 size_t I = 0;
960 for (; I + A.size() < Size; I += A.size())
961 memcpy(Buf + I, A.data(), A.size());
962 memcpy(Buf + I, A.data(), Size - I);
963}
964
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000965template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimare2ee72b2016-02-26 14:48:31 +0000966 ArrayRef<uint8_t> Filler = Script->getFiller(this->Name);
967 if (!Filler.empty())
968 fill(Buf, this->getSize(), Filler);
Rafael Espindola71675852015-09-22 00:16:19 +0000969 for (InputSection<ELFT> *C : Sections)
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000970 C->writeTo(Buf);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000971}
972
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000973template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +0000974EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t Type,
975 uintX_t Flags)
George Rimarf6bc65a2016-01-15 13:34:52 +0000976 : OutputSectionBase<ELFT>(Name, Type, Flags) {
977 Out<ELFT>::EhFrameHdr->assignEhFrame(this);
978}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000979
980template <class ELFT>
981EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *S, unsigned Index)
982 : S(S), Index(Index) {}
983
984template <class ELFT> StringRef EHRegion<ELFT>::data() const {
985 ArrayRef<uint8_t> SecData = S->getSectionData();
986 ArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets;
987 size_t Start = Offsets[Index].first;
988 size_t End =
989 Index == Offsets.size() - 1 ? SecData.size() : Offsets[Index + 1].first;
990 return StringRef((const char *)SecData.data() + Start, End - Start);
991}
992
993template <class ELFT>
994Cie<ELFT>::Cie(EHInputSection<ELFT> *S, unsigned Index)
995 : EHRegion<ELFT>(S, Index) {}
996
George Rimarf6bc65a2016-01-15 13:34:52 +0000997// Read a byte and advance D by one byte.
998static uint8_t readByte(ArrayRef<uint8_t> &D) {
999 if (D.empty())
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001000 fatal("corrupted or unsupported CIE information");
George Rimarf6bc65a2016-01-15 13:34:52 +00001001 uint8_t B = D.front();
1002 D = D.slice(1);
1003 return B;
1004}
1005
1006static void skipLeb128(ArrayRef<uint8_t> &D) {
1007 while (!D.empty()) {
1008 uint8_t Val = D.front();
1009 D = D.slice(1);
1010 if ((Val & 0x80) == 0)
1011 return;
1012 }
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001013 fatal("corrupted or unsupported CIE information");
George Rimarf6bc65a2016-01-15 13:34:52 +00001014}
1015
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001016template <class ELFT> static size_t getAugPSize(unsigned Enc) {
1017 switch (Enc & 0x0f) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001018 case DW_EH_PE_absptr:
1019 case DW_EH_PE_signed:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001020 return ELFT::Is64Bits ? 8 : 4;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001021 case DW_EH_PE_udata2:
1022 case DW_EH_PE_sdata2:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001023 return 2;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001024 case DW_EH_PE_udata4:
1025 case DW_EH_PE_sdata4:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001026 return 4;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001027 case DW_EH_PE_udata8:
1028 case DW_EH_PE_sdata8:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001029 return 8;
1030 }
1031 fatal("unknown FDE encoding");
1032}
1033
1034template <class ELFT> static void skipAugP(ArrayRef<uint8_t> &D) {
1035 uint8_t Enc = readByte(D);
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001036 if ((Enc & 0xf0) == DW_EH_PE_aligned)
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001037 fatal("DW_EH_PE_aligned encoding is not supported");
1038 size_t Size = getAugPSize<ELFT>(Enc);
Rafael Espindola9e072d32016-02-09 22:47:34 +00001039 if (Size >= D.size())
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001040 fatal("corrupted CIE");
1041 D = D.slice(Size);
1042}
1043
George Rimarf6bc65a2016-01-15 13:34:52 +00001044template <class ELFT>
1045uint8_t EHOutputSection<ELFT>::getFdeEncoding(ArrayRef<uint8_t> D) {
Rui Ueyamabe748c22016-02-08 05:18:44 +00001046 if (D.size() < 8)
1047 fatal("CIE too small");
George Rimarf6bc65a2016-01-15 13:34:52 +00001048 D = D.slice(8);
1049
1050 uint8_t Version = readByte(D);
1051 if (Version != 1 && Version != 3)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001052 fatal("FDE version 1 or 3 expected, but got " + Twine((unsigned)Version));
George Rimarf6bc65a2016-01-15 13:34:52 +00001053
Saleem Abdulrasoolc0571e12016-02-15 03:45:18 +00001054 const unsigned char *AugEnd = std::find(D.begin() + 1, D.end(), '\0');
Rui Ueyamabe748c22016-02-08 05:18:44 +00001055 if (AugEnd == D.end())
1056 fatal("corrupted CIE");
Saleem Abdulrasoolc0571e12016-02-15 03:45:18 +00001057 StringRef Aug(reinterpret_cast<const char *>(D.begin()), AugEnd - D.begin());
Rui Ueyamabe748c22016-02-08 05:18:44 +00001058 D = D.slice(Aug.size() + 1);
George Rimarf6bc65a2016-01-15 13:34:52 +00001059
1060 // Code alignment factor should always be 1 for .eh_frame.
1061 if (readByte(D) != 1)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001062 fatal("CIE code alignment must be 1");
Rui Ueyamabe748c22016-02-08 05:18:44 +00001063
1064 // Skip data alignment factor.
George Rimarf6bc65a2016-01-15 13:34:52 +00001065 skipLeb128(D);
1066
1067 // Skip the return address register. In CIE version 1 this is a single
1068 // byte. In CIE version 3 this is an unsigned LEB128.
1069 if (Version == 1)
1070 readByte(D);
1071 else
1072 skipLeb128(D);
1073
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001074 // We only care about an 'R' value, but other records may precede an 'R'
1075 // record. Records are not in TLV (type-length-value) format, so we need
1076 // to teach the linker how to skip records for each type.
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001077 for (char C : Aug) {
1078 if (C == 'R')
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001079 return readByte(D);
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001080 if (C == 'z') {
1081 skipLeb128(D);
1082 continue;
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001083 }
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001084 if (C == 'P') {
1085 skipAugP<ELFT>(D);
1086 continue;
1087 }
1088 if (C == 'L')
1089 continue;
1090 fatal("unknown .eh_frame augmentation string: " + Aug);
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001091 }
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001092 return DW_EH_PE_absptr;
George Rimarf6bc65a2016-01-15 13:34:52 +00001093}
1094
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001095template <class ELFT>
Rui Ueyamac0c92602016-02-05 22:56:03 +00001096static typename ELFFile<ELFT>::uintX_t readEntryLength(ArrayRef<uint8_t> D) {
1097 const endianness E = ELFT::TargetEndianness;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001098 if (D.size() < 4)
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001099 fatal("CIE/FDE too small");
1100
1101 // First 4 bytes of CIE/FDE is the size of the record.
1102 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead.
1103 uint64_t V = read32<E>(D.data());
1104 if (V < UINT32_MAX) {
1105 uint64_t Len = V + 4;
1106 if (Len > D.size())
Rui Ueyamac0c92602016-02-05 22:56:03 +00001107 fatal("CIE/FIE ends past the end of the section");
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001108 return Len;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001109 }
1110
1111 if (D.size() < 12)
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001112 fatal("CIE/FDE too small");
1113 V = read64<E>(D.data() + 4);
1114 uint64_t Len = V + 12;
1115 if (Len < V || D.size() < Len)
Rui Ueyamac0c92602016-02-05 22:56:03 +00001116 fatal("CIE/FIE ends past the end of the section");
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001117 return Len;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001118}
1119
1120template <class ELFT>
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001121template <bool IsRela>
1122void EHOutputSection<ELFT>::addSectionAux(
1123 EHInputSection<ELFT> *S,
1124 iterator_range<const Elf_Rel_Impl<ELFT, IsRela> *> Rels) {
1125 const endianness E = ELFT::TargetEndianness;
1126
1127 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +00001128 this->updateAlign(S->Align);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001129 Sections.push_back(S);
1130
1131 ArrayRef<uint8_t> SecData = S->getSectionData();
1132 ArrayRef<uint8_t> D = SecData;
1133 uintX_t Offset = 0;
1134 auto RelI = Rels.begin();
1135 auto RelE = Rels.end();
1136
George Rimar147747a2016-01-02 16:55:01 +00001137 DenseMap<unsigned, unsigned> OffsetToIndex;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001138 while (!D.empty()) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001139 unsigned Index = S->Offsets.size();
1140 S->Offsets.push_back(std::make_pair(Offset, -1));
1141
Rui Ueyamac0c92602016-02-05 22:56:03 +00001142 uintX_t Length = readEntryLength<ELFT>(D);
George Rimarf6bc65a2016-01-15 13:34:52 +00001143 // If CIE/FDE data length is zero then Length is 4, this
1144 // shall be considered a terminator and processing shall end.
1145 if (Length == 4)
1146 break;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001147 StringRef Entry((const char *)D.data(), Length);
1148
1149 while (RelI != RelE && RelI->r_offset < Offset)
1150 ++RelI;
1151 uintX_t NextOffset = Offset + Length;
1152 bool HasReloc = RelI != RelE && RelI->r_offset < NextOffset;
1153
1154 uint32_t ID = read32<E>(D.data() + 4);
1155 if (ID == 0) {
1156 // CIE
1157 Cie<ELFT> C(S, Index);
George Rimarf6bc65a2016-01-15 13:34:52 +00001158 if (Config->EhFrameHdr)
1159 C.FdeEncoding = getFdeEncoding(D);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001160
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001161 SymbolBody *Personality = nullptr;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001162 if (HasReloc) {
1163 uint32_t SymIndex = RelI->getSymbol(Config->Mips64EL);
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001164 Personality = S->getFile()->getSymbolBody(SymIndex)->repl();
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001165 }
1166
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001167 std::pair<StringRef, SymbolBody *> CieInfo(Entry, Personality);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001168 auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size()));
George Rimar147747a2016-01-02 16:55:01 +00001169 if (P.second) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001170 Cies.push_back(C);
Rui Ueyama489a8062016-01-14 20:53:50 +00001171 this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
George Rimar147747a2016-01-02 16:55:01 +00001172 }
1173 OffsetToIndex[Offset] = P.first->second;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001174 } else {
1175 if (!HasReloc)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001176 fatal("FDE doesn't reference another section");
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001177 InputSectionBase<ELFT> *Target = S->getRelocTarget(*RelI);
Rui Ueyama733153d2016-02-24 18:33:35 +00001178 if (Target != InputSection<ELFT>::Discarded && Target->Live) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001179 uint32_t CieOffset = Offset + 4 - ID;
George Rimar147747a2016-01-02 16:55:01 +00001180 auto I = OffsetToIndex.find(CieOffset);
1181 if (I == OffsetToIndex.end())
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001182 fatal("Invalid CIE reference");
George Rimar147747a2016-01-02 16:55:01 +00001183 Cies[I->second].Fdes.push_back(EHRegion<ELFT>(S, Index));
George Rimarf6bc65a2016-01-15 13:34:52 +00001184 Out<ELFT>::EhFrameHdr->reserveFde();
Rui Ueyama489a8062016-01-14 20:53:50 +00001185 this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001186 }
1187 }
1188
1189 Offset = NextOffset;
1190 D = D.slice(Length);
1191 }
1192}
1193
1194template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001195void EHOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1196 auto *S = cast<EHInputSection<ELFT>>(C);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001197 const Elf_Shdr *RelSec = S->RelocSection;
Rui Ueyama0de86c12016-01-27 22:23:44 +00001198 if (!RelSec) {
1199 addSectionAux(S, make_range<const Elf_Rela *>(nullptr, nullptr));
1200 return;
1201 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001202 ELFFile<ELFT> &Obj = S->getFile()->getObj();
1203 if (RelSec->sh_type == SHT_RELA)
Rui Ueyama0de86c12016-01-27 22:23:44 +00001204 addSectionAux(S, Obj.relas(RelSec));
1205 else
1206 addSectionAux(S, Obj.rels(RelSec));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001207}
1208
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001209template <class ELFT>
1210static typename ELFFile<ELFT>::uintX_t writeAlignedCieOrFde(StringRef Data,
1211 uint8_t *Buf) {
1212 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
1213 const endianness E = ELFT::TargetEndianness;
Rui Ueyama489a8062016-01-14 20:53:50 +00001214 uint64_t Len = alignTo(Data.size(), sizeof(uintX_t));
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001215 write32<E>(Buf, Len - 4);
1216 memcpy(Buf + 4, Data.data() + 4, Data.size() - 4);
1217 return Len;
1218}
1219
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001220template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1221 const endianness E = ELFT::TargetEndianness;
1222 size_t Offset = 0;
1223 for (const Cie<ELFT> &C : Cies) {
1224 size_t CieOffset = Offset;
1225
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001226 uintX_t CIELen = writeAlignedCieOrFde<ELFT>(C.data(), Buf + Offset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001227 C.S->Offsets[C.Index].second = Offset;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001228 Offset += CIELen;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001229
1230 for (const EHRegion<ELFT> &F : C.Fdes) {
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001231 uintX_t Len = writeAlignedCieOrFde<ELFT>(F.data(), Buf + Offset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001232 write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001233 F.S->Offsets[F.Index].second = Offset;
George Rimarf6bc65a2016-01-15 13:34:52 +00001234 Out<ELFT>::EhFrameHdr->addFde(C.FdeEncoding, Offset, Buf + Offset + 8);
George Rimare72beba2015-12-21 09:38:59 +00001235 Offset += Len;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001236 }
1237 }
1238
1239 for (EHInputSection<ELFT> *S : Sections) {
1240 const Elf_Shdr *RelSec = S->RelocSection;
1241 if (!RelSec)
1242 continue;
1243 ELFFile<ELFT> &EObj = S->getFile()->getObj();
1244 if (RelSec->sh_type == SHT_RELA)
1245 S->relocate(Buf, nullptr, EObj.relas(RelSec));
1246 else
Rafael Espindolae02c8682015-11-23 15:28:28 +00001247 S->relocate(Buf, nullptr, EObj.rels(RelSec));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001248 }
1249}
1250
1251template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001252MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001253 uintX_t Flags, uintX_t Alignment)
1254 : OutputSectionBase<ELFT>(Name, Type, Flags),
1255 Builder(llvm::StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001256
1257template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001258 if (shouldTailMerge()) {
1259 StringRef Data = Builder.data();
Rafael Espindolac159c962015-10-19 21:00:02 +00001260 memcpy(Buf, Data.data(), Data.size());
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001261 return;
Rafael Espindolac159c962015-10-19 21:00:02 +00001262 }
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001263 for (const std::pair<StringRef, size_t> &P : Builder.getMap()) {
1264 StringRef Data = P.first;
1265 memcpy(Buf + P.second, Data.data(), Data.size());
1266 }
1267}
1268
1269static size_t findNull(StringRef S, size_t EntSize) {
1270 // Optimize the common case.
1271 if (EntSize == 1)
1272 return S.find(0);
1273
1274 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1275 const char *B = S.begin() + I;
1276 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1277 return I;
1278 }
1279 return StringRef::npos;
Rafael Espindolac159c962015-10-19 21:00:02 +00001280}
1281
1282template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001283void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1284 auto *S = cast<MergeInputSection<ELFT>>(C);
Rafael Espindolac159c962015-10-19 21:00:02 +00001285 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +00001286 this->updateAlign(S->Align);
Rafael Espindolac159c962015-10-19 21:00:02 +00001287
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001288 ArrayRef<uint8_t> D = S->getSectionData();
George Rimarf940d592015-10-25 20:14:07 +00001289 StringRef Data((const char *)D.data(), D.size());
Rafael Espindolac159c962015-10-19 21:00:02 +00001290 uintX_t EntSize = S->getSectionHdr()->sh_entsize;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001291
Rui Ueyamaead75fc2016-01-29 22:18:55 +00001292 // If this is of type string, the contents are null-terminated strings.
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001293 if (this->Header.sh_flags & SHF_STRINGS) {
Rui Ueyamaad87ff72016-01-06 02:52:24 +00001294 uintX_t Offset = 0;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001295 while (!Data.empty()) {
1296 size_t End = findNull(Data, EntSize);
1297 if (End == StringRef::npos)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001298 fatal("String is not null terminated");
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001299 StringRef Entry = Data.substr(0, End + EntSize);
George Rimar4b40ebc2015-11-13 13:44:59 +00001300 uintX_t OutputOffset = Builder.add(Entry);
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001301 if (shouldTailMerge())
1302 OutputOffset = -1;
1303 S->Offsets.push_back(std::make_pair(Offset, OutputOffset));
1304 uintX_t Size = End + EntSize;
1305 Data = Data.substr(Size);
1306 Offset += Size;
1307 }
Rui Ueyamaead75fc2016-01-29 22:18:55 +00001308 return;
1309 }
1310
1311 // If this is not of type string, every entry has the same size.
1312 for (unsigned I = 0, N = Data.size(); I != N; I += EntSize) {
1313 StringRef Entry = Data.substr(I, EntSize);
1314 size_t OutputOffset = Builder.add(Entry);
1315 S->Offsets.push_back(std::make_pair(I, OutputOffset));
Rafael Espindolac159c962015-10-19 21:00:02 +00001316 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001317}
1318
1319template <class ELFT>
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001320unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1321 return Builder.getOffset(Val);
1322}
1323
1324template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1325 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1326}
1327
1328template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1329 if (shouldTailMerge())
1330 Builder.finalize();
1331 this->Header.sh_size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001332}
1333
1334template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001335StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001336 : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1337 Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola35c6af32015-09-25 17:19:10 +00001338 Dynamic(Dynamic) {
1339 this->Header.sh_addralign = 1;
1340}
1341
Rafael Espindolae2c24612016-01-29 01:24:25 +00001342// Adds a string to the string table. If HashIt is true we hash and check for
1343// duplicates. It is optional because the name of global symbols are already
1344// uniqued and hashing them again has a big cost for a small value: uniquing
1345// them with some other string that happens to be the same.
1346template <class ELFT>
1347unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1348 if (HashIt) {
1349 auto R = StringMap.insert(std::make_pair(S, Size));
1350 if (!R.second)
1351 return R.first->second;
1352 }
1353 unsigned Ret = Size;
1354 Size += S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001355 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001356 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001357}
1358
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001359template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001360 // ELF string tables start with NUL byte, so advance the pointer by one.
1361 ++Buf;
1362 for (StringRef S : Strings) {
1363 memcpy(Buf, S.data(), S.size());
1364 Buf += S.size() + 1;
1365 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001366}
1367
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001368template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001369SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001370 SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec)
Rui Ueyamacf07a312016-01-06 22:53:58 +00001371 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1372 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001373 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001374 StrTabSec(StrTabSec), Table(Table) {
Rui Ueyamad1e92aa2016-01-07 18:20:02 +00001375 this->Header.sh_entsize = sizeof(Elf_Sym);
Rui Ueyama5e378dd2016-01-29 22:18:57 +00001376 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001377}
1378
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001379// Orders symbols according to their positions in the GOT,
1380// in compliance with MIPS ABI rules.
1381// See "Global Offset Table" in Chapter 5 in the following document
1382// for detailed description:
1383// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rafael Espindolae2c24612016-01-29 01:24:25 +00001384static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1385 const std::pair<SymbolBody *, unsigned> &R) {
1386 if (!L.first->isInGot() || !R.first->isInGot())
1387 return R.first->isInGot();
1388 return L.first->GotIndex < R.first->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001389}
1390
Rui Ueyama0db335f2015-10-07 16:58:54 +00001391template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001392 if (this->Header.sh_size)
1393 return; // Already finalized.
1394
Rui Ueyama0db335f2015-10-07 16:58:54 +00001395 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001396 this->Header.sh_link = StrTabSec.SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +00001397 this->Header.sh_info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001398
George Rimar58941ee2016-02-25 08:23:37 +00001399 if (Config->Relocatable) {
1400 size_t I = NumLocals;
1401 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1402 P.first->DynsymIndex = ++I;
1403 return;
1404 }
1405
Igor Kudrinab665fc2015-10-20 21:47:58 +00001406 if (!StrTabSec.isDynamic()) {
1407 std::stable_sort(Symbols.begin(), Symbols.end(),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001408 [](const std::pair<SymbolBody *, unsigned> &L,
1409 const std::pair<SymbolBody *, unsigned> &R) {
1410 return getSymbolBinding(L.first) == STB_LOCAL &&
1411 getSymbolBinding(R.first) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001412 });
1413 return;
1414 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001415 if (Out<ELFT>::GnuHashTab)
1416 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1417 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001418 else if (Config->EMachine == EM_MIPS)
1419 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Igor Kudrinab665fc2015-10-20 21:47:58 +00001420 size_t I = 0;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001421 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
Rui Ueyama572a6f72016-01-29 01:49:33 +00001422 P.first->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001423}
1424
1425template <class ELFT>
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001426void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1427 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001428}
1429
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001430template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001431 Buf += sizeof(Elf_Sym);
1432
1433 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1434 // .dynsym only contains global symbols.
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001435 if (!Config->DiscardAll && !StrTabSec.isDynamic())
1436 writeLocalSymbols(Buf);
1437
1438 writeGlobalSymbols(Buf);
1439}
1440
1441template <class ELFT>
1442void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1443 // Iterate over all input object files to copy their local symbols
1444 // to the output symbol table pointed by Buf.
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001445 for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001446 for (const std::pair<const Elf_Sym *, size_t> &P : File->KeptLocalSyms) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001447 const Elf_Sym *Sym = P.first;
Rafael Espindola444576d2015-10-09 19:25:07 +00001448
Rui Ueyamac55733e2015-09-30 00:54:29 +00001449 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolac159c962015-10-19 21:00:02 +00001450 uintX_t VA = 0;
Rafael Espindola10d71ff2016-01-27 18:04:26 +00001451 if (Sym->st_shndx == SHN_ABS) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001452 ESym->st_shndx = SHN_ABS;
Rafael Espindola10d71ff2016-01-27 18:04:26 +00001453 VA = Sym->st_value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001454 } else {
Rafael Espindola10d71ff2016-01-27 18:04:26 +00001455 InputSectionBase<ELFT> *Section = File->getSection(*Sym);
Rafael Espindolac159c962015-10-19 21:00:02 +00001456 const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1457 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola10d71ff2016-01-27 18:04:26 +00001458 VA = Section->getOffset(*Sym);
Tom Stellard80efb162016-01-07 03:59:08 +00001459 // Symbol offsets for AMDGPU need to be the offset in bytes of the
1460 // symbol from the beginning of the section.
1461 if (Config->EMachine != EM_AMDGPU)
1462 VA += OutSec->getVA();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001463 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001464 ESym->st_name = P.second;
Rafael Espindola10d71ff2016-01-27 18:04:26 +00001465 ESym->st_size = Sym->st_size;
1466 ESym->setBindingAndType(Sym->getBinding(), Sym->getType());
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001467 ESym->st_value = VA;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001468 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001469 }
1470 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001471}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001472
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001473template <class ELFT>
Rafael Espindola5d7593b2015-12-22 23:00:50 +00001474static const typename llvm::object::ELFFile<ELFT>::Elf_Sym *
1475getElfSym(SymbolBody &Body) {
Rafael Espindola4d4b06a2015-12-24 00:47:42 +00001476 if (auto *EBody = dyn_cast<DefinedElf<ELFT>>(&Body))
Rafael Espindola5d7593b2015-12-22 23:00:50 +00001477 return &EBody->Sym;
1478 if (auto *EBody = dyn_cast<UndefinedElf<ELFT>>(&Body))
1479 return &EBody->Sym;
1480 return nullptr;
1481}
1482
1483template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001484void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001485 // Write the internal symbol table contents to the output symbol table
1486 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001487 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001488 for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001489 SymbolBody *Body = P.first;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001490 size_t StrOff = P.second;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001491
Rafael Espindola8614c562015-10-06 14:33:58 +00001492 unsigned char Type = STT_NOTYPE;
1493 uintX_t Size = 0;
Rafael Espindola5d7593b2015-12-22 23:00:50 +00001494 if (const Elf_Sym *InputSym = getElfSym<ELFT>(*Body)) {
1495 Type = InputSym->getType();
1496 Size = InputSym->st_size;
Rafael Espindola11191912015-12-24 16:23:37 +00001497 } else if (auto *C = dyn_cast<DefinedCommon>(Body)) {
1498 Type = STT_OBJECT;
1499 Size = C->Size;
Rafael Espindola8614c562015-10-06 14:33:58 +00001500 }
1501
Igor Kudrin853b88d2015-10-20 20:52:14 +00001502 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001503 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001504 ESym->st_name = StrOff;
Rui Ueyama8f2c4da2015-10-21 18:13:47 +00001505 ESym->setVisibility(Body->getVisibility());
Rui Ueyamab5a69702016-02-01 21:00:35 +00001506 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001507
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001508 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001509 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001510 else if (isa<DefinedRegular<ELFT>>(Body))
1511 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001512
1513 // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1514 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1515 // distinguish such symbols and MIPS lazy-binding stubs.
1516 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1517 if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1518 Body->NeedsCopyOrPltAddr)
Simon Atanasyanbea96982016-02-25 21:09:05 +00001519 ESym->st_other |= STO_MIPS_PLT;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001520 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001521 }
1522}
1523
Igor Kudrin853b88d2015-10-20 20:52:14 +00001524template <class ELFT>
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001525const OutputSectionBase<ELFT> *
1526SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1527 switch (Sym->kind()) {
1528 case SymbolBody::DefinedSyntheticKind:
1529 return &cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1530 case SymbolBody::DefinedRegularKind: {
1531 auto *D = cast<DefinedRegular<ELFT>>(Sym->repl());
1532 if (D->Section)
1533 return D->Section->OutSec;
1534 break;
1535 }
1536 case SymbolBody::DefinedCommonKind:
1537 return Out<ELFT>::Bss;
1538 case SymbolBody::SharedKind:
1539 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1540 return Out<ELFT>::Bss;
1541 break;
1542 case SymbolBody::UndefinedElfKind:
1543 case SymbolBody::UndefinedKind:
1544 case SymbolBody::LazyKind:
1545 break;
1546 case SymbolBody::DefinedBitcodeKind:
1547 llvm_unreachable("Should have been replaced");
1548 }
1549 return nullptr;
1550}
1551
1552template <class ELFT>
Igor Kudrin853b88d2015-10-20 20:52:14 +00001553uint8_t SymbolTableSection<ELFT>::getSymbolBinding(SymbolBody *Body) {
Rui Ueyama8f2c4da2015-10-21 18:13:47 +00001554 uint8_t Visibility = Body->getVisibility();
Igor Kudrin853b88d2015-10-20 20:52:14 +00001555 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1556 return STB_LOCAL;
Rafael Espindola5d7593b2015-12-22 23:00:50 +00001557 if (const Elf_Sym *ESym = getElfSym<ELFT>(*Body))
1558 return ESym->getBinding();
Rafael Espindola4d4b06a2015-12-24 00:47:42 +00001559 if (isa<DefinedSynthetic<ELFT>>(Body))
1560 return STB_LOCAL;
Igor Kudrin853b88d2015-10-20 20:52:14 +00001561 return Body->isWeak() ? STB_WEAK : STB_GLOBAL;
1562}
1563
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001564template <class ELFT>
1565MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1566 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1567 this->Header.sh_addralign = 4;
1568 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1569 this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1570}
1571
1572template <class ELFT>
1573void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1574 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
1575 R->ri_gp_value = getMipsGpAddr<ELFT>();
Rui Ueyama70eed362016-01-06 22:42:43 +00001576 R->ri_gprmask = GprMask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001577}
1578
1579template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001580void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama70eed362016-01-06 22:42:43 +00001581 // Copy input object file's .reginfo gprmask to output.
Rui Ueyama40845e62015-12-26 05:51:07 +00001582 auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
Rui Ueyama70eed362016-01-06 22:42:43 +00001583 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001584}
1585
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001586namespace lld {
1587namespace elf2 {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001588template class OutputSectionBase<ELF32LE>;
1589template class OutputSectionBase<ELF32BE>;
1590template class OutputSectionBase<ELF64LE>;
1591template class OutputSectionBase<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001592
George Rimarf6bc65a2016-01-15 13:34:52 +00001593template class EhFrameHeader<ELF32LE>;
1594template class EhFrameHeader<ELF32BE>;
1595template class EhFrameHeader<ELF64LE>;
1596template class EhFrameHeader<ELF64BE>;
1597
George Rimar648a2c32015-10-20 08:54:27 +00001598template class GotPltSection<ELF32LE>;
1599template class GotPltSection<ELF32BE>;
1600template class GotPltSection<ELF64LE>;
1601template class GotPltSection<ELF64BE>;
1602
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001603template class GotSection<ELF32LE>;
1604template class GotSection<ELF32BE>;
1605template class GotSection<ELF64LE>;
1606template class GotSection<ELF64BE>;
1607
1608template class PltSection<ELF32LE>;
1609template class PltSection<ELF32BE>;
1610template class PltSection<ELF64LE>;
1611template class PltSection<ELF64BE>;
1612
1613template class RelocationSection<ELF32LE>;
1614template class RelocationSection<ELF32BE>;
1615template class RelocationSection<ELF64LE>;
1616template class RelocationSection<ELF64BE>;
1617
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001618template class InterpSection<ELF32LE>;
1619template class InterpSection<ELF32BE>;
1620template class InterpSection<ELF64LE>;
1621template class InterpSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001622
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001623template class GnuHashTableSection<ELF32LE>;
1624template class GnuHashTableSection<ELF32BE>;
1625template class GnuHashTableSection<ELF64LE>;
1626template class GnuHashTableSection<ELF64BE>;
1627
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001628template class HashTableSection<ELF32LE>;
1629template class HashTableSection<ELF32BE>;
1630template class HashTableSection<ELF64LE>;
1631template class HashTableSection<ELF64BE>;
1632
1633template class DynamicSection<ELF32LE>;
1634template class DynamicSection<ELF32BE>;
1635template class DynamicSection<ELF64LE>;
1636template class DynamicSection<ELF64BE>;
1637
1638template class OutputSection<ELF32LE>;
1639template class OutputSection<ELF32BE>;
1640template class OutputSection<ELF64LE>;
1641template class OutputSection<ELF64BE>;
1642
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001643template class EHOutputSection<ELF32LE>;
1644template class EHOutputSection<ELF32BE>;
1645template class EHOutputSection<ELF64LE>;
1646template class EHOutputSection<ELF64BE>;
1647
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001648template class MipsReginfoOutputSection<ELF32LE>;
1649template class MipsReginfoOutputSection<ELF32BE>;
1650template class MipsReginfoOutputSection<ELF64LE>;
1651template class MipsReginfoOutputSection<ELF64BE>;
1652
Rafael Espindolac159c962015-10-19 21:00:02 +00001653template class MergeOutputSection<ELF32LE>;
1654template class MergeOutputSection<ELF32BE>;
1655template class MergeOutputSection<ELF64LE>;
1656template class MergeOutputSection<ELF64BE>;
1657
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001658template class StringTableSection<ELF32LE>;
1659template class StringTableSection<ELF32BE>;
1660template class StringTableSection<ELF64LE>;
1661template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001662
1663template class SymbolTableSection<ELF32LE>;
1664template class SymbolTableSection<ELF32BE>;
1665template class SymbolTableSection<ELF64LE>;
1666template class SymbolTableSection<ELF64BE>;
1667
Rui Ueyama5ec41f32016-01-26 01:32:00 +00001668template uint32_t getLocalRelTarget(const ObjectFile<ELF32LE> &,
1669 const ELFFile<ELF32LE>::Elf_Rel &,
1670 uint32_t);
1671template uint32_t getLocalRelTarget(const ObjectFile<ELF32BE> &,
1672 const ELFFile<ELF32BE>::Elf_Rel &,
1673 uint32_t);
1674template uint64_t getLocalRelTarget(const ObjectFile<ELF64LE> &,
1675 const ELFFile<ELF64LE>::Elf_Rel &,
1676 uint64_t);
1677template uint64_t getLocalRelTarget(const ObjectFile<ELF64BE> &,
1678 const ELFFile<ELF64BE>::Elf_Rel &,
1679 uint64_t);
1680template uint32_t getLocalRelTarget(const ObjectFile<ELF32LE> &,
1681 const ELFFile<ELF32LE>::Elf_Rela &,
1682 uint32_t);
1683template uint32_t getLocalRelTarget(const ObjectFile<ELF32BE> &,
1684 const ELFFile<ELF32BE>::Elf_Rela &,
1685 uint32_t);
1686template uint64_t getLocalRelTarget(const ObjectFile<ELF64LE> &,
1687 const ELFFile<ELF64LE>::Elf_Rela &,
1688 uint64_t);
1689template uint64_t getLocalRelTarget(const ObjectFile<ELF64BE> &,
1690 const ELFFile<ELF64BE>::Elf_Rela &,
1691 uint64_t);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001692}
1693}