blob: 18d1ed47350e0d847c8d2eed78f3145a4fc51199 [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"
Rui Ueyamae9809502016-03-11 04:23:12 +000015#include "lld/Core/Parallel.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000016#include "llvm/Support/Dwarf.h"
Igor Kudrin1b0d7062015-10-22 08:21:35 +000017#include "llvm/Support/MathExtras.h"
George Rimarf6bc65a2016-01-15 13:34:52 +000018#include <map>
Rafael Espindola5805c4f2015-09-21 21:38:08 +000019
Rafael Espindola5805c4f2015-09-21 21:38:08 +000020using namespace llvm;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +000021using namespace llvm::dwarf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000022using namespace llvm::object;
Rafael Espindolaa6627382015-10-06 23:56:53 +000023using namespace llvm::support::endian;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000024using namespace llvm::ELF;
25
26using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000027using namespace lld::elf;
Rafael Espindola5805c4f2015-09-21 21:38:08 +000028
George Rimar12737b72016-02-25 08:40:26 +000029static bool isAlpha(char C) {
30 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
31}
32
33static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
34
35// Returns true if S is valid as a C language identifier.
Rafael Espindolae0df00b2016-02-28 00:25:54 +000036bool elf::isValidCIdentifier(StringRef S) {
Rui Ueyamadad77c52016-02-26 15:42:06 +000037 return !S.empty() && isAlpha(S[0]) &&
38 std::all_of(S.begin() + 1, S.end(), isAlnum);
George Rimar12737b72016-02-25 08:40:26 +000039}
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>
Rui Ueyamac63c1db2016-03-13 06:50:33 +000051void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) {
52 *Shdr = Header;
53}
54
55template <class ELFT>
George Rimar648a2c32015-10-20 08:54:27 +000056GotPltSection<ELFT>::GotPltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000057 : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
George Rimar648a2c32015-10-20 08:54:27 +000058 this->Header.sh_addralign = sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000059}
60
Rafael Espindola67d72c02016-03-11 12:06:30 +000061template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
62 Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
63 Entries.push_back(&Sym);
George Rimar648a2c32015-10-20 08:54:27 +000064}
65
66template <class ELFT> bool GotPltSection<ELFT>::empty() const {
Igor Kudrin351b41d2015-11-16 17:44:08 +000067 return Entries.empty();
George Rimar648a2c32015-10-20 08:54:27 +000068}
69
George Rimar648a2c32015-10-20 08:54:27 +000070template <class ELFT> void GotPltSection<ELFT>::finalize() {
Igor Kudrin351b41d2015-11-16 17:44:08 +000071 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +000072 (Target->GotPltHeaderEntriesNum + Entries.size()) * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000073}
74
75template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +000076 Target->writeGotPltHeader(Buf);
Rui Ueyama724d6252016-01-29 01:49:32 +000077 Buf += Target->GotPltHeaderEntriesNum * sizeof(uintX_t);
George Rimar648a2c32015-10-20 08:54:27 +000078 for (const SymbolBody *B : Entries) {
Rui Ueyamab5a69702016-02-01 21:00:35 +000079 Target->writeGotPlt(Buf, B->getPltVA<ELFT>());
George Rimar648a2c32015-10-20 08:54:27 +000080 Buf += sizeof(uintX_t);
81 }
82}
83
84template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +000085GotSection<ELFT>::GotSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +000086 : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
Igor Kudrin15cd9ff2015-11-06 07:43:03 +000087 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +000088 this->Header.sh_flags |= SHF_MIPS_GPREL;
Rui Ueyama5f551ae2015-10-14 14:02:06 +000089 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +000090}
91
Rafael Espindola67d72c02016-03-11 12:06:30 +000092template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +000093 if (Config->EMachine == EM_MIPS) {
Simon Atanasyanbea20c32016-03-23 09:28:02 +000094 // For "true" local symbols which can be referenced from the same module
95 // only compiler creates two instructions for address loading:
96 //
97 // lw $8, 0($gp) # R_MIPS_GOT16
98 // addi $8, $8, 0 # R_MIPS_LO16
99 //
100 // The first instruction loads high 16 bits of the symbol address while
101 // the second adds an offset. That allows to reduce number of required
102 // GOT entries because only one global offset table entry is necessary
103 // for every 64 KBytes of local data. So for local symbols we need to
104 // allocate number of GOT entries to hold all required "page" addresses.
105 //
106 // All global symbols (hidden and regular) considered by compiler uniformly.
107 // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
108 // to load address of the symbol. So for each such symbol we need to
109 // allocate dedicated GOT entry to store its address.
110 //
111 // If a symbol is preemptible we need help of dynamic linker to get its
112 // final address. The corresponding GOT entries are allocated in the
113 // "global" part of GOT. Entries for non preemptible global symbol allocated
114 // in the "local" part of GOT.
115 //
116 // See "Global Offset Table" in Chapter 5:
117 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Simon Atanasyand2980d32016-03-29 14:07:22 +0000118 if (Sym.isLocal()) {
119 // At this point we do not know final symbol value so to reduce number
120 // of allocated GOT entries do the following trick. Save all output
121 // sections referenced by GOT relocations. Then later in the `finalize`
122 // method calculate number of "pages" required to cover all saved output
123 // section and allocate appropriate number of GOT entries.
124 auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
125 MipsOutSections.insert(OutSec);
126 return;
127 }
128 if (!Sym.isPreemptible()) {
129 // In case of non-local symbols require an entry in the local part
130 // of MIPS GOT, we set GotIndex to 1 just to accent that this symbol
131 // has the GOT entry and escape creation more redundant GOT entries.
132 // FIXME (simon): We can try to store such symbols in the `Entries`
133 // container. But in that case we have to sort out that container
134 // and update GotIndex assigned to symbols.
135 Sym.GotIndex = 1;
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +0000136 ++MipsLocalEntries;
137 return;
138 }
Simon Atanasyand2980d32016-03-29 14:07:22 +0000139 // All preemptible symbols with MIPS GOT entries should be represented
140 // in the dynamic symbols table.
141 Sym.MustBeInDynSym = true;
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +0000142 }
Rafael Espindola67d72c02016-03-11 12:06:30 +0000143 Sym.GotIndex = Entries.size();
144 Entries.push_back(&Sym);
George Rimar687138c2015-11-13 16:28:53 +0000145}
146
Rafael Espindola67d72c02016-03-11 12:06:30 +0000147template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
148 if (Sym.hasGlobalDynIndex())
George Rimar90cd0a82015-12-01 19:20:26 +0000149 return false;
Rafael Espindola67d72c02016-03-11 12:06:30 +0000150 Sym.GlobalDynIndex = Target->GotHeaderEntriesNum + Entries.size();
Michael J. Spencer627ae702015-11-13 00:28:34 +0000151 // Global Dynamic TLS entries take two GOT slots.
Rafael Espindola67d72c02016-03-11 12:06:30 +0000152 Entries.push_back(&Sym);
George Rimar687138c2015-11-13 16:28:53 +0000153 Entries.push_back(nullptr);
George Rimar90cd0a82015-12-01 19:20:26 +0000154 return true;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000155}
156
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000157// Reserves TLS entries for a TLS module ID and a TLS block offset.
158// In total it takes two GOT slots.
159template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
160 if (TlsIndexOff != uint32_t(-1))
George Rimarb17f7392015-12-01 18:24:07 +0000161 return false;
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000162 TlsIndexOff = Entries.size() * sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000163 Entries.push_back(nullptr);
164 Entries.push_back(nullptr);
George Rimarb17f7392015-12-01 18:24:07 +0000165 return true;
Michael J. Spencer1e225612015-11-11 01:00:24 +0000166}
167
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000168template <class ELFT>
169typename GotSection<ELFT>::uintX_t
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000170GotSection<ELFT>::getMipsLocalFullAddr(const SymbolBody &B) {
Rui Ueyamab5a69702016-02-01 21:00:35 +0000171 return getMipsLocalEntryAddr(B.getVA<ELFT>());
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000172}
173
174template <class ELFT>
175typename GotSection<ELFT>::uintX_t
176GotSection<ELFT>::getMipsLocalPageAddr(uintX_t EntryValue) {
177 // Initialize the entry by the %hi(EntryValue) expression
178 // but without right-shifting.
179 return getMipsLocalEntryAddr((EntryValue + 0x8000) & ~0xffff);
180}
181
182template <class ELFT>
183typename GotSection<ELFT>::uintX_t
184GotSection<ELFT>::getMipsLocalEntryAddr(uintX_t EntryValue) {
Rui Ueyama724d6252016-01-29 01:49:32 +0000185 size_t NewIndex = Target->GotHeaderEntriesNum + MipsLocalGotPos.size();
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000186 auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
187 assert(!P.second || MipsLocalGotPos.size() <= MipsLocalEntries);
188 return this->getVA() + P.first->second * sizeof(uintX_t);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000189}
190
Igor Kudrin304860a2015-11-12 04:39:49 +0000191template <class ELFT>
George Rimar90cd0a82015-12-01 19:20:26 +0000192typename GotSection<ELFT>::uintX_t
193GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
194 return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
195}
196
197template <class ELFT>
Igor Kudrin304860a2015-11-12 04:39:49 +0000198const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
199 return Entries.empty() ? nullptr : Entries.front();
200}
201
202template <class ELFT>
203unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
Rui Ueyama724d6252016-01-29 01:49:32 +0000204 return Target->GotHeaderEntriesNum + MipsLocalEntries;
Igor Kudrin304860a2015-11-12 04:39:49 +0000205}
206
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000207template <class ELFT> void GotSection<ELFT>::finalize() {
Simon Atanasyand2980d32016-03-29 14:07:22 +0000208 for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) {
209 // Calculate an upper bound of MIPS GOT entries required to store page
210 // addresses of local symbols. We assume the worst case - each 64kb
211 // page of the output section has at least one GOT relocation against it.
212 // Add 0x8000 to the section's size because the page address stored
213 // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
214 MipsLocalEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff;
215 }
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000216 this->Header.sh_size =
Rui Ueyama724d6252016-01-29 01:49:32 +0000217 (Target->GotHeaderEntriesNum + MipsLocalEntries + Entries.size()) *
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000218 sizeof(uintX_t);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000219}
220
Rafael Espindolaa6627382015-10-06 23:56:53 +0000221template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyamac516ae12016-01-29 02:33:45 +0000222 Target->writeGotHeader(Buf);
Rui Ueyama5cbf5d22016-02-02 02:29:03 +0000223 for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000224 uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
225 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
226 }
Rui Ueyama724d6252016-01-29 01:49:32 +0000227 Buf += Target->GotHeaderEntriesNum * sizeof(uintX_t);
Simon Atanasyan56ab5f02016-01-21 05:33:23 +0000228 Buf += MipsLocalEntries * sizeof(uintX_t);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000229 for (const SymbolBody *B : Entries) {
Rafael Espindolae782f672015-10-07 03:56:05 +0000230 uint8_t *Entry = Buf;
231 Buf += sizeof(uintX_t);
Michael J. Spencer1e225612015-11-11 01:00:24 +0000232 if (!B)
233 continue;
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000234 // MIPS has special rules to fill up GOT entries.
235 // See "Global Offset Table" in Chapter 5 in the following document
236 // for detailed description:
237 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
238 // As the first approach, we can just store addresses for all symbols.
Rui Ueyamac4466602016-03-13 19:48:18 +0000239 if (Config->EMachine != EM_MIPS && B->isPreemptible())
Rafael Espindolaa6627382015-10-06 23:56:53 +0000240 continue; // The dynamic linker will take care of it.
Rui Ueyamab5a69702016-02-01 21:00:35 +0000241 uintX_t VA = B->getVA<ELFT>();
Rafael Espindolae782f672015-10-07 03:56:05 +0000242 write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
Rafael Espindolaa6627382015-10-06 23:56:53 +0000243 }
244}
245
Rafael Espindola35c6af32015-09-25 17:19:10 +0000246template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000247PltSection<ELFT>::PltSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000248 : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000249 this->Header.sh_addralign = 16;
250}
251
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000252template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama242ddf42015-10-12 18:56:36 +0000253 size_t Off = 0;
Rui Ueyama9398f862016-01-29 04:15:02 +0000254 if (Target->UseLazyBinding) {
Rui Ueyama74937fc2016-02-02 02:53:58 +0000255 // At beginning of PLT, we have code to call the dynamic linker
256 // to resolve dynsyms at runtime. Write such code.
Rui Ueyama900e2d22016-01-29 03:51:49 +0000257 Target->writePltZero(Buf);
Rui Ueyama62515452016-01-29 03:00:32 +0000258 Off += Target->PltZeroSize;
George Rimar648a2c32015-10-20 08:54:27 +0000259 }
George Rimarfb5d7f22015-11-26 19:58:51 +0000260 for (auto &I : Entries) {
Rui Ueyama9398f862016-01-29 04:15:02 +0000261 const SymbolBody *B = I.first;
George Rimar77b77792015-11-25 22:15:01 +0000262 unsigned RelOff = I.second;
Rui Ueyamab5a69702016-02-01 21:00:35 +0000263 uint64_t Got =
264 Target->UseLazyBinding ? B->getGotPltVA<ELFT>() : B->getGotVA<ELFT>();
Rui Ueyama242ddf42015-10-12 18:56:36 +0000265 uint64_t Plt = this->getVA() + Off;
Rui Ueyama9398f862016-01-29 04:15:02 +0000266 Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
Rui Ueyama724d6252016-01-29 01:49:32 +0000267 Off += Target->PltEntrySize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000268 }
269}
270
Rafael Espindola67d72c02016-03-11 12:06:30 +0000271template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
272 Sym.PltIndex = Entries.size();
Rui Ueyama724d6252016-01-29 01:49:32 +0000273 unsigned RelOff = Target->UseLazyBinding
George Rimar77b77792015-11-25 22:15:01 +0000274 ? Out<ELFT>::RelaPlt->getRelocOffset()
275 : Out<ELFT>::RelaDyn->getRelocOffset();
Rafael Espindola67d72c02016-03-11 12:06:30 +0000276 Entries.push_back(std::make_pair(&Sym, RelOff));
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000277}
278
George Rimar648a2c32015-10-20 08:54:27 +0000279template <class ELFT> void PltSection<ELFT>::finalize() {
Rui Ueyama724d6252016-01-29 01:49:32 +0000280 this->Header.sh_size =
Rui Ueyama62515452016-01-29 03:00:32 +0000281 Target->PltZeroSize + Entries.size() * Target->PltEntrySize;
Hal Finkel6c2a3b82015-10-08 21:51:31 +0000282}
283
284template <class ELFT>
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000285RelocationSection<ELFT>::RelocationSection(StringRef Name)
286 : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
287 SHF_ALLOC) {
288 this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000289 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000290}
291
George Rimar5828c232015-11-30 17:49:19 +0000292template <class ELFT>
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000293void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
294 SymbolBody *Sym = Reloc.Sym;
295 if (!Reloc.UseSymVA && Sym)
Rafael Espindolaabebed92016-02-05 15:27:15 +0000296 Sym->MustBeInDynSym = true;
Rafael Espindolad30eb7d2016-02-05 15:03:10 +0000297 Relocs.push_back(Reloc);
298}
299
300template <class ELFT>
Rui Ueyama9328b2c2016-03-14 23:16:09 +0000301typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000302 switch (OKind) {
303 case Off_GTlsIndex:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000304 return Out<ELFT>::Got->getGlobalDynAddr(*Sym);
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000305 case Off_GTlsOffset:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000306 return Out<ELFT>::Got->getGlobalDynAddr(*Sym) + sizeof(uintX_t);
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000307 case Off_LTlsIndex:
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000308 return Out<ELFT>::Got->getTlsIndexVA();
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000309 case Off_Sec:
310 return OffsetSec->getOffset(OffsetInSec) + OffsetSec->OutSec->getVA();
311 case Off_Bss:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000312 return cast<SharedSymbol<ELFT>>(Sym)->OffsetInBss + Out<ELFT>::Bss->getVA();
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000313 case Off_Got:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000314 return Sym->getGotVA<ELFT>();
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000315 case Off_GotPlt:
Rafael Espindolade9857e2016-02-04 21:33:05 +0000316 return Sym->getGotPltVA<ELFT>();
George Rimar5828c232015-11-30 17:49:19 +0000317 }
George Rimar777f9632016-03-12 08:31:34 +0000318 llvm_unreachable("invalid offset kind");
George Rimar5828c232015-11-30 17:49:19 +0000319}
320
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000321template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000322 for (const DynamicReloc<ELFT> &Rel : Relocs) {
Rui Ueyama614be592016-03-13 05:23:40 +0000323 auto *P = reinterpret_cast<Elf_Rela *>(Buf);
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000324 Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
Rafael Espindolade9857e2016-02-04 21:33:05 +0000325 SymbolBody *Sym = Rel.Sym;
Rui Ueyamab0210e832016-01-26 00:24:57 +0000326
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000327 if (Config->Rela)
Rui Ueyama614be592016-03-13 05:23:40 +0000328 P->r_addend = Rel.UseSymVA ? Sym->getVA<ELFT>(Rel.Addend) : Rel.Addend;
Rui Ueyamaa2b1f452016-02-17 06:08:42 +0000329 P->r_offset = Rel.getOffset();
Rafael Espindolade9857e2016-02-04 21:33:05 +0000330 uint32_t SymIdx = (!Rel.UseSymVA && Sym) ? Sym->DynsymIndex : 0;
331 P->setSymbolAndType(SymIdx, Rel.Type, Config->Mips64EL);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000332 }
333}
334
George Rimar77b77792015-11-25 22:15:01 +0000335template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
Rui Ueyama5a0b2f72016-02-05 19:13:18 +0000336 return this->Header.sh_entsize * Relocs.size();
George Rimar77b77792015-11-25 22:15:01 +0000337}
338
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000339template <class ELFT> void RelocationSection<ELFT>::finalize() {
George Rimara07ff662015-12-21 10:12:06 +0000340 this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
341 : Out<ELFT>::DynSymTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000342 this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
343}
344
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000345template <class ELFT>
346InterpSection<ELFT>::InterpSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000347 : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000348 this->Header.sh_size = Config->DynamicLinker.size() + 1;
349 this->Header.sh_addralign = 1;
350}
351
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000352template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama1e720b92016-03-13 06:50:34 +0000353 StringRef S = Config->DynamicLinker;
354 memcpy(Buf, S.data(), S.size());
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000355}
356
Rafael Espindola35c6af32015-09-25 17:19:10 +0000357template <class ELFT>
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000358HashTableSection<ELFT>::HashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000359 : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
Rafael Espindola35c6af32015-09-25 17:19:10 +0000360 this->Header.sh_entsize = sizeof(Elf_Word);
361 this->Header.sh_addralign = sizeof(Elf_Word);
362}
363
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000364static uint32_t hashSysv(StringRef Name) {
Rui Ueyama5f1eee1a2015-10-15 21:27:17 +0000365 uint32_t H = 0;
366 for (char C : Name) {
367 H = (H << 4) + C;
368 uint32_t G = H & 0xf0000000;
369 if (G)
370 H ^= G >> 24;
371 H &= ~G;
372 }
373 return H;
374}
375
Rui Ueyama0db335f2015-10-07 16:58:54 +0000376template <class ELFT> void HashTableSection<ELFT>::finalize() {
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000377 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000378
George Rimare9e1d322016-02-18 15:17:01 +0000379 unsigned NumEntries = 2; // nbucket and nchain.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000380 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
Rui Ueyama0db335f2015-10-07 16:58:54 +0000381
382 // Create as many buckets as there are symbols.
383 // FIXME: This is simplistic. We can try to optimize it, but implementing
384 // support for SHT_GNU_HASH is probably even more profitable.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000385 NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000386 this->Header.sh_size = NumEntries * sizeof(Elf_Word);
387}
388
389template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000390 unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
Rui Ueyama0db335f2015-10-07 16:58:54 +0000391 auto *P = reinterpret_cast<Elf_Word *>(Buf);
392 *P++ = NumSymbols; // nbucket
393 *P++ = NumSymbols; // nchain
394
395 Elf_Word *Buckets = P;
396 Elf_Word *Chains = P + NumSymbols;
397
Rafael Espindolae2c24612016-01-29 01:24:25 +0000398 for (const std::pair<SymbolBody *, unsigned> &P :
399 Out<ELFT>::DynSymTab->getSymbols()) {
400 SymbolBody *Body = P.first;
Igor Kudrinab665fc2015-10-20 21:47:58 +0000401 StringRef Name = Body->getName();
Rui Ueyama572a6f72016-01-29 01:49:33 +0000402 unsigned I = Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000403 uint32_t Hash = hashSysv(Name) % NumSymbols;
Rui Ueyama0db335f2015-10-07 16:58:54 +0000404 Chains[I] = Buckets[Hash];
405 Buckets[Hash] = I;
406 }
407}
408
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000409static uint32_t hashGnu(StringRef Name) {
410 uint32_t H = 5381;
411 for (uint8_t C : Name)
412 H = (H << 5) + H + C;
413 return H;
414}
415
416template <class ELFT>
417GnuHashTableSection<ELFT>::GnuHashTableSection()
Rui Ueyamacf07a312016-01-06 22:53:58 +0000418 : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000419 this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000420 this->Header.sh_addralign = sizeof(uintX_t);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000421}
422
423template <class ELFT>
424unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
425 if (!NumHashed)
426 return 0;
427
428 // These values are prime numbers which are not greater than 2^(N-1) + 1.
429 // In result, for any particular NumHashed we return a prime number
430 // which is not greater than NumHashed.
431 static const unsigned Primes[] = {
432 1, 1, 3, 3, 7, 13, 31, 61, 127, 251,
433 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
434
435 return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
436 array_lengthof(Primes) - 1)];
437}
438
439// Bloom filter estimation: at least 8 bits for each hashed symbol.
440// GNU Hash table requirement: it should be a power of 2,
441// the minimum value is 1, even for an empty table.
442// Expected results for a 32-bit target:
443// calcMaskWords(0..4) = 1
444// calcMaskWords(5..8) = 2
445// calcMaskWords(9..16) = 4
446// For a 64-bit target:
447// calcMaskWords(0..8) = 1
448// calcMaskWords(9..16) = 2
449// calcMaskWords(17..32) = 4
450template <class ELFT>
451unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
452 if (!NumHashed)
453 return 1;
454 return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
455}
456
457template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000458 unsigned NumHashed = Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000459 NBuckets = calcNBuckets(NumHashed);
460 MaskWords = calcMaskWords(NumHashed);
461 // Second hash shift estimation: just predefined values.
462 Shift2 = ELFT::Is64Bits ? 6 : 5;
463
464 this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
465 this->Header.sh_size = sizeof(Elf_Word) * 4 // Header
466 + sizeof(Elf_Off) * MaskWords // Bloom Filter
467 + sizeof(Elf_Word) * NBuckets // Hash Buckets
468 + sizeof(Elf_Word) * NumHashed; // Hash Values
469}
470
471template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
472 writeHeader(Buf);
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000473 if (Symbols.empty())
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000474 return;
475 writeBloomFilter(Buf);
476 writeHashTable(Buf);
477}
478
479template <class ELFT>
480void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
481 auto *P = reinterpret_cast<Elf_Word *>(Buf);
482 *P++ = NBuckets;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000483 *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000484 *P++ = MaskWords;
485 *P++ = Shift2;
486 Buf = reinterpret_cast<uint8_t *>(P);
487}
488
489template <class ELFT>
490void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
491 unsigned C = sizeof(Elf_Off) * 8;
492
493 auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
Rui Ueyama861c7312016-02-17 05:40:03 +0000494 for (const SymbolData &Sym : Symbols) {
495 size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
496 uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
497 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000498 Masks[Pos] |= V;
499 }
500 Buf += sizeof(Elf_Off) * MaskWords;
501}
502
503template <class ELFT>
504void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
505 Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
506 Elf_Word *Values = Buckets + NBuckets;
507
508 int PrevBucket = -1;
509 int I = 0;
Rui Ueyama861c7312016-02-17 05:40:03 +0000510 for (const SymbolData &Sym : Symbols) {
511 int Bucket = Sym.Hash % NBuckets;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000512 assert(PrevBucket <= Bucket);
513 if (Bucket != PrevBucket) {
Rui Ueyama861c7312016-02-17 05:40:03 +0000514 Buckets[Bucket] = Sym.Body->DynsymIndex;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000515 PrevBucket = Bucket;
516 if (I > 0)
517 Values[I - 1] |= 1;
518 }
Rui Ueyama861c7312016-02-17 05:40:03 +0000519 Values[I] = Sym.Hash & ~1;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000520 ++I;
521 }
522 if (I > 0)
523 Values[I - 1] |= 1;
524}
525
Rafael Espindola31f88882015-11-02 14:33:11 +0000526static bool includeInGnuHashTable(SymbolBody *B) {
Rui Ueyamac112c1b2016-01-29 02:17:01 +0000527 // Assume that includeInDynsym() is already checked.
Rafael Espindola31f88882015-11-02 14:33:11 +0000528 return !B->isUndefined();
529}
530
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000531// Add symbols to this symbol hash table. Note that this function
532// destructively sort a given vector -- which is needed because
533// GNU-style hash table places some sorting requirements.
Rafael Espindola35c6af32015-09-25 17:19:10 +0000534template <class ELFT>
Rafael Espindolae2c24612016-01-29 01:24:25 +0000535void GnuHashTableSection<ELFT>::addSymbols(
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000536 std::vector<std::pair<SymbolBody *, size_t>> &V) {
537 auto Mid = std::stable_partition(V.begin(), V.end(),
538 [](std::pair<SymbolBody *, size_t> &P) {
539 return !includeInGnuHashTable(P.first);
540 });
541 if (Mid == V.end())
Igor Kudrinf1d60292015-10-28 07:05:56 +0000542 return;
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000543 for (auto I = Mid, E = V.end(); I != E; ++I) {
544 SymbolBody *B = I->first;
545 size_t StrOff = I->second;
546 Symbols.push_back({B, StrOff, hashGnu(B->getName())});
547 }
Igor Kudrinf1d60292015-10-28 07:05:56 +0000548
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000549 unsigned NBuckets = calcNBuckets(Symbols.size());
550 std::stable_sort(Symbols.begin(), Symbols.end(),
Rui Ueyama861c7312016-02-17 05:40:03 +0000551 [&](const SymbolData &L, const SymbolData &R) {
Igor Kudrinf1d60292015-10-28 07:05:56 +0000552 return L.Hash % NBuckets < R.Hash % NBuckets;
553 });
554
Rui Ueyama91c0a5d2016-02-17 05:40:01 +0000555 V.erase(Mid, V.end());
Rui Ueyama861c7312016-02-17 05:40:03 +0000556 for (const SymbolData &Sym : Symbols)
557 V.push_back({Sym.Body, Sym.STName});
Igor Kudrinf1d60292015-10-28 07:05:56 +0000558}
559
560template <class ELFT>
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000561DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000562 : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE),
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000563 SymTab(SymTab) {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000564 Elf_Shdr &Header = this->Header;
Rui Ueyama5e378dd2016-01-29 22:18:57 +0000565 Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +0000566 Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
Igor Kudrin304860a2015-11-12 04:39:49 +0000567
568 // .dynamic section is not writable on MIPS.
569 // See "Special Section" in Chapter 4 in the following document:
570 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
571 if (Config->EMachine == EM_MIPS)
Rui Ueyamacf07a312016-01-06 22:53:58 +0000572 Header.sh_flags = SHF_ALLOC;
Rafael Espindola35c6af32015-09-25 17:19:10 +0000573}
574
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000575template <class ELFT> void DynamicSection<ELFT>::finalize() {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000576 if (this->Header.sh_size)
577 return; // Already finalized.
578
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000579 Elf_Shdr &Header = this->Header;
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000580 Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000581
Rafael Espindolae2c24612016-01-29 01:24:25 +0000582 auto Add = [=](Entry E) { Entries.push_back(E); };
583
584 // Add strings. We know that these are the last strings to be added to
Rafael Espindolade069362016-01-25 21:32:04 +0000585 // DynStrTab and doing this here allows this function to set DT_STRSZ.
586 if (!Config->RPath.empty())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000587 Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
588 Out<ELFT>::DynStrTab->addString(Config->RPath)});
Rafael Espindolade069362016-01-25 21:32:04 +0000589 for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
590 if (F->isNeeded())
Rafael Espindolae2c24612016-01-29 01:24:25 +0000591 Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
592 if (!Config->SoName.empty())
593 Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
594
Rafael Espindolade069362016-01-25 21:32:04 +0000595 Out<ELFT>::DynStrTab->finalize();
596
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000597 if (Out<ELFT>::RelaDyn->hasRelocs()) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000598 bool IsRela = Config->Rela;
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000599 Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
600 Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
601 Add({IsRela ? DT_RELAENT : DT_RELENT,
602 uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000603 }
George Rimar648a2c32015-10-20 08:54:27 +0000604 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000605 Add({DT_JMPREL, Out<ELFT>::RelaPlt});
606 Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
607 Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
608 Out<ELFT>::GotPlt});
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000609 Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
George Rimar648a2c32015-10-20 08:54:27 +0000610 }
611
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000612 Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
613 Add({DT_SYMENT, sizeof(Elf_Sym)});
614 Add({DT_STRTAB, Out<ELFT>::DynStrTab});
615 Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000616 if (Out<ELFT>::GnuHashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000617 Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000618 if (Out<ELFT>::HashTab)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000619 Add({DT_HASH, Out<ELFT>::HashTab});
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000620
Rafael Espindolade069362016-01-25 21:32:04 +0000621 if (PreInitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000622 Add({DT_PREINIT_ARRAY, PreInitArraySec});
623 Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000624 }
625 if (InitArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000626 Add({DT_INIT_ARRAY, InitArraySec});
627 Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
Rafael Espindolade069362016-01-25 21:32:04 +0000628 }
629 if (FiniArraySec) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000630 Add({DT_FINI_ARRAY, FiniArraySec});
631 Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
Rui Ueyama7de3f372015-10-01 19:36:04 +0000632 }
633
Rui Ueyama304d1352016-01-25 21:47:25 +0000634 if (SymbolBody *B = SymTab.find(Config->Init))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000635 Add({DT_INIT, B});
Rui Ueyama304d1352016-01-25 21:47:25 +0000636 if (SymbolBody *B = SymTab.find(Config->Fini))
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000637 Add({DT_FINI, B});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000638
Rafael Espindolade069362016-01-25 21:32:04 +0000639 uint32_t DtFlags = 0;
640 uint32_t DtFlags1 = 0;
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000641 if (Config->Bsymbolic)
642 DtFlags |= DF_SYMBOLIC;
643 if (Config->ZNodelete)
644 DtFlags1 |= DF_1_NODELETE;
645 if (Config->ZNow) {
646 DtFlags |= DF_BIND_NOW;
647 DtFlags1 |= DF_1_NOW;
648 }
649 if (Config->ZOrigin) {
650 DtFlags |= DF_ORIGIN;
651 DtFlags1 |= DF_1_ORIGIN;
652 }
653
654 if (DtFlags)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000655 Add({DT_FLAGS, DtFlags});
Rui Ueyamac96d0dd2015-10-21 17:47:10 +0000656 if (DtFlags1)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000657 Add({DT_FLAGS_1, DtFlags1});
Igor Kudrin304860a2015-11-12 04:39:49 +0000658
Ed Mastef5d3cf62016-01-06 15:52:27 +0000659 if (!Config->Entry.empty())
Rafael Espindolacc3ae412016-01-26 01:30:07 +0000660 Add({DT_DEBUG, (uint64_t)0});
Ed Mastef5d3cf62016-01-06 15:52:27 +0000661
Igor Kudrin304860a2015-11-12 04:39:49 +0000662 if (Config->EMachine == EM_MIPS) {
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000663 Add({DT_MIPS_RLD_VERSION, 1});
664 Add({DT_MIPS_FLAGS, RHF_NOTPOT});
665 Add({DT_MIPS_BASE_ADDRESS, (uintX_t)Target->getVAStart()});
666 Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
667 Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
Rafael Espindolade069362016-01-25 21:32:04 +0000668 if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
Rui Ueyama572a6f72016-01-29 01:49:33 +0000669 Add({DT_MIPS_GOTSYM, B->DynsymIndex});
Rafael Espindolade069362016-01-25 21:32:04 +0000670 else
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000671 Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
672 Add({DT_PLTGOT, Out<ELFT>::Got});
Igor Kudrin304860a2015-11-12 04:39:49 +0000673 if (Out<ELFT>::MipsRldMap)
Rui Ueyamaac9fb452016-01-25 23:38:34 +0000674 Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
Igor Kudrin304860a2015-11-12 04:39:49 +0000675 }
676
Rafael Espindolade069362016-01-25 21:32:04 +0000677 // +1 for DT_NULL
678 Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000679}
680
681template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000682 auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
683
Rafael Espindolade069362016-01-25 21:32:04 +0000684 for (const Entry &E : Entries) {
685 P->d_tag = E.Tag;
686 switch (E.Kind) {
687 case Entry::SecAddr:
688 P->d_un.d_ptr = E.OutSec->getVA();
689 break;
690 case Entry::SymAddr:
Rui Ueyamab5a69702016-02-01 21:00:35 +0000691 P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
Rafael Espindolade069362016-01-25 21:32:04 +0000692 break;
693 case Entry::PlainInt:
694 P->d_un.d_val = E.Val;
695 break;
696 }
Rui Ueyama8c205d52015-10-02 01:33:31 +0000697 ++P;
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000698 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000699}
700
701template <class ELFT>
George Rimarf6bc65a2016-01-15 13:34:52 +0000702EhFrameHeader<ELFT>::EhFrameHeader()
703 : OutputSectionBase<ELFT>(".eh_frame_hdr", llvm::ELF::SHT_PROGBITS,
704 SHF_ALLOC) {
705 // It's a 4 bytes of header + pointer to the contents of the .eh_frame section
706 // + the number of FDE pointers in the table.
707 this->Header.sh_size = 12;
708}
709
710// We have to get PC values of FDEs. They depend on relocations
711// which are target specific, so we run this code after performing
712// all relocations. We read the values from ouput buffer according to the
713// encoding given for FDEs. Return value is an offset to the initial PC value
714// for the FDE.
715template <class ELFT>
716typename EhFrameHeader<ELFT>::uintX_t
717EhFrameHeader<ELFT>::getFdePc(uintX_t EhVA, const FdeData &F) {
718 const endianness E = ELFT::TargetEndianness;
Simon Atanasyanea423e22016-03-02 05:38:42 +0000719 uint8_t Size = F.Enc & 0x7;
720 if (Size == DW_EH_PE_absptr)
721 Size = sizeof(uintX_t) == 8 ? DW_EH_PE_udata8 : DW_EH_PE_udata4;
722 uint64_t PC;
723 switch (Size) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000724 case DW_EH_PE_udata2:
Simon Atanasyanea423e22016-03-02 05:38:42 +0000725 PC = read16<E>(F.PCRel);
726 break;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000727 case DW_EH_PE_udata4:
Simon Atanasyanea423e22016-03-02 05:38:42 +0000728 PC = read32<E>(F.PCRel);
729 break;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000730 case DW_EH_PE_udata8:
Simon Atanasyanea423e22016-03-02 05:38:42 +0000731 PC = read64<E>(F.PCRel);
732 break;
733 default:
George Rimar57610422016-03-11 14:43:02 +0000734 fatal("unknown FDE size encoding");
George Rimarf6bc65a2016-01-15 13:34:52 +0000735 }
Simon Atanasyanea423e22016-03-02 05:38:42 +0000736 switch (F.Enc & 0x70) {
737 case DW_EH_PE_absptr:
738 return PC;
739 case DW_EH_PE_pcrel:
740 return PC + EhVA + F.Off + 8;
741 default:
George Rimar57610422016-03-11 14:43:02 +0000742 fatal("unknown FDE size relative encoding");
Simon Atanasyanea423e22016-03-02 05:38:42 +0000743 }
George Rimarf6bc65a2016-01-15 13:34:52 +0000744}
745
746template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
747 const endianness E = ELFT::TargetEndianness;
748
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000749 const uint8_t Header[] = {1, DW_EH_PE_pcrel | DW_EH_PE_sdata4,
750 DW_EH_PE_udata4,
751 DW_EH_PE_datarel | DW_EH_PE_sdata4};
George Rimarf6bc65a2016-01-15 13:34:52 +0000752 memcpy(Buf, Header, sizeof(Header));
753
754 uintX_t EhVA = Sec->getVA();
755 uintX_t VA = this->getVA();
756 uintX_t EhOff = EhVA - VA - 4;
757 write32<E>(Buf + 4, EhOff);
758 write32<E>(Buf + 8, this->FdeList.size());
759 Buf += 12;
760
761 // InitialPC -> Offset in .eh_frame, sorted by InitialPC.
762 std::map<uintX_t, size_t> PcToOffset;
763 for (const FdeData &F : FdeList)
764 PcToOffset[getFdePc(EhVA, F)] = F.Off;
765
766 for (auto &I : PcToOffset) {
767 // The first four bytes are an offset to the initial PC value for the FDE.
768 write32<E>(Buf, I.first - VA);
769 // The last four bytes are an offset to the FDE data itself.
770 write32<E>(Buf + 4, EhVA + I.second - VA);
771 Buf += 8;
772 }
773}
774
775template <class ELFT>
776void EhFrameHeader<ELFT>::assignEhFrame(EHOutputSection<ELFT> *Sec) {
George Rimar45ca88d2016-01-25 19:27:50 +0000777 assert((!this->Sec || this->Sec == Sec) &&
778 "multiple .eh_frame sections not supported for .eh_frame_hdr");
George Rimarf6bc65a2016-01-15 13:34:52 +0000779 Live = Config->EhFrameHdr;
780 this->Sec = Sec;
781}
782
783template <class ELFT>
784void EhFrameHeader<ELFT>::addFde(uint8_t Enc, size_t Off, uint8_t *PCRel) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000785 if (Live && (Enc & 0xF0) == DW_EH_PE_datarel)
Rui Ueyama64cfffd2016-01-28 18:40:06 +0000786 fatal("DW_EH_PE_datarel encoding unsupported for FDEs by .eh_frame_hdr");
George Rimarf6bc65a2016-01-15 13:34:52 +0000787 FdeList.push_back(FdeData{Enc, Off, PCRel});
788}
789
790template <class ELFT> void EhFrameHeader<ELFT>::reserveFde() {
791 // Each FDE entry is 8 bytes long:
792 // The first four bytes are an offset to the initial PC value for the FDE. The
793 // last four byte are an offset to the FDE data itself.
794 this->Header.sh_size += 8;
795}
796
797template <class ELFT>
George Rimar58941ee2016-02-25 08:23:37 +0000798OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
799 : OutputSectionBase<ELFT>(Name, Type, Flags) {
800 if (Type == SHT_RELA)
801 this->Header.sh_entsize = sizeof(Elf_Rela);
802 else if (Type == SHT_REL)
803 this->Header.sh_entsize = sizeof(Elf_Rel);
804}
805
806template <class ELFT> void OutputSection<ELFT>::finalize() {
807 uint32_t Type = this->Header.sh_type;
808 if (Type != SHT_RELA && Type != SHT_REL)
809 return;
810 this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
811 // sh_info for SHT_REL[A] sections should contain the section header index of
812 // the section to which the relocation applies.
813 InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
814 this->Header.sh_info = S->OutSec->SectionIndex;
815}
Rafael Espindola35c6af32015-09-25 17:19:10 +0000816
817template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +0000818void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama0b289522016-02-25 18:43:51 +0000819 assert(C->Live);
Rui Ueyama40845e62015-12-26 05:51:07 +0000820 auto *S = cast<InputSection<ELFT>>(C);
821 Sections.push_back(S);
822 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +0000823 this->updateAlign(S->Align);
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000824}
825
Rui Ueyamac4185702016-02-10 23:20:42 +0000826// If an input string is in the form of "foo.N" where N is a number,
827// return N. Otherwise, returns 65536, which is one greater than the
828// lowest priority.
829static int getPriority(StringRef S) {
830 size_t Pos = S.rfind('.');
831 if (Pos == StringRef::npos)
832 return 65536;
833 int V;
834 if (S.substr(Pos + 1).getAsInteger(10, V))
835 return 65536;
836 return V;
837}
838
Rui Ueyama5af83682016-02-11 23:41:38 +0000839// This function is called after we sort input sections
Simon Atanasyan13f6da12016-03-31 21:26:23 +0000840// and scan relocations to setup sections' offsets.
841template <class ELFT> void OutputSection<ELFT>::assignOffsets() {
Peter Collingbourne4cdade62016-04-04 22:29:24 +0000842 uintX_t Off = this->Header.sh_size;
Rui Ueyama5af83682016-02-11 23:41:38 +0000843 for (InputSection<ELFT> *S : Sections) {
Rui Ueyama5ac58912016-02-24 00:38:18 +0000844 Off = alignTo(Off, S->Align);
Rui Ueyama5af83682016-02-11 23:41:38 +0000845 S->OutSecOff = Off;
846 Off += S->getSize();
847 }
848 this->Header.sh_size = Off;
849}
850
Rui Ueyamac4185702016-02-10 23:20:42 +0000851// Sorts input sections by section name suffixes, so that .foo.N comes
852// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
Rui Ueyama5af83682016-02-11 23:41:38 +0000853// We want to keep the original order if the priorities are the same
854// because the compiler keeps the original initialization order in a
855// translation unit and we need to respect that.
Rui Ueyamac4185702016-02-10 23:20:42 +0000856// For more detail, read the section of the GCC's manual about init_priority.
Rui Ueyama5af83682016-02-11 23:41:38 +0000857template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
Rui Ueyamac4185702016-02-10 23:20:42 +0000858 // Sort sections by priority.
859 typedef std::pair<int, InputSection<ELFT> *> Pair;
Rui Ueyama704da022016-02-10 23:43:16 +0000860 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
861
Rui Ueyamac4185702016-02-10 23:20:42 +0000862 std::vector<Pair> V;
863 for (InputSection<ELFT> *S : Sections)
864 V.push_back({getPriority(S->getSectionName()), S});
Rui Ueyama704da022016-02-10 23:43:16 +0000865 std::stable_sort(V.begin(), V.end(), Comp);
Rui Ueyamac4185702016-02-10 23:20:42 +0000866 Sections.clear();
867 for (Pair &P : V)
868 Sections.push_back(P.second);
Rui Ueyama5af83682016-02-11 23:41:38 +0000869}
Rui Ueyamac4185702016-02-10 23:20:42 +0000870
Rui Ueyama5af83682016-02-11 23:41:38 +0000871// Returns true if S matches /Filename.?\.o$/.
872static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
873 if (!S.endswith(".o"))
874 return false;
875 S = S.drop_back(2);
876 if (S.endswith(Filename))
877 return true;
878 return !S.empty() && S.drop_back().endswith(Filename);
879}
880
881static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
882static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
883
884// .ctors and .dtors are sorted by this priority from highest to lowest.
885//
886// 1. The section was contained in crtbegin (crtbegin contains
887// some sentinel value in its .ctors and .dtors so that the runtime
888// can find the beginning of the sections.)
889//
890// 2. The section has an optional priority value in the form of ".ctors.N"
891// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
892// they are compared as string rather than number.
893//
894// 3. The section is just ".ctors" or ".dtors".
895//
896// 4. The section was contained in crtend, which contains an end marker.
897//
898// In an ideal world, we don't need this function because .init_array and
899// .ctors are duplicate features (and .init_array is newer.) However, there
900// are too many real-world use cases of .ctors, so we had no choice to
901// support that with this rather ad-hoc semantics.
902template <class ELFT>
903static bool compCtors(const InputSection<ELFT> *A,
904 const InputSection<ELFT> *B) {
905 bool BeginA = isCrtbegin(A->getFile()->getName());
906 bool BeginB = isCrtbegin(B->getFile()->getName());
907 if (BeginA != BeginB)
908 return BeginA;
909 bool EndA = isCrtend(A->getFile()->getName());
910 bool EndB = isCrtend(B->getFile()->getName());
911 if (EndA != EndB)
912 return EndB;
913 StringRef X = A->getSectionName();
914 StringRef Y = B->getSectionName();
915 assert(X.startswith(".ctors") || X.startswith(".dtors"));
916 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
917 X = X.substr(6);
918 Y = Y.substr(6);
Rui Ueyama24b794e2016-02-12 00:38:46 +0000919 if (X.empty() && Y.empty())
920 return false;
Rui Ueyama5af83682016-02-11 23:41:38 +0000921 return X < Y;
922}
923
924// Sorts input sections by the special rules for .ctors and .dtors.
925// Unfortunately, the rules are different from the one for .{init,fini}_array.
926// Read the comment above.
927template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
928 std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
Rui Ueyamac4185702016-02-10 23:20:42 +0000929}
930
George Rimare2ee72b2016-02-26 14:48:31 +0000931static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
932 size_t I = 0;
933 for (; I + A.size() < Size; I += A.size())
934 memcpy(Buf + I, A.data(), A.size());
935 memcpy(Buf + I, A.data(), Size - I);
936}
937
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000938template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
George Rimare2ee72b2016-02-26 14:48:31 +0000939 ArrayRef<uint8_t> Filler = Script->getFiller(this->Name);
940 if (!Filler.empty())
941 fill(Buf, this->getSize(), Filler);
Rui Ueyamae9809502016-03-11 04:23:12 +0000942 if (Config->Threads) {
943 parallel_for_each(Sections.begin(), Sections.end(),
944 [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
945 } else {
946 for (InputSection<ELFT> *C : Sections)
947 C->writeTo(Buf);
948 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000949}
950
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000951template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +0000952EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t Type,
953 uintX_t Flags)
George Rimarf6bc65a2016-01-15 13:34:52 +0000954 : OutputSectionBase<ELFT>(Name, Type, Flags) {
955 Out<ELFT>::EhFrameHdr->assignEhFrame(this);
956}
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000957
958template <class ELFT>
959EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *S, unsigned Index)
960 : S(S), Index(Index) {}
961
962template <class ELFT> StringRef EHRegion<ELFT>::data() const {
963 ArrayRef<uint8_t> SecData = S->getSectionData();
964 ArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets;
965 size_t Start = Offsets[Index].first;
966 size_t End =
967 Index == Offsets.size() - 1 ? SecData.size() : Offsets[Index + 1].first;
968 return StringRef((const char *)SecData.data() + Start, End - Start);
969}
970
971template <class ELFT>
972Cie<ELFT>::Cie(EHInputSection<ELFT> *S, unsigned Index)
973 : EHRegion<ELFT>(S, Index) {}
974
George Rimarf6bc65a2016-01-15 13:34:52 +0000975// Read a byte and advance D by one byte.
976static uint8_t readByte(ArrayRef<uint8_t> &D) {
977 if (D.empty())
George Rimar57610422016-03-11 14:43:02 +0000978 fatal("corrupted or unsupported CIE information");
George Rimarf6bc65a2016-01-15 13:34:52 +0000979 uint8_t B = D.front();
980 D = D.slice(1);
981 return B;
982}
983
984static void skipLeb128(ArrayRef<uint8_t> &D) {
985 while (!D.empty()) {
986 uint8_t Val = D.front();
987 D = D.slice(1);
988 if ((Val & 0x80) == 0)
989 return;
990 }
George Rimar57610422016-03-11 14:43:02 +0000991 fatal("corrupted or unsupported CIE information");
George Rimarf6bc65a2016-01-15 13:34:52 +0000992}
993
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000994template <class ELFT> static size_t getAugPSize(unsigned Enc) {
995 switch (Enc & 0x0f) {
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000996 case DW_EH_PE_absptr:
997 case DW_EH_PE_signed:
Rui Ueyama6448f8a2016-02-09 21:41:01 +0000998 return ELFT::Is64Bits ? 8 : 4;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +0000999 case DW_EH_PE_udata2:
1000 case DW_EH_PE_sdata2:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001001 return 2;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001002 case DW_EH_PE_udata4:
1003 case DW_EH_PE_sdata4:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001004 return 4;
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001005 case DW_EH_PE_udata8:
1006 case DW_EH_PE_sdata8:
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001007 return 8;
1008 }
George Rimar57610422016-03-11 14:43:02 +00001009 fatal("unknown FDE encoding");
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001010}
1011
1012template <class ELFT> static void skipAugP(ArrayRef<uint8_t> &D) {
1013 uint8_t Enc = readByte(D);
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001014 if ((Enc & 0xf0) == DW_EH_PE_aligned)
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001015 fatal("DW_EH_PE_aligned encoding is not supported");
1016 size_t Size = getAugPSize<ELFT>(Enc);
Rafael Espindola9e072d32016-02-09 22:47:34 +00001017 if (Size >= D.size())
George Rimar57610422016-03-11 14:43:02 +00001018 fatal("corrupted CIE");
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001019 D = D.slice(Size);
1020}
1021
George Rimarf6bc65a2016-01-15 13:34:52 +00001022template <class ELFT>
1023uint8_t EHOutputSection<ELFT>::getFdeEncoding(ArrayRef<uint8_t> D) {
Rui Ueyamabe748c22016-02-08 05:18:44 +00001024 if (D.size() < 8)
1025 fatal("CIE too small");
George Rimarf6bc65a2016-01-15 13:34:52 +00001026 D = D.slice(8);
1027
1028 uint8_t Version = readByte(D);
1029 if (Version != 1 && Version != 3)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001030 fatal("FDE version 1 or 3 expected, but got " + Twine((unsigned)Version));
George Rimarf6bc65a2016-01-15 13:34:52 +00001031
Saleem Abdulrasoolc0571e12016-02-15 03:45:18 +00001032 const unsigned char *AugEnd = std::find(D.begin() + 1, D.end(), '\0');
Rui Ueyamabe748c22016-02-08 05:18:44 +00001033 if (AugEnd == D.end())
George Rimar57610422016-03-11 14:43:02 +00001034 fatal("corrupted CIE");
Saleem Abdulrasoolc0571e12016-02-15 03:45:18 +00001035 StringRef Aug(reinterpret_cast<const char *>(D.begin()), AugEnd - D.begin());
Rui Ueyamabe748c22016-02-08 05:18:44 +00001036 D = D.slice(Aug.size() + 1);
George Rimarf6bc65a2016-01-15 13:34:52 +00001037
1038 // Code alignment factor should always be 1 for .eh_frame.
1039 if (readByte(D) != 1)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001040 fatal("CIE code alignment must be 1");
Rui Ueyamabe748c22016-02-08 05:18:44 +00001041
1042 // Skip data alignment factor.
George Rimarf6bc65a2016-01-15 13:34:52 +00001043 skipLeb128(D);
1044
1045 // Skip the return address register. In CIE version 1 this is a single
1046 // byte. In CIE version 3 this is an unsigned LEB128.
1047 if (Version == 1)
1048 readByte(D);
1049 else
1050 skipLeb128(D);
1051
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001052 // We only care about an 'R' value, but other records may precede an 'R'
1053 // record. Records are not in TLV (type-length-value) format, so we need
1054 // to teach the linker how to skip records for each type.
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001055 for (char C : Aug) {
1056 if (C == 'R')
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001057 return readByte(D);
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001058 if (C == 'z') {
1059 skipLeb128(D);
1060 continue;
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001061 }
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001062 if (C == 'P') {
1063 skipAugP<ELFT>(D);
1064 continue;
1065 }
Simon Atanasyanea423e22016-03-02 05:38:42 +00001066 if (C == 'L') {
1067 readByte(D);
Rui Ueyamad3bd97a2016-02-09 23:11:21 +00001068 continue;
Simon Atanasyanea423e22016-03-02 05:38:42 +00001069 }
George Rimar57610422016-03-11 14:43:02 +00001070 fatal("unknown .eh_frame augmentation string: " + Aug);
Rui Ueyama6448f8a2016-02-09 21:41:01 +00001071 }
Rui Ueyamadbcfedb2016-02-09 21:46:11 +00001072 return DW_EH_PE_absptr;
George Rimarf6bc65a2016-01-15 13:34:52 +00001073}
1074
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001075template <class ELFT>
Rui Ueyama9328b2c2016-03-14 23:16:09 +00001076static typename ELFT::uint readEntryLength(ArrayRef<uint8_t> D) {
Rui Ueyamac0c92602016-02-05 22:56:03 +00001077 const endianness E = ELFT::TargetEndianness;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001078 if (D.size() < 4)
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001079 fatal("CIE/FDE too small");
1080
1081 // First 4 bytes of CIE/FDE is the size of the record.
1082 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead.
1083 uint64_t V = read32<E>(D.data());
1084 if (V < UINT32_MAX) {
1085 uint64_t Len = V + 4;
1086 if (Len > D.size())
Rui Ueyamac0c92602016-02-05 22:56:03 +00001087 fatal("CIE/FIE ends past the end of the section");
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001088 return Len;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001089 }
1090
1091 if (D.size() < 12)
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001092 fatal("CIE/FDE too small");
1093 V = read64<E>(D.data() + 4);
1094 uint64_t Len = V + 12;
1095 if (Len < V || D.size() < Len)
Rui Ueyamac0c92602016-02-05 22:56:03 +00001096 fatal("CIE/FIE ends past the end of the section");
Rui Ueyama1b45cca2016-02-05 23:24:05 +00001097 return Len;
Rui Ueyamac0c92602016-02-05 22:56:03 +00001098}
1099
1100template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +00001101template <class RelTy>
1102void EHOutputSection<ELFT>::addSectionAux(EHInputSection<ELFT> *S,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +00001103 ArrayRef<RelTy> Rels) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001104 const endianness E = ELFT::TargetEndianness;
1105
1106 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +00001107 this->updateAlign(S->Align);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001108 Sections.push_back(S);
1109
1110 ArrayRef<uint8_t> SecData = S->getSectionData();
1111 ArrayRef<uint8_t> D = SecData;
1112 uintX_t Offset = 0;
1113 auto RelI = Rels.begin();
1114 auto RelE = Rels.end();
1115
George Rimar147747a2016-01-02 16:55:01 +00001116 DenseMap<unsigned, unsigned> OffsetToIndex;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001117 while (!D.empty()) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001118 unsigned Index = S->Offsets.size();
1119 S->Offsets.push_back(std::make_pair(Offset, -1));
1120
Rui Ueyamac0c92602016-02-05 22:56:03 +00001121 uintX_t Length = readEntryLength<ELFT>(D);
George Rimarf6bc65a2016-01-15 13:34:52 +00001122 // If CIE/FDE data length is zero then Length is 4, this
1123 // shall be considered a terminator and processing shall end.
1124 if (Length == 4)
1125 break;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001126 StringRef Entry((const char *)D.data(), Length);
1127
1128 while (RelI != RelE && RelI->r_offset < Offset)
1129 ++RelI;
1130 uintX_t NextOffset = Offset + Length;
1131 bool HasReloc = RelI != RelE && RelI->r_offset < NextOffset;
1132
1133 uint32_t ID = read32<E>(D.data() + 4);
1134 if (ID == 0) {
1135 // CIE
1136 Cie<ELFT> C(S, Index);
George Rimarf6bc65a2016-01-15 13:34:52 +00001137 if (Config->EhFrameHdr)
1138 C.FdeEncoding = getFdeEncoding(D);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001139
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001140 SymbolBody *Personality = nullptr;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001141 if (HasReloc) {
1142 uint32_t SymIndex = RelI->getSymbol(Config->Mips64EL);
Rafael Espindola67d72c02016-03-11 12:06:30 +00001143 Personality = &S->getFile()->getSymbolBody(SymIndex).repl();
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001144 }
1145
Rafael Espindola156ed8d2016-02-10 13:19:32 +00001146 std::pair<StringRef, SymbolBody *> CieInfo(Entry, Personality);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001147 auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size()));
George Rimar147747a2016-01-02 16:55:01 +00001148 if (P.second) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001149 Cies.push_back(C);
Rui Ueyama489a8062016-01-14 20:53:50 +00001150 this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
George Rimar147747a2016-01-02 16:55:01 +00001151 }
1152 OffsetToIndex[Offset] = P.first->second;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001153 } else {
1154 if (!HasReloc)
Rui Ueyama64cfffd2016-01-28 18:40:06 +00001155 fatal("FDE doesn't reference another section");
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001156 InputSectionBase<ELFT> *Target = S->getRelocTarget(*RelI);
Rafael Espindola1f5b70f2016-03-11 14:21:37 +00001157 if (Target && Target->Live) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001158 uint32_t CieOffset = Offset + 4 - ID;
George Rimar147747a2016-01-02 16:55:01 +00001159 auto I = OffsetToIndex.find(CieOffset);
1160 if (I == OffsetToIndex.end())
George Rimar777f9632016-03-12 08:31:34 +00001161 fatal("invalid CIE reference");
George Rimar147747a2016-01-02 16:55:01 +00001162 Cies[I->second].Fdes.push_back(EHRegion<ELFT>(S, Index));
George Rimarf6bc65a2016-01-15 13:34:52 +00001163 Out<ELFT>::EhFrameHdr->reserveFde();
Rui Ueyama489a8062016-01-14 20:53:50 +00001164 this->Header.sh_size += alignTo(Length, sizeof(uintX_t));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001165 }
1166 }
1167
1168 Offset = NextOffset;
1169 D = D.slice(Length);
1170 }
1171}
1172
1173template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001174void EHOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1175 auto *S = cast<EHInputSection<ELFT>>(C);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001176 const Elf_Shdr *RelSec = S->RelocSection;
Rui Ueyama0de86c12016-01-27 22:23:44 +00001177 if (!RelSec) {
Rafael Espindola0f7ccc32016-04-05 14:47:28 +00001178 addSectionAux(S, makeArrayRef<Elf_Rela>(nullptr, nullptr));
Rui Ueyama0de86c12016-01-27 22:23:44 +00001179 return;
1180 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001181 ELFFile<ELFT> &Obj = S->getFile()->getObj();
1182 if (RelSec->sh_type == SHT_RELA)
Rui Ueyama0de86c12016-01-27 22:23:44 +00001183 addSectionAux(S, Obj.relas(RelSec));
1184 else
1185 addSectionAux(S, Obj.rels(RelSec));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001186}
1187
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001188template <class ELFT>
Rui Ueyama9328b2c2016-03-14 23:16:09 +00001189static typename ELFT::uint writeAlignedCieOrFde(StringRef Data, uint8_t *Buf) {
1190 typedef typename ELFT::uint uintX_t;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001191 const endianness E = ELFT::TargetEndianness;
Rui Ueyama489a8062016-01-14 20:53:50 +00001192 uint64_t Len = alignTo(Data.size(), sizeof(uintX_t));
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001193 write32<E>(Buf, Len - 4);
1194 memcpy(Buf + 4, Data.data() + 4, Data.size() - 4);
1195 return Len;
1196}
1197
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001198template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1199 const endianness E = ELFT::TargetEndianness;
1200 size_t Offset = 0;
1201 for (const Cie<ELFT> &C : Cies) {
1202 size_t CieOffset = Offset;
1203
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001204 uintX_t CIELen = writeAlignedCieOrFde<ELFT>(C.data(), Buf + Offset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001205 C.S->Offsets[C.Index].second = Offset;
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001206 Offset += CIELen;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001207
1208 for (const EHRegion<ELFT> &F : C.Fdes) {
Rafael Espindola91bd48a2015-12-24 20:44:06 +00001209 uintX_t Len = writeAlignedCieOrFde<ELFT>(F.data(), Buf + Offset);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001210 write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001211 F.S->Offsets[F.Index].second = Offset;
George Rimarf6bc65a2016-01-15 13:34:52 +00001212 Out<ELFT>::EhFrameHdr->addFde(C.FdeEncoding, Offset, Buf + Offset + 8);
George Rimare72beba2015-12-21 09:38:59 +00001213 Offset += Len;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001214 }
1215 }
1216
Rafael Espindola69082f02016-03-18 18:11:26 +00001217 for (EHInputSection<ELFT> *S : Sections) {
1218 const Elf_Shdr *RelSec = S->RelocSection;
1219 if (!RelSec)
1220 continue;
1221 ELFFile<ELFT> &EObj = S->getFile()->getObj();
1222 if (RelSec->sh_type == SHT_RELA)
1223 S->relocate(Buf, nullptr, EObj.relas(RelSec));
1224 else
1225 S->relocate(Buf, nullptr, EObj.rels(RelSec));
1226 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001227}
1228
1229template <class ELFT>
Rui Ueyamad97e5c42016-01-07 18:33:11 +00001230MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001231 uintX_t Flags, uintX_t Alignment)
1232 : OutputSectionBase<ELFT>(Name, Type, Flags),
1233 Builder(llvm::StringTableBuilder::RAW, Alignment) {}
Rafael Espindolac159c962015-10-19 21:00:02 +00001234
1235template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001236 if (shouldTailMerge()) {
1237 StringRef Data = Builder.data();
Rafael Espindolac159c962015-10-19 21:00:02 +00001238 memcpy(Buf, Data.data(), Data.size());
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001239 return;
Rafael Espindolac159c962015-10-19 21:00:02 +00001240 }
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001241 for (const std::pair<StringRef, size_t> &P : Builder.getMap()) {
1242 StringRef Data = P.first;
1243 memcpy(Buf + P.second, Data.data(), Data.size());
1244 }
1245}
1246
1247static size_t findNull(StringRef S, size_t EntSize) {
1248 // Optimize the common case.
1249 if (EntSize == 1)
1250 return S.find(0);
1251
1252 for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1253 const char *B = S.begin() + I;
1254 if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1255 return I;
1256 }
1257 return StringRef::npos;
Rafael Espindolac159c962015-10-19 21:00:02 +00001258}
1259
1260template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001261void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1262 auto *S = cast<MergeInputSection<ELFT>>(C);
Rafael Espindolac159c962015-10-19 21:00:02 +00001263 S->OutSec = this;
Rui Ueyama5ac58912016-02-24 00:38:18 +00001264 this->updateAlign(S->Align);
Rafael Espindolac159c962015-10-19 21:00:02 +00001265
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001266 ArrayRef<uint8_t> D = S->getSectionData();
George Rimarf940d592015-10-25 20:14:07 +00001267 StringRef Data((const char *)D.data(), D.size());
Rafael Espindolac159c962015-10-19 21:00:02 +00001268 uintX_t EntSize = S->getSectionHdr()->sh_entsize;
George Rimar0baa1d32016-03-18 09:28:39 +00001269 this->Header.sh_entsize = EntSize;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001270
Rui Ueyamaead75fc2016-01-29 22:18:55 +00001271 // If this is of type string, the contents are null-terminated strings.
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001272 if (this->Header.sh_flags & SHF_STRINGS) {
Rui Ueyamaad87ff72016-01-06 02:52:24 +00001273 uintX_t Offset = 0;
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001274 while (!Data.empty()) {
1275 size_t End = findNull(Data, EntSize);
1276 if (End == StringRef::npos)
George Rimar777f9632016-03-12 08:31:34 +00001277 fatal("string is not null terminated");
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001278 StringRef Entry = Data.substr(0, End + EntSize);
George Rimar4b40ebc2015-11-13 13:44:59 +00001279 uintX_t OutputOffset = Builder.add(Entry);
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001280 if (shouldTailMerge())
1281 OutputOffset = -1;
1282 S->Offsets.push_back(std::make_pair(Offset, OutputOffset));
1283 uintX_t Size = End + EntSize;
1284 Data = Data.substr(Size);
1285 Offset += Size;
1286 }
Rui Ueyamaead75fc2016-01-29 22:18:55 +00001287 return;
1288 }
1289
1290 // If this is not of type string, every entry has the same size.
1291 for (unsigned I = 0, N = Data.size(); I != N; I += EntSize) {
1292 StringRef Entry = Data.substr(I, EntSize);
1293 size_t OutputOffset = Builder.add(Entry);
1294 S->Offsets.push_back(std::make_pair(I, OutputOffset));
Rafael Espindolac159c962015-10-19 21:00:02 +00001295 }
Rafael Espindolac159c962015-10-19 21:00:02 +00001296}
1297
1298template <class ELFT>
Rafael Espindolaf82ed2a2015-10-24 22:51:01 +00001299unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1300 return Builder.getOffset(Val);
1301}
1302
1303template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1304 return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1305}
1306
1307template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1308 if (shouldTailMerge())
1309 Builder.finalize();
1310 this->Header.sh_size = Builder.getSize();
Rafael Espindolac159c962015-10-19 21:00:02 +00001311}
1312
1313template <class ELFT>
George Rimar0f5ac9f2015-10-20 17:21:35 +00001314StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001315 : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1316 Dynamic ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindola35c6af32015-09-25 17:19:10 +00001317 Dynamic(Dynamic) {
1318 this->Header.sh_addralign = 1;
1319}
1320
Rafael Espindolae2c24612016-01-29 01:24:25 +00001321// Adds a string to the string table. If HashIt is true we hash and check for
1322// duplicates. It is optional because the name of global symbols are already
1323// uniqued and hashing them again has a big cost for a small value: uniquing
1324// them with some other string that happens to be the same.
1325template <class ELFT>
1326unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1327 if (HashIt) {
1328 auto R = StringMap.insert(std::make_pair(S, Size));
1329 if (!R.second)
1330 return R.first->second;
1331 }
1332 unsigned Ret = Size;
1333 Size += S.size() + 1;
Rui Ueyama76c00632016-01-07 02:35:32 +00001334 Strings.push_back(S);
Rafael Espindolae2c24612016-01-29 01:24:25 +00001335 return Ret;
Rui Ueyama76c00632016-01-07 02:35:32 +00001336}
1337
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001338template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rui Ueyama76c00632016-01-07 02:35:32 +00001339 // ELF string tables start with NUL byte, so advance the pointer by one.
1340 ++Buf;
1341 for (StringRef S : Strings) {
1342 memcpy(Buf, S.data(), S.size());
1343 Buf += S.size() + 1;
1344 }
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001345}
1346
Rafael Espindolad1cf4212015-10-05 16:25:43 +00001347template <class ELFT>
Rafael Espindola35c6af32015-09-25 17:19:10 +00001348SymbolTableSection<ELFT>::SymbolTableSection(
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001349 SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec)
Rui Ueyamacf07a312016-01-06 22:53:58 +00001350 : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1351 StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
Rui Ueyama6ffb42a2016-01-07 20:53:30 +00001352 StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001353 StrTabSec(StrTabSec), Table(Table) {
Rui Ueyamad1e92aa2016-01-07 18:20:02 +00001354 this->Header.sh_entsize = sizeof(Elf_Sym);
Rui Ueyama5e378dd2016-01-29 22:18:57 +00001355 this->Header.sh_addralign = sizeof(uintX_t);
Rafael Espindola35c6af32015-09-25 17:19:10 +00001356}
1357
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001358// Orders symbols according to their positions in the GOT,
1359// in compliance with MIPS ABI rules.
1360// See "Global Offset Table" in Chapter 5 in the following document
1361// for detailed description:
1362// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rafael Espindolae2c24612016-01-29 01:24:25 +00001363static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1364 const std::pair<SymbolBody *, unsigned> &R) {
Simon Atanasyand2980d32016-03-29 14:07:22 +00001365 // Sort entries related to non-local preemptible symbols by GOT indexes.
1366 // All other entries go to the first part of GOT in arbitrary order.
1367 bool LIsInLocalGot = !L.first->isInGot() || !L.first->isPreemptible();
1368 bool RIsInLocalGot = !R.first->isInGot() || !R.first->isPreemptible();
1369 if (LIsInLocalGot || RIsInLocalGot)
1370 return !RIsInLocalGot;
Rafael Espindolae2c24612016-01-29 01:24:25 +00001371 return L.first->GotIndex < R.first->GotIndex;
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001372}
1373
Rui Ueyama0db335f2015-10-07 16:58:54 +00001374template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
Igor Kudrin2169b1b2015-11-02 10:46:14 +00001375 if (this->Header.sh_size)
1376 return; // Already finalized.
1377
Rui Ueyama0db335f2015-10-07 16:58:54 +00001378 this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001379 this->Header.sh_link = StrTabSec.SectionIndex;
Rui Ueyama0db335f2015-10-07 16:58:54 +00001380 this->Header.sh_info = NumLocals + 1;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001381
George Rimar58941ee2016-02-25 08:23:37 +00001382 if (Config->Relocatable) {
1383 size_t I = NumLocals;
1384 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1385 P.first->DynsymIndex = ++I;
1386 return;
1387 }
1388
Igor Kudrinab665fc2015-10-20 21:47:58 +00001389 if (!StrTabSec.isDynamic()) {
1390 std::stable_sort(Symbols.begin(), Symbols.end(),
Rafael Espindolae2c24612016-01-29 01:24:25 +00001391 [](const std::pair<SymbolBody *, unsigned> &L,
1392 const std::pair<SymbolBody *, unsigned> &R) {
1393 return getSymbolBinding(L.first) == STB_LOCAL &&
1394 getSymbolBinding(R.first) != STB_LOCAL;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001395 });
1396 return;
1397 }
Igor Kudrinf1d60292015-10-28 07:05:56 +00001398 if (Out<ELFT>::GnuHashTab)
1399 // NB: It also sorts Symbols to meet the GNU hash table requirements.
1400 Out<ELFT>::GnuHashTab->addSymbols(Symbols);
Igor Kudrinf4cdfe882015-11-12 04:08:12 +00001401 else if (Config->EMachine == EM_MIPS)
1402 std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
Igor Kudrinab665fc2015-10-20 21:47:58 +00001403 size_t I = 0;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001404 for (const std::pair<SymbolBody *, size_t> &P : Symbols)
Rui Ueyama572a6f72016-01-29 01:49:33 +00001405 P.first->DynsymIndex = ++I;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001406}
1407
1408template <class ELFT>
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001409void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1410 Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
Rui Ueyama0db335f2015-10-07 16:58:54 +00001411}
1412
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001413template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001414 Buf += sizeof(Elf_Sym);
1415
1416 // All symbols with STB_LOCAL binding precede the weak and global symbols.
1417 // .dynsym only contains global symbols.
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001418 if (!Config->DiscardAll && !StrTabSec.isDynamic())
1419 writeLocalSymbols(Buf);
1420
1421 writeGlobalSymbols(Buf);
1422}
1423
1424template <class ELFT>
1425void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1426 // Iterate over all input object files to copy their local symbols
1427 // to the output symbol table pointed by Buf.
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001428 for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001429 for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1430 File->KeptLocalSyms) {
1431 const DefinedRegular<ELFT> &Body = *P.first;
1432 InputSectionBase<ELFT> *Section = Body.Section;
Rui Ueyamac55733e2015-09-30 00:54:29 +00001433 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001434
1435 if (!Section) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001436 ESym->st_shndx = SHN_ABS;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001437 ESym->st_value = Body.Value;
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001438 } else {
Rafael Espindolac159c962015-10-19 21:00:02 +00001439 const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1440 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001441 ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001442 }
Rafael Espindolae2c24612016-01-29 01:24:25 +00001443 ESym->st_name = P.second;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001444 ESym->st_size = Body.template getSize<ELFT>();
1445 ESym->setBindingAndType(Body.Binding, Body.Type);
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001446 Buf += sizeof(*ESym);
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001447 }
1448 }
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001449}
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001450
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001451template <class ELFT>
Igor Kudrinea6a8352015-10-19 08:01:51 +00001452void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
Rui Ueyama8ddfa812015-09-30 00:32:10 +00001453 // Write the internal symbol table contents to the output symbol table
1454 // pointed by Buf.
Igor Kudrinab665fc2015-10-20 21:47:58 +00001455 auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001456 for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
Rafael Espindolae2c24612016-01-29 01:24:25 +00001457 SymbolBody *Body = P.first;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001458 size_t StrOff = P.second;
Rui Ueyamac4aaed92015-10-22 18:49:53 +00001459
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001460 uint8_t Type = Body->Type;
1461 uintX_t Size = Body->getSize<ELFT>();
Rafael Espindola8614c562015-10-06 14:33:58 +00001462
Igor Kudrin853b88d2015-10-20 20:52:14 +00001463 ESym->setBindingAndType(getSymbolBinding(Body), Type);
Rafael Espindola8614c562015-10-06 14:33:58 +00001464 ESym->st_size = Size;
Rui Ueyamac2e863a2016-02-17 05:06:40 +00001465 ESym->st_name = StrOff;
Rui Ueyama8f2c4da2015-10-21 18:13:47 +00001466 ESym->setVisibility(Body->getVisibility());
Rui Ueyamab5a69702016-02-01 21:00:35 +00001467 ESym->st_value = Body->getVA<ELFT>();
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001468
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001469 if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
Rui Ueyama2317d0d2015-10-15 20:55:22 +00001470 ESym->st_shndx = OutSec->SectionIndex;
Rafael Espindola02ce26a2015-12-24 14:22:24 +00001471 else if (isa<DefinedRegular<ELFT>>(Body))
1472 ESym->st_shndx = SHN_ABS;
Simon Atanasyand040a582016-02-25 16:19:15 +00001473
1474 // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1475 // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1476 // distinguish such symbols and MIPS lazy-binding stubs.
1477 // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1478 if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1479 Body->NeedsCopyOrPltAddr)
Simon Atanasyanbea96982016-02-25 21:09:05 +00001480 ESym->st_other |= STO_MIPS_PLT;
Igor Kudrinab665fc2015-10-20 21:47:58 +00001481 ++ESym;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001482 }
1483}
1484
Igor Kudrin853b88d2015-10-20 20:52:14 +00001485template <class ELFT>
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001486const OutputSectionBase<ELFT> *
1487SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1488 switch (Sym->kind()) {
1489 case SymbolBody::DefinedSyntheticKind:
1490 return &cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1491 case SymbolBody::DefinedRegularKind: {
Rafael Espindola67d72c02016-03-11 12:06:30 +00001492 auto &D = cast<DefinedRegular<ELFT>>(Sym->repl());
1493 if (D.Section)
1494 return D.Section->OutSec;
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001495 break;
1496 }
1497 case SymbolBody::DefinedCommonKind:
1498 return Out<ELFT>::Bss;
1499 case SymbolBody::SharedKind:
1500 if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1501 return Out<ELFT>::Bss;
1502 break;
1503 case SymbolBody::UndefinedElfKind:
Rafael Espindolaf4765732016-04-06 13:22:41 +00001504 case SymbolBody::UndefinedBitcodeKind:
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001505 case SymbolBody::LazyKind:
1506 break;
1507 case SymbolBody::DefinedBitcodeKind:
Davide Italianof6523ae2016-03-29 02:20:10 +00001508 llvm_unreachable("should have been replaced");
Rui Ueyama874e7ae2016-02-17 04:56:44 +00001509 }
1510 return nullptr;
1511}
1512
1513template <class ELFT>
Igor Kudrin853b88d2015-10-20 20:52:14 +00001514uint8_t SymbolTableSection<ELFT>::getSymbolBinding(SymbolBody *Body) {
Rui Ueyama8f2c4da2015-10-21 18:13:47 +00001515 uint8_t Visibility = Body->getVisibility();
Igor Kudrin853b88d2015-10-20 20:52:14 +00001516 if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1517 return STB_LOCAL;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001518 return Body->Binding;
Igor Kudrin853b88d2015-10-20 20:52:14 +00001519}
1520
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001521template <class ELFT>
Rui Ueyama634ddf02016-03-11 20:51:53 +00001522BuildIdSection<ELFT>::BuildIdSection()
1523 : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC) {
1524 // 16 bytes for the note section header and 8 bytes for FNV1 hash.
1525 this->Header.sh_size = 24;
1526}
1527
1528template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1529 const endianness E = ELFT::TargetEndianness;
1530 write32<E>(Buf, 4); // Name size
1531 write32<E>(Buf + 4, sizeof(Hash)); // Content size
1532 write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1533 memcpy(Buf + 12, "GNU", 4); // Name string
1534 HashBuf = Buf + 16;
1535}
1536
1537template <class ELFT> void BuildIdSection<ELFT>::update(ArrayRef<uint8_t> Buf) {
1538 // 64-bit FNV1 hash
1539 const uint64_t Prime = 0x100000001b3;
1540 for (uint8_t B : Buf) {
1541 Hash *= Prime;
1542 Hash ^= B;
1543 }
1544}
1545
1546template <class ELFT> void BuildIdSection<ELFT>::writeBuildId() {
1547 const endianness E = ELFT::TargetEndianness;
1548 write64<E>(HashBuf, Hash);
1549}
1550
1551template <class ELFT>
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001552MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1553 : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1554 this->Header.sh_addralign = 4;
1555 this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1556 this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1557}
1558
1559template <class ELFT>
1560void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1561 auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
1562 R->ri_gp_value = getMipsGpAddr<ELFT>();
Rui Ueyama70eed362016-01-06 22:42:43 +00001563 R->ri_gprmask = GprMask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001564}
1565
1566template <class ELFT>
Rui Ueyama40845e62015-12-26 05:51:07 +00001567void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
Rui Ueyama70eed362016-01-06 22:42:43 +00001568 // Copy input object file's .reginfo gprmask to output.
Rui Ueyama40845e62015-12-26 05:51:07 +00001569 auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
Rui Ueyama70eed362016-01-06 22:42:43 +00001570 GprMask |= S->Reginfo->ri_gprmask;
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001571}
1572
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001573namespace lld {
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001574namespace elf {
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001575template class OutputSectionBase<ELF32LE>;
1576template class OutputSectionBase<ELF32BE>;
1577template class OutputSectionBase<ELF64LE>;
1578template class OutputSectionBase<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001579
George Rimarf6bc65a2016-01-15 13:34:52 +00001580template class EhFrameHeader<ELF32LE>;
1581template class EhFrameHeader<ELF32BE>;
1582template class EhFrameHeader<ELF64LE>;
1583template class EhFrameHeader<ELF64BE>;
1584
George Rimar648a2c32015-10-20 08:54:27 +00001585template class GotPltSection<ELF32LE>;
1586template class GotPltSection<ELF32BE>;
1587template class GotPltSection<ELF64LE>;
1588template class GotPltSection<ELF64BE>;
1589
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001590template class GotSection<ELF32LE>;
1591template class GotSection<ELF32BE>;
1592template class GotSection<ELF64LE>;
1593template class GotSection<ELF64BE>;
1594
1595template class PltSection<ELF32LE>;
1596template class PltSection<ELF32BE>;
1597template class PltSection<ELF64LE>;
1598template class PltSection<ELF64BE>;
1599
1600template class RelocationSection<ELF32LE>;
1601template class RelocationSection<ELF32BE>;
1602template class RelocationSection<ELF64LE>;
1603template class RelocationSection<ELF64BE>;
1604
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001605template class InterpSection<ELF32LE>;
1606template class InterpSection<ELF32BE>;
1607template class InterpSection<ELF64LE>;
1608template class InterpSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001609
Igor Kudrin1b0d7062015-10-22 08:21:35 +00001610template class GnuHashTableSection<ELF32LE>;
1611template class GnuHashTableSection<ELF32BE>;
1612template class GnuHashTableSection<ELF64LE>;
1613template class GnuHashTableSection<ELF64BE>;
1614
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001615template class HashTableSection<ELF32LE>;
1616template class HashTableSection<ELF32BE>;
1617template class HashTableSection<ELF64LE>;
1618template class HashTableSection<ELF64BE>;
1619
1620template class DynamicSection<ELF32LE>;
1621template class DynamicSection<ELF32BE>;
1622template class DynamicSection<ELF64LE>;
1623template class DynamicSection<ELF64BE>;
1624
1625template class OutputSection<ELF32LE>;
1626template class OutputSection<ELF32BE>;
1627template class OutputSection<ELF64LE>;
1628template class OutputSection<ELF64BE>;
1629
Rafael Espindola0c6a4f12015-11-11 19:54:14 +00001630template class EHOutputSection<ELF32LE>;
1631template class EHOutputSection<ELF32BE>;
1632template class EHOutputSection<ELF64LE>;
1633template class EHOutputSection<ELF64BE>;
1634
Simon Atanasyan1d7df402015-12-20 10:57:34 +00001635template class MipsReginfoOutputSection<ELF32LE>;
1636template class MipsReginfoOutputSection<ELF32BE>;
1637template class MipsReginfoOutputSection<ELF64LE>;
1638template class MipsReginfoOutputSection<ELF64BE>;
1639
Rafael Espindolac159c962015-10-19 21:00:02 +00001640template class MergeOutputSection<ELF32LE>;
1641template class MergeOutputSection<ELF32BE>;
1642template class MergeOutputSection<ELF64LE>;
1643template class MergeOutputSection<ELF64BE>;
1644
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001645template class StringTableSection<ELF32LE>;
1646template class StringTableSection<ELF32BE>;
1647template class StringTableSection<ELF64LE>;
1648template class StringTableSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001649
1650template class SymbolTableSection<ELF32LE>;
1651template class SymbolTableSection<ELF32BE>;
1652template class SymbolTableSection<ELF64LE>;
1653template class SymbolTableSection<ELF64BE>;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001654
1655template class BuildIdSection<ELF32LE>;
1656template class BuildIdSection<ELF32BE>;
1657template class BuildIdSection<ELF64LE>;
1658template class BuildIdSection<ELF64BE>;
Rafael Espindola5805c4f2015-09-21 21:38:08 +00001659}
1660}